hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
8d432569a9609b207687346d1077699e8cf450c8
498
js
JavaScript
test/language/expressions/unary-plus/S11.4.6_A3_T2.js
ptomato/test262
10ad4c159328d12ad8d12b95a8f8aefa0e4fd49b
[ "BSD-3-Clause" ]
1,849
2015-01-15T12:42:53.000Z
2022-03-30T21:23:59.000Z
test/language/expressions/unary-plus/S11.4.6_A3_T2.js
ptomato/test262
10ad4c159328d12ad8d12b95a8f8aefa0e4fd49b
[ "BSD-3-Clause" ]
2,157
2015-01-06T05:01:55.000Z
2022-03-31T17:18:08.000Z
test/language/expressions/unary-plus/S11.4.6_A3_T2.js
ptomato/test262
10ad4c159328d12ad8d12b95a8f8aefa0e4fd49b
[ "BSD-3-Clause" ]
411
2015-01-22T01:40:04.000Z
2022-03-28T19:19:16.000Z
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: Operator +x returns ToNumber(x) es5id: 11.4.6_A3_T2 description: Type(x) is number primitive or Number object ---*/ //CHECK#1 if (+0.1 !== 0.1) { throw new Test262Error('#1: +0.1 === 0.1. Actual: ' + (+0.1)); } //CHECK#2 if (+new Number(-1.1) !== -1.1) { throw new Test262Error('#2: +new Number(-1.1) === -1.1. Actual: ' + (+new Number(-1.1))); }
26.210526
91
0.620482
8d4466afb1fe2b266a97f2dd483b10ec9137a628
3,282
js
JavaScript
src/Modules/Dashboard/components/CardChart.js
terrygreen0606/React-Dashboard-App
9bc778ebeb601ef34d472d6dc4beb4eed552bc3b
[ "Net-SNMP", "Xnet", "RSA-MD" ]
4
2020-09-30T00:47:41.000Z
2021-08-03T15:40:33.000Z
src/Modules/Dashboard/components/CardChart.js
terrygreen0606/React-Dashboard-App
9bc778ebeb601ef34d472d6dc4beb4eed552bc3b
[ "Net-SNMP", "Xnet", "RSA-MD" ]
null
null
null
src/Modules/Dashboard/components/CardChart.js
terrygreen0606/React-Dashboard-App
9bc778ebeb601ef34d472d6dc4beb4eed552bc3b
[ "Net-SNMP", "Xnet", "RSA-MD" ]
1
2021-04-19T17:58:30.000Z
2021-04-19T17:58:30.000Z
import React from "react"; import { Col, Card, CardBody } from "reactstrap"; import { CustomTooltips } from "@coreui/coreui-plugin-chartjs-custom-tooltips"; // Line Chart const chartDataOpt = { tooltips: { enabled: false, custom: CustomTooltips, }, maintainAspectRatio: false, legend: { display: false, }, scales: { xAxes: [ { gridLines: { color: "transparent", zeroLineColor: "transparent", }, ticks: { fontSize: 2, fontColor: "transparent", }, }, ], yAxes: [ { display: false, ticks: { display: false, // maxTicksLimit: 3, // min: Math.min.apply(Math, chartData.datasets[0].data) - 5, // max: Math.max.apply(Math, chartData.datasets[0].data) + 5, }, }, ], }, elements: { line: { tension: 0.00001, borderWidth: 1, }, point: { radius: 4, hitRadius: 10, hoverRadius: 4, }, }, }; // Bar Chart const barChartOpt = { tooltips: { enabled: false, custom: CustomTooltips, }, maintainAspectRatio: false, legend: { display: false, }, scales: { xAxes: [ { display: false, }, ], yAxes: [ { display: false, // ticks: { // maxTicksLimit: 3, // }, }, ], }, }; const CardChart = ({ card }) => { const labels = []; const datasets = []; if (card.data) { // If performance score chart if (card.id === 1) { labels.push(...card.data.department.map((item) => item.date)); datasets.push( { label: "Overall", backgroundColor: "transparent", borderColor: "rgba(255,255,255,.55)", data: card.data.department.map((item) => parseFloat(item.value).toFixed(2) ), }, { label: "User Dependent", backgroundColor: "transparent", borderColor: "rgba(37,44,45,.3)", data: card.data.user.map((item) => parseFloat(item.value).toFixed(2)), } ); // datasets.push({ // label: card.title, // backgroundColor: "transparent", // borderColor: "rgba(255,255,255,.55)", // data: card.data.map((item) => item.value.toFixed(2)), // }); } else { labels.push(...card.data.map((item) => item.date)); datasets.push({ label: card.title, backgroundColor: card.id === 4 ? "rgba(255,255,255,.3)" : "transparent", borderColor: card.id === 4 ? "transparent" : "rgba(255,255,255,.55)", data: card.data.map((item) => parseFloat(item.value).toFixed(2)), barPercentage: 0.6, }); } } return ( <Col xs="12" sm="6" lg="3"> <Card className={`text-white bg-${card.color}`}> <CardBody className="pb-0"> <div>{card.title}</div> <div className="chart-wrapper mt-3" style={{ height: "120px" }}> <card.component data={{ labels, datasets }} options={card.id === 4 ? barChartOpt : chartDataOpt} height={120} /> </div> </CardBody> </Card> </Col> ); }; export default CardChart;
23.276596
80
0.499695
8d45b1bc1439e3f15fa223bdba79ec8dbba0d429
2,687
js
JavaScript
index.js
LucasMonteiroi/pontos-umbanda
de6815b9510dd6dc0541471b0426cf4a793f08b8
[ "MIT" ]
null
null
null
index.js
LucasMonteiroi/pontos-umbanda
de6815b9510dd6dc0541471b0426cf4a793f08b8
[ "MIT" ]
null
null
null
index.js
LucasMonteiroi/pontos-umbanda
de6815b9510dd6dc0541471b0426cf4a793f08b8
[ "MIT" ]
null
null
null
const { parse } = require("csv-parse"); const fs = require("fs"); const { resolve } = require("path"); const path = require("path"); const gcloudAdatpter = require("./gcloud"); const { PythonShell } = require("python-shell"); const pontos = []; const exportPontos = []; const categories = []; function addCategory(category) { const categoryAlreadyExists = categories.find( (cat) => cat.id === category.id ); if (!categoryAlreadyExists) { categories.push({ id: category.id, subcategories: [], }); return; } const storedCategory = categories.find((cat) => cat.id === category.id); const subCategoryAlreadyExists = storedCategory.subcategories.find( (sub) => sub.id === category.subCategory ); if (!subCategoryAlreadyExists) { storedCategory.subcategories.push({ id: category.subCategory, }); } } function sortCategories() { categories.forEach((cat) => { exportPontos.push(`Pontos de ${cat.id}`); cat.subcategories.forEach((sub) => { const pontos = searchPontos(cat.id, sub.id); exportPontos.push(pontos); }); }); } function searchPontos(linha, ritmo) { const retorno = pontos .filter((line) => line.ritmo === ritmo && line.linha === linha) .map((line) => { exportPontos.push(`Entidade: ${line.entidade}`); exportPontos.push(`Toque: ${ritmo}`); exportPontos.push(line.letra); return; }) .join(""); return retorno; } function callScript(rows) { let options = { mode: "text", pythonPath: "/usr/local/bin/python3", pythonOptions: ["-u"], // get print results in real-time scriptPath: "", args: rows, }; PythonShell.run("createDocument.py", options, function (err, results) { if (err) throw err; // results is an array consisting of messages collected during execution console.log("results: %j", results); }); } function importFile() { const fileName = "input.csv"; const filePath = path.resolve(`./inputs/${fileName}`); const stream = fs.createReadStream(filePath); const parseFile = parse({ delimiter: ",", fromLine: 2 }); stream.pipe(parseFile); parseFile .on("data", async (line) => { pontos.push({ linha: line[0], entidade: line[1], ritmo: line[2], letra: line[3], }); addCategory({ id: line[0], subCategory: line[2], subcategories: [], }); }) .on("end", () => { sortCategories(); // gcloudAdatpter.execute("pontos", exportPontos.join("")); callScript(exportPontos); resolve(filePath); }) .on("error", (error) => { reject(error); }); } importFile();
23.570175
76
0.603275
8d4667ca3c477651b27a5f154be13c71a821101a
988
js
JavaScript
docs/src/examples/collections/Menu/Variations/MenuExampleStackable.js
Fox32/Semantic-UI-React
9dd0596a8ab39e6c1d47d5630ddb878ec31a7d7a
[ "MIT" ]
1
2022-03-21T02:23:11.000Z
2022-03-21T02:23:11.000Z
docs/src/examples/collections/Menu/Variations/MenuExampleStackable.js
Fox32/Semantic-UI-React
9dd0596a8ab39e6c1d47d5630ddb878ec31a7d7a
[ "MIT" ]
1
2022-03-02T13:37:47.000Z
2022-03-02T13:37:47.000Z
docs/src/examples/collections/Menu/Variations/MenuExampleStackable.js
Fox32/Semantic-UI-React
9dd0596a8ab39e6c1d47d5630ddb878ec31a7d7a
[ "MIT" ]
null
null
null
import React, { Component } from 'react' import { Menu } from 'semantic-ui-react' export default class MenuExampleStackable extends Component { state = {} handleItemClick = (e, { name }) => this.setState({ activeItem: name }) render() { const { activeItem } = this.state return ( <Menu stackable> <Menu.Item> <img alt="logo" src='/logo.png' /> </Menu.Item> <Menu.Item name='features' active={activeItem === 'features'} onClick={this.handleItemClick} > Features </Menu.Item> <Menu.Item name='testimonials' active={activeItem === 'testimonials'} onClick={this.handleItemClick} > Testimonials </Menu.Item> <Menu.Item name='sign-in' active={activeItem === 'sign-in'} onClick={this.handleItemClick} > Sign-in </Menu.Item> </Menu> ) } }
21.955556
72
0.522267
8d468df0d270c30f6d3ea931d2000cc921dcc776
1,060
js
JavaScript
src/models/index.js
taegorov/basic-api-server
f1e191a1eb2972acbd098ae3a709e083fb32d0fe
[ "MIT" ]
1
2021-06-27T09:48:36.000Z
2021-06-27T09:48:36.000Z
src/models/index.js
taegorov/basic-api-server
f1e191a1eb2972acbd098ae3a709e083fb32d0fe
[ "MIT" ]
null
null
null
src/models/index.js
taegorov/basic-api-server
f1e191a1eb2972acbd098ae3a709e083fb32d0fe
[ "MIT" ]
null
null
null
'use strict'; require('dotenv').config(); const DATABASE_URL = process.env.DATABASE_URL || 'sqlite:memory:'; const { Sequelize, DataTypes } = require('sequelize'); const carModel = require('./car.js'); const foodModel = require('./food.js'); const todoSchema = require('./todo.schema.js'); const userSchema = require('./user.schema.js'); // // tests might not pass with this commented out. Either have this uncommented out, or new Sequelize(DATABASE_URL) below // let sequelize = new Sequelize(DATABASE_URL); // let sequelize = new Sequelize(process.env.DATABASE_URL || 'sqlite:memory:'); // Heroku needs this to run Sequelize let sequelize = new Sequelize(DATABASE_URL, { dialectOptions: { ssl: { require: true, rejectUnauthorized: false, } } }); const car = carModel(sequelize, DataTypes); const food = foodModel(sequelize, DataTypes); const todo = todoSchema(sequelize, DataTypes); const user = userSchema(sequelize, DataTypes); module.exports = { db: sequelize, car: car, food: food, todo: todo, user: user, }
24.090909
122
0.7
8d46cec179d3d9a4a9289612d14e9c7e237b0428
522
js
JavaScript
pages/weixinlink/weixinlink.js
ddabb/FreeKnowledgeSource
3205db1958cbb0d018558dc58adcf7dfb166745a
[ "MIT" ]
null
null
null
pages/weixinlink/weixinlink.js
ddabb/FreeKnowledgeSource
3205db1958cbb0d018558dc58adcf7dfb166745a
[ "MIT" ]
null
null
null
pages/weixinlink/weixinlink.js
ddabb/FreeKnowledgeSource
3205db1958cbb0d018558dc58adcf7dfb166745a
[ "MIT" ]
1
2021-05-08T07:22:52.000Z
2021-05-08T07:22:52.000Z
var util = require('../../util.js') Page({ data: { articleSrc: "" }, onLoad: function (option) { let articleurl = wx.getStorageSync("articleurl"); let articletitle = wx.getStorageSync("articletitle"); wx.setNavigationBarTitle({ title: articletitle, }) this.setData({ articleSrc: articleurl }) }, handlerGobackClick() { util.handlerGobackClick(function (e) {}, 1000) }, handlerGohomeClick() { util.handlerGohomeClick(function (e) { }, 1000) }, })
16.3125
57
0.60728
8d4821edfffd2902784a8a83e009410019290b6c
917
js
JavaScript
build/tasks/zip.js
juniarta/godeg-api
dfd80e26c8b9b9ed4a9e57e84344fc4168fbc184
[ "MIT" ]
187
2017-01-25T11:29:05.000Z
2022-03-21T13:48:37.000Z
build/tasks/zip.js
keonakhon/express-graphql-typescript-boilerplate
28b2e84ee0063d6cc464a45bd05be2bc914b3a34
[ "MIT" ]
7
2017-03-15T21:01:16.000Z
2018-04-03T14:04:12.000Z
build/tasks/zip.js
keonakhon/express-graphql-typescript-boilerplate
28b2e84ee0063d6cc464a45bd05be2bc914b3a34
[ "MIT" ]
95
2017-01-26T10:05:12.000Z
2021-07-23T10:50:56.000Z
'use strict'; const gulp = require('gulp'); const path = require('path'); const paths = require('../paths'); const runSequence = require('run-sequence'); const pkg = require('../../package.json'); const $ = require('gulp-load-plugins')({ lazy: true }); gulp.task('zip', (callback) => runSequence( 'build', 'zip:create', 'clean', callback )); gulp.task('zip:create', () => { const packageFileFilter = $.filter(['package.json'], { restore: true }); return gulp .src([ path.join(paths.src, '**/*.js'), 'manifest.yml', 'package.json' ]) .pipe(packageFileFilter) .pipe($.jsonEditor((json) => { json.scripts.start = 'node index.js'; return json; })) .pipe(packageFileFilter.restore) .pipe($.zip(pkg.name + '-' + pkg.version + '.zip')) .pipe(gulp.dest(paths.dist)) });
25.472222
76
0.539804
8d485294b25c77f9912d1eb45020722f6305ef70
90
js
JavaScript
node_modules/standardized-audio-context/build/es2019/types/media-stream-audio-source-node-constructor.js
chadpalmer2/the-music-machine-frontend
e00aac3406e0a3d2721b2d042402b657a85c5607
[ "MIT" ]
null
null
null
node_modules/standardized-audio-context/build/es2019/types/media-stream-audio-source-node-constructor.js
chadpalmer2/the-music-machine-frontend
e00aac3406e0a3d2721b2d042402b657a85c5607
[ "MIT" ]
null
null
null
node_modules/standardized-audio-context/build/es2019/types/media-stream-audio-source-node-constructor.js
chadpalmer2/the-music-machine-frontend
e00aac3406e0a3d2721b2d042402b657a85c5607
[ "MIT" ]
null
null
null
//# sourceMappingURL=/build/es2019/types/media-stream-audio-source-node-constructor.js.map
90
90
0.822222
8d4854f570e775dfdd3aaa7683392c3a70a607d1
736
js
JavaScript
src/pages/components/Login/FormMain.js
MaAnShanGuider/Security-Tracebilty
a03dfa0855420237b74c78d5d1a7529a9c5ace83
[ "MIT" ]
null
null
null
src/pages/components/Login/FormMain.js
MaAnShanGuider/Security-Tracebilty
a03dfa0855420237b74c78d5d1a7529a9c5ace83
[ "MIT" ]
null
null
null
src/pages/components/Login/FormMain.js
MaAnShanGuider/Security-Tracebilty
a03dfa0855420237b74c78d5d1a7529a9c5ace83
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import * as types from '@constants/actions/login'; import { createForm } from 'rc-form'; import { LOGIN } from "@constants/constants"; import From from './Form'; import "./Styles.scss"; @createForm() class LoginForm extends Component { constructor(props, context) { super(props, context); } render() { return ( <div className="v-login-box g-white g-flex-cc g-jc-c g-ai-c" > <div className="g-col g-tc g-pd-20 _left"> <img src={LOGIN} className="_logo"/> <div className="g-fs-60 g-pd-t-10 g-color-white g-lh-66"> 防伪追溯系统 </div> <div className="g-fs-24"> 店铺管理后台 </div> </div> <From /> </div> ); } } export default LoginForm;
23.741935
62
0.616848
8d4868ccd5cb1cadee01cdf61a7aed126034963d
284
js
JavaScript
source/actions/manageWarning.js
aMarcireau/origami
59db8495c0e2e98d09992b960dee5d3a1b4ddcfe
[ "MIT" ]
18
2017-11-22T17:05:17.000Z
2022-01-17T18:36:04.000Z
source/actions/manageWarning.js
aMarcireau/origami
59db8495c0e2e98d09992b960dee5d3a1b4ddcfe
[ "MIT" ]
50
2017-11-24T08:14:07.000Z
2021-09-23T06:44:52.000Z
source/actions/manageWarning.js
aMarcireau/origami
59db8495c0e2e98d09992b960dee5d3a1b4ddcfe
[ "MIT" ]
2
2020-01-06T14:00:12.000Z
2020-01-07T20:00:44.000Z
import { REMOVE_WARNING, REMOVE_ALL_WARNINGS } from "../constants/actionTypes"; export function removeWarning(warningIndex) { return { type: REMOVE_WARNING, warningIndex, }; } export function removeAllWarnings() { return { type: REMOVE_ALL_WARNINGS }; }
21.846154
79
0.697183
8d497fe2bad0f02eac8cf8a6ac7637ab58aa2819
14,816
js
JavaScript
contentcuration/contentcuration/frontend/shared/mixins.js
kollivier/studio
9089780858ae9870421056b4e6e5659ae854db57
[ "MIT" ]
1
2019-03-30T18:14:25.000Z
2019-03-30T18:14:25.000Z
contentcuration/contentcuration/frontend/shared/mixins.js
kollivier/studio
9089780858ae9870421056b4e6e5659ae854db57
[ "MIT" ]
2
2019-04-06T07:06:08.000Z
2019-04-08T23:33:53.000Z
contentcuration/contentcuration/frontend/shared/mixins.js
MisRob/studio
92a5c780c8952f7d37db38952483ab7a28d3cb9d
[ "MIT" ]
null
null
null
import isEqual from 'lodash/isEqual'; import transform from 'lodash/transform'; import uniq from 'lodash/uniq'; import { mapGetters } from 'vuex'; import { ChannelListTypes, fileErrors, ONE_B, ONE_KB, ONE_MB, ONE_GB, ONE_TB, filterTypes, } from './constants'; import { createTranslator, updateTabTitle } from 'shared/i18n'; import Languages from 'shared/leUtils/Languages'; import Licenses from 'shared/leUtils/Licenses'; const sizeStrings = createTranslator('BytesForHumansStrings', { fileSizeInBytes: '{n, number, integer} B', fileSizeInKilobytes: '{n, number, integer} KB', fileSizeInMegabytes: '{n, number, integer} MB', fileSizeInGigabytes: '{n, number, integer} GB', fileSizeInTerabytes: '{n, number, integer} TB', }); const stringMap = { [ONE_B]: 'fileSizeInBytes', [ONE_KB]: 'fileSizeInKilobytes', [ONE_MB]: 'fileSizeInMegabytes', [ONE_GB]: 'fileSizeInGigabytes', [ONE_TB]: 'fileSizeInTerabytes', }; export default function bytesForHumans(bytes) { bytes = bytes || 0; const unit = [ONE_TB, ONE_GB, ONE_MB, ONE_KB].find(x => bytes >= x) || ONE_B; return sizeStrings.$tr(stringMap[unit], { n: Math.round(bytes / unit) }); } export const fileSizeMixin = { methods: { formatFileSize(size) { return bytesForHumans(size); }, }, }; const statusStrings = createTranslator('StatusStrings', { uploadFileSize: '{uploaded} of {total}', uploadFailedError: 'Upload failed', noStorageError: 'Not enough space', }); export const fileStatusMixin = { mixins: [fileSizeMixin], computed: { ...mapGetters('file', ['getFileUpload']), }, methods: { statusMessage(id) { const errorMessage = this.errorMessage(id); if (errorMessage) { return errorMessage; } const file = this.getFileUpload(id); if (file && file.total) { return statusStrings.$tr('uploadFileSize', { uploaded: bytesForHumans(file.loaded), total: bytesForHumans(file.total), }); } }, errorMessage(id) { const file = this.getFileUpload(id); if (!file) { return; } if (file.error === fileErrors.NO_STORAGE) { return statusStrings.$tr('noStorageError'); } else if (file.error === fileErrors.UPLOAD_FAILED) { return statusStrings.$tr('uploadFailedError'); } }, }, }; export const constantStrings = createTranslator('ConstantStrings', { [ChannelListTypes.EDITABLE]: 'My channels', [ChannelListTypes.VIEW_ONLY]: 'View-only', [ChannelListTypes.PUBLIC]: 'Content library', [ChannelListTypes.STARRED]: 'Starred', do_all: '100% correct', num_correct_in_a_row_10: '10 in a row', num_correct_in_a_row_2: '2 in a row', num_correct_in_a_row_3: '3 in a row', num_correct_in_a_row_5: '5 in a row', m_of_n: 'M of N...', do_all_description: 'Learner must answer all questions in the exercise correctly (not recommended for long exercises)', num_correct_in_a_row_10_description: 'Learner must answer 10 questions in a row correctly', num_correct_in_a_row_2_description: 'Learner must answer 2 questions in a row correctly', num_correct_in_a_row_3_description: 'Learner must answer 3 questions in a row correctly', num_correct_in_a_row_5_description: 'Learner must answer 5 questions in a row correctly', m_of_n_description: 'Learner must answer M questions correctly from the last N answered questions. For example, ‘3 of 5’ means learners must answer 3 questions correctly out of the 5 most recently answered.', input_question: 'Numeric input', multiple_selection: 'Multiple choice', single_selection: 'Single choice', perseus_question: 'Khan Academy question', true_false: 'True/False', unknown_question: 'Unknown question type', mp4: 'MP4 video', vtt: 'VTT caption', mp3: 'MP3 audio', pdf: 'PDF document', epub: 'EPub document', jpg: 'JPG image', jpeg: 'JPEG image', png: 'PNG image', gif: 'GIF image', json: 'JSON', svg: 'SVG image', perseus: 'Perseus Exercise', zip: 'HTML5 zip', topic: 'Topic', video: 'Video', audio: 'Audio', document: 'Document', exercise: 'Exercise', h5p: 'H5P App', html5: 'HTML5 App', slideshow: 'Slideshow', coach: 'Coaches', learner: 'Anyone', high_res_video: 'High resolution', low_res_video: 'Low resolution', video_subtitle: 'Captions', html5_zip: 'HTML5 zip', video_thumbnail: 'Thumbnail', audio_thumbnail: 'Thumbnail', document_thumbnail: 'Thumbnail', exercise_thumbnail: 'Thumbnail', topic_thumbnail: 'Thumbnail', html5_thumbnail: 'Thumbnail', 'CC BY': 'CC BY', 'CC BY-SA': 'CC BY-SA', 'CC BY-ND': 'CC BY-ND', 'CC BY-NC': 'CC BY-NC', 'CC BY-NC-SA': 'CC BY-NC-SA', 'CC BY-NC-ND': 'CC BY-NC-ND', 'All Rights Reserved': 'All Rights Reserved', 'Public Domain': 'Public Domain', 'Special Permissions': 'Special Permissions', 'CC BY_description': 'The Attribution License lets others distribute, remix, tweak, and build upon your work, even commercially, as long as they credit you for the original creation. This is the most accommodating of licenses offered. Recommended for maximum dissemination and use of licensed materials.', 'CC BY-SA_description': 'The Attribution-ShareAlike License lets others remix, tweak, and build upon your work even for commercial purposes, as long as they credit you and license their new creations under the identical terms. This license is often compared to "copyleft" free and open source software licenses. All new works based on yours will carry the same license, so any derivatives will also allow commercial use. This is the license used by Wikipedia, and is recommended for materials that would benefit from incorporating content from Wikipedia and similarly licensed projects.', 'CC BY-ND_description': 'The Attribution-NoDerivs License allows for redistribution, commercial and non-commercial, as long as it is passed along unchanged and in whole, with credit to you.', 'CC BY-NC_description': "The Attribution-NonCommercial License lets others remix, tweak, and build upon your work non-commercially, and although their new works must also acknowledge you and be non-commercial, they don't have to license their derivative works on the same terms.", 'CC BY-NC-SA_description': 'The Attribution-NonCommercial-ShareAlike License lets others remix, tweak, and build upon your work non-commercially, as long as they credit you and license their new creations under the identical terms.', 'CC BY-NC-ND_description': "The Attribution-NonCommercial-NoDerivs License is the most restrictive of our six main licenses, only allowing others to download your works and share them with others as long as they credit you, but they can't change them in any way or use them commercially.", 'All Rights Reserved_description': 'The All Rights Reserved License indicates that the copyright holder reserves, or holds for their own use, all the rights provided by copyright law under one specific copyright treaty.', 'Public Domain_description': 'Public Domain work has been identified as being free of known restrictions under copyright law, including all related and neighboring rights.', 'Special Permissions_description': 'Special Permissions is a custom license to use when the current licenses do not apply to the content. The owner of this license is responsible for creating a description of what this license entails.', // global copy strings firstCopy: 'Copy of {title}', nthCopy: 'Copy {n, number, integer} of {title}', }); export const constantsTranslationMixin = { methods: { translateConstant(constant) { return constantStrings.$tr(constant); }, translateLanguage(language) { return Languages.has(language) && Languages.get(language).native_name; }, translateLicense(license) { return Licenses.has(license) && this.translateConstant(Licenses.get(license).license_name); }, }, }; /** * jayoshih: using a mixin to handle this to handle the translations * and handle cases where user opens page at a component */ export const routerMixin = { methods: { updateTabTitle(title) { updateTabTitle(title); }, }, }; export const contentNodeStrings = createTranslator('ContentNodeStrings', { untitled: 'Untitled' }); export const titleMixin = { computed: { hasTitle() { return node => node && node.title && node.title.trim(); }, getTitle() { return node => (this.hasTitle(node) ? node.title : contentNodeStrings.$tr('untitled')); }, getTitleClass() { return node => (this.hasTitle(node) ? 'notranslate' : ''); }, }, }; export const printingMixin = { inject: { printing: { from: 'printing', default: false, }, }, }; export function generateSearchMixin(filterMap) { return { computed: { ...transform( filterMap, (result, type, key) => { result[key] = { get() { if (type === filterTypes.MULTISELECT) { return this.$route.query[key] ? this.$route.query[key].split(',') : []; } else if (type === filterTypes.BOOLEAN) { return String(this.$route.query[key]) === 'true'; } return this.$route.query[key]; }, set(value) { if (type === filterTypes.MULTISELECT) { value.length ? this.updateQueryParams({ [key]: uniq(value).join(',') }) : this.deleteQueryParam(key); } else if (type === filterTypes.BOOLEAN) { value ? this.updateQueryParams({ [key]: value }) : this.deleteQueryParam(key); } else { this.updateQueryParams({ [key]: value }); } }, }; }, {} ), filterKeys() { return Object.keys(filterMap).filter(k => this.$route.query[k]); }, }, methods: { deleteQueryParam(key) { let query = { ...this.$route.query }; delete query[key]; this.navigate(query); }, updateQueryParams(params) { let query = { ...this.$route.query, ...params, }; this.navigate(query); }, clearFilters() { this.navigate({}); }, navigate(params) { if (!isEqual(this.$route.query, params)) { this.$router .replace({ ...this.$route, query: { ...params, page: 1, // Make sure we're on page 1 for every new query }, }) .catch(error => { if (error && error.name != 'NavigationDuplicated') { throw error; } }); } }, }, }; } /* Return mixin based on form fields passed in Sample form field data: { fieldName: { required: false, multiSelect: false, validator: value => Boolean(value) } } */ function _cleanMap(formFields) { // Make sure all fields have the relevant validator field return transform( formFields, (result, value, key) => { result[key] = value; // Make sure all fields have a validator // Some fields depend on other fields, so pass in // context to use in validator (e.g. checking an "other" // option may require a text field as a result) if (value.validator) { result[key].validator = value.validator; } else if (!value.required) { result[key].validator = () => true; } else if (value.multiSelect) { // eslint-disable-next-line no-unused-vars result[key].validator = (v, _) => Boolean(v.length); } else { // eslint-disable-next-line no-unused-vars result[key].validator = (v, _) => Boolean(v); } }, {} ); } const formStrings = createTranslator('formStrings', { errorText: 'Please fix {count, plural,\n =1 {# error}\n other {# errors}} below', }); export function generateFormMixin(formFields) { const cleanedMap = _cleanMap(formFields); return { data() { return { // Store errors errors: {}, // Store entries form: transform( formFields, (result, value, key) => { result[key] = value.multiSelect ? [] : ''; }, {} ), }; }, computed: { formStrings() { return formStrings; }, // Create getters/setters for all items ...transform( cleanedMap, function(result, value, key) { result[key] = { get() { return this.form[key] || (value.multiSelect ? [] : ''); }, set(v) { this.$set(this.form, key, v); if (!value.validator(v, this)) { this.$set(this.errors, key, true); } else { this.$delete(this.errors, key); } }, }; }, {} ), }, methods: { /* For some reason, having an errorCount computed property doesn't get updated on form changes. Use methods to track errorCount and errorText instead */ errorCount() { return Object.keys(this.errors).length; }, errorText() { return this.formStrings.$tr('errorText', { count: this.errorCount(), }); }, clean() { return transform( cleanedMap, (result, value, key) => { result[key] = this[key]; if (value.multiSelect) { result[key] = result[key] || []; } else { result[key] = (result[key] || '').trim(); } }, {} ); }, validate(formData) { this.errors = transform( cleanedMap, (result, value, key) => { if (!value.validator(formData[key], this)) { result[key] = true; } }, {} ); return !Object.keys(this.errors).length; }, submit() { const formData = this.clean(); if (this.validate(formData)) { this.onSubmit(formData); } else { this.onValidationFailed(); } }, // eslint-disable-next-line no-unused-vars onSubmit(formData) { throw Error('Must implement onSubmit when using formMixin'); }, onValidationFailed() { // Optional method for forms - overwrite in components }, reset() { this.form = {}; this.resetValidation(); }, resetValidation() { this.errors = {}; }, }, }; }
32.706402
568
0.611906
8d49b4b0dad08714c439ba4d2deec1803feff6ad
6,987
js
JavaScript
node_modules/@grpc/grpc-js/build/src/compression-filter.js
kendrak922/sign-up
2334bd1f37bea3e927e8267dc46a5b1d9143ec59
[ "MIT" ]
19
2020-10-05T17:05:19.000Z
2020-11-23T16:07:49.000Z
node_modules/@grpc/grpc-js/build/src/compression-filter.js
kendrak922/sign-up
2334bd1f37bea3e927e8267dc46a5b1d9143ec59
[ "MIT" ]
71
2021-01-13T21:39:56.000Z
2021-03-08T06:22:28.000Z
node_modules/@grpc/grpc-js/build/src/compression-filter.js
kendrak922/sign-up
2334bd1f37bea3e927e8267dc46a5b1d9143ec59
[ "MIT" ]
14
2021-02-03T15:59:38.000Z
2022-01-03T14:18:17.000Z
"use strict"; /* * Copyright 2019 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ Object.defineProperty(exports, "__esModule", { value: true }); exports.CompressionFilterFactory = exports.CompressionFilter = void 0; const zlib = require("zlib"); const filter_1 = require("./filter"); class CompressionHandler { /** * @param message Raw uncompressed message bytes * @param compress Indicates whether the message should be compressed * @return Framed message, compressed if applicable */ async writeMessage(message, compress) { let messageBuffer = message; if (compress) { messageBuffer = await this.compressMessage(messageBuffer); } const output = Buffer.allocUnsafe(messageBuffer.length + 5); output.writeUInt8(compress ? 1 : 0, 0); output.writeUInt32BE(messageBuffer.length, 1); messageBuffer.copy(output, 5); return output; } /** * @param data Framed message, possibly compressed * @return Uncompressed message */ async readMessage(data) { const compressed = data.readUInt8(0) === 1; let messageBuffer = data.slice(5); if (compressed) { messageBuffer = await this.decompressMessage(messageBuffer); } return messageBuffer; } } class IdentityHandler extends CompressionHandler { async compressMessage(message) { return message; } async writeMessage(message, compress) { const output = Buffer.allocUnsafe(message.length + 5); /* With "identity" compression, messages should always be marked as * uncompressed */ output.writeUInt8(0, 0); output.writeUInt32BE(message.length, 1); message.copy(output, 5); return output; } decompressMessage(message) { return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); } } class DeflateHandler extends CompressionHandler { compressMessage(message) { return new Promise((resolve, reject) => { zlib.deflate(message, (err, output) => { if (err) { reject(err); } else { resolve(output); } }); }); } decompressMessage(message) { return new Promise((resolve, reject) => { zlib.inflate(message, (err, output) => { if (err) { reject(err); } else { resolve(output); } }); }); } } class GzipHandler extends CompressionHandler { compressMessage(message) { return new Promise((resolve, reject) => { zlib.gzip(message, (err, output) => { if (err) { reject(err); } else { resolve(output); } }); }); } decompressMessage(message) { return new Promise((resolve, reject) => { zlib.unzip(message, (err, output) => { if (err) { reject(err); } else { resolve(output); } }); }); } } class UnknownHandler extends CompressionHandler { constructor(compressionName) { super(); this.compressionName = compressionName; } compressMessage(message) { return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); } decompressMessage(message) { // This should be unreachable return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); } } function getCompressionHandler(compressionName) { switch (compressionName) { case 'identity': return new IdentityHandler(); case 'deflate': return new DeflateHandler(); case 'gzip': return new GzipHandler(); default: return new UnknownHandler(compressionName); } } class CompressionFilter extends filter_1.BaseFilter { constructor() { super(...arguments); this.sendCompression = new IdentityHandler(); this.receiveCompression = new IdentityHandler(); } async sendMetadata(metadata) { const headers = await metadata; headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); headers.set('accept-encoding', 'identity,gzip'); return headers; } receiveMetadata(metadata) { const receiveEncoding = metadata.get('grpc-encoding'); if (receiveEncoding.length > 0) { const encoding = receiveEncoding[0]; if (typeof encoding === 'string') { this.receiveCompression = getCompressionHandler(encoding); } } metadata.remove('grpc-encoding'); metadata.remove('grpc-accept-encoding'); return metadata; } async sendMessage(message) { /* This filter is special. The input message is the bare message bytes, * and the output is a framed and possibly compressed message. For this * reason, this filter should be at the bottom of the filter stack */ const resolvedMessage = await message; const compress = resolvedMessage.flags === undefined ? false : (resolvedMessage.flags & 2 /* NoCompress */) === 0; return { message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), flags: resolvedMessage.flags, }; } async receiveMessage(message) { /* This filter is also special. The input message is framed and possibly * compressed, and the output message is deframed and uncompressed. So * this is another reason that this filter should be at the bottom of the * filter stack. */ return this.receiveCompression.readMessage(await message); } } exports.CompressionFilter = CompressionFilter; class CompressionFilterFactory { constructor(channel) { this.channel = channel; } createFilter(callStream) { return new CompressionFilter(); } } exports.CompressionFilterFactory = CompressionFilterFactory; //# sourceMappingURL=compression-filter.js.map
34.761194
132
0.602691
8d4a012073afca081f57d08db09ece333fe008c2
1,159
js
JavaScript
src/run-visitor/script.js
parro-it/px
16a68b03da105cd9c27ffc4e838bd7e94cb4fb5d
[ "MIT" ]
4
2017-12-14T21:17:00.000Z
2019-06-18T12:33:04.000Z
src/run-visitor/script.js
parro-it/px
16a68b03da105cd9c27ffc4e838bd7e94cb4fb5d
[ "MIT" ]
null
null
null
src/run-visitor/script.js
parro-it/px
16a68b03da105cd9c27ffc4e838bd7e94cb4fb5d
[ "MIT" ]
null
null
null
import AbstractCommand from "piper-process/abstract-command"; import _debug from "debug"; const debug = _debug("px"); class ScriptCommand extends AbstractCommand { constructor(node) { super(""); this.node = node; } async start(runtimeEnv) { debug("start script"); const pipe = cmd => { cmd.process.stdout.pipe(this.stdout, { end: false }); cmd.process.stderr.pipe(this.stderr, { end: false }); this.stdin.pipe(cmd.process.stdin, { end: false }); }; const executingAsync = []; for (const cmd of this.node.commands.slice(0, -1)) { pipe(cmd); const result = cmd.process.start(runtimeEnv); if (cmd.async) { executingAsync.push(result); } else { await result; } } const lastCmd = this.node.commands[this.node.commands.length - 1]; pipe(lastCmd); const exitCode = lastCmd.process.start(runtimeEnv); const results = await Promise.all([exitCode].concat(executingAsync)); this.emit("exit", 0); debug("done script"); return results[0]; } } export function Script(node) { node.process = new ScriptCommand(node); return node; }
25.195652
73
0.63503
8d4a572d534f0e142264ac24c8442e1e384e23c6
75
js
JavaScript
proto/wtools/amid/docparser.test/_asset/basic/param/paramBad.js
dmvict/wDocParser
a3a5b8dc401e0f5baae41ed68eb379f4adfc4704
[ "MIT" ]
null
null
null
proto/wtools/amid/docparser.test/_asset/basic/param/paramBad.js
dmvict/wDocParser
a3a5b8dc401e0f5baae41ed68eb379f4adfc4704
[ "MIT" ]
null
null
null
proto/wtools/amid/docparser.test/_asset/basic/param/paramBad.js
dmvict/wDocParser
a3a5b8dc401e0f5baae41ed68eb379f4adfc4704
[ "MIT" ]
3
2020-04-09T17:38:17.000Z
2021-06-09T05:40:58.000Z
/** * @param {argument} * @function paramTest * @namespace testSpace */
15
23
0.64
8d4a907148701f500c589e50910b9867d2cd43be
4,052
js
JavaScript
src/components/CargoControl.js
mmanchee/StarRacks
a6a3cae7ff864060f2d57dde6a277b3fb83703a9
[ "MIT", "Unlicense" ]
null
null
null
src/components/CargoControl.js
mmanchee/StarRacks
a6a3cae7ff864060f2d57dde6a277b3fb83703a9
[ "MIT", "Unlicense" ]
null
null
null
src/components/CargoControl.js
mmanchee/StarRacks
a6a3cae7ff864060f2d57dde6a277b3fb83703a9
[ "MIT", "Unlicense" ]
null
null
null
import React from "react"; import CargoList from "./CargoList"; import EditCargoForm from "./EditCargoForm"; import NewCargoForm from "./NewCargoForm"; import CargoDetail from './CargoDetail'; class CargoControl extends React.Component{ constructor(props){ super(props); this.state = { formVisibleOnPage: false, cargoManifest: [], selectedCargo: null, editing: false }; } //event handlers // Edit handleEditingCargoInManifest = (cargoToEdit) => { // editing cargo in actual array const editedCargoManifest = this.state.cargoManifest .filter(cargo => cargo.id !== this.state.selectedCargo.id) .concat(cargoToEdit); this.setState({ cargoManifest: editedCargoManifest, editing: false, selectedCargo: null }); } handleEditClick = () => { // sets cargo to edit this.setState({editing: true}); } // Delete handleDeletingCargo = (id) => { /// deletes cargo from array const newCargoManifest = this.state.cargoManifest .filter(cargo => cargo.id !== id); this.setState({ cargoManifest: newCargoManifest, selectedCargo: null }); } handleClick = () => { // sets state to normal if (this.state.selectedCargo != null) { this.setState({ formVisibleOnPage: false, selectedCargo: null, editing: false }); } else { if(this.state.cargoManifest.length < 20) { this.setState(prevState => ({ formVisibleOnPage: !prevState.formVisibleOnPage, })); } } } // Detail handleChangingSelectedCargo = (id) => { // view cargo in Detail const selectedCargo = this.state.cargoManifest .filter(cargo => cargo.id === id)[0]; this.setState({selectedCargo}); } //Create handleAddingNewCargoToManifest = (newCargo) => { // adds new cargo to Array const newCargoManifest = this.state.cargoManifest .concat(newCargo); this.setState({ cargoManifest: newCargoManifest, formVisibleOnPage: false }); } handleChangeCargoCratesClick = (cargoToEdit) => { const editedCargoManifest = this.state.cargoManifest .filter(cargo => cargo.id !== this.state.selectedCargo.id) .concat(cargoToEdit); this.setState({ cargoManifest: editedCargoManifest, }); } render(){ let currentlyVisibleState = null; let buttonText = null; if (this.state.editing) { // edit currentlyVisibleState = <EditCargoForm cargo = {this.state.selectedCargo} onEditCargo = {this.handleEditingCargoInManifest} />; buttonText = "Return to Cargo Manifest"; } else if (this.state.selectedCargo !== null) { // delete and edit currentlyVisibleState = <CargoDetail cargo = {this.state.selectedCargo} onClickingDelete = {this.handleDeletingCargo} onClickingEdit = {this.handleEditClick} onChangeCargoCratesClick = {this.handleChangeCargoCratesClick} />; buttonText = "Return to Cargo Manifest"; } else if (this.state.formVisibleOnPage) { // catch is set currentlyVisibleState = <NewCargoForm onNewCargoCreation={this.handleAddingNewCargoToManifest} />; buttonText = "Return to Cargo Manifest"; } else { // default currentlyVisibleState = <CargoList Cargos={this.state.cargoManifest} onCargoSelection={this.handleChangingSelectedCargo} />; if (this.state.cargoManifest.length > 19) { buttonText = "Cargo Bay if Full"; } else { buttonText = "Add Cargo"; } } return ( <React.Fragment> <div className="nav-button"> <button onClick={this.handleClick}>{buttonText}</button> </div> {currentlyVisibleState} {this.state.cargoManifest.length === 0 && currentlyVisibleState.props.Cargos !== undefined ? "There are no cargos currently on the ship" : ""} </React.Fragment> ); } } export default CargoControl;
31.169231
110
0.634008
8d4b64629a395e0802effe15f30fe63924e0e109
1,286
js
JavaScript
src/pages/Components/Body/_InfoCointainer.js
naidubobbili/SpaceAPI
94f43f7d90deb8e79cda83e578a97a3ac457d6cf
[ "BSD-2-Clause" ]
2
2021-01-12T12:57:02.000Z
2021-01-13T05:40:46.000Z
src/pages/Components/Body/_InfoCointainer.js
MIKKY-ai/SpaceAPI
be620fb60e688a9a51b48e013724d6948f3742d8
[ "BSD-2-Clause" ]
null
null
null
src/pages/Components/Body/_InfoCointainer.js
MIKKY-ai/SpaceAPI
be620fb60e688a9a51b48e013724d6948f3742d8
[ "BSD-2-Clause" ]
1
2021-01-13T05:41:27.000Z
2021-01-13T05:41:27.000Z
import useBaseUrl from "@docusaurus/useBaseUrl" import React from "react" function InfoContainer() { return ( <div className="hero shadow--md" style={{ marginTop: "10px" }}> <div className="container"> <h1 className="hero__title">SpaceAPI</h1> <p className="hero__subtitle"> <b>SpaceAPI </b>is an American adult animated space opera comedy-drama television series created by Olan Rogers for TBS. The series involves a prisoner named <b>Gary Goodspeed</b> and his alien friend, <b>Mooncake</b>, and focuses on their intergalactic adventures as they try to solve the mystery of the titular &quot;Final Space&quot;. <br /> The data and images are used without claim of ownership and belong to their respective owners. This API is open source and uses a{" "} <a href="https://github.com/suryateja011/SpaceAPI/blob/main/LICENSE"> BSD license </a> . </p> <div> <a className="button button--success button--outline button--lg" href={useBaseUrl("docs/react")} > Examples </a> </div> </div> </div> ) } export default InfoContainer
33.842105
80
0.594868
8d4b9a8111e3510e69a72d30f2b80dd128661705
1,218
js
JavaScript
packages/api/src/controllers/user/login.js
th31nvad3r/emjpm
1ad680075be554da25a44a1170893388270df9ca
[ "Apache-2.0" ]
null
null
null
packages/api/src/controllers/user/login.js
th31nvad3r/emjpm
1ad680075be554da25a44a1170893388270df9ca
[ "Apache-2.0" ]
null
null
null
packages/api/src/controllers/user/login.js
th31nvad3r/emjpm
1ad680075be554da25a44a1170893388270df9ca
[ "Apache-2.0" ]
null
null
null
const passport = require("~/auth/auth-passport"); const { validationResult } = require("express-validator"); const { User, Logs } = require("~/models"); /** * Sign in using username and password and returns JWT */ const login = async (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors }); } passport.authenticate("login-password", async (err, user) => { if (err) { return res.status(401).json({ errors: { error: err, location: "body", msg: "Vos informations de connexion sont erronées", }, }); } if (user) { await User.query() .where("id", user.id) .update({ last_login: new Date().toISOString() }); await Logs.query().insert({ action: "connexion", result: "success", user_id: user.id, }); const userResult = await user.getUser(); return res .cookie("token", userResult.token, { httpOnly: true, path: "/api/auth", secure: req.secure, }) .status(200) .json(userResult); } })(req, res, next); }; module.exports = login;
23.882353
64
0.549261
8d4bdd66cc89e3b713d998fbfbfc20cf07c1dca5
9,968
js
JavaScript
js/utils/save.js
QwQe308/A-tree-about-a-dev-makes-a-tree
4ce405524ad25c9ff19ddcd85ceadaceff7272fc
[ "MIT" ]
null
null
null
js/utils/save.js
QwQe308/A-tree-about-a-dev-makes-a-tree
4ce405524ad25c9ff19ddcd85ceadaceff7272fc
[ "MIT" ]
null
null
null
js/utils/save.js
QwQe308/A-tree-about-a-dev-makes-a-tree
4ce405524ad25c9ff19ddcd85ceadaceff7272fc
[ "MIT" ]
null
null
null
// ************ Save stuff ************ function save() { localStorage.setItem(modInfo.id, unescape(encodeURIComponent("eyJhdXRvc2F2ZSI6dHJ1ZSwibXNEaXNwbGF5IjoiYWx3YXlzIiwidGhlbWUiOm51bGwsImhxVHJlZSI6ZmFsc2UsIm9mZmxpbmVQcm9kIjp0cnVlLCJoaWRlQ2hhbGxlbmdlcyI6ZmFsc2UsInNob3dTdG9yeSI6dHJ1ZSwiZm9yY2VPbmVUYWIiOmZhbHNlLCJvbGRTdHlsZSI6ZmFsc2V9"+LZString.compressToBase64(JSON.stringify(player))))); localStorage.setItem(modInfo.id+"_options", unescape(encodeURIComponent(btoa(JSON.stringify(options))))); //ok it saved fine so the problem must be when loading } function startPlayerBase() { return { tab: layoutInfo.startTab, navTab: (layoutInfo.showTree ? layoutInfo.startNavTab : "none"), time: Date.now(), notify: {}, versionType: modInfo.id, version: VERSION.num, beta: VERSION.beta, timePlayed: 0, keepGoing: false, hasNaN: false, points: modInfo.initialStartPoints, subtabs: {}, lastSafeTab: (readData(layoutInfo.showTree) ? "none" : layoutInfo.startTab) }; } function getStartPlayer() { playerdata = startPlayerBase(); if (addedPlayerData) { extradata = addedPlayerData(); for (thing in extradata) playerdata[thing] = extradata[thing]; } playerdata.infoboxes = {}; for (layer in layers) { playerdata[layer] = getStartLayerData(layer); if (layers[layer].tabFormat && !Array.isArray(layers[layer].tabFormat)) { playerdata.subtabs[layer] = {}; playerdata.subtabs[layer].mainTabs = Object.keys(layers[layer].tabFormat)[0]; } if (layers[layer].microtabs) { if (playerdata.subtabs[layer] == undefined) playerdata.subtabs[layer] = {}; for (item in layers[layer].microtabs) playerdata.subtabs[layer][item] = Object.keys(layers[layer].microtabs[item])[0]; } if (layers[layer].infoboxes) { if (playerdata.infoboxes[layer] == undefined) playerdata.infoboxes[layer] = {}; for (item in layers[layer].infoboxes) playerdata.infoboxes[layer][item] = false; } } return playerdata; } function getStartLayerData(layer) { layerdata = {}; if (layers[layer].startData) layerdata = layers[layer].startData(); if (layerdata.unlocked === undefined) layerdata.unlocked = true; if (layerdata.total === undefined) layerdata.total = new ExpantaNum(0); if (layerdata.best === undefined) layerdata.best = new ExpantaNum(0); if (layerdata.resetTime === undefined) layerdata.resetTime = 0; if (layerdata.forceTooltip === undefined) layerdata.forceTooltip = false; layerdata.buyables = getStartBuyables(layer); if (layerdata.noRespecConfirm === undefined) layerdata.noRespecConfirm = false if (layerdata.clickables == undefined) layerdata.clickables = getStartClickables(layer); layerdata.spentOnBuyables = new ExpantaNum(0); layerdata.upgrades = []; layerdata.milestones = []; layerdata.lastMilestone = null; layerdata.achievements = []; layerdata.challenges = getStartChallenges(layer); layerdata.grid = getStartGrid(layer); layerdata.prevTab = "" return layerdata; } function getStartBuyables(layer) { let data = {}; if (layers[layer].buyables) { for (id in layers[layer].buyables) if (isPlainObject(layers[layer].buyables[id])) data[id] = new ExpantaNum(0); } return data; } function getStartClickables(layer) { let data = {}; if (layers[layer].clickables) { for (id in layers[layer].clickables) if (isPlainObject(layers[layer].clickables[id])) data[id] = ""; } return data; } function getStartChallenges(layer) { let data = {}; if (layers[layer].challenges) { for (id in layers[layer].challenges) if (isPlainObject(layers[layer].challenges[id])) data[id] = 0; } return data; } function fixSave() { defaultData = getStartPlayer(); fixData(defaultData, player); for (layer in layers) { if (player[layer].best !== undefined) player[layer].best = new ExpantaNum(player[layer].best); if (player[layer].total !== undefined) player[layer].total = new ExpantaNum(player[layer].total); if (layers[layer].tabFormat && !Array.isArray(layers[layer].tabFormat)) { if (!Object.keys(layers[layer].tabFormat).includes(player.subtabs[layer].mainTabs)) player.subtabs[layer].mainTabs = Object.keys(layers[layer].tabFormat)[0]; } if (layers[layer].microtabs) { for (item in layers[layer].microtabs) if (!Object.keys(layers[layer].microtabs[item]).includes(player.subtabs[layer][item])) player.subtabs[layer][item] = Object.keys(layers[layer].microtabs[item])[0]; } } } function getStartGrid(layer) { let data = {}; if (! layers[layer].grid) return data if (layers[layer].grid.maxRows === undefined) layers[layer].grid.maxRows=layers[layer].grid.rows if (layers[layer].grid.maxCols === undefined) layers[layer].grid.maxCols=layers[layer].grid.cols for (let y = 1; y <= layers[layer].grid.maxRows; y++) { for (let x = 1; x <= layers[layer].grid.maxCols; x++) { data[100*y + x] = layers[layer].grid.getStartData(100*y + x) } } return data; } function fixData(defaultData, newData) { for (item in defaultData) { if (defaultData[item] == null) { if (newData[item] === undefined) newData[item] = null; } else if (Array.isArray(defaultData[item])) { if (newData[item] === undefined) newData[item] = defaultData[item]; else fixData(defaultData[item], newData[item]); } else if (defaultData[item] instanceof ExpantaNum) { // Convert to ExpantaNum if (newData[item] === undefined) newData[item] = defaultData[item]; else{ let newItemThing=new ExpantaNum(0) newItemThing.array = newData[item].array newItemThing.sign = newData[item].sign newItemThing.layer = newData[item].layer newData[item] = newItemThing } } else if ((!!defaultData[item]) && (typeof defaultData[item] === "object")) { if (newData[item] === undefined || (typeof defaultData[item] !== "object")) newData[item] = defaultData[item]; else fixData(defaultData[item], newData[item]); } else { if (newData[item] === undefined) newData[item] = defaultData[item]; } } } function load() { let get = localStorage.getItem(modInfo.id); if (get === null || get === undefined) { player = getStartPlayer(); options = getStartOptions(); } else { var a = LZString.decompressFromBase64(get.substr(216)); if(a=="null"){a=atob(get)} else if(a[0]!="{"){a = atob(get)} if(a=="null"){ player = getStartPlayer(); options = getStartOptions(); if (player.offlineProd) { if (player.offTime === undefined){ player.offTime = { remain: 0 } }; player.offTime.remain += (Date.now() - player.time) / 1000; } player.time = Date.now(); versionCheck(); changeTheme(); changeTreeQuality(); updateLayers(); setupModInfo(); setupTemp(); updateTemp(); updateTemp(); updateTabFormats(); loadVue(); return } if(a[0]!="{"){ player = getStartPlayer(); options = getStartOptions(); if (player.offlineProd) { if (player.offTime === undefined){ player.offTime = { remain: 0 } }; player.offTime.remain += (Date.now() - player.time) / 1000; } player.time = Date.now(); versionCheck(); changeTheme(); changeTreeQuality(); updateLayers(); setupModInfo(); setupTemp(); updateTemp(); updateTemp(); updateTabFormats(); loadVue(); return } a = JSON.parse(a); player = Object.assign(getStartPlayer(), a); fixSave(); loadOptions(); } if (player.offlineProd) { if (player.offTime === undefined){ player.offTime = { remain: 0 } }; player.offTime.remain += (Date.now() - player.time) / 1000; } player.time = Date.now(); versionCheck(); changeTheme(); changeTreeQuality(); updateLayers(); setupModInfo(); setupTemp(); updateTemp(); updateTemp(); updateTabFormats(); loadVue(); } function loadOptions() { let get2 = localStorage.getItem(modInfo.id+"_options"); if (get2) { options = Object.assign(getStartOptions(), JSON.parse(decodeURIComponent(escape(atob(get2))))); } else { options = getStartOptions() } } function setupModInfo() { modInfo.changelog = changelog; modInfo.winText = winText ? winText : `Congratulations! You have reached the end and beaten this game, but for now...`; } function exportSave() { let str = JSON.stringify(player); str = "eyJhdXRvc2F2ZSI6dHJ1ZSwibXNEaXNwbGF5IjoiYWx3YXlzIiwidGhlbWUiOm51bGwsImhxVHJlZSI6ZmFsc2UsIm9mZmxpbmVQcm9kIjp0cnVlLCJoaWRlQ2hhbGxlbmdlcyI6ZmFsc2UsInNob3dTdG9yeSI6dHJ1ZSwiZm9yY2VPbmVUYWIiOmZhbHNlLCJvbGRTdHlsZSI6ZmFsc2V9"+LZString.compressToBase64(str); const el = document.createElement("textarea"); el.value = str; document.body.appendChild(el); el.select(); el.setSelectionRange(0, 99999); document.execCommand("copy"); document.body.removeChild(el); } function importSave(imported = undefined, forced = false) { if (imported === undefined){ imported = prompt("Paste your save here") }; try { var a = LZString.decompressFromBase64(imported.substr(216)); if(a[0] != "{"){a = atob(imported)}; a = JSON.parse(a); tempPlr = Object.assign(getStartPlayer(), a); if (tempPlr.versionType != modInfo.id && !forced && !confirm("This save appears to be for a different mod! Are you sure you want to import?")){return}; player = tempPlr; player.versionType = modInfo.id; fixSave(); versionCheck(); save(); window.location.reload(); } catch (e) { return; } } function versionCheck() { let setVersion = true; if (player.versionType === undefined || player.version === undefined) { player.versionType = modInfo.id; player.version = 0; } if (setVersion) { if (player.versionType == modInfo.id && VERSION.num > player.version) { player.keepGoing = false; if (fixOldSave){ fixOldSave(player.version) }; } player.versionType = getStartPlayer().versionType; player.version = VERSION.num; player.beta = VERSION.beta; } } var saveInterval = setInterval(function () { if (options.autosave){save()}; }, 500);
29.491124
334
0.68449
8d4c199a49a8957e9c6b50f0a3bb88a8b02edf47
930
js
JavaScript
public/javascript/edit-dog.js
JenniferFadare/D.O.G.S.
bb64ccb0aa55ad4f7743507eeacccfe6a650092e
[ "MIT" ]
1
2021-01-18T19:18:43.000Z
2021-01-18T19:18:43.000Z
public/javascript/edit-dog.js
JenniferFadare/Team6_Project
bb64ccb0aa55ad4f7743507eeacccfe6a650092e
[ "MIT" ]
8
2021-01-18T02:12:49.000Z
2021-01-28T17:40:24.000Z
public/javascript/edit-dog.js
JenniferFadare/Team6_Project
bb64ccb0aa55ad4f7743507eeacccfe6a650092e
[ "MIT" ]
null
null
null
async function editDogFormHandler(event) { event.preventDefault(); const dog_id = document.querySelector("#edit-dog-id").value const name = document.querySelector("#edit-dog-name").value.trim(); const breed = document.querySelector("#edit-dog-breed").value.trim(); const temperament = document.querySelector("#edit-dog-temperament").value.trim(); console.log(dog_id, name, breed, temperament) if (name || breed || temperament) { const response = await fetch(`/api/dog/${dog_id}`, { method: "put", body: JSON.stringify({ name, breed, temperament }), headers: { "Content-Type": "application/json" }, }); if (response.ok) { console.log("success"); document.location.replace('/dashboard'); } else { alert(response.statusText); } } } document .querySelector(".edit-dog-form") .addEventListener("submit", editDogFormHandler);
28.181818
83
0.644086
8d4d4956a329777d1de2477fe1829ef808220caf
1,110
js
JavaScript
src/app.js
CoreyBurkhart/prioritizely-api-gateway
88665ab7ff4faafc15da7793d8b5a5771b334588
[ "MIT" ]
null
null
null
src/app.js
CoreyBurkhart/prioritizely-api-gateway
88665ab7ff4faafc15da7793d8b5a5771b334588
[ "MIT" ]
null
null
null
src/app.js
CoreyBurkhart/prioritizely-api-gateway
88665ab7ff4faafc15da7793d8b5a5771b334588
[ "MIT" ]
null
null
null
import express from 'express'; import mongoose from 'mongoose'; import authRouter from './routers/auth'; import adminRouter from './routers/admin'; import morganMiddleware from './middleware/morgan'; import bodyParserMiddleware from './middleware/bodyParser'; import cookieParserMiddleware from './middleware/cookieParser'; import defaultProxy from './middleware/defaultProxy'; import authMiddleware from './middleware/auth'; import errorMiddleware from './middleware/error'; require('./../config/config'); const app = express(); /* * mongoose */ mongoose.Promise = Promise; /* * non-error middleware. * TODO: implement Helmet security middleware. */ app.use(bodyParserMiddleware); app.use(morganMiddleware); app.use(cookieParserMiddleware); /* * use auth middleware on non "/auth" routes */ app.use(/\/api(?!\/auth)/, authMiddleware); /* * routers */ app.use('/api/auth', authRouter); app.use('/api/admin', adminRouter); /* * proxy */ app.use(/\/api\/(?!(admin|auth)).+/, defaultProxy); /* * error middleware (must be last call to app.use) */ app.use(errorMiddleware); export default app;
22.653061
63
0.720721
8d4dc714e29e0b007b2e494425582b9561e11a91
5,422
js
JavaScript
Loose/scripts/mod.js
NeonOcean/NOC.Main
76e17de1e93e2bf5b4331837da2e8eeee75d25ad
[ "CC-BY-4.0" ]
1
2021-06-27T21:18:24.000Z
2021-06-27T21:18:24.000Z
Loose/scripts/mod.js
NeonOcean/NOC.Main
76e17de1e93e2bf5b4331837da2e8eeee75d25ad
[ "CC-BY-4.0" ]
null
null
null
Loose/scripts/mod.js
NeonOcean/NOC.Main
76e17de1e93e2bf5b4331837da2e8eeee75d25ad
[ "CC-BY-4.0" ]
null
null
null
Mod_TabButtonInactiveClass = "Mod_Tab_Button"; Mod_TabButtonActiveClass = "Mod_Tab_Button_Active"; Mod_TabButtonIdentifierPrefix = "Mod_"; Mod_TabButtonIdentifierSuffix = "_Tab_Button"; Mod_TabIdentifierPrefix = "Mod_"; Mod_TabIdentifierSuffix = "_Tab"; Mod_TabNames = [ "Overview", "Gallery", "Files", "Requirements", "Issues", "Changes", "Development" ]; Mod_TabOpenedCallbacks = { "Files": Mod_OnFilesTabOpened }; Mod_DefaultTab = "Overview"; Mod_RequirementWarningDialogIdentifier = "Requirement_Warning_Dialog"; Mod_HasRequirementsAttribute = "mod_HasRequirements"; function Mod_OnPageLoad () { startTabName = null; startTabTarget = location.hash.toLowerCase(); if(startTabTarget.length != 0) { for(var tabNameIndex = 0; tabNameIndex < Mod_TabNames.length; tabNameIndex++) { if("#" + Mod_TabNames[tabNameIndex].toLowerCase() == startTabTarget) { startTabName = Mod_TabNames[tabNameIndex]; break; } } } if(startTabName == null) { startTabName = Mod_DefaultTab; } else { if(document.getElementById(Mod_TabIdentifierPrefix + startTabName + Mod_TabIdentifierSuffix) == null) { startTabName = Mod_DefaultTab; } } if(document.getElementById(Mod_TabIdentifierPrefix + startTabName + Mod_TabIdentifierSuffix) == null) { return } Mod_OpenTab(startTabName, false); } function Mod_EnabledTab (tabName) { tabButtonIdentifier = Mod_TabButtonIdentifierPrefix + tabName + Mod_TabButtonIdentifierSuffix; tabIdentifier = Mod_TabIdentifierPrefix + tabName + Mod_TabIdentifierSuffix; tab = document.getElementById(tabIdentifier); tabButton = document.getElementById(tabButtonIdentifier); if(tab != null && tabButton != null) { tab.style.display = null; tabButton.className = Mod_TabButtonActiveClass; } else { if(tab != null || tabButton != null) { console.warn("Tried to enable a tab named '" + tabName + "' but only the tab or tab button exists, not both or neither as expected."); } } } function Mod_DisableTab (tabName) { tabButtonIdentifier = Mod_TabButtonIdentifierPrefix + tabName + Mod_TabButtonIdentifierSuffix; tabIdentifier = Mod_TabIdentifierPrefix + tabName + Mod_TabIdentifierSuffix; tab = document.getElementById(tabIdentifier); tabButton = document.getElementById(tabButtonIdentifier); if(tab != null && tabButton != null) { tab.style.display = "none"; tabButton.className = Mod_TabButtonInactiveClass; } else { if(tab != null || tabButton != null) { console.warn("Tried to enable a tab named '" + tabName + "' but only the tab or tab button exists, not both or neither as expected."); } } } function Mod_OpenTab (targetTabName, changeHash) { Mod_EnabledTab(targetTabName); for(var tabNameIndex = 0; tabNameIndex < Mod_TabNames.length; tabNameIndex++) { if(Mod_TabNames[tabNameIndex] == targetTabName) { continue; } Mod_DisableTab(Mod_TabNames[tabNameIndex]); } if(changeHash) { location.hash = "#" + targetTabName.toLowerCase(); } tabOpenedCallback = Mod_TabOpenedCallbacks["Files"]; if(tabOpenedCallback != undefined) { tabOpenedCallback(); } } function Mod_OpenOverviewTab () { Mod_OpenTab("Overview", true); } function Mod_OpenGalleryTab () { Mod_OpenTab("Gallery", true); } function Mod_OpenFilesTab () { Mod_OpenTab("Files", true); } function Mod_OpenRequirementsTab () { Mod_OpenTab("Requirements", true); } function Mod_OpenIssuesTab () { Mod_OpenTab("Issues", true); } function Mod_OpenChangesTab () { Mod_OpenTab("Changes", true); } function Mod_OpenDevelopmentTab () { Mod_OpenTab("Development", true); } function Mod_OnFilesTabOpened () { Mod_ShowRequirementsWarning(); } function Mod_ModHasRequirements () { metaElements = document.getElementsByTagName("meta"); for(var metaElementIndex = 0; metaElementIndex < metaElements.length; metaElementIndex++) { if(metaElements[metaElementIndex].getAttribute("Name") == Mod_HasRequirementsAttribute) { hasRequirements = false; hasRequirementsString = metaElements[metaElementIndex].getAttribute("content"); hasRequirementsString = hasRequirementsString.toLowerCase(); if(hasRequirementsString == "true") { hasRequirements = true; } else if(hasRequirementsString != "false") { console.error("Dark page meta data value is not a boolean."); } return hasRequirements; } } return false; } function Mod_ShowRequirementsWarning (ignoreDisabled = false, ignoreNoRequirements = false) { if(!ignoreNoRequirements) { if(!Mod_ModHasRequirements) { return; } } if(!ignoreDisabled) { if(window.Mod_RequirementWarningDialogEnabled != undefined && !window.Mod_RequirementWarningDialogEnabled) { return; } } dialog = document.getElementById("Requirement_Warning_Dialog"); if(dialog) { dialog.style.display = null; } else { console.error("Couldn't find the requirement warning dialog dialog for in this document."); } } function Mod_HideRequirementsWarning () { dialog = document.getElementById("Requirement_Warning_Dialog"); if(dialog) { dialog.style.display = "none"; } else { console.error("Couldn't find the requirement warning dialog dialog for in this document."); } } function Mod_DisableRequirementsWarning () { window.Mod_RequirementWarningDialogEnabled = false; } function Mod_EnableRequirementsWarning () { window.Mod_RequirementWarningDialogEnabled = true; } window.addEventListener("load", Mod_OnPageLoad);
26.067308
137
0.741608
8d4ddd3c2669bd777871f4d4ba31982e43bef8a3
2,771
js
JavaScript
src/database/database.js
scriptkid23/purify
fc1021538b94dbcd1e3eb1e9286e9f622c6c75f6
[ "MIT" ]
1
2021-01-19T14:36:34.000Z
2021-01-19T14:36:34.000Z
src/database/database.js
scriptkid23/purify
fc1021538b94dbcd1e3eb1e9286e9f622c6c75f6
[ "MIT" ]
null
null
null
src/database/database.js
scriptkid23/purify
fc1021538b94dbcd1e3eb1e9286e9f622c6c75f6
[ "MIT" ]
1
2021-02-05T14:07:54.000Z
2021-02-05T14:07:54.000Z
import { reject } from 'lodash'; import Realm from 'realm'; export const SCHEMA = 'list'; export const LISTDB = { name: SCHEMA, primaryKey: 'id', properties: { id: 'int', temperature: {type: 'string', indexed: true}, done: {type: 'bool', default: false}, humidity: {type: 'string', indexed: true}, timestamp: {type: 'string', indexed: true}, }, }; const databaseOptions = { path: 'list.realm', schema: [LISTDB], schemaVersion: 0, }; export const insertObject = newTodoList => new Promise((resolve, reject) => { Realm.open(databaseOptions) .then(realm => { realm.write(() => { newTodoList.id=(realm.objects(SCHEMA).max('id')!=null)?realm.objects(SCHEMA).max('id')+1:1; // console.log((realm.objects(SCHEMA).max('id')!=null)?realm.objects(SCHEMA).max('id')+1:1) realm.create(SCHEMA, newTodoList); resolve(newTodoList); }); }) .catch(error => reject(error)); }); export const UpDateObJect = TodoList => new Promise((resolve, reject) => { Realm.open(databaseOptions) .then(realm => { realm.write(() => { let Update = realm.objectForPrimaryKey(SCHEMA, TodoList.id); Update.value = TodoList.value; resolve(); }); }) .catch(error => reject(error)); }); export const queryALLTodoList = () => new Promise((resolve, reject) => { Realm.open(databaseOptions) .then(realm => { let allList = realm.objects(SCHEMA); let newlist = allList.filtered('done=false').sorted('timestamp'); resolve(newlist); }) .catch(error => { reject(error); }); }); export const deleteTodoList = todoListID => new Promise((resolve, reject) => { Realm.open(databaseOptions) .then(realm => { realm.write(() => { let deleTodoList = realm.objectForPrimaryKey(SCHEMA, todoListID); realm.delete(deleTodoList); }); }) .catch(error => reject(error)); }); export const Deleteall = () => new Promise((resolve, reject) => { Realm.open(databaseOptions) .then(realm => { realm.write(() => { let AllList = realm.objects(SCHEMA); AllList.forEach(element => { element.done=true; }); resolve(); }); }) .catch(error => reject(error)); }); export const findMaxID=()=> new Promise((resolve,reject)=>{ Realm.open(databaseOptions) .then(realm=>{ realm.write(()=>{ let AllList = realm.objects(SCHEMA).sorted('id',true); var num=AllList[0].id; resolve(AllList[0]); }); }) .catch(error=>reject(error)); }); export default new Realm(databaseOptions);
27.71
101
0.566582
8d4eee785ded76467572158a1e6a6a38fb826343
1,136
js
JavaScript
models/users.js
adedrey/result-checker-api
28ad6d402ddb88d71ffee8a1e190c9c40fcbe59b
[ "MIT" ]
null
null
null
models/users.js
adedrey/result-checker-api
28ad6d402ddb88d71ffee8a1e190c9c40fcbe59b
[ "MIT" ]
null
null
null
models/users.js
adedrey/result-checker-api
28ad6d402ddb88d71ffee8a1e190c9c40fcbe59b
[ "MIT" ]
null
null
null
const mongoose = require('mongoose'); const uniqueValidator = require('mongoose-unique-validator'); const Schema = mongoose.Schema; const userSchema = new Schema({ name: { type: String, lowercase: true }, matric_no: { type: String, required: true }, jamb_no: { type: String, required: true }, rank: { type: String, required: true }, department: { type: String, required: true }, moe:{ type: String, enum: ['UME', 'DE'], required: true }, yoe:{ type: String, required: true }, email: { type: String, lowercase: true }, hash: { type: String }, salt: { type: String }, image : { type : String, }, created_on : { type : Date, default: Date.now() }, is_active : { type : Boolean, default: true }, resetToken: String, resetTokenExpiration: Date }); userSchema.plugin(uniqueValidator); module.exports = mongoose.model('User', userSchema);
18.933333
61
0.507042
8d4f59a37ff444c0dd7e48ddd4b2c9484e3075ae
481
js
JavaScript
src/util/readdirRecursively.js
tu4mo/teg
ac7482ee6a1243b4037ecc7e3e9a14fbf75fa79e
[ "ISC" ]
null
null
null
src/util/readdirRecursively.js
tu4mo/teg
ac7482ee6a1243b4037ecc7e3e9a14fbf75fa79e
[ "ISC" ]
null
null
null
src/util/readdirRecursively.js
tu4mo/teg
ac7482ee6a1243b4037ecc7e3e9a14fbf75fa79e
[ "ISC" ]
null
null
null
const fs = require('fs') const path = require('path') const readdirRecursively = (dir, files = []) => { try { fs.readdirSync(dir).forEach(file => { const fullPath = path.join(dir, file) files.push(fullPath) if (fs.lstatSync(fullPath).isDirectory()) { return readdirRecursively(fullPath, files) } }) return files } catch (err) { throw new Error(`Directory not found in '${err.path}'`) } } module.exports = readdirRecursively
22.904762
59
0.623701
8d4fb74ab08f0cb885d12023de3558f40882fe81
582
js
JavaScript
drop.js
fredj/advanon-graph
dcac1b2a41875f3158d01d73280c565664b7fc52
[ "WTFPL" ]
null
null
null
drop.js
fredj/advanon-graph
dcac1b2a41875f3158d01d73280c565664b7fc52
[ "WTFPL" ]
null
null
null
drop.js
fredj/advanon-graph
dcac1b2a41875f3158d01d73280c565664b7fc52
[ "WTFPL" ]
null
null
null
var dropzone = document.querySelector('#instructions'); var cancel = function(event) { event.preventDefault(); }; dropzone.addEventListener('dragover', cancel, false); dropzone.addEventListener('dragenter', cancel, false); dropzone.addEventListener('drop', function(event) { var reader = new FileReader(); event.preventDefault(); var files = event.dataTransfer.files; console.assert(files.length === 1); reader.onload = function() { plot(reader.result); document.querySelector('body').classList.add('has-data'); }; reader.readAsText(files[0]); }, false);
27.714286
61
0.714777
8d50044fb3e9d4e71e9853b7cf3bd79fd5d670d9
367
js
JavaScript
the-persimmon-boutique-api/the-persimmon-boutique-client/src/components/reviews/Review.js
alpbourne/The-Persimmon-Boutique
c306581d9d6d7f49cbdd8d8dd6bbf65c58ee5d2b
[ "MIT" ]
null
null
null
the-persimmon-boutique-api/the-persimmon-boutique-client/src/components/reviews/Review.js
alpbourne/The-Persimmon-Boutique
c306581d9d6d7f49cbdd8d8dd6bbf65c58ee5d2b
[ "MIT" ]
null
null
null
the-persimmon-boutique-api/the-persimmon-boutique-client/src/components/reviews/Review.js
alpbourne/The-Persimmon-Boutique
c306581d9d6d7f49cbdd8d8dd6bbf65c58ee5d2b
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; class Review extends Component { render() { const { review, deleteReview } = this.props return ( <div> <p> <b>{review.author}:</b> {review.body} <button onClick={() => deleteReview(review)}>Delete</button> </p> </div> ); } }; export default Review;
19.315789
70
0.52861
8d501199d2c1cb186dcbdce947a6f2f2697342c7
415
js
JavaScript
server/models/User.js
developer-delta/halogen
27ab95dae9235f9181e0ee1c5ccad49617014634
[ "MIT" ]
5
2021-01-28T16:58:15.000Z
2021-08-03T15:42:57.000Z
server/models/User.js
developer-delta/halogen
27ab95dae9235f9181e0ee1c5ccad49617014634
[ "MIT" ]
146
2021-01-28T15:43:10.000Z
2022-01-06T22:30:06.000Z
server/models/User.js
developer-delta/halogen
27ab95dae9235f9181e0ee1c5ccad49617014634
[ "MIT" ]
12
2021-01-30T17:06:44.000Z
2022-02-12T17:28:20.000Z
const mongoose = require("mongoose"); // Schema defines the structure of our data so we can save users to the database in a uniform format const user = new mongoose.Schema({ username: String, password: String, palettes: [ { outerGradientColor: String, innerGradientColor: String, ringColor: String, ringName: String, }, ], }); module.exports = mongoose.model("User", user);
24.411765
100
0.674699
8d50903709884ce9e02940cd49081d5f7b6d971f
171
js
JavaScript
test/models/recursive/model2.js
hortopan/mongoose.autoload
09eae48585b7518418ec58642e9a4d58456cfe2f
[ "MIT" ]
1
2015-11-20T02:38:28.000Z
2015-11-20T02:38:28.000Z
test/models/recursive/model2.js
hortopan/mongoose.autoload
09eae48585b7518418ec58642e9a4d58456cfe2f
[ "MIT" ]
1
2020-08-17T11:55:59.000Z
2020-08-17T11:55:59.000Z
test/models/recursive/model2.js
hortopan/mongoose.autoload
09eae48585b7518418ec58642e9a4d58456cfe2f
[ "MIT" ]
1
2015-06-25T09:06:49.000Z
2015-06-25T09:06:49.000Z
module.exports = function(mongoose){ let schema = new mongoose.Schema({ name: String, }); schema.methods.test = function(){ return 'model2'; } return schema; }
14.25
36
0.666667
8d51142723aca485a91727b1cda5e1d832defdf9
39,249
js
JavaScript
third_party/WebKit/LayoutTests/http/tests/inspector/inspector-test.js
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
third_party/WebKit/LayoutTests/http/tests/inspector/inspector-test.js
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
third_party/WebKit/LayoutTests/http/tests/inspector/inspector-test.js
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
if (window.GCController) GCController.collectAll(); var initialize_InspectorTest = function() { var results = []; function consoleOutputHook(messageType) { InspectorTest.addResult(messageType + ": " + Array.prototype.slice.call(arguments, 1)); } window._originalConsoleLog = console.log.bind(console); console.log = consoleOutputHook.bind(InspectorTest, "log"); console.error = consoleOutputHook.bind(InspectorTest, "error"); console.info = consoleOutputHook.bind(InspectorTest, "info"); console.assert = function(condition, object) { if (condition) return; var message = "Assertion failed: " + (typeof object !== "undefined" ? object : ""); InspectorTest.addResult(new Error(message).stack); } InspectorTest.startDumpingProtocolMessages = function() { Protocol.InspectorBackend.Connection.prototype._dumpProtocolMessage = testRunner.logToStderr.bind(testRunner); Protocol.InspectorBackend.Options.dumpInspectorProtocolMessages = 1; } InspectorTest.completeTest = function() { InspectorTest.RuntimeAgent.evaluate("completeTest(\"" + escape(JSON.stringify(results)) + "\")", "test"); } InspectorTest.flushResults = function() { InspectorTest.RuntimeAgent.evaluate("flushResults(\"" + escape(JSON.stringify(results)) + "\")", "test"); results = []; } InspectorTest.evaluateInPage = function(code, callback) { callback = InspectorTest.safeWrap(callback); function mycallback(error, result, exceptionDetails) { if (!error) callback(InspectorTest.runtimeModel.createRemoteObject(result), exceptionDetails); } InspectorTest.RuntimeAgent.evaluate(code, "console", false, mycallback); } InspectorTest.evaluateInPagePromise = function(code) { return new Promise(succ => InspectorTest.evaluateInPage(code, succ)); } InspectorTest.evaluateInPageAsync = function(code) { var callback; var promise = new Promise((fulfill) => { callback = fulfill }); InspectorTest.RuntimeAgent.evaluate(code, "console", /* includeCommandLineAPI */ false, /* doNotPauseOnExceptionsAndMuteConsole */ undefined, /* contextId */ undefined, /* returnByValue */ undefined, /* generatePreview */ undefined, /* userGesture */ undefined, /* awaitPromise */ true, mycallback); function mycallback(error, result, exceptionDetails) { if (!error && !exceptionDetails) { callback(InspectorTest.runtimeModel.createRemoteObject(result)); } else { if (error) InspectorTest.addResult("Error: " + error); else InspectorTest.addResult("Error: " + (exceptionDetails ? exceptionDetails.text : " exception while evaluation in page.")); InspectorTest.completeTest(); } } return promise; } InspectorTest.callFunctionInPageAsync = function(name, args) { args = args || []; return InspectorTest.evaluateInPageAsync(name + "(" + args.map(JSON.stringify).join(",") + ")"); } InspectorTest.evaluateInPageWithTimeout = function(code) { // FIXME: we need a better way of waiting for chromium events to happen InspectorTest.evaluateInPage("setTimeout(unescape('" + escape(code) + "'), 1)"); } InspectorTest.evaluateFunctionInOverlay = function(func, callback) { var expression = "testRunner.evaluateInWebInspectorOverlay(\"(\" + " + func + " + \")()\")"; var mainContext = InspectorTest.runtimeModel.executionContexts()[0]; mainContext.evaluate(expression, "", false, false, true, false, false, wrapCallback); function wrapCallback(result, exceptionDetails) { callback(result.value) } } InspectorTest.check = function(passCondition, failureText) { if (!passCondition) InspectorTest.addResult("FAIL: " + failureText); } InspectorTest.addResult = function(text) { results.push(String(text)); } InspectorTest.addResults = function(textArray) { if (!textArray) return; for (var i = 0, size = textArray.length; i < size; ++i) InspectorTest.addResult(textArray[i]); } window.onerror = function (message, filename, lineno, colno, error) { InspectorTest.addResult("Uncaught exception in inspector front-end: " + message + " [" + error.stack + "]"); InspectorTest.completeTest(); } InspectorTest.formatters = {}; InspectorTest.formatters.formatAsTypeName = function(value) { return "<" + typeof value + ">"; } InspectorTest.formatters.formatAsRecentTime = function(value) { if (typeof value !== "object" || !(value instanceof Date)) return InspectorTest.formatAsTypeName(value); var delta = Date.now() - value; return 0 <= delta && delta < 30 * 60 * 1000 ? "<plausible>" : value; } InspectorTest.formatters.formatAsURL = function(value) { if (!value) return value; var lastIndex = value.lastIndexOf("inspector/"); if (lastIndex < 0) return value; return ".../" + value.substr(lastIndex); } InspectorTest.formatters.formatAsDescription = function(value) { if (!value) return value; return "\"" + value.replace(/^function [gs]et /, "function ") + "\""; } InspectorTest.addObject = function(object, customFormatters, prefix, firstLinePrefix) { prefix = prefix || ""; firstLinePrefix = firstLinePrefix || prefix; InspectorTest.addResult(firstLinePrefix + "{"); var propertyNames = Object.keys(object); propertyNames.sort(); for (var i = 0; i < propertyNames.length; ++i) { var prop = propertyNames[i]; if (!object.hasOwnProperty(prop)) continue; var prefixWithName = " " + prefix + prop + " : "; var propValue = object[prop]; if (customFormatters && customFormatters[prop]) { var formatterName = customFormatters[prop]; if (formatterName !== "skip") { var formatter = InspectorTest.formatters[formatterName]; InspectorTest.addResult(prefixWithName + formatter(propValue)); } } else InspectorTest.dump(propValue, customFormatters, " " + prefix, prefixWithName); } InspectorTest.addResult(prefix + "}"); } InspectorTest.addArray = function(array, customFormatters, prefix, firstLinePrefix) { prefix = prefix || ""; firstLinePrefix = firstLinePrefix || prefix; InspectorTest.addResult(firstLinePrefix + "["); for (var i = 0; i < array.length; ++i) InspectorTest.dump(array[i], customFormatters, prefix + " "); InspectorTest.addResult(prefix + "]"); } InspectorTest.dumpDeepInnerHTML = function(element) { function innerHTML(prefix, element) { var openTag = []; if (element.nodeType === Node.TEXT_NODE) { if (!element.parentElement || element.parentElement.nodeName !== "STYLE") InspectorTest.addResult(element.nodeValue); return; } openTag.push("<" + element.nodeName); var attrs = element.attributes; for (var i = 0; attrs && i < attrs.length; ++i) { openTag.push(attrs[i].name + "=" + attrs[i].value); } openTag.push(">"); InspectorTest.addResult(prefix + openTag.join(" ")); for (var child = element.firstChild; child; child = child.nextSibling) innerHTML(prefix + " ", child); if (element.shadowRoot) innerHTML(prefix + " ", element.shadowRoot); InspectorTest.addResult(prefix + "</" + element.nodeName + ">"); } innerHTML("", element) } InspectorTest.dump = function(value, customFormatters, prefix, prefixWithName) { prefixWithName = prefixWithName || prefix; if (prefixWithName && prefixWithName.length > 80) { InspectorTest.addResult(prefixWithName + "was skipped due to prefix length limit"); return; } if (value === null) InspectorTest.addResult(prefixWithName + "null"); else if (value && value.constructor && value.constructor.name === "Array") InspectorTest.addArray(value, customFormatters, prefix, prefixWithName); else if (typeof value === "object") InspectorTest.addObject(value, customFormatters, prefix, prefixWithName); else if (typeof value === "string") InspectorTest.addResult(prefixWithName + "\"" + value + "\""); else InspectorTest.addResult(prefixWithName + value); } InspectorTest.dumpDataGrid = function(dataGrid) { InspectorTest.addResult(InspectorTest.dumpDataGridIntoString(dataGrid)); } InspectorTest.dumpDataGridIntoString = function(dataGrid) { var tableElement = dataGrid.element; var textRows = []; var textWidths = []; var rows = tableElement.getElementsByTagName("tr"); for (var i = 0, row; row = rows[i]; ++i) { if (!row.offsetHeight || !row.textContent) continue; var textCols = []; var cols = row.getElementsByTagName("td"); for (var j = 0, col; col = cols[j]; ++j) { if (!col.offsetHeight) continue; var index = textCols.length; var content = col.textContent || (col.firstChild && col.firstChild.title) || ""; var text = padding(col) + content; textWidths[index] = Math.max(textWidths[index] || 0, text.length); textCols[index] = text; } if (textCols.length) textRows.push(textCols); } function padding(target) { var cell = target.enclosingNodeOrSelfWithNodeName("td"); if (!cell.classList.contains("disclosure")) return ""; var node = dataGrid.dataGridNodeFromNode(target); var spaces = (node ? node.depth : 0) * 2; return Array(spaces + 1).join(" "); } function alignText(text, width) { var spaces = width - text.length; return text + Array(spaces + 1).join(" ");; } var output = []; for (var i = 0; i < textRows.length; ++i) { var line = ""; for (var j = 0; j < textRows[i].length; ++j) { if (j) line += " | "; line += alignText(textRows[i][j], textWidths[j]); } line += "|"; output.push(line); } return output.join("\n"); } InspectorTest.dumpObjectPropertyTreeElement = function(treeElement) { var expandedSubstring = treeElement.expanded ? "[expanded]" : "[collapsed]"; InspectorTest.addResult(expandedSubstring + " " + treeElement.listItemElement.deepTextContent()); for (var i = 0; i < treeElement.childCount(); ++i) { var property = treeElement.childAt(i).property; var key = property.name; var value = property.value._description; InspectorTest.addResult(" " + key + ": " + value); } } InspectorTest.expandAndDumpEventListeners = function(eventListenersView, callback, force) { function listenersArrived() { var listenerTypes = eventListenersView._treeOutline.rootElement().children(); for (var i = 0; i < listenerTypes.length; ++i) { listenerTypes[i].expand(); var listenerItems = listenerTypes[i].children(); for (var j = 0; j < listenerItems.length; ++j) listenerItems[j].expand(); } InspectorTest.deprecatedRunAfterPendingDispatches(objectsExpanded); } function objectsExpanded() { var listenerTypes = eventListenersView._treeOutline.rootElement().children(); for (var i = 0; i < listenerTypes.length; ++i) { if (!listenerTypes[i].children().length) continue; var eventType = listenerTypes[i]._title; InspectorTest.addResult(""); InspectorTest.addResult("======== " + eventType + " ========"); var listenerItems = listenerTypes[i].children(); for (var j = 0; j < listenerItems.length; ++j) { InspectorTest.addResult("== " + listenerItems[j].eventListener().listenerType()); InspectorTest.dumpObjectPropertyTreeElement(listenerItems[j]); } } callback(); } if (force) listenersArrived(); else InspectorTest.addSniffer(Components.EventListenersView.prototype, "_eventListenersArrivedForTest", listenersArrived); } InspectorTest.dumpNavigatorView = function(navigatorView, dumpIcons) { dumpNavigatorTreeOutline(navigatorView._scriptsTree); function dumpNavigatorTreeElement(prefix, treeElement) { var titleText = ''; if (treeElement._leadingIconsElement && dumpIcons) { var icons = treeElement._leadingIconsElement.querySelectorAll('[is=ui-icon]'); icons = Array.prototype.slice.call(icons); var iconTypes = icons.map(icon => icon._iconType); if (iconTypes.length) titleText = titleText + "[" + iconTypes.join(", ") + "] "; } titleText += treeElement.title; if (treeElement._nodeType === Sources.NavigatorView.Types.FileSystem || treeElement._nodeType === Sources.NavigatorView.Types.FileSystemFolder) { var hasMappedFiles = treeElement.listItemElement.classList.contains("has-mapped-files"); if (!hasMappedFiles) titleText += " [dimmed]"; } InspectorTest.addResult(prefix + titleText); treeElement.expand(); var children = treeElement.children(); for (var i = 0; i < children.length; ++i) dumpNavigatorTreeElement(prefix + " ", children[i]); } function dumpNavigatorTreeOutline(treeOutline) { var children = treeOutline.rootElement().children(); for (var i = 0; i < children.length; ++i) dumpNavigatorTreeElement("", children[i]); } } InspectorTest.dumpNavigatorViewInAllModes = function(view) { ["frame", "frame/domain", "frame/domain/folder", "domain", "domain/folder"].forEach(InspectorTest.dumpNavigatorViewInMode.bind(InspectorTest, view)); } InspectorTest.dumpNavigatorViewInMode = function(view, mode) { InspectorTest.addResult(view instanceof Sources.SourcesNavigatorView ? "Sources:" : "Content Scripts:"); view._groupByFrame = mode.includes("frame"); view._groupByDomain = mode.includes("domain"); view._groupByFolder = mode.includes("folder"); view._resetForTest(); InspectorTest.addResult("-------- Setting mode: [" + mode + "]"); InspectorTest.dumpNavigatorView(view); } InspectorTest.waitForUISourceCode = function(callback, url, projectType) { function matches(uiSourceCode) { if (projectType && uiSourceCode.project().type() !== projectType) return false; if (!projectType && uiSourceCode.project().type() === Workspace.projectTypes.Service) return false; if (url && !uiSourceCode.url().endsWith(url)) return false; return true; } for (var uiSourceCode of Workspace.workspace.uiSourceCodes()) { if (url && matches(uiSourceCode)) { callback(uiSourceCode); return; } } Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded); function uiSourceCodeAdded(event) { if (!matches(event.data)) return; Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded); callback(event.data); } } InspectorTest.waitForUISourceCodeRemoved = function(callback) { Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, uiSourceCodeRemoved); function uiSourceCodeRemoved(event) { Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeRemoved, uiSourceCodeRemoved); callback(event.data); } } InspectorTest.createMockTarget = function(name, capabilities) { return SDK.targetManager.createTarget(name, capabilities || SDK.Target.Capability.AllForTests, params => new SDK.StubConnection(params), null); } InspectorTest.assertGreaterOrEqual = function(a, b, message) { if (a < b) InspectorTest.addResult("FAILED: " + (message ? message + ": " : "") + a + " < " + b); } InspectorTest.navigate = function(url, callback) { InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback); InspectorTest.evaluateInPage("window.location.replace('" + url + "')"); } InspectorTest.hardReloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor) { InspectorTest._innerReloadPage(true, callback, scriptToEvaluateOnLoad, scriptPreprocessor); } InspectorTest.reloadPage = function(callback, scriptToEvaluateOnLoad, scriptPreprocessor) { InspectorTest._innerReloadPage(false, callback, scriptToEvaluateOnLoad, scriptPreprocessor); } InspectorTest.reloadPagePromise = function(scriptToEvaluateOnLoad, scriptPreprocessor) { var fulfill; var promise = new Promise(x => fulfill = x); InspectorTest.reloadPage(fulfill, scriptToEvaluateOnLoad, scriptPreprocessor); return promise; } InspectorTest._innerReloadPage = function(hardReload, callback, scriptToEvaluateOnLoad, scriptPreprocessor) { InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(callback); if (UI.panels.network) UI.panels.network._networkLogView.reset(); InspectorTest.PageAgent.reload(hardReload, scriptToEvaluateOnLoad, scriptPreprocessor); } InspectorTest.pageLoaded = function() { InspectorTest.addResult("Page reloaded."); if (InspectorTest._pageLoadedCallback) { var callback = InspectorTest._pageLoadedCallback; delete InspectorTest._pageLoadedCallback; callback(); } } InspectorTest.runWhenPageLoads = function(callback) { var oldCallback = InspectorTest._pageLoadedCallback; function chainedCallback() { if (oldCallback) oldCallback(); callback(); } InspectorTest._pageLoadedCallback = InspectorTest.safeWrap(chainedCallback); } InspectorTest.deprecatedRunAfterPendingDispatches = function(callback) { var barrier = new CallbackBarrier(); var targets = SDK.targetManager.targets(); for (var i = 0; i < targets.length; ++i) targets[i]._deprecatedRunAfterPendingDispatches(barrier.createCallback()); barrier.callWhenDone(InspectorTest.safeWrap(callback)); } InspectorTest.createKeyEvent = function(key, ctrlKey, altKey, shiftKey, metaKey) { return new KeyboardEvent("keydown", {key: key, bubbles: true, cancelable: true, ctrlKey: ctrlKey, altKey: altKey, shiftKey: shiftKey, metaKey: metaKey}); } InspectorTest.runTestSuite = function(testSuite) { var testSuiteTests = testSuite.slice(); function runner() { if (!testSuiteTests.length) { InspectorTest.completeTest(); return; } var nextTest = testSuiteTests.shift(); InspectorTest.addResult(""); InspectorTest.addResult("Running: " + /function\s([^(]*)/.exec(nextTest)[1]); InspectorTest.safeWrap(nextTest)(runner); } runner(); } InspectorTest.assertEquals = function(expected, found, message) { if (expected === found) return; var error; if (message) error = "Failure (" + message + "):"; else error = "Failure:"; throw new Error(error + " expected <" + expected + "> found <" + found + ">"); } InspectorTest.assertTrue = function(found, message) { InspectorTest.assertEquals(true, !!found, message); } InspectorTest.wrapListener = function(func) { function wrapper() { var wrapArgs = arguments; var wrapThis = this; // Give a chance to other listeners. setTimeout(apply, 0); function apply() { func.apply(wrapThis, wrapArgs); } } return wrapper; } InspectorTest.safeWrap = function(func, onexception) { function result() { if (!func) return; var wrapThis = this; try { return func.apply(wrapThis, arguments); } catch(e) { InspectorTest.addResult("Exception while running: " + func + "\n" + (e.stack || e)); if (onexception) InspectorTest.safeWrap(onexception)(); else InspectorTest.completeTest(); } } return result; } InspectorTest.addSniffer = function(receiver, methodName, override, opt_sticky) { override = InspectorTest.safeWrap(override); var original = receiver[methodName]; if (typeof original !== "function") throw ("Cannot find method to override: " + methodName); receiver[methodName] = function(var_args) { try { var result = original.apply(this, arguments); } finally { if (!opt_sticky) receiver[methodName] = original; } // In case of exception the override won't be called. try { Array.prototype.push.call(arguments, result); override.apply(this, arguments); } catch (e) { throw ("Exception in overriden method '" + methodName + "': " + e); } return result; }; } InspectorTest.addSnifferPromise = function(receiver, methodName) { return new Promise(function (resolve, reject) { var original = receiver[methodName]; if (typeof original !== "function") { reject("Cannot find method to override: " + methodName); return; } receiver[methodName] = function(var_args) { try { var result = original.apply(this, arguments); } finally { receiver[methodName] = original; } // In case of exception the override won't be called. try { Array.prototype.push.call(arguments, result); resolve.apply(this, arguments); } catch (e) { reject("Exception in overriden method '" + methodName + "': " + e); } return result; }; }); } InspectorTest.addConsoleSniffer = function(override, opt_sticky) { InspectorTest.addSniffer(SDK.ConsoleModel.prototype, "addMessage", override, opt_sticky); } InspectorTest.override = function(receiver, methodName, override, opt_sticky) { override = InspectorTest.safeWrap(override); var original = receiver[methodName]; if (typeof original !== "function") throw ("Cannot find method to override: " + methodName); receiver[methodName] = function(var_args) { try { try { var result = override.apply(this, arguments); } catch (e) { throw ("Exception in overriden method '" + methodName + "': " + e); } } finally { if (!opt_sticky) receiver[methodName] = original; } return result; }; return original; } InspectorTest.textContentWithLineBreaks = function(node) { function padding(currentNode) { var result = 0; while (currentNode && currentNode !== node) { if (currentNode.nodeName === "OL" && !(currentNode.classList && currentNode.classList.contains("object-properties-section"))) ++result; currentNode = currentNode.parentNode; } return Array(result * 4 + 1).join(" "); } var buffer = ""; var currentNode = node; var ignoreFirst = false; while (currentNode = currentNode.traverseNextNode(node)) { if (currentNode.nodeType === Node.TEXT_NODE) { buffer += currentNode.nodeValue; } else if (currentNode.nodeName === "LI" || currentNode.nodeName === "TR") { if (!ignoreFirst) buffer += "\n" + padding(currentNode); else ignoreFirst = false; } else if (currentNode.nodeName === "STYLE") { currentNode = currentNode.traverseNextNode(node); continue; } else if (currentNode.classList && currentNode.classList.contains("object-properties-section")) { ignoreFirst = true; } } return buffer; } InspectorTest.textContentWithoutStyles = function(node) { var buffer = ""; var currentNode = node; while (currentNode = currentNode.traverseNextNode(node)) { if (currentNode.nodeType === Node.TEXT_NODE) buffer += currentNode.nodeValue; else if (currentNode.nodeName === "STYLE") currentNode = currentNode.traverseNextNode(node); } return buffer; } InspectorTest.clearSpecificInfoFromStackFrames = function(text) { var buffer = text.replace(/\(file:\/\/\/(?:[^)]+\)|[\w\/:-]+)/g, "(...)"); buffer = buffer.replace(/\(<anonymous>:[^)]+\)/g, "(...)"); buffer = buffer.replace(/VM\d+/g, "VM"); return buffer.replace(/\s*at[^()]+\(native\)/g, ""); } InspectorTest.hideInspectorView = function() { UI.inspectorView.element.setAttribute("style", "display:none !important"); } InspectorTest.mainFrame = function() { return SDK.ResourceTreeModel.fromTarget(InspectorTest.mainTarget).mainFrame; } InspectorTest.StringOutputStream = function(callback) { this._callback = callback; this._buffer = ""; }; InspectorTest.StringOutputStream.prototype = { open: function(fileName, callback) { callback(true); }, write: function(chunk, callback) { this._buffer += chunk; if (callback) callback(this); }, close: function() { this._callback(this._buffer); } }; InspectorTest.MockSetting = function(value) { this._value = value; }; InspectorTest.MockSetting.prototype = { get: function() { return this._value; }, set: function(value) { this._value = value; } }; /** * @constructor * @param {!string} dirPath * @param {!string} name * @param {!function(?Bindings.TempFile)} callback */ InspectorTest.TempFileMock = function(dirPath, name) { this._chunks = []; this._name = name; } InspectorTest.TempFileMock.prototype = { /** * @param {!Array.<string>} chunks * @param {!function(boolean)} callback */ write: function(chunks, callback) { var size = 0; for (var i = 0; i < chunks.length; ++i) size += chunks[i].length; this._chunks.push.apply(this._chunks, chunks); setTimeout(callback.bind(this, size), 1); }, finishWriting: function() { }, /** * @param {function(?string)} callback */ read: function(callback) { this.readRange(undefined, undefined, callback); }, /** * @param {number|undefined} startOffset * @param {number|undefined} endOffset * @param {function(?string)} callback */ readRange: function(startOffset, endOffset, callback) { var blob = new Blob(this._chunks); blob = blob.slice(startOffset || 0, endOffset || blob.size); reader = new FileReader(); var self = this; reader.onloadend = function() { callback(reader.result); } reader.readAsText(blob); }, /** * @param {!Common.OutputStream} outputStream * @param {!Bindings.OutputStreamDelegate} delegate */ copyToOutputStream: function(outputStream, delegate) { var name = this._name; var text = this._chunks.join(""); var chunkedReaderMock = { loadedSize: function() { return text.length; }, fileSize: function() { return text.length; }, fileName: function() { return name; }, cancel: function() { } } delegate.onTransferStarted(chunkedReaderMock); outputStream.write(text); delegate.onChunkTransferred(chunkedReaderMock); outputStream.close(); delegate.onTransferFinished(chunkedReaderMock); }, remove: function() { } } InspectorTest.TempFileMock.create = function(dirPath, name) { var tempFile = new InspectorTest.TempFileMock(dirPath, name); return Promise.resolve(tempFile); } InspectorTest.dumpLoadedModules = function(next) { function moduleSorter(left, right) { return String.naturalOrderComparator(left._descriptor.name, right._descriptor.name); } InspectorTest.addResult("Loaded modules:"); var modules = self.runtime._modules; modules.sort(moduleSorter); for (var i = 0; i < modules.length; ++i) { if (modules[i]._loadedForTest) InspectorTest.addResult(" " + modules[i]._descriptor.name); } if (next) next(); } InspectorTest.TimeoutMock = function() { this._timeoutId = 0; this._timeoutIdToProcess = {}; this._timeoutIdToMillis = {}; this.setTimeout = this.setTimeout.bind(this); this.clearTimeout = this.clearTimeout.bind(this); } InspectorTest.TimeoutMock.prototype = { setTimeout: function(operation, timeout) { this._timeoutIdToProcess[++this._timeoutId] = operation; this._timeoutIdToMillis[this._timeoutId] = timeout; return this._timeoutId; }, clearTimeout: function(timeoutId) { delete this._timeoutIdToProcess[timeoutId]; delete this._timeoutIdToMillis[timeoutId]; }, activeTimersTimeouts: function() { return Object.values(this._timeoutIdToMillis); }, fireAllTimers: function() { for (var timeoutId in this._timeoutIdToProcess) this._timeoutIdToProcess[timeoutId].call(window); this._timeoutIdToProcess = {}; this._timeoutIdToMillis = {}; } } SDK.targetManager.observeTargets({ targetAdded: function(target) { if (InspectorTest.CSSAgent) return; InspectorTest.CSSAgent = target.cssAgent(); InspectorTest.DeviceOrientationAgent = target.deviceOrientationAgent(); InspectorTest.DOMAgent = target.domAgent(); InspectorTest.DOMDebuggerAgent = target.domdebuggerAgent(); InspectorTest.DebuggerAgent = target.debuggerAgent(); InspectorTest.EmulationAgent = target.emulationAgent(); InspectorTest.HeapProfilerAgent = target.heapProfilerAgent(); InspectorTest.InspectorAgent = target.inspectorAgent(); InspectorTest.NetworkAgent = target.networkAgent(); InspectorTest.PageAgent = target.pageAgent(); InspectorTest.ProfilerAgent = target.profilerAgent(); InspectorTest.RuntimeAgent = target.runtimeAgent(); InspectorTest.TargetAgent = target.targetAgent(); InspectorTest.consoleModel = target.consoleModel; InspectorTest.networkManager = SDK.NetworkManager.fromTarget(target); InspectorTest.securityOriginManager = SDK.SecurityOriginManager.fromTarget(target); InspectorTest.resourceTreeModel = SDK.ResourceTreeModel.fromTarget(target); InspectorTest.networkLog = SDK.NetworkLog.fromTarget(target); InspectorTest.debuggerModel = SDK.DebuggerModel.fromTarget(target); InspectorTest.runtimeModel = target.runtimeModel; InspectorTest.domModel = SDK.DOMModel.fromTarget(target); InspectorTest.cssModel = SDK.CSSModel.fromTarget(target); InspectorTest.powerProfiler = target.powerProfiler; InspectorTest.cpuProfilerModel = target.cpuProfilerModel; InspectorTest.heapProfilerModel = target.heapProfilerModel; InspectorTest.animationModel = target.animationModel; InspectorTest.serviceWorkerCacheModel = target.serviceWorkerCacheModel; InspectorTest.serviceWorkerManager = target.serviceWorkerManager; InspectorTest.tracingManager = target.tracingManager; InspectorTest.mainTarget = target; }, targetRemoved: function(target) { } }); InspectorTest._panelsToPreload = []; InspectorTest.preloadPanel = function(panelName) { InspectorTest._panelsToPreload.push(panelName); } InspectorTest._modulesToPreload = []; InspectorTest.preloadModule = function(moduleName) { InspectorTest._modulesToPreload.push(moduleName); } InspectorTest.isDedicatedWorker = function(target) { return target && !target.hasBrowserCapability() && target.hasJSCapability() && !target.hasNetworkCapability() && !target.hasTargetCapability(); } InspectorTest.isServiceWorker = function(target) { return target && !target.hasBrowserCapability() && !target.hasJSCapability() && target.hasNetworkCapability() && target.hasTargetCapability(); } InspectorTest.describeTargetType = function(target) { if (InspectorTest.isDedicatedWorker(target)) return "worker"; if (InspectorTest.isServiceWorker(target)) return "service-worker"; if (!target.parentTarget()) return "page"; return "frame"; } }; // initialize_InspectorTest var initializeCallId = 0; var runTestCallId = 1; var evalCallbackCallId = 2; var frontendReopeningCount = 0; function reopenFrontend() { closeFrontend(openFrontendAndIncrement); } function closeFrontend(callback) { // Do this asynchronously to allow InspectorBackendDispatcher to send response // back to the frontend before it's destroyed. // FIXME: we need a better way of waiting for chromium events to happen setTimeout(function() { testRunner.closeWebInspector(); callback(); }, 1); } function openFrontendAndIncrement() { frontendReopeningCount++; testRunner.showWebInspector(JSON.stringify({testPath: '"' + location.href + '"'}).replace(/\"/g,"%22")); setTimeout(runTest, 1); } function runAfterIframeIsLoaded() { if (window.testRunner) testRunner.waitUntilDone(); function step() { if (!window.iframeLoaded) setTimeout(step, 100); else runTest(); } setTimeout(step, 100); } function runTest(pixelTest, enableWatchDogWhileDebugging) { if (!window.testRunner) return; if (pixelTest) testRunner.dumpAsTextWithPixelResults(); else testRunner.dumpAsText(); testRunner.waitUntilDone(); function initializeFrontend(initializationFunctions) { if (window.InspectorTest) { InspectorTest.pageLoaded(); return; } InspectorTest = {}; for (var i = 0; i < initializationFunctions.length; ++i) { try { initializationFunctions[i](); } catch (e) { console.error("Exception in test initialization: " + e + " " + e.stack); InspectorTest.completeTest(); } } } function runTestInFrontend(testFunction) { if (InspectorTest.wasAlreadyExecuted) return; InspectorTest.wasAlreadyExecuted = true; // 1. Preload panels. var lastLoadedPanel; var promises = []; for (var moduleName of InspectorTest._modulesToPreload) promises.push(self.runtime.loadModulePromise(moduleName)); for (var i = 0; i < InspectorTest._panelsToPreload.length; ++i) { lastLoadedPanel = InspectorTest._panelsToPreload[i]; promises.push(UI.inspectorView.panel(lastLoadedPanel)); } var testPath = Common.settings.createSetting("testPath", "").get(); // 2. Show initial panel based on test path. var initialPanelByFolder = { "animation": "elements", "audits": "audits", "console": "console", "elements": "elements", "editor": "sources", "layers": "layers", "network": "network", "profiler": "heap_profiler", "resource-tree": "resources", "search": "sources", "security": "security", "service-workers": "resources", "sources": "sources", "timeline": "timeline", "tracing": "timeline", } var initialPanelShown = false; for (var folder in initialPanelByFolder) { if (testPath.indexOf(folder + "/") !== -1) { lastLoadedPanel = initialPanelByFolder[folder]; promises.push(UI.inspectorView.panel(lastLoadedPanel)); break; } } // 3. Run test function. Promise.all(promises).then(() => { if (lastLoadedPanel) UI.inspectorView.showPanel(lastLoadedPanel).then(testFunction); else testFunction(); }).catch(function(e) { console.error(e); InspectorTest.completeTest(); }); } var initializationFunctions = [ String(initialize_InspectorTest) ]; for (var name in window) { if (name.indexOf("initialize_") === 0 && typeof window[name] === "function" && name !== "initialize_InspectorTest") initializationFunctions.push(window[name].toString()); } var toEvaluate = "(" + initializeFrontend + ")(" + "[" + initializationFunctions + "]" + ");"; testRunner.evaluateInWebInspector(initializeCallId, toEvaluate); if (window.debugTest) test = "function() { window.test = " + test.toString() + "; InspectorTest.addResult = window._originalConsoleLog; InspectorTest.completeTest = function() {}; }"; toEvaluate = "(" + runTestInFrontend + ")(" + test + ");"; testRunner.evaluateInWebInspector(runTestCallId, toEvaluate); if (enableWatchDogWhileDebugging) { function watchDog() { console.log("Internal watchdog triggered at 20 seconds. Test timed out."); closeInspectorAndNotifyDone(); } window._watchDogTimer = setTimeout(watchDog, 20000); } } function runTestAfterDisplay(enableWatchDogWhileDebugging) { if (!window.testRunner) return; testRunner.waitUntilDone(); requestAnimationFrame(runTest.bind(this, enableWatchDogWhileDebugging)); } function completeTest(results) { flushResults(results); closeInspectorAndNotifyDone(); } function flushResults(results) { results = (JSON && JSON.parse ? JSON.parse : eval)(unescape(results)); for (var i = 0; i < results.length; ++i) _output(results[i]); } function closeInspectorAndNotifyDone() { if (window._watchDogTimer) clearTimeout(window._watchDogTimer); testRunner.closeWebInspector(); setTimeout(function() { testRunner.notifyDone(); }, 0); } var outputElement; function createOutputElement() { outputElement = document.createElement("div"); // Support for svg - add to document, not body, check for style. if (outputElement.style) { outputElement.style.whiteSpace = "pre"; outputElement.style.height = "10px"; outputElement.style.overflow = "hidden"; } document.documentElement.appendChild(outputElement); } function output(text) { _output("[page] " + text); } function _output(result) { if (!outputElement) createOutputElement(); outputElement.appendChild(document.createTextNode(result)); outputElement.appendChild(document.createElement("br")); }
31.780567
169
0.637086
8d511be1beed3871e03d489801744584cbc484bb
2,424
js
JavaScript
dist/tag/tag.cjs.js
hakiiver2/primevue
f4be9f051ca57baf5ce11f15e795e0a8352ebf1f
[ "MIT" ]
null
null
null
dist/tag/tag.cjs.js
hakiiver2/primevue
f4be9f051ca57baf5ce11f15e795e0a8352ebf1f
[ "MIT" ]
1
2021-08-31T09:21:28.000Z
2021-08-31T09:21:28.000Z
dist/tag/tag.cjs.js
hakiiver2/primevue
f4be9f051ca57baf5ce11f15e795e0a8352ebf1f
[ "MIT" ]
null
null
null
'use strict'; var vue = require('vue'); var script = { name: 'Tag', props: { value: null, severity: null, rounded: Boolean, icon: String }, computed: { containerClass() { return ['p-tag p-component', { 'p-tag-info': this.severity === 'info', 'p-tag-success': this.severity === 'success', 'p-tag-warning': this.severity === 'warning', 'p-tag-danger': this.severity === 'danger', 'p-tag-rounded': this.rounded }]; }, iconClass() { return ['p-tag-icon', this.icon]; } } }; const _hoisted_1 = { class: "p-tag-value" }; function render(_ctx, _cache, $props, $setup, $data, $options) { return (vue.openBlock(), vue.createBlock("span", vue.mergeProps({ class: $options.containerClass }, _ctx.$attrs), [ vue.renderSlot(_ctx.$slots, "default", {}, () => [ ($props.icon) ? (vue.openBlock(), vue.createBlock("span", { key: 0, class: $options.iconClass }, null, 2)) : vue.createCommentVNode("", true), vue.createVNode("span", _hoisted_1, vue.toDisplayString($props.value), 1) ]) ], 16)) } function styleInject(css, ref) { if ( ref === void 0 ) ref = {}; var insertAt = ref.insertAt; if (!css || typeof document === 'undefined') { return; } var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (insertAt === 'top') { if (head.firstChild) { head.insertBefore(style, head.firstChild); } else { head.appendChild(style); } } else { head.appendChild(style); } if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } } var css_248z = "\n.p-tag {\n display: -webkit-inline-box;\n display: -ms-inline-flexbox;\n display: inline-flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center;\n}\n.p-tag-icon,\n.p-tag-value,\n.p-tag-icon.pi {\n line-height: 1.5;\n}\n.p-tag.p-tag-rounded {\n border-radius: 10rem;\n}\n"; styleInject(css_248z); script.render = render; module.exports = script;
31.076923
455
0.562706
8d5151bc924d9b9cb966054bda0badb6cf984892
547,578
js
JavaScript
dist/main-67a2142901.js
visdata/eiffel-web
2271200b568604bc9ab036bc11553aae29ccac59
[ "Apache-2.0" ]
null
null
null
dist/main-67a2142901.js
visdata/eiffel-web
2271200b568604bc9ab036bc11553aae29ccac59
[ "Apache-2.0" ]
null
null
null
dist/main-67a2142901.js
visdata/eiffel-web
2271200b568604bc9ab036bc11553aae29ccac59
[ "Apache-2.0" ]
null
null
null
function initColor(colorStyle){ var color={}; if(colorStyle=='dark'){ color.fullScreenButtonColor='white'; color.sizeBarColor='white'; color.titleTextColor='rgb(26,48,72)'; color.titleDivColor='rgb(140,160,170)'; // color.authorDivColor='rgb(50,70,90)'; // color.authorDivColor='rgb(15,40,60)'; color.authorDivColor='rgb(140,160,170)'; color.mainTransition1='rgb(25,35,45)'; color.mainTransition2='rgb(50,70,90)'; color.whiteBarTransition1='rgb(127,127,127)'; color.whiteBarTransition2='rgb(255,255,255)'; color.greyBarTransition1='rgb(74, 90, 103)'; color.greyBarTransition2='rgb(140, 160, 170)'; color.optionTextColor='white'; color.screenTextColor='white'; color.nodeLabelColor='white'; color.panelTitleColor='white'; color.nodeLabelHighlightColor='red'; color.nodeLabelHighlightStroke='red'; color.svgColor='rgb(15,40,60)'; // color.axisSVGColor='rgb(140,160,170)'; color.nodeColor ='rgb(70,190,210)'; color.markerColor='yellow'; color.nodeHighlightColor='white'; color.nodeGreyColor ='rgb(190,200,200)'; color.nodeHighlightStroke='red'; color.edgeColor='yellow'; color.edgeHightLightColor='red'; color.sizeLabelColor='black'; color.yearSliderHighlightColor='red'; color.yearSliderColor='rgb(40,120,200)'; color.axisTickColor='rgb(15,40,60)'; color.axisColor='rgb(15,40,60)'; color.yearPathColor='rgb(15,40,60)'; color.yearPathHighlightColor='white'; color.yearPathHighLightStroke='red'; color.textDisableColor='grey'; color.buttonStyle={ on:{ div:'rgb(185,200,200)', text:'rgb(10,40,60)' }, off:{ div:'rgb(50,70,90)', text:'rgb(135,155,165)' } }; color.divRender={}; color.divRender.highlight={ textColor:'rgb(16,38,51)', bodyDivBackground:color.greyBarTransition2, titleDivBackground:color.greyBarTransition2, transitionDivBackground:'-webkit-linear-gradient(right, '+color.greyBarTransition2+','+color.greyBarTransition1+')', lineBackground:color.greyBarTransition2, leftLineBackground:color.greyBarTransition2, transitionLineBackground:'-webkit-linear-gradient(right, '+color.greyBarTransition2+','+color.greyBarTransition1+')' }; color.divRender.recovery={ textColor:'white', bodyDivBackground:color.mainTransition2, titleDivBackground:color.mainTransition2, transitionDivBackground:'-webkit-linear-gradient(right, '+color.mainTransition2+','+color.mainTransition1+')', lineBackground:color.mainTransition2, leftLineBackground:color.greyBarTransition2, transitionLineBackground:'-webkit-linear-gradient(right, '+color.mainTransition2+','+color.mainTransition1+')' }; } else if(colorStyle=='light'){ color.fullScreenButtonColor='black'; color.sizeBarColor='black'; color.titleTextColor='rgb(26,48,72)'; color.titleDivColor='rgb(170,190,200)'; //color.authorDivColor='rgb(50,70,90)'; color.authorDivColor='rgb(216,235,241)'; color.svgColor='rgb(255,255,255)'; // color.axisSVGColor='rgb(140,160,170)' color.mainTransition1='rgb(160,170,180)'; color.mainTransition2='rgb(216,235,240)'; color.whiteBarTransition1='rgb(180,180,180)'; color.whiteBarTransition2='rgb(255,255,255)'; color.greyBarTransition1='rgb(140, 155, 160)'; color.greyBarTransition2='rgb(200, 220, 225)'; color.optionTextColor='rgb(15,40,60)'; color.screenTextColor='rgb(15,40,60)'; color.nodeLabelColor='black'; color.panelTitleColor='rgb(15,40,60)'; color.nodeLabelHighlightColor='red'; color.nodeLabelHighlightStroke='red'; color.nodeColor ='rgb(70,190,210)'; color.nodeHighlightColor='rgb(50,70,90)'; color.nodeGreyColor ='rgb(150,240,250)'; color.nodeHighlightStroke='red'; // color.edgeColor='yellow'; // color.edgeColor='rgb(102,194,165)'; // color.edgeColor='rgb(252,141,98)'; // color.edgeColor='rgb(31,120,180)'; color.edgeColor='rgb(190,186,218)'; // color.edgeColor='rgb(255,255,179)'; color.edgeHightLightColor='red'; color.sizeLabelColor='white'; color.yearSliderHighlightColor='red'; color.yearSliderColor='rgb(40,120,200)'; color.axisTickColor='rgb(15,40,60)'; color.yearPathColor='rgb(140,160,160)'; color.yearPathHighlightColor='white'; color.yearPathHighLightStroke='red'; color.textDisableColor='grey'; color.buttonStyle={ on:{ div:'rgb(60,100,120)', text:'rgb(255,255,255)' }, off:{ div:'rgb(140,160,170)', text:'rgb(60,90,110)' } } color.divRender={}; color.divRender.highlight={ textColor:'rgb(16,38,51)', bodyDivBackground:color.greyBarTransition2, titleDivBackground:color.greyBarTransition2, transitionDivBackground:'-webkit-linear-gradient(left, '+color.greyBarTransition2+','+color.greyBarTransition1+')', lineBackground:color.greyBarTransition2, leftLineBackground:color.greyBarTransition2, transitionLineBackground:'-webkit-linear-gradient(left, '+color.greyBarTransition2+','+color.greyBarTransition1+')' }; color.divRender.recovery={ textColor:'black', bodyDivBackground:color.mainTransition2, titleDivBackground:color.mainTransition2, transitionDivBackground:'-webkit-linear-gradient(left, '+color.mainTransition2+','+color.mainTransition1+')', lineBackground:color.mainTransition2, leftLineBackground:color.greyBarTransition2, transitionLineBackground:'-webkit-linear-gradient(left, '+color.mainTransition2+','+color.mainTransition1+')' }; } return color; } function initAuthorData(){ authorData ={ "281604":[ { "title":"The Skyline Operator", "image":'image/Stephan.jpg', "author":"Stephan Borzsonyi", "apartment":'Universitat Passau', "location":"D-94030 Passau, Germany D-81667 ", 'email':'Email:borzsonyi@db.fmi.uni-passau.de' }, { "title":"The Skyline Operator", "image":'image/Donald.jpg', "author":"Donald Kossmann", "apartment":'Technische Universitat Munchen', "location":"D-81667 M¨unchen, Germany", 'email':'Email:kossmann@in.tue.de' } ], "1140731":[//1141410 { "title":"LANDMARC: Indoor Location Sensing Using Active RFID.", "author":"Lionel M. Ni", "image":"image/1141410_L.jpg", "basicInfo":"Chair Professor and Head Department of Computer Science and Engineering The Hong Kong University of Science and Technology", "papers":294, "citations":18010, "Hindex":57, "field":'High-speed Networks' }, { "title":"LANDMARC: Indoor Location Sensing Using Active RFID.", "author":"Yunhao Liu", "image":"image/1141410_Y.jpg", "basicInfo":"Chang Jiang Professor and Dean of School of Software, Tsinghua University", "papers":319, "citations":10680, "Hindex":48, "field":"Wireless Sensor Networks/RFID" }], "1140582":[//1141261 { "title":"Analysis of a hybrid cutoff priority scheme for multiple classes of traffic in multimedia wireless networks", "author":"Bo Li", "image":"image/default.jpg", "basicInfo":"Hong Kong University of Science and Technology, Hong Kong", "papers":107, "citations":2084, "Hindex":24 }, { "title":"Analysis of a hybrid cutoff priority scheme for multiple classes of traffic in multimedia wireless networks", "author":"Samuel T. Chanson", "image":"image/chanson.jpg", "basicInfo":"Univ. of British Columbia, Vancouver, B.C., Canada", "papers":147, "citations":2028, "Hindex":20 }], "501699":[//1141410 { "title":"Manifold-ranking based image retrieval", "author":"Hongjiang Zhang", "image":"image/502309_1.jpg", "basicInfo":"Managing Director,Microsoft Research Asia Advanced Technology Center 5/F, Beijing Sigma Center", "papers":304, "citations":29948, "Hindex":87, "field":'Large-scale video retrieval' }, { "title":"Manifold-ranking based image retrieval", "author":"Changshui Zhang", "image":"image/502309_2.jpg", "basicInfo":"Professor Dept of Automation Tsinghua University", "papers":276, "citations":5501, "Hindex":38, 'field':"Face recognition / Image analysis" }], "default":[//1141410 { "title":"null", "author":"null", "image":"image/default.jpg", "papers":'null', }, { "title":"null", "author":"null", "image":"image/default.jpg", "papers":'null', } ] } } function initRightClickMenu(){ var clear=function(){ d3.select('.rightClickMenu') .styles({ visibility:'hidden' }); d3.selectAll('.clicked') .each(function(d){ if(d.self){ d.self.style('fill',function(d){return "url(#linearGradient"+ d.id+")"}); d.self.style('stroke',color.nodeHighlightStroke); d.self.style('stroke-width','0px'); d.self.attr('class','node'); d.clicked=false; } }) d3.selectAll('.subYearPath').remove(); if(data.postData[focusedID].subNodeYearData){ var subNodeYearData=data.postData[focusedID].subNodeYearData; for (var i=0;i<subNodeYearData.length;i++){ subNodeYearData[i][1]=0; } } } var commonMenuList=[ { text:'clear all highlight effects', id:0, click:clear } ]; var menuDiv=d3.select('body') .append('div') .attr('class','rightClickMenu') .styles({ position:'fixed', visibility:'hidden', width:'auto', height:'auto' // left:'500px', // top:'500px' }); menuDiv.selectAll('whatever') .data(commonMenuList) .enter() .append('div') .on('mouseover',function(d){ d3.select(this) .styles({ background:'blue' }) d3.select(this) .select('text') .styles({ color:'white' }) }) .on('mouseout',function(d){ d3.select(this) .styles({ background:'white' }) d3.select(this) .select('text') .styles({ color:'black' }) }) .attr('style','cursor: pointer; fill: rgb(0, 0, 0);') .styles({ background:'white' }) .attrs({ class:'menuOption' }) .append('text') .styles({ 'font-family':'Arial', 'color':'black' }) .html(function(d){ return d.text; }) .on('click',function(d){ return d.click(); }) document.oncontextmenu = function(e){ if(window.event) e = window.event; console.log(e.clientX,e.clientY); d3.select('.rightClickMenu') .styles({ visibility:'visible', top:e.clientY+px, left:e.clientX+2+px }); return false; } } function initVenueList(){ venueList={ "13067568": { "oldVenue": "", "venue": "CU" }, "11344560": { "oldVenue": "In Proceedings of the Vision, Modeling, and Visualization Workshop (VMV 09", "venue": "VMV" }, "11934211": { "oldVenue": "", "venue": "" }, "14165028": { "oldVenue": "In Proc. of MobiDE", "venue": "MDE" }, "1949002": { "oldVenue": "In Proc. of the 1st DELOS Workshop on Information Seeking, Searching and Querying in Digital Libraries", "venue": "ISSQ" }, "12123167": { "oldVenue": "Computer and Graphics", "venue": "CG" }, "24512199": { "oldVenue": "International Conference on Indoor Positioning and Indoor Navigation (IPIN), pp.I-S, IS-17", "venue": "IPIN" }, "10644003": { "oldVenue": "Comp. Graph. Forum (Proc. EG", "venue": "EuroVis" }, "14283791": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics", "venue": "TVCG" }, "19270250": { "oldVenue": "In: EG 2012 - State of the Art Reports", "venue": "EuroVis" }, "3723685": { "oldVenue": "ACM Proc. of Symposium on Solid Modeling and Applications", "venue": "SMA" }, "20077299": { "oldVenue": "Computer Graphics Forum", "venue": "EuroVis" }, "4877550": { "oldVenue": "In Proc. Afrigraph", "venue": "EuroVis" }, "19635110": { "oldVenue": "ACM Transactions on Graphics", "venue": "TOG" }, "14111591": { "oldVenue": "In Proceedings of the International Conference on Robotics and Automation (ICRA", "venue": "ICRA" }, "27371047": { "oldVenue": "In DASFAA (2", "venue": "DASFAA" }, "14267315": { "oldVenue": "Data, 15th International Conference on System Theory and Control (accepted", "venue": "ICSTC" }, "19930580": { "oldVenue": "In IJCAI", "venue": "IJCAI" }, "5533267": { "oldVenue": "ACM AFRIGRAPH04, Stellenbosch, Cape Town, South Africa", "venue": "TOG" }, "11807711": { "oldVenue": "Computer Graphics Forum (EUROGRAPHICS", "venue": "EuroVis" }, "3872607": { "oldVenue": "In Proceedings of Spring Conference on Computer Graphics 2007", "venue": "SCCG" }, "9475665": { "oldVenue": "In SIGMOD", "venue": "SIGMOD" }, "19384895": { "oldVenue": "IS&T/SPIE Electronic Imaging", "venue": "EI" }, "6320": { "oldVenue": "In Proceedings of the 8th DASSFA Conference, Kyoto, Japan", "venue": "DASSFA" }, "24321726": { "oldVenue": "In: Proceedings of the International Conference on Educational Data Mining", "venue": "ICEDM" }, "14271226": { "oldVenue": "IEEE Transactions on", "venue": "TVCG" }, "7768159": { "oldVenue": "", "venue": "" }, "10643998": { "oldVenue": "ACM Transactions on Graphics (SIGGRAPH", "venue": "TOG" }, "10896050": { "oldVenue": "In Proc. SMI", "venue": "SMI" }, "24657228": { "oldVenue": "Artificial Life", "venue": "AL" }, "15292918": { "oldVenue": "In Proc. 29th IEEE Int. Conf. Data Eng", "venue": "ICDE" }, "19515503": { "oldVenue": "in Collaborative Computing: Networking, Applications and Worksharing (CollaborateCom), 2012 8th International Conference on", "venue": "CC" }, "13791906": { "oldVenue": "In Proceedings of the 2011 SIGGRAPH Asia Conference, SA", "venue": "TOG" }, "9646343": { "oldVenue": "In SSTD", "venue": "SSTD" }, "19766323": { "oldVenue": "IEEE TVCG", "venue": "TVCG" }, "11740967": { "oldVenue": "IEEE TVCG", "venue": "TVCG" }, "11781769": { "oldVenue": "In Proc. 7th Intl Conf. Web Engineering", "venue": "ICWE" }, "14271223": { "oldVenue": "In: Proceedings of the SIGGRAPH Asia Conference", "venue": "TOG" }, "19270249": { "oldVenue": "ACM Trans. Graphics", "venue": "TOG" }, "3872606": { "oldVenue": "In Proceedings of the 8th international symposium on Smart Graphics", "venue": "ISSG" }, "104921": { "oldVenue": "In Proceedings of the 12th annual ACM international workshop on Geographic information systems (GIS04", "venue": "GIS" }, "13801082": { "oldVenue": "ACM Trans. Graph. (SIGGRAPH Asia", "venue": "TOG" }, "10436022": { "oldVenue": "Visualization Symposium, 2008. PacificVIS 08. IEEE Pacific", "venue": "PacificVis" }, "11857012": { "oldVenue": "In Proceedings of UIST", "venue": "UIST" }, "12985264": { "oldVenue": "In Proceedings of the International Conference on Robotics and Automation (ICRA", "venue": "ICRA" }, "9863978": { "oldVenue": "ACM Trans. Graphics", "venue": "TOG" }, "14284238": { "oldVenue": "Institute of Computer Graphics and Algorithms, Vienna University of Technology, Favoritenstrasse", "venue": "CGA" }, "13801084": { "oldVenue": "ACM Trans. on Graph (SIGGRAPH Asia", "venue": "TOG" }, "24024984": { "oldVenue": "Scientific Visualization: Advanced Concepts, Dagstuhl Follow-Ups, chapter 10. The article was originally written in 2005 after the Dagstuhl Seminar on Scientific Visualization and reflects the", "venue": "SV" }, "26849404": { "oldVenue": "In SSTD", "venue": "SSTD" }, "13001645": { "oldVenue": "In 12th International Conference on Mobile Data Management (MDM", "venue": "MDM" }, "20023618": { "oldVenue": "In Communications Control and Signal Processing (ISCCSP), 2012 5th International Symposium on", "venue": "ISCCSP" }, "6311": { "oldVenue": "In Proceedings of the 3rd International Conference on Image and Video Retrieval (CIVR04", "venue": "CIVR" }, "6317": { "oldVenue": "in: IJCAT", "venue": "IJCAI" }, "7271174": { "oldVenue": "In Proceedings of 25th IEEE International Conference on Distributed Computing Systems (ICDCS05", "venue": "ICDCS" }, "19305088": { "oldVenue": "In: CIKM", "venue": "CIKM" }, "15524770": { "oldVenue": "Digital Geometry Algorithms. Theoretical Foundations and Applications to Computational Imaging", "venue": "DGA" }, "6319": { "oldVenue": "Proceedings of the Smart Graphics Symposium (SG 2004), Lecture Notes in Computer Science", "venue": "SG" }, "6345269": { "oldVenue": "In Papadias", "venue": "PA" }, "19497771": { "oldVenue": "In Proceedings of the 12th SIAM international conference on data mining (SDM), Anaheim, CA", "venue": "SDM" }, "24583268": { "oldVenue": "In Proc. ACM Intl. Conf. on Web search and data mining (WSDM", "venue": "WSDM" }, "13919249": { "oldVenue": "In International Conference on Human-Computer Interaction", "venue": "CHI" }, "24259897": { "oldVenue": "ACM Trans. Graph", "venue": "TOG" }, "19656156": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics (Proc. SciVis", "venue": "TVCG" }, "4620296": { "oldVenue": "In EDBT", "venue": "EDBT" }, "24509024": { "oldVenue": "", "venue": "" }, "1135312": { "oldVenue": "In EDBT", "venue": "EDBT" }, "19377832": { "oldVenue": "in IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS", "venue": "IROS" }, "10214848": { "oldVenue": "In Proc. SAC", "venue": "SAC" }, "7705267": { "oldVenue": "IEEE Trans. Visualization and Computer Graphics", "venue": "TVCG" }, "10175227": { "oldVenue": "ACM Trans. Graph", "venue": "TOG" }, "3875729": { "oldVenue": "In: Proc. of Pacific Graphics 2003, Los Alamitos, IEEE Computer Society", "venue": "PG" }, "4285223": { "oldVenue": "Wiley Interdisciplinary Reviews: Data Mining and Knowledge Discovery", "venue": "WileyDMKD" }, "11585905": { "oldVenue": "IEEE Trans. Vis. Comput. Graph", "venue": "TVCG" }, "9684872": { "oldVenue": "In ICDE", "venue": "ICDE" }, "9094237": { "oldVenue": "VLDB", "venue": "VLDB" }, "13360158": { "oldVenue": "In Proceedings of the International Conference on Mobile Data Management", "venue": "MDM" }, "14007440": { "oldVenue": "In CHI12", "venue": "CHI" }, "19261675": { "oldVenue": "In IJCAI", "venue": "IJCAI" }, "14266603": { "oldVenue": "In Human Computation Workshop", "venue": "HC" }, "14077755": { "oldVenue": "Comp. Graph. Forum (Proc. Eurographics", "venue": "EuroVis" }, "19261678": { "oldVenue": "In PLDI", "venue": "PLDI" }, "9907894": { "oldVenue": "in Streamspin, ?? Proc. of the 10th IEEE International Conference on Mobile Data Management: Systems, Services and Middleware", "venue": "MDM" }, "9094238": { "oldVenue": "In SSTD", "venue": "SSTD" }, "14395706": { "oldVenue": "In Proceedings of the 28th international conference on Human factors in computing systems, CHI 10", "venue": "CHI" }, "25655424": { "oldVenue": "In Proceedings of the 17th International Conference on 3D Web Technology, ACM", "venue": "3WT" }, "19305091": { "oldVenue": "In: WAIM", "venue": "WAIM" }, "19305090": { "oldVenue": "", "venue": "" }, "9898494": { "oldVenue": "In IEEE Internationa Conference on Computer Vision (ICCV) Workshops", "venue": "ICCV" }, "19265458": { "oldVenue": "ACM Transactions on Graphics (Proc. SIGGRAPH", "venue": "TOG" }, "24509029": { "oldVenue": "in Proceedings of Int. Conf. Ubiquitous Positioning Indoor Navigation & Location Based Service", "venue": "ICUP" }, "19265457": { "oldVenue": "ACM Trans. Graph. (SIGGRAPH Asia", "venue": "TOG" }, "19354694": { "oldVenue": "In Proceedings of the 13th ACM Conference on Electronic Commerce", "venue": "EC" }, "9417929": { "oldVenue": "in MDD, SOA und IT-Management (MSI 2008", "venue": "MSI" }, "5623544": { "oldVenue": "In: Lernen - Wissen - Adaption Workshop (LWA", "venue": "LWA" }, "14469444": { "oldVenue": "ACM Trans. on Graphics (Proc. SIGGRAPH", "venue": "TOG" }, "19971169": { "oldVenue": "SIGMOD Record", "venue": "SIGMOD" }, "10168854": { "oldVenue": "In Proc. of Human Vision and Electronic Imaging X, SPIE/IS&T", "venue": "SPIE" }, "4227137": { "oldVenue": "In ADBIS 06: Proceedings of 10th East European Conference of Advances in Databases and Information Systems", "venue": "ADBIS" }, "19305089": { "oldVenue": "In: CIKM", "venue": "CIKM" }, "14140923": { "oldVenue": "In Proceedings of the ACM SIGGRAPH/Eurographics Symposium on Non-Photorealistic Animation and Rendering, NPAR 11", "venue": "NPAR" }, "19282020": { "oldVenue": "on Graphis (Proc. of SIGGRAPH", "venue": "TOG" }, "15524769": { "oldVenue": "In: Proc. 14th International Workshop on Combinatorial Image Analysis, IWCIA2011", "venue": "IWCIA" }, "10060292": { "oldVenue": "Proc. SIGGRAPH ASIA", "venue": "TOG" }, "19291301": { "oldVenue": "Computer Graphics Forum (Proceedings of Eurographics 2013", "venue": "EuroVis" }, "26883189": { "oldVenue": "In Proceedings of DNIS", "venue": "DNIS" }, "11972166": { "oldVenue": "In Proceedings of Graphics Interface 2010", "venue": "GI" }, "15227562": { "oldVenue": "In Proceedings of the 26th AAAI Conference on Artificial Intelligence, AAAI 12", "venue": "AAAI" }, "4027690": { "oldVenue": "In Proc of the 5th international Symposium on NonPhotorealistic Animation and Rendering", "venue": "AR" }, "14151775": { "oldVenue": "in ICDE", "venue": "ICDE" }, "26357499": { "oldVenue": "In 2012 IEEE International Symposium on Mixed and Augmented Reality (ISMAR", "venue": "ISMAR" }, "3906448": { "oldVenue": "In SimVis, SCS", "venue": "SCS" }, "14151772": { "oldVenue": "Proceedings of the VLDB Endowment", "venue": "VLDB" }, "28243468": { "oldVenue": "", "venue": "" }, "19906748": { "oldVenue": "ACM Trans. on Graphics (Proc. SIGGRAPH Asia", "venue": "TOG" }, "264621": { "oldVenue": "Shape Analysis and Structuring, Mathematics and Visualization, chapter 1", "venue": "SAS" }, "7543667": { "oldVenue": "In Proc. UIST", "venue": "UIST" }, "13317506": { "oldVenue": "International Journal of Managing Information Technology (IJMIT) vol.3, no.4", "venue": "IJMIT" }, "14088347": { "oldVenue": "In: Proceedings of the 2011 ACM SIGMOD International Conference on Management of Data, SIGMOD 2011", "venue": "SIGMOD" }, "9271624": { "oldVenue": "Proc. Int. Conference in Central Europe on Computer Graphics, Visualization and Computer Vision", "venue": "CV" }, "9066791": { "oldVenue": "In Proceedings of the 25th Wirel. Commun. Mob. Comput. (in press) ACCESS IN WMC ENVIRONMENTS International Conference on Distributed Computing Systems (ICDCS", "venue": "ICDCS" }, "5492733": { "oldVenue": "in Wireless Broadcast Environments, Proc. 23rd IEEE Intl Conf. Data Eng. (ICDE", "venue": "ICDE" }, "782850": { "oldVenue": "Procedings of IEEE Eurographics Symposium on Visualization", "venue": "EuroVis" }, "13365680": { "oldVenue": "IEEE International", "venue": "ICDE" }, "11662021": { "oldVenue": "In: DASFAA", "venue": "DASFAA" }, "10608423": { "oldVenue": "In Proceedings of the International Conference on Advanced Visual Interfaces, AVI 10", "venue": "AVI" }, "11709278": { "oldVenue": "CGF (EUROGRAPHICS", "venue": "EuroVis" }, "19248971": { "oldVenue": "ACM TOCHI", "venue": "TOCHI" }, "11773063": { "oldVenue": "In Advances in Computer Graphics and Computer Vision - VISIGRAPP 2008, Communications in Computer and Information Science (CCIS", "venue": "CCIS" }, "20077031": { "oldVenue": "In TODS", "venue": "TODS" }, "1196775": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics", "venue": "TVCG" }, "15191657": { "oldVenue": "ACM Trans. Graph", "venue": "TOG" }, "10481239": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics", "venue": "TVCG" }, "264681": { "oldVenue": "Computer Graphics Forum", "venue": "EuroVis" }, "10188592": { "oldVenue": "In: ICDE", "venue": "ICDE" }, "9897224": { "oldVenue": "in Proc. MDM", "venue": "" }, "13198002": { "oldVenue": "In Proc. SIGGRAPH 2011", "venue": "TOG" }, "12974013": { "oldVenue": "ICIAR 2010. LNCS", "venue": "ICIAR" }, "12974016": { "oldVenue": "In: Proc. 7th IASTED Int. Conf. Signal Processing, Pattern Recognition and Applications", "venue": "IASTED" }, "11048295": { "oldVenue": "ACM Trans. Graph. (SIGGRAPH Asia", "venue": "TOG" }, "25677789": { "oldVenue": "SSDBM 2012. LNCS", "venue": "SSDBM" }, "5259671": { "oldVenue": "In: Proceedings of Vision, Modeling and Visualization 2006", "venue": "VMV" }, "26989": { "oldVenue": "", "venue": "" }, "3906455": { "oldVenue": "In 14th International Conference in Central Europe on Computer Graphics, Visualization and Computer Vision, WSCG06", "venue": "EuroVis" }, "13134051": { "oldVenue": "", "venue": "" }, "9986008": { "oldVenue": "Proc. of Shape Modeling International", "venue": "SMI" }, "19389228": { "oldVenue": "SIGGRAPH Asia", "venue": "TOG" }, "19252085": { "oldVenue": "In Proc. of SIGMOD", "venue": "SIGMOD" }, "4929339": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics (Proc. of Visualization) 13:6", "venue": "TVCG" }, "27346484": { "oldVenue": "In Proceedings of the Tenth Annual International Conference on International Computing Education Research, ICER 13", "venue": "ICER" }, "19288975": { "oldVenue": "In Proceedings of the 25th ACM Symposium on User Interface Software and Technology", "venue": "UIST" }, "19288977": { "oldVenue": "In Proc", "venue": "UIST" }, "20108101": { "oldVenue": "IEEE Transactions on Computational Intelligence and AI in Games", "venue": "TCIA" }, "9677161": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics", "venue": "TVCG" }, "4111208": { "oldVenue": "In SCA", "venue": "EuroVis" }, "11098548": { "oldVenue": "International Journal of Computer Vision", "venue": "IJCV" }, "13835653": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics", "venue": "TVCG" }, "26173847": { "oldVenue": "in \"ACM SIGGRAPH / Eurographics Symposium on Computer Animation", "venue": "CA" }, "14228769": { "oldVenue": "n o 1, p. 1-13 [DOI : 10.1016/J.GMOD.2011.07.001], http://hal.inria.fr/inria00536840", "venue": "DOI" }, "9417271": { "oldVenue": "In Smart Graphics", "venue": "SG" }, "13373366": { "oldVenue": "In: Service-Oriented Computing. ICSOC/ServiceWave 2009 Workshops", "venue": "ICSOC" }, "13378249": { "oldVenue": "J. GooInformatica", "venue": "GI" }, "9944824": { "oldVenue": "Artif. Intell", "venue": "AAAI" }, "13942156": { "oldVenue": "IEEE Commun. Mag", "venue": "COMMAG" }, "19930585": { "oldVenue": "In Workshops at the Twenty-Sixth AAAI Conference on Artificial Intelligence", "venue": "AAAI" }, "19930584": { "oldVenue": "In MobiSys", "venue": "MobiSys" }, "13036547": { "oldVenue": "In: GIS 07 Proceedings of the 15th annual ACM international symposium on Advances in", "venue": "GIS" }, "1135500": { "oldVenue": "Proceedings of the working conference on Advanced visual interfaces", "venue": "AVI" }, "9601456": { "oldVenue": "In Proceedings of EUROGRAPHICS Workshop on Sketch-Based Interfaces and Modeling", "venue": "EuroVis" }, "414552": { "oldVenue": "4th Int. Conf. on Integrated Design and Manufacture in Mechanical Engineering", "venue": "IDM" }, "14020227": { "oldVenue": "ACM Trans. Graph", "venue": "TOG" }, "14299973": { "oldVenue": "In Proc. of IEEE Pacific Visualization Symposium", "venue": "PacificVis" }, "11876613": { "oldVenue": "Journal of WSCG", "venue": "WSCG" }, "13378250": { "oldVenue": "IEEE Trans. Mob. Comput", "venue": "TMC" }, "10232556": { "oldVenue": "In Vision, Modeling, and Visualization", "venue": "VMV" }, "10232557": { "oldVenue": "In Proceedings of the 6th international symposium on Non-photorealistic animation and rendering, NPAR 08", "venue": "NPAR" }, "1032395": { "oldVenue": "ACM ,Press", "venue": "TOG" }, "15261002": { "oldVenue": "ACM Trans. Graph", "venue": "TOG" }, "14123600": { "oldVenue": "PVLDB", "venue": "VLDB" }, "25654786": { "oldVenue": "In EUROGRAPHICS State-of-the-art Report", "venue": "EuroVis" }, "9748082": { "oldVenue": "In VLDB", "venue": "" }, "19949746": { "oldVenue": "In SIGGRAPH", "venue": "TOG" }, "24712245": { "oldVenue": "in \"ACM SIGGRAPH / Eurographics Symposium on Computer Animation", "venue": "CA" }, "24349875": { "oldVenue": "In Proceedings of the 7th international conference on Advances in visual computing - Volume Part I, ISVC11", "venue": "ISVC" }, "19389229": { "oldVenue": "", "venue": "" }, "22815206": { "oldVenue": "In Beyond Time and Errors Novel Evaluation Methods for Visualization (BELIV", "venue": "BELIV" }, "10008": { "oldVenue": "IEEE Transactions on Knowledge and Data Engineering (TKDE", "venue": "TKDE" }, "7017550": { "oldVenue": "Proc. First Intl Conf. Mobile and Ubiquitous Computing: Networks and Services", "venue": "MUC" }, "15292925": { "oldVenue": "Proc. 18th SIGSPATIAL Intl Conf. Advances in Geographic Information Systems", "venue": "PLDI" }, "15274369": { "oldVenue": "in CIKM", "venue": "CIKM" }, "19795996": { "oldVenue": "The Visual Comp. (Proc. CGI", "venue": "CGI" }, "10405247": { "oldVenue": "In EUROGRAPHICS Workshop on Sketch-Based Interfaces and Modeling, SBIM 2008", "venue": "SBIM" }, "5548117": { "oldVenue": "Wireless Networks", "venue": "WN" }, "2430814": { "oldVenue": "In MDM", "venue": "MDM" }, "10693007": { "oldVenue": "In Proc. of Eurographics State-of-the-art Report", "venue": "EuroVis" }, "15292928": { "oldVenue": "in DASFAA 2012", "venue": "DASFAA" }, "434215": { "oldVenue": "In Proceedings of the 14th International Conference on Scientific and Statistical Database Management(SSDBM02", "venue": "SSDBM" }, "14046900": { "oldVenue": "", "venue": "" }, "15030243": { "oldVenue": "ACM SIGKDD Explorations Newsletter", "venue": "KDD" }, "26080259": { "oldVenue": "In: 7th German Conference on Robotics (ROBOTIK 2012", "venue": "ROBOT" }, "4046077": { "oldVenue": "Computer Graphics Forum", "venue": "EuroVis" }, "414565": { "oldVenue": "", "venue": "" }, "19330938": { "oldVenue": "In Proc. First Workshop on CPS Education (CPS-Ed", "venue": "CPS" }, "11806291": { "oldVenue": "In ICDE", "venue": "ICDE" }, "10652493": { "oldVenue": "ACM Transactions on Graphics", "venue": "TOG" }, "10569677": { "oldVenue": "IEEE Data Eng. Bull", "venue": "ICDE" }, "15297703": { "oldVenue": "Structure-Aware Shape Processing", "venue": "SASP" }, "24524137": { "oldVenue": "Cornell University", "venue": "CU" }, "4044135": { "oldVenue": "In In 4th International Symposium on Smart Graphics, SG04", "venue": "SG" }, "19282809": { "oldVenue": "ACM Trans. Graph. (SIGGRAPH", "venue": "TOG" }, "9628673": { "oldVenue": "In SIGMOD Conference", "venue": "SIGMOD" }, "3725164": { "oldVenue": "In Mathematics of Surfaces XI: 11th IMA International Conference, Springer Lecture Notes in Computer Science (LNCS", "venue": "Surface" }, "3725576": { "oldVenue": "In: SYMPOSIUM ON INTERACTIVE 3D GRAPHICS AND GAMES, I3D, 2005. Proceedings", "venue": "I3D" }, "9409219": { "oldVenue": "In VMV 2008", "venue": "VMV" }, "14088346": { "oldVenue": "In: Proceedings of the 31st Symposium on Principles of Database Systems, PODS 2012", "venue": "PODS" }, "24581291": { "oldVenue": "In KDD", "venue": "KDD" }, "19389234": { "oldVenue": "ACM Transactions on Graphics - Proceedings of ACM SIGGRAPH Asia", "venue": "TOG" }, "4879025": { "oldVenue": "Proceedings of the Workshop on Text-Based Information Retrieval TIR 06", "venue": "TIR" }, "3778243": { "oldVenue": "In Proceedings of the 9th International Conference on Extending Database Technology (EDBT), Heraklion", "venue": "EDBT" }, "19942528": { "oldVenue": "Discrete Differential Forms for Computational Modeling", "venue": "CM" }, "14130885": { "oldVenue": "In: IEEE transactions on visualization and computer graphics 18.8", "venue": "TVCG" }, "12076829": { "oldVenue": "In Proc. Smart Graphics", "venue": "SG" }, "13812765": { "oldVenue": "ACM Transactions on Graphics", "venue": "TOG" }, "11104272": { "oldVenue": "Trans. Vis. Comput. Graph", "venue": "TVCG" }, "19333396": { "oldVenue": "In: Web Science", "venue": "WS" }, "22873677": { "oldVenue": "", "venue": "" }, "15243229": { "oldVenue": "TACCESS", "venue": "TACCESS" }, "11125204": { "oldVenue": "Proceedings of the International Conference on Motion in Games (MiG", "venue": "ICM" }, "15201235": { "oldVenue": "In Proceedings of the ACM Symposium on Applied Perception", "venue": "AP" }, "19557472": { "oldVenue": "in: IEEE Conference on Computer Vision and Pattern Recognition (CVPR", "venue": "CVPR" }, "1430147": { "oldVenue": "Axiomathes", "venue": "AX" }, "14345901": { "oldVenue": "ACM Trans. Graph", "venue": "TOG" }, "9601473": { "oldVenue": "Comput. Graph. Forum", "venue": "EuroVis" }, "9601471": { "oldVenue": "In Proc. of ACM Symposium on", "venue": "UIST" }, "9601475": { "oldVenue": "IEEE Trans. Vis. & Comp. Graphics", "venue": "TVCG" }, "19308906": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics", "venue": "TVCG" }, "7679936": { "oldVenue": "", "venue": "" }, "13818296": { "oldVenue": "Comp. Graph. Forum", "venue": "EuroVis" }, "13994706": { "oldVenue": "IEEE Transactions on Visualization and Computer Graphics", "venue": "TVCG" }, "24335483": { "oldVenue": "IEEE Transactions on", "venue": "TVCG" }, "693374": { "oldVenue": "In Mathematical Foundations of Scientific Visualization, Computer Graphics, and Massive Data Exploration, Mathematics and Visualization", "venue": "EuroVis" } } } function changeAnimateMode() { var animateMode = this.animateMode; //console.log(this); if (animateMode == flipBook) { this.changeToMovieMode(); } else if (animateMode == movie) { this.changeToFlipBookMode(); } } function changeToMovieMode() { this.animateMode = movie; var that = this; var yearFilter = this.yearFilter; var minYear = this.minYear; var maxYear = this.maxYear; var axisSVG = this.axisSVG; var xScale = this.xScale; var yScale = this.yScale; var yearSliderDrag = this.yearSliderDrag; axisSVG.select('.movieSlider').remove(); d3.select('.movieModeDiv') .style('background', color.buttonStyle.on.div); d3.select('.movieModeText') .style('color', color.buttonStyle.on.text); d3.select('.flipBookModeDiv') .style('background', color.buttonStyle.off.div); d3.select('.flipBookModeText') .style('color', color.buttonStyle.off.text); if (yearFilter) { if (yearFilter[0] == minYear && yearFilter[1] == maxYear) { var defaultYearDuration = 3; var rYear = defaultYearDuration + minYear; axisSVG.select('#rightAxisCircle') .attrs({ cx: function (d) { d.x = xScale(rYear); return d.x; } }); yearFilter[1] = rYear; } var left = axisSVG.select('#leftAxisCircle'); var right = axisSVG.select('#rightAxisCircle'); var leftX = parseFloat(left.attr('cx')); var rightX = parseFloat(right.attr('cx')); var y = parseFloat(left.attr('cy')); var movieSliderData = [{ p1: { x: leftX, y: y }, p2: { x: rightX, y: y }, index: 1 }]; axisSVG.selectAll('whatever') .data(movieSliderData) .enter() .append('path') .attr('class', 'movieSlider axisController') .attr('index', 1) .attr('id', 'movieSlider') .styles({ 'stroke-width': 4, 'stroke': 'white' }) .attr('d', function (d) { var e = {}; clone(d, e); var avg = (d.p1.x + d.p2.x) / 2; e.p1.x = avg; e.p2.x = avg; return yearSliderPathData(e); }) .on('mouseover', function (d) { d3.select(this) .style('stroke-width', 8) }) .on('mouseout', function (d) { d3.select(this) .style('stroke-width', 4) }) .transition() .duration(100) .attr('d', yearSliderPathData) .styles({ 'stroke-width': 4, 'stroke': 'white', 'cursor': 'hand' }) .on('end', function () { var ids = ['leftAxisCircle', 'rightAxisCircle']; axisSVG.select('#leftAxisCircle') .attr('class', 'axisCircle axisController') .style('filter', 'url(#moveToLeft_filter)') .style('visibility', 'visible'); axisSVG.select('#rightAxisCircle') .attr('class', 'axisCircle axisController') .style('filter', 'url(#moveToRight_filter)'); axisSVG.selectAll('.axisController').sort(function (a, b) { return d3.descending(a.index, b.index); }); }); axisSVG.select('.movieSlider') .each(function (d) { d.that = that; }) .call(yearSliderDrag); this.greyBackground(); updateAnimation(false, that); } } function changeToFlipBookMode() { var drawnodes = this.drawnodes; var drawedges = this.drawedges; var data = this.data; var focusedID = this.focusedID; var axisSVG = this.axisSVG; this.animateMode = flipBook; drawnodes.selectAll('*').remove(); drawedges.selectAll('*').remove(); this.preLayout(data.postData[focusedID]); d3.select('.movieModeDiv') .style('background', color.buttonStyle.off.div); d3.select('.movieModeText') .style('color', color.buttonStyle.off.text); d3.select('.flipBookModeDiv') .style('background', color.buttonStyle.on.div); d3.select('.flipBookModeText') .style('color', color.buttonStyle.on.text); axisSVG.select('.movieSlider').remove(); axisSVG.selectAll('.axisCircle') .style('filter', 'url(#leftOrRight_filter)'); } function drawAnimateControlPanel() { var that = this; var axisSVG = this.axisSVG; axisSVG.selectAll('*').remove(); var authorDiv = d3.select('.authorDiv_' + this.position); var width = authorDiv._groups[0][0].clientWidth; var height = authorDiv._groups[0][0].clientHeight; axisSVG.attrs({ width: width, height: height }); var nameFunDic = { play: play, playBack: playBack, pause: pause, stop: stop, temporal: temporalTimeLine, general: generalTimeLine }; var buttonControl = function (d, thisNode) { var layer = d.layer; //var thisNode=d3.select(this); var thisID = thisNode.attr('id'); if (thisID == 'play')nameFunDic.play(thisNode, layer); else if (thisID == 'playBack')nameFunDic.playBack(thisNode, layer); else if (thisID == 'pause')nameFunDic.pause(thisNode, layer); else if (thisID == 'stop')nameFunDic.stop(thisNode, layer); else if (thisID == 'temporalTimeLine')nameFunDic.general(thisNode, layer); else if (thisID == 'generalTimeLine')nameFunDic.temporal(thisNode, layer); }; var controlPanelButtonsData = [ { name: 'play', fun: play, fun1: pause }, { name: 'playBack', fun: playBack, fun1: pause }, { name: 'pause', fun: function () { } }, { name: 'stop', fun: stop }, { name: 'moveToLeft', fun: function () { } }, { name: 'moveToRight', fun: function () { } }, { name: 'leftOrRight', fun: function () { } }, { name: 'speedUp', fun: function () { } }, { name: 'speedUp', fun: function () { } }, { name: 'speedDown', fun: function () { } }, { name: 'lock', fun: function () { } }, { name: 'temporalTimeLine', fun: generalTimeLine }, { name: 'generalTimeLine', fun: temporalTimeLine } ]; axisSVG.selectAll('filter') .data(controlPanelButtonsData) .enter() .append('filter') .attrs({ class: 'ButtonFilter', id: function (d) { return d.name + '_filter'; }, x: 0, y: 0, width: 1, height: 1 }) .each(function (d) { var thisFilter = d3.select(this); thisFilter.append('feImage') .attrs({ 'xlink:href': 'image/animateControlPanel/' + d.name + '.png' }) }); var midControlPanelButtonData = [ //{ // name:'playBack', // fun:playBack, // fun1:pause //}, { name: 'play', fun: play, fun1: pause, layer: that }, { name: 'stop', fun: stop, layer: that } ]; var midNum = midControlPanelButtonData.length; var midButtonRadius = 10; var midButtonY = 20; var midButtonDistance = 10; var temporalButtonLength = 60; var controlPanelLength = (midNum - 1) * (midButtonRadius * 2 + midButtonDistance) + midButtonDistance + temporalButtonLength; var width = parseFloat(axisSVG.style('width')); var initX = (width - controlPanelLength) / 2; // var initX=35; axisSVG.selectAll('controlButton') .data(midControlPanelButtonData) .enter() .append('circle') .attrs({ cx: function (d, i) { return initX + i * (2 * midButtonRadius + midButtonDistance); }, cy: midButtonY, r: midButtonRadius, id: function (d) { return d.name; }, name: function (d) { return d.name; }, class: function (d) { return 'controlButton' + ' ' + 'controlButton_' + d.name + '_' + that.source; } }) .on('click', function (d) { d3.selectAll('#' + d.name) .each(function (e) { if (d3.select(this).attr('class') != 'ButtonFilter') { var thisNode = d3.select(this); buttonControl(e, thisNode); } }); }) //.on('click',buttonControl) .styles({ 'filter': function (d) { return 'url(#' + d.name + '_filter)'; }, 'cursor': 'hand' }); var temporalButtonData = [{ name: 'generalTimeLine', fun: temporalTimeLine, x: initX + controlPanelLength - temporalButtonLength + 10, y: midButtonRadius, height: midButtonRadius * 2, width: temporalButtonLength, layer: that }]; axisSVG.selectAll('whatever') .data(temporalButtonData) .enter() .append('rect') .each(function (d) { d3.select(this) .attrs({ id: d.name, x: d.x, y: d.y, width: d.width, height: d.height }) .style('filter', function (d) { return 'url(#' + d.name + '_filter)'; }) .style('cursor', 'hand') .on('click', function (d) { d3.selectAll('#' + d.name) .each(function (e) { if (d3.select(this).attr('class') != 'ButtonFilter') { var thisNode = d3.select(this); buttonControl(e, thisNode); } }); }) }) } function updateAnimation(flag, that) { var animateMode = that.animateMode; var minYear = that.minYear; var maxYear = that.maxYear; var data = that.data; var focusedID = that.focusedID; var svg = that.svg; if (animateMode == flipBook && !flag) { if (that.yearFilter[0] == minYear && that.yearFilter[1] == maxYear) { that.yearFilter = [minYear, maxYear]; } else { that.yearFilter = [that.yearFilter[1], maxYear]; } } var yearFilter = that.yearFilter; var graphData = {}; //clone(data.postData[focusedID],graphData); var newD = that.filterDataByYear(data.postData[focusedID], [that.yearFilter[0], that.yearFilter[1]], that); that.preYear = yearFilter[0]; var preYear = that.preYear; if (yearFilter[0] != minYear || yearFilter[1] != maxYear) { if (animateMode == flipBook && !flag)newD.keepAll = true; } if (animateMode == flipBook) { if (!flag) { that.layout(optionNumber, true, 'flowMap', newD); } else { that.layout(optionNumber, false, false, newD); } } if (animateMode == movie) { // yearFilter=[minYear,minYear+3]; that.layout(optionNumber, false, false, newD); } svg.selectAll('.node') .each(function (d) { var thisNode = d3.select(this); if (thisNode.attr('transitionStatus') == 'start')thisNode.remove(); }); } function playBack(thisNode) { changeFilter(thisNode, 'pause'); if (animateMode == flipBook) { //updateAnimation(); //yearAxisTransition(yearFilter[0],yearFilter[1]); } else { var remainYear = yearFilter[0] - minYear; var animationNum = remainYear; var currentYearDuration = yearFilter[1] - yearFilter[0]; yearFilters = []; for (var i = 0; i < animationNum - 1; i++) { // yearFilters.push([yearFilter[0]+(i+1)*currentYearDuration,yearFilter[1]+(i+1)*currentYearDuration]) yearFilters.push([yearFilter[0] - (i + 1), yearFilter[1] - (i + 1)]) } yearFilters.push([minYear, minYear + currentYearDuration]); recurMovieTransition(yearFilters); } } function play(thisNode, that) { changeFilter(thisNode, 'pause'); var animateMode = that.animateMode; var maxYear = that.maxYear; var minYear = that.minYear; var temporal = that.temporal; var requestMethod = that.requestMethod; var ifTemporal = that.ifTemporal; that.transitionFlag = true; if (animateMode == flipBook) { that.updateAnimation(false, that); var yearFilter = that.yearFilter; console.log(yearFilter); that.yearAxisTransition(yearFilter[0], yearFilter[1], that); } else { var remainYear = maxYear - that.yearFilter[1]; var currentYearDuration = that.yearFilter[1] - that.yearFilter[0]; // var animationNum=Math.ceil(remainYear/currentYearDuration); var animationNum = remainYear; var division = temporal.maxDivision; that.yearFilters = []; var yearFilters = that.yearFilters; if (ifTemporal) { for (var i = 1; i < division.length; i++) { var len = division[i].length; yearFilters.push([division[i][0].year.toInt(), division[i][len - 1].year.toInt()]); } } else { for (var i = 0; i < animationNum - 1; i++) { // yearFilters.push([yearFilter[0]+(i+1)*currentYearDuration,yearFilter[1]+(i+1)*currentYearDuration]) yearFilters.push([that.yearFilter[0] + (i + 1), that.yearFilter[1] + (i + 1)]) } yearFilters.push([maxYear - currentYearDuration, maxYear]); } //console.log(yearFilters); //console.log(yearFilters); // var sliderDuration=yearDelay*currentYearDuration; recurMovieTransition(yearFilters, that); } } function recurMovieTransition(yearFilters, that) { var yearDelay = that.yearDelay; var axisSVG = that.axisSVG; var xScale = that.xScale; var sliderDuration = yearDelay; var yearFilter = that.yearFilter; var k = 0 if (yearFilters.length > 0) { axisSVG.select('#leftAxisCircle') .transition() // .delay(k*yearDelay*currentYearDuration) .duration(sliderDuration) .ease(d3.easeLinear) .attrs({ cx: function (d) { d.x = xScale(yearFilters[0][0]); return d.x; } }) axisSVG.select('#rightAxisCircle') .transition() .duration(sliderDuration) // .delay(k*yearDelay*currentYearDuration) .ease(d3.easeLinear) .attrs({ cx: function (d) { d.x = xScale(yearFilters[0][1]); return d.x; } }) .on('end', function (d) { that.yearFilter = [yearFilters[0][0], yearFilters[0][1]]; updateAnimation(false, that); yearFilters = yearFilters.splice(1, yearFilters.length - 1); recurMovieTransition(yearFilters, that) }) axisSVG.select('.movieSlider') .transition() .duration(sliderDuration) // .delay(k*yearDelay*currentYearDuration) .ease(d3.easeLinear) .attrs({ d: function (d) { d.p1.x = xScale(yearFilters[0][0]); d.p2.x = xScale(yearFilters[0][1]); k += 1; return yearSliderPathData(d); } }) } else { axisSVG.selectAll('.controlButton') .each(function (d) { if (d.name == 'pause') { d3.select(this) .attrs({ id: function (d) { d.name = 'play'; return d.name; } }) .styles({ filter: function (d) { return 'url(#' + d.name + '_filter)'; } }) } }); } } function pause(thisNode, that) { var name = thisNode.attr('name'); changeFilter(thisNode, name); var adjustData = adjustSliderPosition(false, that); var adjustDirection = adjustData.direction; var adjustYear = adjustData.year; d3.selectAll('*').interrupt(); updateAnimation(true, that); // addNodes(adjustYear); // } // that.removeAnimation(); //console.log(that.yearFilter) // console.log('pause'); } function stop(thisNode, that) { var axisSVG = that.axisSVG; var svg_g = that.svg_g; var animateMode = that.animateMode; var drawnodes = that.drawnodes; var drawedges = that.drawedges; var data = that.data; var focusedID = that.focusedID; var minYear = that.minYear; axisSVG.selectAll('.controlButton') .each(function (d) { if (d.name == 'pause') { d3.select(this) .attrs({ id: function (d) { d.name = 'play'; return d.name; } }) .styles({ filter: function (d) { return 'url(#' + d.name + '_filter)'; } }) } }); if (animateMode == flipBook) { d3.selectAll('*').interrupt(); drawnodes.selectAll('*').remove(); drawedges.selectAll('*').remove(); that.preLayout(data.postData[focusedID]); } else { d3.selectAll('*').interrupt(); var adjustData = adjustSliderPosition('stop', that); var adjustDirection = adjustData.direction; var adjustYear = adjustData.year; if (adjustDirection == 'left') { that.removeEdges(); } else { // addNodes(adjustYear); } svg_g.select('#nodeG2').remove(); svg_g.select('#edgeG2').remove(); svg_g.select('#nodeG4').selectAll('*').remove(); svg_g.select('#edgeG4').selectAll('*').remove(); //that.yearFilter=[minYear,minYear+3]; updateAnimation(false, that); //that.preLayout(data.postData[focusedID]); //that.changeToMovieMode(); } } function temporalTimeLine(thisNode, that) { thisNode .attrs({ id: function (d) { d.name = 'temporalTimeLine'; return d.name; } }) .styles({ filter: function (d) { return 'url(#' + d.name + '_filter)' } }); that.ifTemporal = true; that.changeToMovieMode(); // updateAnimation(); var division; var temporal = that.temporal; //division = temporal.maxDivision; var maxDivision = division; if(getUrlParam('twitter') == 20) { maxDivision = [ [{year: '1', flow: 1}, {year: '4', flow: 1}], [{year: '4', flow: 1}, {year: '8', flow: 1}] ]; } else if (getUrlParam('aminerV8_id') == 1182989) { maxDivision = [ [{year: '2007', flow: 1}, {year: '2011', flow: 1}], [{year: '2011', flow: 1}, {year: '2013', flow: 1}], [{year: '2013', flow: 1}, {year: '2016', flow: 1}] ]; } temporal.maxDivision = maxDivision; var firstPart = maxDivision[0]; var yearFilter = that.yearFilter; var axisSVG = that.axisSVG; var xScale = that.xScale; yearFilter = [firstPart[0].year.toInt(), firstPart[firstPart.length - 1].year.toInt()]; axisSVG.select('.movieSlider') .transition() .duration(100) // .delay(k*yearDelay*currentYearDuration) .ease(d3.easeLinear) .attrs({ d: function (d) { d.p1.x = xScale(yearFilter[0]); d.p2.x = xScale(yearFilter[1]); return yearSliderPathData(d); } }) .on('end', function () { updateAnimation(false, that); }) axisSVG.select('#leftAxisCircle') .transition() // .delay(k*yearDelay*currentYearDuration) .duration(100) .ease(d3.easeLinear) .attrs({ cx: function (d) { d.x = xScale(yearFilter[0]); return d.x; } }) .styles({ visibility: 'visible' }); axisSVG.select('#rightAxisCircle') .transition() .duration(100) // .delay(k*yearDelay*currentYearDuration) .ease(d3.easeLinear) .attrs({ cx: function (d) { d.x = xScale(yearFilter[1]); return d.x; } }); axisSVG.select('#leftAxisCircle') .attrs({ 'class': 'axisCircle axisController', index: function (d) { return d.index } }); axisSVG.select('#rightAxisCircle') .attrs({ 'class': 'axisCircle axisController', index: function (d) { return d.index } }); axisSVG.selectAll('.axisController').sort(function (a, b) { return d3.descending(a.index, b.index) }); } function generalTimeLine(thisNode, that) { thisNode .attrs({ id: function (d) { d.name = 'generalTimeLine'; return d.name; } }) .styles({ filter: function (d) { return 'url(#' + d.name + '_filter)' } }); that.ifTemporal = false; } function removeEdges() { var svg = this.svg; svg.selectAll('path') .each(function (d) { var thisEdge = d3.select(this); var status = thisEdge.attr('transitionStatus'); if (status == 'start') { thisEdge.remove(); } }) } function removeAnimation() { var animateMode = this.animateMode; var svg = this.svg; var yearFilter = this.yearFilter; if (animateMode == flipBook) { var types = ['.backgroundNode', 'path', '.node', '.size', '.label']; for (var i = 0; i < types.length; i++) { var type = types[i]; var selector = svg; if (type == 'path')selector = selector.select('.edgeField'); selector.selectAll(type) .each(function (e, i) { var thisObj = d3.select(this); if (thisObj.attr('class') != 'legend') { if (thisObj.attr('transitionStatus') == null) { thisObj.remove(); } } }) } } svg.select('.rightYear') .html(yearFilter[1]) .transition() .duration(100) .tween("text", function () { var i = d3.interpolateRound(yearFilter[1], yearFilter[1]); return function (t) { this.textContent = i(t); }; }) svg.selectAll('.backgroundNode').remove() // .each(function(d){ // var thisNode=d3.select(this); // var r=thisNode.attr('r').toFloat(); // thisNode.transition() // .duration(100) // .attr('r',r) // }); svg.selectAll('.node') .each(function (d) { var thisNode = d3.select(this); thisNode.attrs({ transitionStatus: 'end' }); if (thisNode.attr('r')) { var r = thisNode.attr('r').toFloat(); thisNode.transition() .duration(100) .attr('r', r) } }); svg.selectAll('.size') .each(function (d) { var thisNode = d3.select(this); var size = thisNode.html().toFloat(); thisNode.attrs({ transitionStatus: 'end' }) thisNode.transition() .duration(100) .tween("text", function (d) { var i = d3.interpolateRound(size, size); return function (t) { this.textContent = i(t); }; }) }); } function changeFilter(thisNode, id) { thisNode .style('filter', 'url(#' + id + '_filter)'); thisNode .attr('id', function (d) { d.name = id; return d.name }); } function DirectedGraph(data) { this.nodes = data.node; this.edges = data.edge; this.graph = {}; this.edgeSourceTargetDic = {}; this.initEdgeSourceTargetDic={}; this.edgeSourceDic = {}; this.edgeTargetDic = {}; this.minYear = 10000; this.maxYear = 0; this.deletedEdges=[]; this.maximalSpanningTree={}; this.spanningTree = { nodes: [], edges: [], deletedTreeEdges: [], deletedNonTreeEdges: [], deletedEdges: [] }; this.ifGetBFSTree=false; this.BFSTree=''; this.getEdgeDic = function (keyType,filter) { if(arguments.length==1)filter='flow'; var dic = {}; for (var i = 0; i < this.edges.length; i++) { if(this.edges[i][filter]>0&&!this.edges[i].disable){ var key = this.edges[i][keyType]; if (dic[key])dic[key].push(this.edges[i]); else dic[key] = [this.edges[i]]; } } return dic; }; // this.getEdgeSourceTargetDic=function (){ // var dic={}; // for(var i=0;i<this.edges.length;i++){ // var source=this.edges[i].source; // var target=this.edges[i].target; // var key=String(source)+'_'+String(target); // dic[key]=this.edges[i]; // } // this.edgeSourceTargetDic=dic; // }; this.init = function () { // this.getEdgeSourceTargetDic(); this.initNodeRelation(); this.getYearDuration(); this.initEdgeYearWeight(); this.storeInitEdgeSourceTargetDic(); this.build(); }; this.initNodeRelation = function () { for (var i = 0; i < this.nodes.length; i++) { var node = this.nodes[i]; node.children = []; node.parents = []; } }; this.storeInitEdgeSourceTargetDic=function(){ var dic={}; for(var i=0;i<this.edges.length;i++){ var source=this.edges[i].source; var target=this.edges[i].target; var key=source+'_'+target; var newEdge={}; clone(this.edges[i],newEdge); dic[key]=newEdge; } this.initEdgeSourceTargetDic=dic; }; this.getYearDuration = function () { for (var i = 0; i < this.edges.length; i++) { for (var key in this.edges[i].weight) { var year = parseInt(key); if (year > this.maxYear)this.maxYear = year; if (year < this.minYear)this.minYear = year; } } }; this.initEdgeYearWeight = function () { for (var i = 0; i < this.edges.length; i++) { var edge = this.edges[i]; if(!edge.yearWeight){ var sum = 0; for (var year in edge.weight) { sum += edge.weight[year]; } var yearWeight = 0; for (var year in edge.weight) { // yearWeight += Math.sqrt(this.maxYear - year.toInt() + 1) * edge.weight[year]; yearWeight += this.maxYear - year.toInt() + 1 * edge.weight[year]; } yearWeight /= sum; edge.yearWeight = yearWeight; edge.yearFlow = yearWeight*edge.flow; } } }; this.resetYearFlow=function(){ for(var i=0;i<this.edges.length;i++){ var edge=this.edges[i]; edge.yearFlow=edge.flow*edge.yearWeight; } }; this.addEdge = function (edge) { var source = edge.source; var target = edge.target; var key = source + '_' + target; if (this.edgeSourceTargetDic[key]) { // console.log('edge already exists in current graph'); } else { this.edges.push(edge); this.edgeSourceTargetDic[key] = edge; var sourceNode = this.nodes[source]; var targetNode = this.nodes[target]; sourceNode.children.push(targetNode); targetNode.parents.push(sourceNode); } }; this.removeEdge = function (edge) { var source = edge.source; var target = edge.target; var key = source + '_' + target; if (!this.edgeSourceTargetDic[key]) { console.log('this edge not exists in current graph'); } else { //delete dic // delete this.edgeSourceTargetDic[key]; this.edgeSourceTargetDic[key]=null; var newEdges = []; for (var i = 0; i < this.edges.length; i++) { var thisEdge = this.edges[i]; var thisKey = thisEdge.source + '_' + thisEdge.target; if (thisKey != key) { newEdges.push(thisEdge); } } //delete edge // this.edges = newEdges; this.edges = newEdges; //delete node in children and parents var sourceNode = this.nodes[source]; var targetNode = this.nodes[target]; var newChildren = []; var newParents = []; if (sourceNode.children.length > 0) { for (var j = 0; j < sourceNode.children.length; j++) { var child = sourceNode.children[j]; var childID = child.id; if (childID != target) { newChildren.push(child); } } } if (targetNode.parents.length > 0) { for (var j = 0; j < targetNode.parents.length; j++) { var parent = targetNode.parents[j]; var parentID = parent.id; if (parentID != source) { newParents.push(parent); } } } sourceNode.children = newChildren; targetNode.parents = newParents; this.deletedEdges.push(edge); } }; this.build = function () { // console.log(this.nodes); this.nodes = this.nodes; this.root = ''; var tmpEdges=[]; clone(this.edges, tmpEdges); this.edges = [] for (var i = 0; i < tmpEdges.length; i++) { var edge = tmpEdges[i]; this.addEdge(edge); } for (var i = 0; i < this.nodes.length; i++) { if (this.nodes[i].focused == 'true') { this.root = this.nodes[i]; break; } } }; this.checkConnection = function (method) { if (this.root) { var visitedNodes = [this.root.id]; if (method == 'DFS') { this.DFS(this.root, visitedNodes); } if (method == 'BFS' || arguments.length == 0) { visitedNodes = []; this.BFS(this.root, visitedNodes); } var disableList=[]; for(var i=0;i<this.nodes.length;i++){ if(this.nodes[i].disable)disableList.push(this.nodes[i].id); } if ((visitedNodes.length == this.nodes.length-disableList.length)) { return true; } else { return false; } } }; this.BFS = function (node, visitedNodes) { //have some problems that can not traverse all the graph var nodeStep = []; var rootWeight = 1; var root = node; var level = 0; var k = 0.5; nodeStep.push(root); var BFSEdge=[]; var bfsNodes=[]; while (nodeStep[0]) { var newStep = []; for (var i = 0; i < nodeStep.length; i++) { var step = nodeStep[i]; if ((!step.disable)&&(!in_array(step.id, visitedNodes))) { visitedNodes.push(step.id); if (!step.BFSWeight)step.BFSWeight = rootWeight * Math.pow(k, level); if (step.children) { for (var j = 0; j < step.children.length; j++) { if(!step.children[j].disable){ var source = step.id; var target = step.children[j].id; var key = source + '_' + target; var edge = this.edgeSourceTargetDic[key]; if (!edge.BFSWeight)edge.BFSWeight = rootWeight * Math.pow(k, level); if (!in_array(step.children[j].id, visitedNodes)) { if(!in_array(target, bfsNodes)){ bfsNodes.push(target); BFSEdge.push(edge); } newStep.push(step.children[j]); } } } } } } level += 1; nodeStep = newStep; } if(this.ifGetBFSTree){ var newNodes=[]; var newEdges=[]; clone(this.nodes,newNodes); clone(BFSEdge,newEdges) var BFSTreeData={node:newNodes,edge:newEdges}; var BFSTree=new DirectedGraph(BFSTreeData); BFSTree.init(); this.BFSTree=BFSTree; } }; this.DFS = function (node, visitedNodes) { // console.log('nodeID:'+node.id); if (node.children.length > 0) { var children = node.children; for (var i = 0; i < children.length; i++) { if (!in_array(children[i].id, visitedNodes)&&(!children[i].disable)) { visitedNodes.push(children[i].id); this.DFS(children[i], visitedNodes); } } } }; this.sortEdge = function (attr, order) { // var weightKey='BFSWeight'; var weightKey = 'yearWeight'; if (arguments.length == 0) { attr = 'flow'; order = 'decrease'; } if (arguments.length == 1) { order = 'decrease'; } this.edges.sort(function (a, b) { if (order == 'increase')return a[attr] * a[weightKey] - b[attr] * b[weightKey]; else if (order == 'decrease')return b[attr] * b[weightKey] - a[attr] * a[weightKey]; }); }; this.filterTopFlow=function(k){ this.sortEdge('flow','increase'); while(this.checkConnection()&&this.edges.length>this.nodes.length*k){ var edge; for (var i = 0; i < this.edges.length; i++) { if (!this.edges[i].deleteTimes) { edge = this.edges[i]; break; } } this.removeEdge(edge); if (!this.checkConnection()) { edge.deleteTimes = 1; this.addEdge(edge); } } }; this.recurRemoveEdge=function(edge){ this.removeEdge(edge); if(edge.originEdge){ this.recurRemoveEdge(edge.originEdge); } }; this.openCircle=function(node){ if(node.children){ var newChildren=[]; for(var i=0;i<node.children.length;i++){ var child=node.children[i]; if(child.pseudoNode){ if(!child.disable)newChildren.push(child); } else{ newChildren.push(child); } } node.children = newChildren; for(var i=0;i<node.children.length;i++){ var child=node.children[i]; if(!child.disable){ if(!child.pseudoNode){ var source=node.id; var target=child.id; var key=source+'_'+target; var edge=this.edgeSourceTargetDic[key]; if(edge.disable)edge.disable=false; this.openCircle(child); } else{ child.disable = true; if(child.children){ for(var j=0;j<child.children.length;j++){ var source=child.id; var target=child.children[j].id; var key=source+'_'+target; var edge=this.edgeSourceTargetDic[key]; edge.disable=true; edge.originEdge.disable=false; } } var tmpChildren=[]; for(var j=0;j<node.children;j++){ if(!node.children[j].pseudoNode){ if(!node.children[j].disable)tmpChildren.push(node.children[j]); } } if(child.circleEdges){ var source=node.id; var target=child.id; var key=source+'_'+target; var originEdge=this.edgeSourceTargetDic[key].originEdge; var newChild=this.nodes[originEdge.target]; newChild.disable=false; tmpChildren.push(newChild); for(var j=0;j<child.circleEdges.length;j++){ var edge=child.circleEdges[j]; if(edge.target!=originEdge.target)edge.disable=false; else{ this.recurRemoveEdge(edge); } } } if(child.innerNodesIDList){ for(var j=0;j<child.innerNodesIDList.length;j++){ var id=child.innerNodesIDList[j]; var innerNode=this.nodes[id]; innerNode.disable=false; } } node.children=tmpChildren; if(!this.checkConnection()){ console.log('does not connected'); } else{ this.openCircle(this.root); } } } } } }; this.contractCircle = function (circle) { var edgeSourceDic=this.getEdgeDic('source'); var edgeTargetDic=this.getEdgeDic('target'); var len=this.nodes.length; var newNode={ id:len, children:[], parents:[], innerNodesIDList:[], intoThisNodeEdges:[], outThisNodeEdges:[], circleEdges:[], pseudoNode:true }; this.nodes.push(newNode); var circleIDList=[]; for(var i=0;i<circle.edges.length;i++){ var edge=circle.edges[i]; var source=edge.source; var target=edge.target; this.nodes[source].disable = true; this.nodes[target].disable = true; if(!in_array(source, circleIDList))circleIDList.push(source); if(!in_array(target, circleIDList))circleIDList.push(target); newNode.circleEdges.push(edge); } newNode.innerNodesIDList=circleIDList; for(var i=0;i<circleIDList.length;i++){ if(edgeSourceDic[circleIDList[i]]){ for(var j=0;j<edgeSourceDic[circleIDList[i]].length;j++){ var edge=edgeSourceDic[circleIDList[i]][j]; edge.disable = true; if(!in_array(edge.target,circleIDList)){ if(this.directedTree){ var directedTreeEdgeTargetDic=this.directedTree.getEdgeDic('target'); var tmpEdge=directedTreeEdgeTargetDic[edge.target]; if(tmpEdge.originEdge){ var key=tmpEdge[0].originEdge.source+'_'+tmpEdge[0].originEdge.target; edge = this.edgeSourceTargetDic[key]; } } var newEdge={}; clone(edge, newEdge); newEdge.disable=false; newEdge.pseudoEdge=true; newEdge.originEdge=edge; newEdge.source = newNode.id; this.addEdge(newEdge); newNode.outThisNodeEdges.push(edge); } } for(var j=0;j<edgeTargetDic[circleIDList[i]].length;j++){ var edge=edgeTargetDic[circleIDList[i]][j]; edge.disable = true; if(!in_array(edge.source,circleIDList)){ if(this.directedTree){ var directedTreeEdgeSourceDic=this.directedTree.getEdgeDic('source'); var tmpEdge; // if(directedTreeEdgeSourceDic[edge.source]){ // tmpEdge=directedTreeEdgeSourceDic[edge.source][0]; // edge = {}; // key = tmpEdge.source+'_'+tmpEdge.target; // edge = this.edgeSourceTargetDic[key]; // } // else{ var maxEdge={circleFlow:-100000000}; for(var k=0;k<edgeSourceDic[edge.source].length;k++){ if(in_array(edgeSourceDic[edge.source][k].target,circleIDList)){ tmpEdge=edgeSourceDic[edge.source][k]; if(tmpEdge.circleFlow>maxEdge.circleFlow)maxEdge=tmpEdge; } } key = maxEdge.source+'_'+maxEdge.target; edge = this.edgeSourceTargetDic[key]; // } } var newEdge={}; clone(edge, newEdge); newEdge.disable=false; newEdge.pseudoEdge=true; newEdge.originEdge=edge; newEdge.target = newNode.id; this.addEdge(newEdge); newNode.intoThisNodeEdges.push(edge); } } } } }; this.generateMaximalSpanningTree = function () { //the method is provided by Guangdi Li http://www.mathworks.com/matlabcentral/profile/authors/1714285-guangdi-li //Email: lowellli121@gmail.com //http://mcbench.cs.mcgill.ca/benchmark/24327-maximumminimum-weight-spanning-tree-directed?query=%2F%2FForStmt%2F%2FAssignStmt%5Bname(lhs())%3D%27NameExpr%27+and+name(rhs())%3D%27NameExpr%27+and+rhs()%2F%40kind%3D%27VAR%27%5D /* %1 Discard the arcs entering the root if any; For each node other than the root, select the entering arc with the highest cost; Let the selected n-1 arcs be the set S. % If no cycle is formed, G( N,S ) is a MST. Otherwise, continue. %2 For each cycle formed, contract the nodes in the cycle into a pseudo-node (k), and modify the cost of each arc which enters a node (j) in the cycle from some node (i) % outside the cycle according to the following equation. c(i,k)=c(i,j)-(c(x(j),j)-min_{j}(c(x(j),j)) where c(x(j),j) is the cost of the arc in the cycle which enters j. %3 For each pseudo-node, select the entering arc which has the smallest modified cost; Replace the arc which enters the same real node in S by the new selected arc. %4 Go to step 2 with the contracted graph. */ //the below code is written by Yue Su //in our data there should not exist a path that target to the root //select the entering arc with the highest cost var treeNodes=[]; var treeEdges=[]; var tmpEdges=[]; clone(this.nodes, treeNodes); for(var i=0;i<treeNodes.length;i++){ if(!(treeNodes[i].focused=='true')){ var id=parseInt(treeNodes[i].id); var nodeEdge=[]; var maxEdge={yearFlow:0}; for(var j=0;j<this.edges.length;j++){ if(this.edges[j].target==id){ if(this.edges[j].yearFlow>maxEdge.yearFlow)maxEdge=this.edges[j]; } } tmpEdges.push(maxEdge); } } clone(tmpEdges,treeEdges); var treeData={node:treeNodes,edge:treeEdges}; // for(var i=0;i<treeEdges.length;i++){ // console.log(edge[]) // } var directedTree=new DirectedGraph(treeData); this.directedTree=directedTree; directedTree.init(); directedTree.sortEdge('source','increase'); for(var i=0;i<this.edges.length;i++){ this.edges[i].circleFlow=this.edges[i].yearFlow; } for(var i=0;i<directedTree.edges.length;i++){ directedTree.edges[i].circleFlow=directedTree.edges[i].yearFlow; } //detect circle while(!directedTree.checkConnection()){ //find circle for each node for(var i=0;i<directedTree.nodes.length;i++){ var node=directedTree.nodes[i]; if(!node.disable){ var id=node.id; var pathTarget = {id: id, preEdge: [], currentIDList: [id], next: []}; var paths=[]; directedTree.findCircle(id, id, id, pathTarget,paths,false); if(paths[0]){ //circle find //contract the nodes in the cycle into a pseudo-node (k) var len=this.nodes.length; var circleIDList=[]; for(var j=0;j<paths[0].edges.length;j++){ var edge=paths[0].edges[j]; var source=edge.source; var target=edge.target; if(!in_array(source, circleIDList))circleIDList.push(source); if(!in_array(target, circleIDList))circleIDList.push(target); if(!directedTree.nodes[source].circleTarget)directedTree.nodes[source].circleTarget=target; if(!directedTree.nodes[target].circleSource)directedTree.nodes[target].circleSource=source; } var edgeTargetToCircle=[]; var circleEdgeDic={}; for(var j=0;j<circleIDList.length;j++){ var circleNodeID=circleIDList[j]; var parents=this.nodes[circleNodeID].parents; var len=0; for(var x=0;x<parents.length;x++){ if(!parents[x].disable)len+=1; } if(len>1){ var circleSource=directedTree.nodes[circleNodeID].circleSource; var circleEdgeKey=circleSource+'_'+circleNodeID; var circleEdge=this.edgeSourceTargetDic[circleEdgeKey]; circleEdgeDic[circleNodeID]=circleEdge; for(var k=0;k<parents.length;k++){ if(!in_array(parents[k].id,circleIDList)&&!parents[k].disable){ // if(parents[k].id!=circleSource&&!parents[k].disable){ var edgeKey=parents[k].id+'_'+circleNodeID; var edge=this.edgeSourceTargetDic[edgeKey]; edge.circleFlow-=circleEdge.circleFlow; edgeTargetToCircle.push(edge); } } } } // console.log(edgeTargetToCircle); var maxCircleFlowEdge={circleFlow:-100000000}; for(var j=0;j<edgeTargetToCircle.length;j++){ if(edgeTargetToCircle[j].circleFlow>maxCircleFlowEdge.circleFlow){ maxCircleFlowEdge=edgeTargetToCircle[j]; } } var circleTarget=maxCircleFlowEdge.target; var targetCircleEdge=circleEdgeDic[circleTarget]; // console.log('try remove: '+targetCircleEdge.source+'->'+targetCircleEdge.target) // recurRemove(targetCircleEdge); function recurRemove(targetCircleEdge){ if(targetCircleEdge.originEdge){ directedTree.removeEdge(targetCircleEdge); // console.log('try remove: '+targetCircleEdge.originEdge.source+'->'+targetCircleEdge.originEdge.target); recurRemove(targetCircleEdge.originEdge) } } var tmpEdge={}; clone(maxCircleFlowEdge,tmpEdge); maxCircleFlowEdge=tmpEdge; function recurAdd(maxCircleFlowEdge){ directedTree.addEdge(maxCircleFlowEdge); if(maxCircleFlowEdge.originEdge){ // console.log('try add: '+maxCircleFlowEdge.originEdge.source+'->'+maxCircleFlowEdge.originEdge.target) recurAdd(maxCircleFlowEdge.originEdge) } } // console.log('try add: '+maxCircleFlowEdge.source+'->'+maxCircleFlowEdge.target) recurAdd(maxCircleFlowEdge); directedTree.contractCircle(paths[0]); this.contractCircle(paths[0]); // console.log(directedTree.edgeSourceTargetDic) // console.log('merge ',circleIDList,'as node'); for(var j=0;j<directedTree.nodes.length;j++){ // delete directedTree.nodes[j].circleSource; directedTree.nodes[j].circleSource=null; // delete directedTree.nodes[j].circleTarget; directedTree.nodes[j].circleTarget=null; } break; } } } } var tmpcurrentEdges=[]; var tmpcurrentNodes=[]; for(var tmpkey in directedTree.edgeSourceTargetDic){ var tmpsource=parseInt(tmpkey.split('_')[0]); var tmptarget=parseInt(tmpkey.split('_')[1]); if(!directedTree.edgeSourceTargetDic[tmpkey].pseudoEdge){ // console.log(tmpkey); var tmpedge={}; clone(directedTree.edgeSourceTargetDic[tmpkey],tmpedge); if(tmpedge.disable)delete tmpedge.disable; tmpcurrentEdges.push(tmpedge) } } for(var i=0;i<directedTree.nodes.length;i++){ var node=directedTree.nodes[i]; if(!node.pseudoNode){ var newNode={}; clone(node, newNode); if(newNode.children)delete newNode.children; if(newNode.parents)delete newNode.parents; if(newNode.disable)delete newNode.disable; tmpcurrentNodes.push(newNode); } } var tmpGraphData={node:tmpcurrentNodes,edge:tmpcurrentEdges}; var tmpGraph=new DirectedGraph(tmpGraphData); tmpGraph.init(); tmpGraph.ifGetBFSTree=true; tmpGraph.checkConnection(); // tmpcurrentEdges.sort(function(a,b){return d3.ascending(a.target, b.target)}); // // tmpcurrentEdges.sort(function(a,b){return d3.ascending(a.source, b.source)}); // for(var i=0;i<tmpcurrentEdges.length;i++){ // console.log(tmpcurrentEdges[i].source+'->'+tmpcurrentEdges[i].target); // } // console.log(tmpcurrentEdges); // directedTree.openCircle(directedTree.root); // var newTreeEdges=[]; // var newTreeNodes=[]; // for(var i=0;i<directedTree.edges.length;i++){ // var edge=directedTree.edges[i]; // var source=edge.source; // var target=edge.target; // var edgeStr=source+'->'+target; // // if(!edge.disable&&!edge.pseudoEdge){ //// console.log(edgeStr); // newTreeEdges.push(edge); // } // } // for(var i=0;i<directedTree.nodes.length;i++){ // var node=directedTree.nodes[i]; // if(!node.disable)newTreeNodes.push(node); // } // var spanningTreeData={node:newTreeNodes,edge:newTreeEdges}; // var spanningTree=new DirectedGraph(spanningTreeData); // spanningTree.init(); var spanningTree=tmpGraph.BFSTree; this.maximalSpanningTree=spanningTree; spanningTree.deletedTreeEdges=[]; spanningTree.deletedNonTreeEdges=[]; var originEdgeDic=this.initEdgeSourceTargetDic; var mstEdgeDic=spanningTree.edgeSourceTargetDic; for(var key in originEdgeDic){ if(!mstEdgeDic[key]){ var deletedEdge=originEdgeDic[key]; this.maximalSpanningTree.deletedTreeEdges.push(deletedEdge); } } // if(!directedTree.checkConnection()){ // //can not traverse all nodes from the root, means that there exist one or more cycle in the current graph // for(var i=0;i<this.nodes.length;i++){ // // } // } // else{ // // } }; this.generateSpanningTree = function () { this.resetYearFlow(); while (!this.checkIfSpanningTree()) { this.edges=this.edges.sort(function(a,b){return a.source- b.source}); this.sortEdge('flow', 'increase'); var edge; for (var i = 0; i < this.edges.length; i++) { if (!this.edges[i].deleteTimes) { edge = this.edges[i]; break; } } this.removeEdge(edge); if (!this.checkConnection()) { edge.deleteTimes = 1; this.addEdge(edge); } else { this.spanningTree.deletedEdges.push(edge); var source = edge.source; var target = edge.target; var originTarget = edge.target; var pathTarget = {id: target, preEdge: [], currentIDList: [target], next: []}; var paths = []; // this.findAllPathBetween(source, target, originTarget, pathTarget, paths); // this.findMaxPathBetween(source, target, originTarget, pathTarget, paths); paths = this.findMaxPathBetween(source, target); //console.log(paths.length); if (paths.length > 0) { var maxAvgFlowPath={avgFlow:0}; for(var i=0;i<paths.length;i++){ paths[i].avgFlow=paths[i].totalFlow/paths[i].edges.length; if(paths[i].avgFlow>maxAvgFlowPath.avgFlow)maxAvgFlowPath=paths[i]; } for (var i = 0; i < maxAvgFlowPath.edges.length; i++) { maxAvgFlowPath.edges[i].yearFlow += edge.yearFlow; maxAvgFlowPath.totalFlow += edge.yearFlow; } // paths.sort(function (a, b) { // return b.totalFlow - a.totalFlow; // }); // paths.sort(function (a, b) { // return a.length - b.length; // }); this.spanningTree.deletedTreeEdges.push({ originEdge: edge, newPath: maxAvgFlowPath }) } else { this.spanningTree.deletedNonTreeEdges.push(edge); } } } // for(var i=0;i<this.spanningTree.deletedEdges.length;i++){ // var edge=this.spanningTree.deletedEdges[i]; // var source=edge.source; // var target=edge.target; // var originTarget=edge.target; // var pathTarget={id:target, preEdge:[],currentIDList:[target],next:[]}; // var paths=[]; // this.findAllPathBetween(source,target,originTarget,pathTarget,paths); //// console.log(paths.length); // if(paths.length>0){ // for(var j=0;j<paths[0].edges.length;j++){ // paths[0].edges[j].flow+=edge.flow; // paths[0].totalFlow+=edge.flow; // } // paths.sort(function(a,b){ // return b.totalFlow-a.totalFlow; // }); // paths.sort(function(a,b){ // return a.length-b.length; // }); // this.spanningTree.deletedTreeEdges.push({ // originEdge:edge, // newPath:paths[0] // }) // } // else{ // this.spanningTree.deletedNonTreeEdges.push(edge); // } // } }; this.checkIfSpanningTree = function () { if (this.checkConnection("DFS") && (this.nodes.length - this.edges.length == 1)) { return true; } else { return false; } }; this.findCircle=function(source, target, originTarget, pathTarget, paths,circleFlag){ this.edgeTargetDic = this.getEdgeDic('target','flow'); var targetParents = this.edgeTargetDic[target]; pathTarget.next = []; if (targetParents) { for (var i = 0; i < targetParents.length; i++) { var newSource = targetParents[i].source; if (!circleFlag) { if(newSource == source){ circleFlag=true; } var newPreEdge = []; var key = newSource + '_' + target; var newCurrentIDList = []; var reverseKey = target + '_' + newSource; if ((newSource!=originTarget&&(!in_array(newSource, pathTarget.currentIDList)))||newSource==originTarget) { clone(pathTarget.preEdge, newPreEdge); clone(pathTarget.currentIDList, newCurrentIDList); newPreEdge.push(key); newCurrentIDList.push(newSource); var newPathTarget = {id: newSource, preEdge: newPreEdge, currentIDList: newCurrentIDList, next: []}; pathTarget.next.push(newPathTarget); if (!circleFlag) { this.findCircle(source, newSource, originTarget, newPathTarget, paths,circleFlag) } else { var circle = {}; circle.edges = []; circle.length = newPathTarget.preEdge.length; circle.totalFlow = 0; for (var j = 0; j < circle.length; j++) { var edge = this.edgeSourceTargetDic[newPathTarget.preEdge[j]] circle.edges.push(edge); circle.totalFlow += edge.flow; } paths.push(circle); } } } } } } this.findAllPathBetween = function (source, target, originTarget, pathTarget, paths) { this.edgeTargetDic = this.getEdgeDic('target','flow'); var targetParents = this.edgeTargetDic[target]; pathTarget.next = []; if (targetParents) { for (var i = 0; i < targetParents.length; i++) { var newSource = targetParents[i].source; if (newSource != originTarget) { var newPreEdge = []; var key = newSource + '_' + target; var newCurrentIDList = []; var reverseKey = target + '_' + newSource; if ((!in_array(newSource, pathTarget.currentIDList))) { clone(pathTarget.preEdge, newPreEdge); clone(pathTarget.currentIDList, newCurrentIDList); newPreEdge.push(key); newCurrentIDList.push(newSource); var newPathTarget = {id: newSource, preEdge: newPreEdge, currentIDList: newCurrentIDList, next: []}; pathTarget.next.push(newPathTarget); if (newSource != source) { this.findAllPathBetween(source, newSource, originTarget, newPathTarget, paths) } else { var newPath = {}; newPath.edges = []; newPath.length = newPathTarget.preEdge.length; newPath.totalFlow = 0; for (var j = 0; j < newPath.length; j++) { var edge = this.edgeSourceTargetDic[newPathTarget.preEdge[j]] newPath.edges.push(edge); newPath.totalFlow += edge.flow; } paths.push(newPath); // var pathStr=''; // for(var j=0;j<newPath.edges.length;j++){ // pathStr+=newPath.edges[j].target; // pathStr+='<-' // } // pathStr+=newPath.edges[newPath.edges.length-1].source; // console.log(pathStr); } } } } } }; this.dijkstra=function(source,target){ var dijGraph=new dijkstraGraph(); var nodes=this.nodes; var edges=this.edges; var dijNodes=[]; for(var i=0;i<nodes.length;i++){ var newNode=dijGraph.addNode(nodes[i].id); dijNodes.push(newNode); } var maxYearFlow=d3.max(edges,function(d){return d.yearFlow})+1; for(var i=0;i<edges.length;i++){ var edgeSource=edges[i].source; var edgeTarget=edges[i].target; var sourceNode=dijNodes[edgeSource]; var targetNode=dijNodes[edgeTarget]; sourceNode.addEdge(targetNode,maxYearFlow-edges[i].yearFlow); } return dijkstra(dijGraph,dijNodes[source],dijNodes[target]); }; this.findMaxPathBetween=function(source,target){ var paths=[]; // while(1){ var shortestPathEdges=this.dijkstra(source, target); // var minEdge={yearFlow:Number.POSITIVE_INFINITY}; var newPath={}; newPath.edges = []; newPath.totalFlow = 0; newPath.length = 0; for(var i=0;i<shortestPathEdges.length;i++){ var edge=this.edgeSourceTargetDic[shortestPathEdges[i]]; newPath.edges.push(edge); newPath.totalFlow+=edge.yearFlow; newPath.length=newPath.edges.length; // if(edge.yearFlow<minEdge.yearFlow)minEdge=edge; } if(newPath.length>0)paths.push(newPath); // minEdge.ignoreInDijkstra=true; // } return paths; }; this.findMaxPathBetweenOld=function(source, target, originTarget, pathTarget, paths){ if(paths.length>=50){ return } this.edgeTargetDic = this.getEdgeDic('target','yearFlow'); var targetParents = this.edgeTargetDic[target]; pathTarget.next = []; if (targetParents) { for (var i = 0; i < targetParents.length; i++) { var newSource = targetParents[i].source; if (newSource != originTarget) { var newPreEdge = []; var key = newSource + '_' + target; var newCurrentIDList = []; var reverseKey = target + '_' + newSource; if ((!in_array(newSource, pathTarget.currentIDList))) { clone(pathTarget.preEdge, newPreEdge); clone(pathTarget.currentIDList, newCurrentIDList); newPreEdge.push(key); newCurrentIDList.push(newSource); var newPathTarget = {id: newSource, preEdge: newPreEdge, currentIDList: newCurrentIDList, next: []}; pathTarget.next.push(newPathTarget); if (newSource != source) { this.findMaxPathBetween(source, newSource, originTarget, newPathTarget, paths) } else { var newPath = {}; newPath.edges = []; newPath.length = newPathTarget.preEdge.length; newPath.totalFlow = 0; for (var j = 0; j < newPath.length; j++) { var edge = this.edgeSourceTargetDic[newPathTarget.preEdge[j]]; newPath.edges.push(edge); newPath.totalFlow += edge.yearFlow; } var minEdge=d3.min(newPath.edges,function(d){ return d.yearFlow; }); for(var j=0;j<this.edges.length;j++){ this.edges[j].yearFlow-=minEdge; } if(paths.length>=50){ return } paths.push(newPath); // var pathStr=''; // for(var j=0;j<newPath.edges.length;j++){ // pathStr+=newPath.edges[j].target; // pathStr+='<-' // } // pathStr+=newPath.edges[newPath.edges.length-1].source; // console.log(pathStr); } } } } } } } function updateCheckBox(d) { var status = sourceCheckedStatus; if (status.left && status.right) { d3.selectAll('.' + d.type + 'CheckBox').attrs({ disabled: function () { return null; } }) } else if (status.left) { d3.select('.' + d.type + 'CheckBox_left') .attrs({ disabled: true }) } else if (status.right) { d3.select('.' + d.type + 'CheckBox_right') .attrs({ disabled: true }) } } function updateSvgBySourceCheckBox() { var status = sourceCheckedStatus; var ratio = {}; var totalWidth = usefulWidth; if (status.left && status.right) { ratio.left = 0.5; ratio.mid = 0.5; ratio.right = 0; ratio.control = 1; leftLayer.dataSourceVisibility = 'visible'; rightLayer.dataSourceVisibility = 'visible'; leftLayer.ifLayout = true; rightLayer.ifLayout = true; currentLayer = null; } else if (status.left) { ratio.left = 0.63; ratio.mid = 0; ratio.right = 0.37; ratio.control = 0.63; leftLayer.dataSourceVisibility = 'hidden'; rightLayer.dataSourceVisibility = 'hidden'; currentLayer = leftLayer; leftLayer.ifLayout = true; rightLayer.ifLayout = false; } else if (status.right) { ratio.left = 0; ratio.mid = 0.63; ratio.right = 0.37; ratio.control = 0.63; leftLayer.dataSourceVisibility = 'hidden'; rightLayer.dataSourceVisibility = 'hidden'; currentLayer = rightLayer; leftLayer.ifLayout = false; rightLayer.ifLayout = true; } var newWidth = {}; newWidth.left = totalWidth * ratio.left; newWidth.right = totalWidth * ratio.right; newWidth.mid = totalWidth * ratio.mid; newWidth.control = totalWidth * ratio.control; //console.log(newWidth); var transitionData = [ {class: '.graphDiv_left', ease: 'linear', duration: 1000, width: newWidth.left, layer: leftLayer}, {class: '.authorDiv_left', ease: 'linear', duration: 1000, width: newWidth.left, layer: leftLayer}, {class: '.graphDiv_right', ease: 'linear', duration: 1000, width: newWidth.mid, layer: rightLayer}, {class: '.authorDiv_right', ease: 'linear', duration: 1000, width: newWidth.mid, layer: rightLayer}, {class: '.paperDiv', ease: 'linear', duration: 1000, width: newWidth.right}, {class: '.topControlDiv', ease: 'linear', duration: 1000, width: newWidth.control}, {class: '.bottomControlDiv', ease: 'linear', duration: 1000, width: newWidth.control}, ]; transitionData.forEach(function (item) { d3.select(item.class) //.transition() //.ease(item.ease) //.duration(item.duration) .styles({ width: item.width + px }); if (item.class == '.graphDiv_left' || item.class == '.graphDiv_right' || item.class == '.authorDiv_left' || item.class == '.authorDiv_right') { item.layer.svg .attrs({ width: item.width }); item.layer.axisSVG .attrs({ width: item.width }); item.layer.size = { width: item.layer.svg.attr("width") * 0.9, height: item.layer.svg.attr("height") * 1 }; } }); requestData(); //var layers=[leftLayer,rightLayer]; //layers.forEach(function(layer){ // if(layer.size.width==0)return; // var tmpData={}; // clone(layer.data.sourceData[layer.focusedID],tmpData); // layer.processData(tmpData); // if(layer.focusedID&&layer.preFocusedID){ // layer.layout(optionNumber,true, 'incremental',layer.data.postData[layer.focusedID]); // } // else{ // layer.preLayout(layer.data.postData[layer.focusedID]); // } //}); var animationModeDiv = d3.select('.directionDiv'); var bottomDiv = d3.select('.bottomControlDiv'); var bottomLength = bottomDiv.style('width').split('px')[0]; var animaLength = animationModeDiv.style('width').split('px')[0]; var leftDistance = (bottomLength - animaLength) / 2; animationModeDiv.styles({ 'margin-left': leftDistance + px }); } function changeOption(d) { console.log(d.fatherID); if (d.fatherID == 3) { optionNumber.nodeLabelOption = parseInt(d.selectID); } else if (d.fatherID == 4) { if (d['selectID'] == 0) nodeOpacityOption = 'uniform'; else if (d['selectID'] == 1) nodeOpacityOption = 'citation'; else if (d['selectID'] == 2) nodeOpacityOption = 'avgCitation'; requestData(); } else if (d.fatherID == 7) { if (d['selectID'] == 0)edgeThickNessOption = 'flowStrokeWidth'; else if (d['selectID'] == 1) edgeThickNessOption = 'citationStrokeWidth'; //requestData(); console.log(1); var edgeBrush = d3.brushX() .extent([[0, -5], [100, 5]]) .on("end", currentLayer.edgeBrushed); currentLayer.edgeAxisX.domain(eDomain[edgeThickNessOption]); gEdgeSizeBarBrush.call(edgeBrush).call(edgeBrush.move, [currentLayer.edgeAxisX(eMin[edgeThickNessOption]), currentLayer.edgeAxisX(eMax[edgeThickNessOption])]); } else if (d.fatherID == 2) { optionNumber.style = d.selectID.toInt(); if (d.selectID == 0) { colorStyle = 'dark'; } else if (d.selectID == 1) { colorStyle = 'light'; } initSetting(colorStyle); initFullScreenAndSizeBar(); gTranslation(); drawFullScreenIcon(gFullScreen, fullScreenButtonTranWidth, fullScreenButtonTranHeight); requestData(); } else if (d.fatherID == 0) { var aminerV8ID = getUrlParam('aminerV8_id'); var citeseerxID = getUrlParam('citeseerx_id'); if (d.selectID == 0) { if (source != 'aminerV8') { var url = 'graph.html?' if (aminerV8ID)url += 'aminerV8_id=' + aminerV8ID + '&'; if (citeseerxID)url += 'citeseerx_id=' + citeseerxID + '&'; url += 'selected=aminerV8'; window.open(url); } } else if (d.selectID == 1) { if (source != 'citeseerx') { var url = 'graph.html?' if (aminerV8ID)url += 'aminerV8_id=' + aminerV8ID + '&'; if (citeseerxID)url += 'citeseerx_id=' + citeseerxID + '&'; url += 'selected=citeseerx'; window.open(url); } } } else if (d.fatherID == 1) { //optionNumber.clusterNum=parseInt(d.cluster); clusterCount = String(d.cluster); requestData(); } } function doubleClick(d){ // console.log(d); // var oldKey=d.oldKey; // $.getJSON('http://'+server+':5001/GetTree/?callback=?',{target:paperID},function(tree){ // incrementalTree=tree; //// console.log(incrementalTree); // processData(data); // // }) } function dragmove(d) { var that = d.that; that.ifDrag = true; that.markerAdjust = false; var pathData = that.pathData; var relation = that.relation; var currentData = that.currentData; var ralation = that.relation; var focusedID = that.focusedID; var data = that.data; var nodes = data.postData[focusedID].node; var edges = data.postData[focusedID].edge; var oldX = d.x; var oldY = d.y; d.x = d3.event.x; d.y = d3.event.y; var x = d.x; var y = d.y; var x1 = x - oldX; var y1 = y - oldY; var delta_x; var delta_y; var k = that.zoomK || 1; for (var i = 0; i < relation[d.id].edges.length; i++) { for (var j = 0; j < edges[relation[d.id].edges[i]].nodes.length; j++) { if (d.id == edges[relation[d.id].edges[i]].nodes[j]) { break; } } var dx = 0; var dy = 0; if (edges[i].dx)dx = edges[i].dx; if (edges[i].dy)dy = edges[i].dy; var points = edges[relation[d.id].edges[i]].points; var length = edges[relation[d.id].edges[i]].points.length; if (j == 1) { points[length - 1].x += d3.event.dx + dx; points[length - 1].y += d3.event.dy + dy; } else { points[j].x += d3.event.dx + dx; points[j].y += d3.event.dy + dy; } var edgeLabelX = (points[0].x + points[length - 1].x) / 2; var edgeLabelY = (points[0].y + points[length - 1].y) / 2; if (d.edgeLabelElem[i]) { d.edgeLabelElem[i].attrs({ x: edgeLabelX, y: edgeLabelY }) } } if (d.focused == 'true')d.self.attrs({x: d.x + d.imageShift / k, y: d.y + d.imageShift / k}); else d.self.attrs({cx: d.x, cy: d.y}); function updatePaths(paths) { paths.forEach(function (path) { path.attr('d', function (d) { return pathData(d, that, k); }) .style("stroke-dasharray", function (d) { var thisEdge = d3.select(this); var edgeLength = thisEdge.node().getTotalLength(); return edgeLength; }); }) } if (d.pathElem) { updatePaths(d.pathElem); } if (d.backgroundPathElem) { updatePaths(d.backgroundPathElem); } if (d.relatedEdges) { updatePaths(d.relatedEdges); } if (d.textElem)for (var i = 0; i < d.textElem.textElem.length; i++) { // console.log(d.textElem.textElem[i].attr("delta_x"),d.textElem.textElem[i].attr("delta_y")); var thisLabel = d.textElem.textElem[i]; var indexStr = thisLabel.attr('index'); var prefix = indexStr.split('_')[0]; var index = indexStr.split('_')[1]; thisLabel.attrs({ x: x, y: y + d[prefix + 'Y'][index] / initDMax * (dMax+dMin-8) / k }); //d.textElem.textElem[i].attrs({ // x:function(d){return x-delta_x;}, // y:function(d){return y-delta_y;} //}) } if (d.idElem) { //delta_x= d.idElem.attr("delta_x"); //delta_y= d.idElem.attr("delta_y"); d.idElem.attrs({ x: x, y: function (d) { return y + d.nodeSizeTextShiftY / k; } }); //d.idElem.attrs({ // x:function(d){return x-delta_x;}, // y:function(d){return y-delta_y;} //}) } //if(d.selfEdgeElem){ // var selfPath=selfPathData(x, y, d.size); // d.selfEdgeElem.attrs({ // d:selfPath // }); //} //if(d.selfEdgeLabelElem){ // var oriX=parseInt(d.selfEdgeLabelElem.attr('x')); // var oriY=parseInt(d.selfEdgeLabelElem.attr('y')); // d.selfEdgeLabelElem.attrs({ // x:oriX+x1, // y:oriY+y1 // }) //} //var str_size= d.size.toString(); // console.log(d.size, str_size.length); // console.log(d.idElem); // console.log(d.textElem.textElem[0].attr("x")); ifDrag = false; } function requestTitleList(d, clusterId) { var yearFilter = this.yearFilter; var source = this.source; var clusterCount = this.clusterCount; var that = this; var rootID = getUrlParam(source + '_id'); var pageSize = 50; var year = 0; var requestData = { page_size: pageSize, year: year, rootID: rootID, clusterCount: clusterCount, selectedCluster: clusterId, source: source, yearFilter: [yearFilter[0], yearFilter[1] - 1] }; var url = 'http://' + server + ':' + port + '/GetCluster/'; var success = function (data) { d.nodes = data; if (currentLayer) { clusterSummary(d); that.nodeList(d); } }; ajax(url, success, requestData); } function processVenue(d) { d.venueList = [] var venueDic = {}; for (var i = 0; i < d.nodeidlist.length; i++) { var id = d.nodeidlist[i]; if (venueList[id]) { if (venueList[id].venue) { var venue = venueList[id]['venue']; if (venueDic[venue])venueDic[venue] += 1; else venueDic[venue] = 1 } } else { for (var key in venueDic) { venueDic[key] += 1; break; } } } for (var venue in venueDic) { d.venueList.push({venue: venue, count: venueDic[venue]}); } d.venueList.sort(function (a, b) { return d3.descending(a.count, b.count) }) // console.log(d.venueList); } function clusterSummary(d) { var rightContent = d3.select('.rightContentDiv'); var rightWidth = rightContent.style('width').split('px')[0]; var rightHeight = rightContent.style('height').split('px')[0]; //console.log('current right content height'+rightHeight) //console.log('current right content width'+rightWidth) // var clusterSummaryHeight=rightHeight*0.13; // var clusterSummaryWidth=rightWidth; // var topMargin=rightWidth*0.05; //processVenue // processVenue(d) // var venueList=d.venueList; d3.select('.CSDTitleDiv').remove(); d3.select('.CSDBodyDiv').remove(); d3.select('.NVDTitleDiv').remove(); d3.select('.NVDBodyDiv').remove(); var clusterSummary = d3.select('.clusterSummaryDiv') .styles({ width: rightWidth + px, height: 'auto', //position:'absolute', //left:0+px, //top:topMargin+px }); var CSDTitleDiv = clusterSummary.append('div') .styles({ //'margin-top':rightWidth*0.05+px //combine with init.js line 297 }) .attr('class', 'CSDTitleDiv'); var CSDBodyDiv = clusterSummary.append('div').attr('class', 'CSDBodyDiv') .styles({ 'margin-top': rightWidth * 0.05 + px }); CSDTitleDiv.append('text') .styles({ 'margin-left': rightMarginLeft + px, 'font-family': 'Arial Black', 'font-size': '16px', 'color': color.panelTitleColor }) .html('<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Selected Group'); CSDBodyDiv.append('div').attr('class', 'clusterInfoDiv').append('text') .styles({ 'margin-left': rightMarginLeft + px, 'margin-top': rightWidth * 0.05 + px, 'font-family': 'Arial ', 'font-size': '14px', 'color': color.panelTitleColor }) .html(function () { return '<b>Group Size: </b>' + d.size; }) CSDBodyDiv.append('div').attr('class', 'clusterInfoDiv').append('div') .styles({ //'word-break':'break-all', 'margin-left': rightMarginLeft + px, 'margin-top': rightWidth * 0.05 + px, 'font-family': 'Arial ', 'font-size': '14px', 'color': color.panelTitleColor }) .append('g') .each(function () { var g = d3.select(this); g.append('text') .html('<b>Content Summary: </b>') g.append('text') .style('display', tfidfStatus) .attr('class', 'tfidfSummary') .html(function () { // if(d.focused=='true'){ //// if(authorData[focusedID]){ //// return '<b>Paper Title: </b>'+authorData[focusedID][0].field+','+authorData[focusedID][1].field; //// } //// else{ //// return '<b>Paper Title: </b>'+authorData['default'][0].field+','+authorData['default'][1].field; //// } // } // else{ var str = ''; var keywords = d.keywords; for (var i = 0, len = keywords.length; i < len; i++) { if (keywords[i]) { if (i != len - 1) { if (i >= 3 && (i + 1) % 4 == 0) { str += keywords[i]; str += ' '; } else { str += keywords[i]; str += ' '; } } else if (i == len - 1) { str += keywords[i]; } } } return keywords.join(', '); //} }) g.append('text') .attr('class', 'freqSummary') .style('display', freqStatus) //.style('visibility','hidden') .html(function () { // if(d.focused=='true'){ //// if(authorData[focusedID]){ //// return '<b>Paper Title: </b>'+authorData[focusedID][0].field+','+authorData[focusedID][1].field; //// } //// else{ //// return '<b>Paper Title: </b>'+authorData['default'][0].field+','+authorData['default'][1].field; //// } // } // else{ var str = ''; var keywords = d.bigrams; for (var i = 0, len = keywords.length; i < len; i++) { if (keywords[i]) { if (i != len - 1) { if (i >= 3 && (i + 1) % 4 == 0) { str += keywords[i]; str += ' '; } else { str += keywords[i]; str += ' '; } } else if (i == len - 1) { str += keywords[i]; } } } return keywords.join(', '); //} }) }) // if(venueList.length>=3){ // CSDBodyDiv.append('div').attr('class','clusterInfoDiv').append('div') // .styles({ // 'margin-left':rightMarginLeft+px, // 'margin-top':rightWidth*0.05+px, // 'font-family':'Arial ', // 'font-size':'14px', // 'color':color.panelTitleColor // }) // .html(function(d){ // // var venueStr='' // for(var i=0;i<3;i++){ // venueStr+=venueList[i].venue+'('+venueList[i].count+')'+' '; // } // return '<b>Venue: </b>'+venueStr // }) // } // CSDBodyDiv.append('div').attr('class','clusterInfoDiv').append('div') // .styles({ // 'margin-left':rightMarginLeft+px, // 'margin-top':rightWidth*0.05+px, // 'font-family':'Arial ', // 'font-size':'14px', // 'color':'white' // }) // .html( // function(){ // return '<b>Max Citation: </b>'+d.nodes[0].citation_count; // } // ) // CSDBodyDiv.append('div').attr('class','clusterInfoDiv').append('div') // .styles({ // 'margin-left':rightMarginLeft+px, // 'margin-top':rightWidth*0.05+px, // 'font-family':'Arial ', // 'font-size':'14px', // 'color':'white' // }) // .html( // function(){ // var len=d.nodes.length; // var sum=0; // var avg; // for(var i= 0;i<len;i++){ // if(parseInt(d.nodes[i].citation_count)>0){ // sum+=parseInt(d.nodes[i].citation_count); // } // } // avg = sum/len; // return '<b>Average Citation: </b>'+avg.toFixed(2); // } // ) } function nodeList(d) { var that = this; var nodeValue = that.nodeValue; // console.log(d.id); // nodeValue(d); selectedNode = d.id; var CSDHeight = d3.select('.clusterSummaryDiv')._groups[0][0].offsetHeight; var leftDiv = d3.select('.rightContentDiv'); var leftHeight = leftDiv.style('height').split('px')[0]; var leftWidth = leftDiv.style('width').split('px')[0]; var leftContentWidth = d3.select('.leftTopBarDiv').style('width').split('px')[0]; var leftTransitionWidth = leftWidth - leftContentWidth; // var leftTransitionWidth=d3.select('.leftTransitionTopBarDiv').style('width').split('px')[0]; // var ruler=d3.select('.ruler'); // console.log(leftWidth,leftContentWidth,leftTransitionWidth); var fontFamily = 'Arial Black'; var fontSize = 16; // ruler.styles({ // 'font-family':'Arial Black', // 'font-size':'16px' // }); var title = 'Selected Papers'; var titleHeight = title.visualHeight(fontFamily, fontSize); var LeftRatio = 0.114; var titleTopRatio = 0.114; var bodyMargin = 0.03 * leftWidth; d3.select('.NLDTitleDiv').remove(); d3.select('.NLDTransitionDiv').remove(); d3.select('.NLDBodyDiv').remove(); var nodeList = d3.select('.nodeListDiv') .styles({ height: '60%', //height:leftHeight-CSDHeight+px, 'margin-top': leftWidth * 0.05 + px }) //.styles({ // 'margin-top':50+px //}) // .attr('onkeydown','keyboardEvent(event.keyCode||event.which);') // .attr('tabindex',1); var leftRatio = (leftContentWidth / leftWidth) * 100; var transitionRatio = 100 - leftRatio; var transitionMethod = '-webkit-linear-gradient'; var NLDBodyBackground = transitionBackground(transitionMethod, 'left', transitionRatio, color.mainTransition1, color.mainTransition2) //console.log(NLDBodyBackground); //NLDBodyBackground='-webkit-linear-gradient(left,rgb(50,70,90) 0%,rgb(50,70,90) '+leftRatio+'%,rgb(50,70,90) '+leftRatio+'%,rgb(25,35,45) 100%)' // var NLDBodyBackground1='-webkit-linear-gradient(left,rgb(50,70,90) 0%,rgb(50,70,90) '+leftRatio+'%,rgb(143, 162, 168) '+leftRatio+'%,rgb(74, 90, 103) 100%)' var NLDTitleDiv = nodeList.append('div').attr('class', 'NLDTitleDiv') .styles({ // float:'left', background: NLDBodyBackground, // position:'absolute', width: leftWidth + px, height: titleHeight + px // left:leftWidth*LeftRatio+px, // top:leftWidth*titleTopRatio+px }); var NLDBodyDiv = nodeList.append('div').attr('class', 'NLDBodyDiv') .on('mouseover', function () { var thisDiv = d3.select(this); thisDiv.styles({ // background:NLDBodyBackground1, 'overflow-y': 'scroll' }); // console.log(thisDiv); // console.log(this); }) .on('mouseout', function () { var thisDiv = d3.select(this); thisDiv.styles({ // background:NLDBodyBackground, 'overflow-y': 'hidden' }) }) .styles({ // position:'absolute', 'overflow-y': 'hidden', 'overflow-x': 'hidden', background: NLDBodyBackground, width: leftWidth + px, //height:leftHeight-titleHeight-CSDHeight+px height: '100%' // 'margin-left':leftWidth*LeftRatio+px // top:leftWidth*titleTopRatio+leftWidth*0.1+px }); var listData = []; var pageSize = 50; if (d.nodes.length < pageSize)pageSize = d.nodes.length; for (var i = 0; i < pageSize; i++) { listData[i] = {}; listData[i].paperID = d.nodes[i].id; listData[i].paperTitle = d.nodes[i].title; } NLDTitleDiv.append('text') .styles({ 'margin-left': leftTransitionWidth + px, 'font-family': 'Arial Black', 'font-size': '16px', 'color': color.panelTitleColor }) .html(title); for (var i = 0, length = listData.length; i < length; i++) { var TitleDiv = NLDBodyDiv.append('div') .attr('class', 'nodeTitleDiv') .attr('id', function () { maxListID = i; return 'listID' + i; }) .attr('paperID', listData[i].paperID) .attr('cursor', 'hand') .styles({ width: leftWidth + px, height: 'auto', background: color.mainTransition2 // 'margin-bottom':bodyMargin+px }) .on('click', nodeValue); // .each(function(d,i){ // if(i==0){ // var thisDiv=d3.select(this); // thisDiv.attr('id','firstPaper'); // } // }) // NLDTitleDiv.append('div') // .styles({ // float:'left', // background:'rgb(50,70,90)', // width: // }) var textDiv = TitleDiv.append('div') .attr('class', 'leftTextDiv') .styles({ float: 'right', background: color.mainTransition2, width: leftContentWidth - leftTransitionWidth + px, 'margin-top': bodyMargin / 2 + px, 'margin-right': leftTransitionWidth + px }); textDiv.append('text') .attr('class', 'nodeTitleText') .attr('style', 'cursor: pointer; fill: rgb(0, 0, 0);') .styles({ 'font-family': 'Microsoft YaHei', 'font-size': '14px', 'color': color.panelTitleColor }) .html(listData[i].paperTitle); // console.log(textDiv[0][0].offsetHeight); var transitionHeight = textDiv._groups[0][0].offsetHeight; TitleDiv.styles({ height: transitionHeight + bodyMargin + px }) var transitionDiv = TitleDiv.append('div') .attr('class', 'leftTransitionDiv') .styles({ float: 'right', width: leftTransitionWidth + px, height: transitionHeight + bodyMargin + px, 'background-image': '-webkit-linear-gradient(right, ' + color.mainTransition2 + ',' + color.mainTransition1 + ')' }) if (i < length - 1) { var leftAndTransitionLineDiv = NLDBodyDiv.append('div') .attr('id', function () { return 'lineID' + i; }) .styles({ width: leftWidth + px, height: 1 + px }); var leftLineDiv = leftAndTransitionLineDiv.append('div') .attr('class', 'leftLineDiv') .styles({ float: 'right', width: leftContentWidth - leftTransitionWidth + px, height: 1 + px, background: color.greyBarTransition2, 'margin-right': leftTransitionWidth + px // 'margin-bottom':bodyMargin+px }); var leftTransitionLineDiv = leftAndTransitionLineDiv.append('div') .attr('class', 'leftTransitionLineDiv') .styles({ float: 'right', width: leftTransitionWidth + px, height: 1 + px, 'background-image': '-webkit-linear-gradient(right, ' + color.mainTransition2 + ',' + color.mainTransition1 + ')' }) } } var firstPaper = document.getElementById('listID0'); // console.log(firstPaper.id); selectedID = 0; // var firstPaper=d3.select("#firstPaper"); firstPaper.click(); // .on('click',nodeValue); } function nodeValue(d) { ///* var rightContent = d3.select('.leftAndTransitionContentDiv'); var rightWidth = rightContent.style('width').split('px')[0]; var rightHeight = rightContent.style('height').split('px')[0]; var marginBottom = rightWidth * 0.114; function DivRender() { this.highLight = color.divRender.highlight; this.recovery = color.divRender.recovery; this.manner = ''; this.render = function (div, lineDiv) { var styleData; if (this.manner == 'highLight') { styleData = this.highLight; } else if (this.manner == 'recovery') { styleData = this.recovery; } var titleDiv = div.select('.leftTextDiv'); var transitionDiv = div.select('.leftTransitionDiv'); var text = titleDiv.select('.nodeTitleText'); text.styles({ color: styleData.textColor }) div.styles({ background: styleData.bodyDivBackground }); titleDiv.styles({ background: styleData.titleDivBackground }); transitionDiv.styles({ 'background-image': styleData.transitionDivBackground }); for (var i = 0; i < 2; i++) { if (lineDiv[i]._groups[0][0]) { var leftLine = lineDiv[i].select('.leftLineDiv'); var leftTransition = lineDiv[i].select('.leftTransitionLineDiv'); lineDiv[i].styles({ background: styleData.lineBackground }); leftLine.styles({ background: styleData.leftLineBackground }); leftTransition.styles({ 'background-image': styleData.transitionLineBackground }) } } } } var render = new DivRender(); var selectedDiv = d3.select('#listID' + selectedID); var selectedLine = [d3.select('#lineID' + (selectedID - 1)), d3.select('#lineID' + selectedID)]; render.manner = 'recovery'; render.render(selectedDiv, selectedLine); // .style('background','rgb(50,70,90)') var thisDiv = d3.select(this); var paperID = thisDiv.attr('paperid'); var url = 'http://' + server + ':' + port + '/GetNode/'; var success = function (data) { //if(typeofObj(data)=='[object String]')data = JSON.parse(data); var paper = data; var id = parseInt(thisDiv.attr('id').split('D')[1]); var thisLine = [d3.select('#lineID' + (id - 1)), d3.select('#lineID' + id)]; render.manner = 'highLight'; render.render(thisDiv, thisLine); selectedID = id; // thisDiv.style('background','#34b9f7'); // } // console.log(nodes[selectedNode].nodes[thisDiv.attr('listId')]); // console.log(thisDiv.attr('listId')); d3.select('.NVDTitleDiv').remove(); d3.select('.NVDBodyDiv').remove(); // console.log(thisDiv); // var text=thisDiv.select('text'); var title = paper.title; var abstract = paper.abstract; var authors = paper.authors; var year = paper.year; var citation = paper.citation; var field = paper.field; var venue = paper.venue; // console.log(title); var nodeValue = d3.select('.nodeValueDiv') .styles({ 'margin-right': rightMarginLeft + px, //position:'absolute', width: rightWidth, height: '100%', 'margin-top': 0 + px }); // var NVDTitleDiv=nodeValue.append('div').attr('class','NVDTitleDiv'); var NVDTitleDiv = nodeValue.append('div').attr('class', 'NVDTitleDiv'); NVDTitleDiv.append('text') .styles({ 'font-family': 'Arial Black', 'font-size': '16px', 'color': color.panelTitleColor }) .html('Selected Paper'); var NVDBodyDiv = nodeValue.append('div').attr('class', 'NVDBodyDiv'); var textList = ['Title: ', 'Authors: ', 'Year: ', 'Citation: ', 'Venue: ', 'Abstract: ']; var valueList = [title, authors, year, citation, venue, abstract]; for (var i = 0, length = textList.length; i < length; i++) { var newDiv = NVDBodyDiv.append('div') .attrs({ class: 'nodeValueItemDiv' }) .styles({ 'margin-top': 10 + px }) .append('text') .styles({ 'font-family': 'Arial Black', 'font-size': '14px', 'color': color.panelTitleColor }) .html(textList[i]); newDiv.append('text') .styles({ 'font-family': 'Microsoft YaHei', 'font-size': '14px', 'color': color.panelTitleColor }) .html(valueList[i]); } var safeHeight = rightHeight * 3 / 5; var NVDHeight = d3.select('.NVDBodyDiv')._groups[0][0].offsetHeight; if (NVDHeight > safeHeight) { NVDBodyDiv.styles({ height: '90%', overflow: 'hidden' }) .on('mouseover', function () { d3.select(this).style('overflow-y', 'scroll'); }) .on('mouseout', function () { d3.select(this).style('overflow', 'hidden'); }) } } var source = currentLayer.source; ajax(url, success, {id: paperID, source: source}); //*/ } function reverseData(){ // if(dataType=='multiple'){ // for (var j=0;j<json_edges_list.length;j++){ // reverseXY(json_nodes_list[j],json_edges_list[j]); // } // } // else{ // reverseXY(nodes,edges); // } reverseXY(data.postData[focusedID]); } function changeColor(text,thisDivClass){ var anotherText; if (thisDivClass=='horizontal'){ anotherText=d3.select('.verticalText'); } else{ anotherText=d3.select('.horizontalText'); } var color=text.style('color'); if(color=='rgb(128, 128, 128)'){ text.style('color','rgb(255, 255, 255)'); anotherText.style('color','rgb(128, 128, 128)'); // .each(function(d){ // if(d.style('color')=='rgb(128, 128, 128)')d.style('color','rgb(255, 255, 255)'); // else if(d.style('color')=='rgb(255, 255, 255)')d.style('color','rgb(128, 128, 128)'); // }) } } function reverse() { var thisDiv=d3.select(this); var thisDivClass=thisDiv.attr('class'); var text=thisDiv.select('text'); if(thisDivClass=='horizontal'&currentDirection=='vertical'){ currentDirection='horizontal'; selectedReverse=1; } else if(thisDivClass=='vertical'&currentDirection=='horizontal'){ selectedReverse=0; currentDirection='vertical'; } changeColor(text,thisDivClass); reverseData() coordinateOffset(data.postData[focusedID]); getCurves(data.postData[focusedID]); clear(); layout(optionNumber,true,'flowMap',data.postData[focusedID]); } function reverseXY(d){ var nodes=d.node; var edges=d.edge; for (var i=0;i<nodes.length;i++){ var t=nodes[i].x; nodes[i].x=nodes[i].y; nodes[i].y=t; } // for (var i=0;i<curves.length;i++){ // for (var j=0;j<curves[i].points.length;j++){ // var t=curves[i].points[j].x; // curves[i].points[j].x=curves[i].points[j].y; // curves[i].points[j].y=t; // } // } for (var i=0;i<edges.length;i++){ for(var j=0;j<edges[i].assists.length;j++){ var t=edges[i].assists[j][0]; edges[i].assists[j][0]=edges[i].assists[j][1]; edges[i].assists[j][1]=t; } } } function clear(){ svg.selectAll('.node').remove(); svg.selectAll('path').remove(); svg.selectAll('text').remove(); } function yearSliderDragMove(d){ var that= d.that; var data=that.data; var animateMode=that.animateMode; var xScale=that.xScale; var yScale=that.yScale; var axisSVG=that.axisSVG; var focusedID=that.focusedID; var nodeYearData=data.postData[focusedID].nodeYearData; var maxYear=nodeYearData.maxYear; var minYear=nodeYearData.minYear; if(animateMode==flipBook){ d.x=d3.event.x; var thisNode=d3.select(this); if(thisNode.attr('id')=='leftAxisCircle'){ if(d.x>=xScale(minYear)&&d.x<=parseFloat(axisSVG.select('#rightAxisCircle').attr('cx'))){ thisNode.attr('cx',d.x); } } else{ if(d.x>=parseFloat(axisSVG.select('#leftAxisCircle').attr('cx'))&& d.x<=xScale(maxYear)){ thisNode.attr('cx',d.x); } } } else if(animateMode='movie'){ var thisObj=d3.select(this); var rightAxisCircle=axisSVG.select('#rightAxisCircle'); var leftAxisCircle=axisSVG.select('#leftAxisCircle'); var movieSlider=axisSVG.select('.movieSlider'); var rx=parseFloat(rightAxisCircle.attr('cx')); var lx=parseFloat(leftAxisCircle.attr('cx')); var dx=d3.event.dx; var id=thisObj.attr('id'); if((id == 'rightAxisCircle'&& rx<=xScale(maxYear)) && rx>=lx&&lx!=rx||(id == 'leftAxisCircle'&& lx>=xScale(minYear)&&lx<=rx&&lx!=rx)){ if(thisObj.attr('class')!='movieSlider'){ thisObj .attrs({ cx:function(d){ d.x = d.x+dx; return d.x; } }); if(id == 'leftAxisCircle'){ movieSlider.attrs({ d:function(d){ d.p1.x+=dx; return yearSliderPathData(d); } }) } else{ movieSlider.attrs({ d:function(d){ d.p2.x+=dx; return yearSliderPathData(d); } }) } } } else if(id =='movieSlider'||lx == rx){ if(lx>=xScale(minYear)&&rx<=xScale(maxYear)){ axisSVG.selectAll('.axisCircle') .attrs({ cx:function(d){ d.x = d.x+dx; return d.x; } }); movieSlider.attrs({ d:function(d){ d.p1.x+=dx; d.p2.x+=dx; return yearSliderPathData(d); } }) } } } } function yearSliderDragStart(d){ // var thisNode=d3.select(this); // thisNode.style('fill',color.yearSliderHighlightColor); } function yearSliderDragEnd(d){ var that= d.that; // var thisNode=d3.select(this); // thisNode.style('fill',color.yearSliderColor); adjustSliderPosition(false, that); // if(animateMode=='movie'){ updateAnimation(true,that); // } // play() } function adjustSliderPosition(measure,that){ var direction=''; var endYear; var yearFilter=that.yearFilter; var axisSVG=that.axisSVG; var minYear=that.minYear; var maxYear=that.maxYear; var duration=yearFilter[1]-yearFilter[0]; var xScale=that.xScale; var yScale=that.yScale; var yearPosition=that.yearPosition; //var lx,rx; axisSVG.selectAll('.axisCircle') .each(function(d){ var thisNode=d3.select(this); var id= d.id; var x=parseFloat(thisNode.attr('cx')); if(measure=='stop'){ that.yearFilter=[minYear,minYear+duration]; if(id == 'leftAxisCircle'){ thisNode.attrs({ cx:function(d){d.x = xScale(that.yearFilter[0]);lx = d.x;return d.x;} }) } else{ thisNode.attrs({ cx:function(d){d.x = xScale(that.yearFilter[1]);rx = d.x;return d.x;} }) } } else{ for(var year in yearPosition){ if(x>=yearPosition[year][0]&&x<yearPosition[year][1]){ endYear=year; if(xScale(year)>x){ direction='right'; } else{ direction='left'; } if(id == 'leftAxisCircle'){ that.yearFilter[0]=year.toInt(); lx = xScale(year); } else{ that.yearFilter[1]=year.toInt(); rx = xScale(year); } d.x=xScale(year); thisNode.attrs({ cx:d.x }); break; } } } }); axisSVG.select('.movieSlider') .transition() .duration(100) .attr('d',function(d){ d.p1.x = lx; d.p2.x = rx; return yearSliderPathData(d); }); return {year:endYear,direction:direction}; } function yearSliderPathData(d){ return 'M' + d.p1.x + ' ' + d.p1.y + 'L' + d.p2.x + ' ' + d.p2.y } function nodeClick(d,that){ console.log(d); var axisSVG=that.axisSVG; var svg=that.svg; var data=that.data; var nodeClass=d.self.attr('class'); var focusedID=that.focusedID; if(nodeClass=='node') { d.self.attr('class','node clicked'); d.self.style('stroke',color.nodeHighlightStroke); d.self.style('stroke-width', function (d) { d.strokeWidth=2; return d.strokeWidth; }); d.self.style('fill',color.nodeHighlightColor); if(d.textElem)for(var i=0;i<d.textElem.textElem.length;i++){ d.textElem.textElem[i] .styles({ 'fill':color.nodeLabelHighlightColor }); } // } else if(nodeClass=='node clicked'){ // d.self.style('stroke','rgb(0,220,225)'); d.self.style('fill',function(d){return "url(#linearGradient"+ d.id+")"}); d.self.style('stroke',color.nodeHighlightStroke); d.self.style('stroke-width', function (d) { d.strokeWidth=0; return d.strokeWidth; }); d.self.attr('class','node'); if(d.textElem)for(var i=0;i<d.textElem.textElem.length;i++){ d.textElem.textElem[i].styles({ 'fill':color.nodeLabelColor, // 'stroke':'none', // 'stroke-width':0+px }); } // } svg.selectAll('.linearGradient') .each(function(){ d3.select(this).selectAll('stop') .each(function(d,i){ var thisStop=d3.select(this); if(i == 1||i == 2)thisStop.attr('offset',0); }) }) axisSVG.selectAll('.yearPath') .each(function(){ d3.select(this).style('fill',color.yearPathColor); // d3.select(this).style('stroke',color.); d3.select(this).attr('class','yearPath'); }) var clusterID=d.oldKey; var yearPath=d3.selectAll('.yearPath'); var yearDic=d.newNodeYearInfo; var subNodeYearData=[]; if(data.postData[focusedID].subNodeYearData){ subNodeYearData=data.postData[focusedID].subNodeYearData; } else{ clone(data.postData[focusedID].nodeYearData.data,subNodeYearData) for (var i=0;i<subNodeYearData.length;i++){ subNodeYearData[i][1]=0; } } var subNodeYearDic={}; for(var i=0;i<subNodeYearData.length;i++){ var key=subNodeYearData[i][0]; var value=subNodeYearData[i][1]; subNodeYearDic[key]=value; } axisSVG.selectAll('.subYearPath').remove(); if(d.clicked){ for(var key in yearDic){ subNodeYearDic[key]-=yearDic[key]; } var tmpData=[] for(var key in subNodeYearDic){ tmp=[key, subNodeYearDic[key]] tmpData.push(tmp); } data.postData[focusedID].subNodeYearData=tmpData; d.clicked=false; that.drawNodeYearDataSet(data.postData[focusedID].subNodeYearData,'subYearPath') that.recoveryPath(d); } else{ for(var key in yearDic){ subNodeYearDic[key]+=yearDic[key]; } var tmpData=[] for(var key in subNodeYearDic){ tmp=[key, subNodeYearDic[key]] tmpData.push(tmp); } data.postData[focusedID].subNodeYearData=tmpData; d.clicked=true; that.drawNodeYearDataSet(data.postData[focusedID].subNodeYearData,'subYearPath') that.highlightPath(d); } // console.log(d); that.requestTitleList(d, clusterID); } function ifObjectHasProperty(obj){ var flag=false; for(var key in obj){ flag=true; break } return flag } function recoveryPath(d){ var directedGraph=this.directedGraph; var currentEdgeSourceTargetDic=this.currentEdgeSourceTargetDic; var thisID=parseInt(d.id) var rootID=directedGraph.root.id.toInt(); var backPath=directedGraph.findMaxPathBetween(rootID,thisID); if(backPath.length>0){ for(var i=0;i<backPath[0].edges.length;i++){ var edge=backPath[0].edges[i]; var source=edge.source; var target=edge.target; var key=source+'_'+target; var currentEdges=[]; if(currentEdgeSourceTargetDic[key]){ currentEdges=currentEdgeSourceTargetDic[key]; for(var j=0;j<currentEdges.length;j++){ if(currentEdges[j].highlightedByNodeDic[thisID]){ delete currentEdges[j].highlightedByNodeDic[thisID]; } if(!ifObjectHasProperty(currentEdges[j].highlightedByNodeDic)){ var pathClass='.'+currentEdges[j].class; var path=d3.select(pathClass) .each(function(d){ d.levelIndex=0 }) .styles({ stroke:color.edgeColor }); var pathMarker=path.data()[0].marker; pathMarker.styles({ fill:color.markerColor }); } } } } } } function highlightPath(d){ var that=this; var directedGraph=this.directedGraph; var currentEdgeSourceTargetDic=this.currentEdgeSourceTargetDic; var thisID=parseInt(d.id); var rootID=directedGraph.root.id.toInt(); var backPath=directedGraph.findMaxPathBetween(rootID,thisID); if(backPath.length>0){ for(var i=0;i<backPath[0].edges.length;i++){ var edge=backPath[0].edges[i]; var source=edge.source; var target=edge.target; var key=source+'_'+target; var currentEdges=[]; if(currentEdgeSourceTargetDic[key]){ currentEdges=currentEdgeSourceTargetDic[key]; for(var j=0;j<currentEdges.length;j++){ if(currentEdges[j].highlightedByNodeDic){ currentEdges[j].highlightedByNodeDic[thisID]=1; } else{ currentEdges[j].highlightedByNodeDic={}; currentEdges[j].highlightedByNodeDic[thisID]=1; } var pathClass='.'+currentEdges[j].class; var path=d3.select(pathClass) .each(function(d){ d.levelIndex=1 }) .styles({ stroke:color.edgeHightLightColor }); if(path.data()[0].marker){ var pathMarker=path.data()[0].marker; pathMarker.styles({ fill:color.edgeHightLightColor }); } } } } that.drawedges.select('.edgeField').selectAll('path') .sort(function(a,b){ return d3.ascending(a.levelIndex,b.levelIndex); }); } } function mouseover(d,that){ var k=leftLayer.zoomK||1; var transitionFlag=that.transitionFlag; if(transitionFlag==false){ function changeNode(d,that,changePath){ if(d&&d.self){ d.self.style('stroke',color.nodeHighlightStroke); d.self.style('stroke-width', function (d) { d.strokeWidth=2; return d.strokeWidth/k; }); } if(d&&d.textElem){ for(var i=0;i<d.textElem.textElem.length;i++){ d.textElem.textElem[i] .styles({ 'fill':color.nodeLabelHighlightColor //visibility: function () { // if(d.textElem.textElem[i]._groups[0][0].classList[2]=='tfidf'){ // return 'hidden'; // } // else return null; //} // 'stroke':color.nodeLabelHighlightStroke, // 'stroke-width':1+px }); //.attr('x',function(e){return e.x+ e.fullLabelDeltaX/k;}) //.html(function(e){return e.nodeFullName;}); } } if(d&&d.pathElem&&changePath){ for(var i=0;i<d.pathElem.length;i++){ d.pathElem[i].each(function (p) { if(!p.isBackgroundEdge){ var self=d3.select(this); self.style('stroke',color.edgeHightLightColor); self.style('visibility','visible'); p.levelIndex=1; if(p.marker){ p.marker.style('fill',color.edgeHightLightColor); p.marker.style('visibility','visible'); } } }) } that.drawedges.select('.edgeField').selectAll('path') .sort(function(a,b){ return d3.ascending(a.levelIndex,b.levelIndex); }); } if(d&&d.idElem)d.idElem.style('fill',color.sizeLabelColor); } changeNode(d,that,true); d.sourceNodes.forEach(function (node) { changeNode(node,that); }); d.targetNodes.forEach(function(node){ changeNode(node,that); }); } } function mouseout(d,that){ var k=leftLayer.zoomK||1; var transitionFlag=that.transitionFlag; if(transitionFlag==false){ function changeNode(d,that,changePath){ var thisnode=d3.select(this); if(d&&d.self&&d.self.attr('class')=='node'){ d.self.style('stroke','none'); d.self.style('stroke-width', function (d) { d.strokeWidth=0; return d.strokeWidth; }); if(d.idElem)d.idElem.style('fill',color.sizeLabelColor); if(d.textElem)for(var i=0;i<d.textElem.textElem.length;i++){ d.textElem.textElem[i] .styles({ 'fill':color.nodeLabelColor //visibility: function () { // if(d.textElem.textElem[i]._groups[0][0].classList[2]=='tfidf'){ // return null; // } // else return 'hidden'; //} }) //.attr('x',function(e){return e.x+ e.labelDeltaX/k;}) //.html(function(e){return e.nodeName;}); } } else{ if(d&&d.textElem)for(var i=0;i<d.textElem.textElem.length;i++){ //d.textElem.textElem[i] // .attr('x',function(e){return e.x+ e.labelDeltaX/k;}) // .html(function(e){return e.nodeName;}); } } if(d&&d.pathElem&&changePath){ for(var i=0;i<d.pathElem.length;i++){ d.pathElem[i].each(function (p) { if(!p.isBackgroundEdge){ var self=d3.select(this); if (p.marker) { p.marker.style('fill', color.markerColor); p.marker.style('visibility', 'hidden'); } if (!ifObjectHasProperty(self.data()[0].highlightedByNodeDic)) { self.style('stroke', color.edgeColor); self.style('visibility','hidden'); } } }); } } that.drawedges.select('.edgeField').selectAll('path') .each(function(d){ d.levelIndex=0 }); } changeNode(d,that,true); d.sourceNodes.forEach(function (node) { changeNode(node,that); }); d.targetNodes.forEach(function(node){ changeNode(node,that); }); } } function drawBackgroundYear(transition){ // var initX=300; // var initY=250; var dataSourceVisibility=this.dataSourceVisibility; var focusedID=this.focusedID; var time_g=this.time_g; var yearFilter=this.yearFilter; var animateMode=this.animateMode; var minYear=this.minYear; var maxYear=this.maxYear; var initX=30; var initY=30; var family='Arial'; var size='30'; var weight='bold'; var color='grey'; var textValue; if(focusedID.split('_')[0]=='twitter'){ var july='July'; var julyLen=july.visualLength(family,size); time_g.append('text') .attrs({ class:'july', x:initX, y:initY }) .styles({ 'font-size':size, 'font-family': family, 'font-weight':weight, 'fill':color }) .html(july) initX+=julyLen+20; // textValue=['July'+yearFilter[0]+' ',' - ',' July'+yearFilter[1]]; } // else{ textValue=[String(yearFilter[0]),' - ',String(yearFilter[1]-1)]; // } var textData=[ { type:'leftYear', value:textValue[0], x:initX, y:initY, size:size, family:family, weight:weight, color:color }, { type:'middleText', value:textValue[1], x:initX+textValue[0].visualLength(family,size), y:initY, size:size, family:family, weight:weight, color:color }, { type:'rightYear', value:textValue[2], x:initX+textValue[0].visualLength(family,size)+textValue[1].visualLength(family,size), y:initY, size:size, family:family, weight:weight, color:color } ]; var yearLength='2000-2000'.visualLength(family,size); var yearHeight='2000-2000'.visualHeight(family,size); var sourceText=this.sourceTextDic[this.source]; var sourceLength=sourceText.visualLength(family,size); var sourceX=initX+yearLength/2-sourceLength/2; var sourceY=initY+yearHeight+5; if(transition){ if(animateMode==flipBook){ time_g.select('.rightYear') .html(function(d){ if(yearFilter[1]==maxYear&&yearFilter[0]==minYear){ d.value=String(minYear); } else{ d.value=String(yearFilter[0]-1); } return d.value; }) .transition() .ease(d3.easeLinear) .delay(1000) .duration(function(d){ if(yearFilter[1]==maxYear&&yearFilter[0]==minYear){ return 2000*(maxYear- minYear) } else{ return 2000*(maxYear- yearFilter[0]) } }) .tween("text", function() { var that = d3.select(this); if(yearFilter[1]==maxYear&&yearFilter[0]==minYear){ var i = d3.interpolateRound(minYear, maxYear); return function(t) { that.text(i(t)); }; } else{ var i = d3.interpolateRound(yearFilter[0]-1, maxYear); return function(t) { that.text(i(t)); }; } }) } else{ } } else{ time_g.selectAll('*') .each(function(d){ if(d3.select(this).attr('class')!='july'){ d3.select(this).remove() } }); time_g.append('text') .styles({ 'font-family':family, 'font-size':size, 'font-weight':weight, fill:color, visibility:dataSourceVisibility }) .attrs({ class:'dataSource', x:sourceX, y:sourceY }) .html(sourceText); time_g.selectAll('whatever') .data(textData) .enter() .append('text') .each(function(d){ d3.select(this) .attrs({ class:d.type, x:d.x, y:d.y }) .styles({ 'font-size':d.size, 'font-family': d.family, 'font-weight':d.weight, 'fill':d.color }) .html(d.value) }) } } function getEdgeScale(edges, type) { var edgeFlowList = []; var edgeWeightList = []; var edgeCitationList = []; for (var i = 0; i < edges.length; i++) { edgeFlowList.push(edges[i].flow); edgeCitationList.push(edges[i].citation); var weightSum = 0; for (var key in edges[i].weight) { weightSum += edges[i].weight[key]; } edgeWeightList.push(weightSum); } var range = [eMin[edgeThickNessOption], eMax[edgeThickNessOption]]; var flowScale = d3.scaleLinear() .domain([d3.min(edgeFlowList), d3.max(edgeFlowList)]) .range(range); var weightScale = d3.scaleLinear() .domain([d3.min(edgeWeightList), d3.max(edgeWeightList)]) .range(range); var uniformScale = function () { return 2; }; var scaleDic = { 'weight': weightScale, 'flow': flowScale, 'citation': weightScale, 'uniform': uniformScale }; return scaleDic[type]; } function drawEdges(optionNumber, doTransition, transitionType, d) { this.pathElem = []; this.tmpEdgeAssistCount = 0; var that = this; var pathElem = this.pathElem; var tmpEdgeAssistCount = this.tmpEdgeAssistCount; var data = this.data; var focusedID = this.focusedID; var drawedges = this.drawedges; var nodes = d.node; var edges = d.edge; var k = this.zoomK || 1; var pathData = this.pathData; var duration = this.duration; var screenPreEdges = data.screenPreviousData[focusedID].edge; var edgeFlowList = []; var edgeWeightList = []; var edgeLabelElem = this.edgeLabelElem; var drawEdgeLabel = this.drawEdgeLabel; for (var i = 0; i < edges.length; i++) { edges[i].transitionCount = 0; edgeFlowList.push(edges[i].flow); var weightSum = 0; for (var key in edges[i].weight) { weightSum += edges[i].weight[key]; } edgeWeightList.push(weightSum); } if (!(that.flowScale) && !(that.flowScale)) { that.flowScale = d3.scaleLinear() .domain([d3.min(edgeFlowList), d3.max(edgeFlowList)]) .range([2, 6]); that.weightScale = d3.scaleLinear() .domain([d3.min(edgeWeightList), d3.max(edgeWeightList)]) .range([2, 6]); } var markerSize = 25; var g = drawedges.append('g').attr('class', 'edgeField'); var markerG = drawedges.append('g').attr('class', 'markerField'); var currentLevel = drawedges.attr('id'); var svgEdges = g.selectAll('path.curves') .data(edges) .enter() .append('path') .attrs({ class: function (d, i) { d.levelIndex = 0; d.class = currentLevel + 'path' + i; return d.class; }, id: function (d) { var yearID = ''; for (var key in d.weight) { yearID += key + '_'; } return yearID; }, year: function (d) { return d.year; }, source: function (d) { return d.source; }, target: function (d) { return d.target; } }) .style("opacity", function (d) { if (d.edgeType == 'dash') { return 0.2; } }) .style("visibility", function (d) { if (d.isForegroundSourceEdge || d.isForegroundTargetEdge || d.isNontreeEdge) { return 'hidden'; } //if(d.isBackgroundEdge || d.isNontreeEdge) { // return 'hidden'; //} //else if(d.isForegroundSourceEdge){ // return 'hidden'; // //return 'visible'; //} //else if(d.isForegroundTargetEdge){ // //return 'hidden'; // return 'visible'; //} else { return 'visible'; } }) .style("stroke", color.edgeColor) .style('fill', 'none') .style("stroke-width", function (d) { d.that = that; d.strokeWidth = d.ratio * d[edgeThickNessOption]; return d.strokeWidth / k; }) .each(function (d, i) { d.that = that; var stroke = d.ratio * d[edgeThickNessOption] || 1; var size = 13 / (stroke); var marker = markerG.append("svg:defs").selectAll("marker") .data([{marker: 1}]) .enter().append("svg:marker") .attr("id", function (d) { d.id = currentLevel + "markerArrow" + i + '_' + that.focusedID; return d.id; }) .attr('class', 'marker') .attr("viewBox", "0 0 10 10") .attr("refX", 0) .attr("refY", 4) .attr("markerWidth", size) .attr("markerHeight", size) .attr("orient", 'auto') .append("svg:path") // .attr("d", "M0,3 L0,8 L8,3 L0,3") .attr("d", "M0,0 L0,8 L8,4 L0,0") .style("fill", color.markerColor); var thisEdge = d3.select(this); d.self = thisEdge; marker.style("visibility", "hidden"); d.marker = marker; thisEdge.attr("marker-end", function () { return "url(#" + currentLevel + "markerArrow" + i + '_' + that.focusedID + ")" }); pathElem.push(d); }); if (doTransition) { g.selectAll('path') .each(function (d) { d.marker.style('fill', 'none') }); g.selectAll('path') .attr('d', function (d) { return pathData(d, that); }); g.selectAll('path') .each(function (d) { //if(d.isBackgroundEdge) { // d3.select(this).style('visibility', 'hidden'); //} if(d.isBackgroundEdge){ d.transitionCount = that.yearFilter[0] - d.flipBookStartYear; var thisPath=d3.select(this); var pathLength=thisPath.node().getTotalLength(); var oldStrokeWidth; var newStrokeWidth=0; pathLength=parseInt(pathLength); thisPath .styles({ 'stroke-dasharray': function () { return pathLength; }, 'stroke-dashoffset': function () { return pathLength; }, 'stroke-width': 0, 'fill': 'none' }) .transition() .duration(0) .delay(1000) .ease(d3.easeLinear) .on('start', function repeat() { if(d.transitionCount+ d.flipBookStartYear> d.flipBookEndYear){ thisPath.style('stroke-width',d[edgeThickNessOption]) .style('stroke-dashoffset',0); d3.selectAll('.transitionPath').remove(); currentLayer.svg.select('.edgeField').selectAll('path') .each(function (d) { if(d.isBackgroundEdge) { d3.select(this) .style('visibility','visible'); } }); return; } var yearKey= d.flipBookStartYear+'_'+(d.flipBookStartYear+ d.transitionCount); oldStrokeWidth=newStrokeWidth; newStrokeWidth= d.flipBookRatio[yearKey]* d[edgeThickNessOption]; d.transitionCount+=1; var pathD=thisPath.attr('d'); var newPath=g.append('path') .attrs({ d:pathD, class:'transitionPath' }) .styles({ //'stroke-dasharray': function () { // return pathLength; //}, //'stroke-dashoffset': function () { // return pathLength; //}, 'stroke-width':oldStrokeWidth, 'fill': 'none', 'stroke': color.edgeColor }) .transition() .duration(1000) .ease(d3.easeLinear) //.styleTween('stroke-dashoffset', function () { // return d3.interpolateRound(pathLength,0) //}) .styleTween('stroke-width',function(){ return d3.interpolateNumber(oldStrokeWidth,newStrokeWidth); }) //.on('end', function () { // d3.select(this) // .style('stroke',color.edgeColor); //}) .transition() .duration(1000) .delay(1000) .ease(d3.easeLinear) .on('start', repeat) }) } //if(d.isForegroundTargetEdge){ if (d.isForegroundSourceEdge) { d.transitionCount = that.yearFilter[0] - d.flipBookStartYear; var thisPath = d3.select(this); var pathLength = thisPath.node().getTotalLength(); var oldStrokeWidth; var newStrokeWidth = 0; pathLength = parseInt(pathLength); thisPath.styles({ 'stroke-dasharray': function () { return pathLength; }, 'stroke-dashoffset': function () { return pathLength; }, 'stroke-width': 0, 'fill': 'none' }) .transition() .duration(0) //.delay(2000) .ease(d3.easeLinear) .on('start', function repeat() { if(d.source == 20 && d.target == 18) { console.log(d.flipBookRatio); } if (d.transitionCount + d.flipBookStartYear > d.flipBookEndYear) { thisPath.style('stroke-width', d[edgeThickNessOption]) .style('stroke-dashoffset', 0); d3.selectAll('.transitionPath').remove(); currentLayer.svg.select('.edgeField').selectAll('path') .each(function (d) { if (d.isBackgroundEdge) { d3.select(this) .style('visibility', 'visible'); } }); return; } var yearKey = d.flipBookStartYear + '_' + (d.flipBookStartYear + d.transitionCount); oldStrokeWidth = newStrokeWidth; newStrokeWidth = d.flipBookRatio[yearKey] * d[edgeThickNessOption]; d.transitionCount += 1; var pathD = thisPath.attr('d'); var newPath = g.append('path') .attrs({ d: pathD, class: 'transitionPath' }) .styles({ 'stroke-dasharray': function () { return pathLength; }, 'stroke-dashoffset': function () { return pathLength; }, 'stroke-width': 0, 'fill': 'none', 'stroke': function () { if (oldStrokeWidth < newStrokeWidth) { return color.edgeHightLightColor } else return color.edgeColor } }) .transition() .duration(1000) .ease(d3.easeLinear) .styleTween('stroke-dashoffset', function () { return d3.interpolateRound(pathLength, 0) }) .styleTween('stroke-width', function () { return d3.interpolateNumber(newStrokeWidth, newStrokeWidth); }) .on('end', function () { d3.select(this) .style('stroke', color.edgeColor); }) .transition() .duration(1000) .delay(1000) .ease(d3.easeLinear) .on('start', repeat) }) } }); //.on('start', function (d) { // var thisEdge = d3.select(this); // //var originStrokeWidth = thisEdge.style('stroke-width'); // thisEdge.attrs({ // transitionStatus: function (d) { // d.transitionStatus = 'start'; // return d.transitionStatus; // }, // //'originStrokeWidth': originStrokeWidth // }) // .styles({ // 'stroke': 'red', // 'stroke-width': '3px' // }); // if (d.marker)d.marker.attrs({ // transitionStatus: function (d) { // d.transitionStatus = 'start'; // return d.transitionStatus; // } // }) //}) //.on('end', function (d) { // d.marker.style('fill', color.markerColor); // var thisEdge = d3.select(this); // var originStrokeWidth = thisEdge.attr('originStrokeWidth'); // // thisEdge.attrs({ // transitionStatus: function (d) { // d.transitionStatus = 'end'; // return d.transitionStatus; // } // }) // .styles({ // 'stroke': 'yellow', // 'stroke-width': originStrokeWidth // }); // if (d.marker)d.marker.attrs({ // transitionStatus: function (d) { // d.transitionStatus = 'end'; // return d.transitionStatus; // } // }) //}) } else { svgEdges.data(edges) .attrs({ d: function (d) { return pathData(d, that); }, transitionStatus: 'end' }) .each(function (d) { var thisEdge = d3.select(this); var edgeClass = thisEdge.attr('class'); var pathData = thisEdge.attr('d').split('M')[1].split(' '); var textX = (parseFloat(pathData[0]) + parseFloat(pathData[2])) / 2; var textY = (parseFloat(pathData[1]) + parseFloat(pathData[3])) / 2; var edgeLabel = drawEdgeLabel(optionNumber.edgeLabelOption, d.flow, d.citation, textX, textY, edgeClass, d.dx, d.dy); thisEdge.edgeLabel = edgeLabel; thisEdge.attrs({ dx: d.dx, dy: d.dy }); edgeLabelElem.push(edgeLabel); }); } this.getYearEdgeRelation(); } function drawEdgeLabel(option, flow, citation, textX, textY, edgeClass, dx, dy) { var fontSize = 14; var drawedges = this.drawedges; if (option == 1) { var txt = drawedges.append('text').attr('class', 'edgeLabel').attr('id', 'edgeLabel' + edgeClass) .attrs({ dx: dx, dy: dy, x: textX, y: textY }) .html(citation) .styles({ 'font-family': 'Microsoft Yahei', 'font-size': fontSize + px, fill: 'yellow' }); } else if (option == 2) { var txt = drawedges.append('text').attr('class', 'edgeLabel').attr('id', 'edgeLabel' + edgeClass) .attrs({ dx: dx, dy: dy, x: textX, y: textY }) .html(flow) .styles({ 'font-family': 'Microsoft Yahei', 'font-size': fontSize + px, fill: 'yellow' }); } return txt; } function getYearEdgeRelation() { var yearEdgeDic = {}; var edgeClassList = []; var edges = d3.selectAll('path') .each(function (d) { var thisEdge = d3.select(this); var id = thisEdge.attr('id'); var edgeClass = thisEdge.attr('class'); if (edgeClass)edgeClassList.push(edgeClass); if (id) { var yearID = id.split('_'); yearID.pop(); for (var i = 0, length = yearID.length; i < length; i++) { if (!yearEdgeDic[yearID[i]]) { yearEdgeDic[yearID[i]] = []; yearEdgeDic[yearID[i]].push(thisEdge) } else { yearEdgeDic[yearID[i]].push(thisEdge); } } } }); return yearEdgeDic; } function drawSelfEdgeLabel(option, flow, weight, textX, textY, edgeClass) { var fontSize = 14; var drawedges = this.drawedges; if (option == 1) { d3.select('.ruler').style('font-size', fontSize + px); var dx = String(weight).visualLength() / 2; var txt = drawedges.append('text').attr('class', 'selfEdgeLabel').attr('id', 'selfEdgeLabel' + edgeClass) .attrs({ x: textX - dx, y: textY }) .html(weight) .styles({ 'font-family': 'Microsoft Yahei', 'font-size': fontSize + px, fill: color.edgeColor }); } else if (option == 2) { d3.select('.ruler').style('font-size', fontSize + px); var dx = String(flow).visualLength() / 2; var txt = drawedges.append('text').attr('class', 'selfEdgeLabel').attr('id', 'selfEdgeLabel' + edgeClass) .attrs({ x: textX - dx, y: textY }) .html(flow) .styles({ 'font-family': 'Microsoft Yahei', 'font-size': fontSize + px, fill: color.edgeColor }); } return txt; } function drawSelfEdge(optionNumber, doTransition, transitionType, data) { var nodes = data.node; var edges = data.edge; d3.selectAll('.selfEdge').remove(); d3.selectAll('.selfEdgeLabel').remove(); getSelfData(nodes); drawselfedges.selectAll('selfEdge').data(nodes) .enter() .append('g') .each(function (d) { var thisG = d3.select(this); if (d.selfEdge > 0) { thisG.append('path') .attr('d', function (d) { return d.selfPathStr; }) .attr('class', 'selfEdge') .attr('stroke-width', '2px') .style('stroke', color.edgeColor) .attr('fill', 'none') .each(function (d, i) { selfEdgeElem[d.id] = d3.select(this); var selfLabel = drawSelfEdgeLabel(optionNumber.edgeLabelOption, d.selfEdge, parseInt(d.selfEdge * d.size), d.selfEdgeLabelX, d.selfEdgeLabelY, 'selfEdge'); selfEdgeLabelElem[d.id] = selfLabel; var stroke = getSelfEdgeStrokeWidth(d); var size = 13 / (stroke); var marker = svg.append("svg:defs") .append("svg:marker") .attr("id", "selfMarkerArrow" + i) .attr('class', 'marker') .attr("viewBox", "0 0 10 10") .attr("refX", 0.2) .attr("refY", 1.1) .attr("markerWidth", size) .attr("markerHeight", size) .attr("orient", 'auto') .append("svg:path") .attr("d", "M0,1 L0,2.666 L2.666,1 L0,1"); var thisEdge = d3.select(this); thisEdge.marker = marker; }); } }); d3.selectAll('.node').each(function (d) { if (selfEdgeElem[d.id])d.selfEdgeElem = selfEdgeElem[d.id]; if (selfEdgeLabelElem[d.id])d.selfEdgeLabelElem = selfEdgeLabelElem[d.id]; }) } function drawLabels(optionNumber, doTransition, transitionType, d) { var data = this.data; var that = this; var sizeScale = this.sizeScale; var drawnodes = this.drawnodes; var focusedID = this.focusedID; var screenPreNodes = data.screenPreviousData[focusedID].node; var nodeClick = this.nodeClick; var mouseover = this.mouseover; var mouseout = this.mouseout; var textElem = this.textElem; var drag = this.drag; var k = this.zoomK || 1; var preYearNode = this.preYearNode; var clusterSummary = this.clusterSummary; var nodeList = this.nodeList; var nodes = d.node; var edges = d.edge; var fontSize = dMax/2; var fontFamily = 'Microsoft YaHei'; var pre; if (this.preLabelLayer) { pre = this.preNodeLayer; } var g = drawnodes.append('g') .attr('class', 'labelLayer'); this.preLabelLayer = g; // d3.select('.ruler') // .styles({ // 'font-size':fontSize+'px', // 'font-family':'Microsoft YaHei' // // }); var x; if (nodes.length > 20) { x = 2; } else { x = 2; } nodes.forEach(function (node) { if (node.focused == 'true') { node.frequencyKeywords = node.keywords; } }); function getAuthorVenue(d, i) { // console.log(d); var author = d.author_venue.author; var venue = d.author_venue.venue; var label = [author, venue]; return label[i]; } function setLabelAttributes(nodes) { g.selectAll('node_label') .data(nodes).enter() .append('g') .attr('id', function (d) { return 'g'+ d.id + '_' + i; }) .each(function () { var thisLabelG = d3.select(this); thisLabelG.append('text') .styles({ 'font-size': function (d) { d.fontSize = fontSize; return fontSize / k + 'px' }, 'font-family': 'Microsoft YaHei', fill: function () { return color.nodeLabelColor; }, visibility: 'hidden', 'text-anchor' : 'middle' }) .html(function (d, j) { if (optionNumber.nodeLabelOption < 2) { if ((x == 2) || ((x == 1) && d.focused == 'true') || ((x == 1) && (i == 0))) { var keywords = d.keywords; if (keywords[i] && keywords[i].length > 2)return keywords[i].substring(0, 1).toUpperCase() + keywords[i].substring(1); } } else if (optionNumber.nodeLabelOption == 2) { if ((x == 2) || ((x == 1) && d.focused == 'true' && d.id != 0) || ((x == 1) && i == 0 && d.id != 0)) { if (d.id != 0) { var label = getAuthorVenue(d, i); return label; } } } }) .attr('index', 'nodeFirstLabelTextShift_' + i) .attrs({ "x": function (d) { //下面这段if很神奇,虽然没什么实际的作用,但是去掉之后y会出问题,没时间找问题在哪了 if (d.keywords[i] && d.keywords[i].length > 2) { var len = d.keywords[i].visualLength(fontFamily, fontSize); } return d.x; }, "y": function (d) { if (!d.nodeFirstLabelTextShiftY)d.nodeFirstLabelTextShiftY = [0, 0, 0]; d.nodeFirstLabelTextShiftY[i] = sizeScale.sizeScale(d.size) + (i + 1) * 'A'.visualHeight(); return d.y + d.nodeFirstLabelTextShiftY[i] / k; }, "id": function (d) { return 'label' + d.id }, "disable": true, "class": "label TFIDFLevel" + i + ' tfidf' }) .on('dblclick', doubleClick) .on('click', function (d) { return nodeClick(d, that); }) .on('mouseover', function (d) { return mouseover(d, that); }) .on('mouseout', function (d) { return mouseout(d, that); }) .each(function (d) { d.that = that; }) .call(drag) .style('cursor', 'hand') .each(function (d, i) { if (d.size == 0) { d3.select(this).remove(); } if (textElem[d.id] == null) { textElem[d.id] = { textElem: [], id: d.id }; textElem[d.id].textElem.push(d3.select(this)); } else { textElem[d.id].textElem.push(d3.select(this)); } }); thisLabelG.append('text') .styles({ 'font-size': function (d) { d.fontSize = fontSize; return fontSize / k + 'px' }, 'font-family': 'Microsoft YaHei', fill: function () { return color.nodeLabelColor; }, 'text-anchor' : 'middle' }) .attr('index', 'nodeSecondLabelTextShift_' + i) .html(function (d, j) { if (optionNumber.nodeLabelOption == 0) { if ((x == 2) || ((x == 1) && d.focused == 'true') || ((x == 1) && (i == 0))) { var keywords = d.onegram; if (keywords[i] && keywords[i].length > 2)return keywords[i].substring(0, 1).toUpperCase() + keywords[i].substring(1); } } else if (optionNumber.nodeLabelOption == 1) { if ((x == 2) || ((x == 1) && d.focused == 'true' && d.id != 0) || ((x == 1) && i == 0 && d.id != 0)) { if (d.id != 0) { var label = getAuthorVenue(d, i); return label; } } } }) .attrs({ "x": function (d) { return d.x ; }, "y": function (d) { if (!d.nodeSecondLabelTextShiftY)d.nodeSecondLabelTextShiftY = [0, 0, 0]; d.nodeSecondLabelTextShiftY[i] = sizeScale.sizeScale(d.size) + (i + 1) * 'A'.visualHeight(); return d.y + d.nodeSecondLabelTextShiftY[i] / k; }, "id": function (d) { return 'label' + d.id }, "disable": true, "class": "label FrequencyLevel" + i + ' freq' }) .on('dblclick', doubleClick) .on('click', function (d) { return nodeClick(d, that); }) .on('mouseover', function (d) { return mouseover(d, that); }) .on('mouseout', function (d) { return mouseout(d, that); }) .each(function (d) { d.that = that; }) .call(drag) .style('cursor', 'hand') .styles({ 'visibility': function () { if (i <= 1) { return 'visible'; } else { return 'hidden'; } } }) .each(function (d, i) { if (d.size == 0) { d3.select(this).remove(); } if (textElem[d.id] == null) { textElem[d.id] = { textElem: [], id: d.id }; textElem[d.id].textElem.push(d3.select(this)); } else { textElem[d.id].textElem.push(d3.select(this)); } }); //thisLabelG.append('text') // .styles({ // 'font-size': function (d) { // d.fontSize = fontSize; // return fontSize / k + 'px' // }, // 'font-family': 'Microsoft YaHei', // fill: function () { // return color.nodeLabelColor; // }, // visibility: 'hidden' // }) // .html(function (d, j) { // if ((x == 2) || ((x == 1) && d.focused == 'true' && d.id != 0) || ((x == 1) && i == 0 && d.id != 0)) { // if (d.id != 0) { // var label = getAuthorVenue(d, i); // return label; // } // } // }) // .attrs({ // "x": function (d) { // if (!d.nodeThirdLabelTextShiftX)d.nodeThirdLabelTextShiftX = [0, 0, 0]; // // if (d.id != 0) { // var label = getAuthorVenue(d, i); // if (label) { // d.nodeThirdLabelTextShiftX[i] = -label.visualLength(fontFamily, fontSize) / 2; // } // } // return d.x + d.nodeThirdLabelTextShiftX[i] / k; // }, // "y": function (d) { // if (!d.nodeThirdLabelTextShiftY)d.nodeThirdLabelTextShiftY = [0, 0, 0]; // d.nodeThirdLabelTextShiftY[i] = sizeScale.sizeScale(d.size) + (i + 1) * 'A'.visualHeight(); // return d.y + d.nodeThirdLabelTextShiftY[i] / k; // }, // "id": function (d) { // return 'label' + d.id // }, // "disable": true, // "class": "label venueLabel" // }) // .on('dblclick', doubleClick) // .on('click', function (d) { // return nodeClick(d, that); // }) // .on('mouseover', function (d) { // return mouseover(d, that); // }) // .on('mouseout', function (d) { // return mouseout(d, that); // }) // .each(function (d) { // d.that = that; // }) // .call(drag) // .style('cursor', 'hand') // .each(function (d, i) { // if (d.size == 0) { // d3.select(this).remove(); // } // if (textElem[d.id] == null) { // textElem[d.id] = { // textElem: [], // id: d.id // }; // textElem[d.id].textElem.push(d3.select(this)); // } // else { // textElem[d.id].textElem.push(d3.select(this)); // } // // }); }); } for (var i = 0; i < 3; i++) { if (doTransition) { setLabelAttributes(nodes); g.selectAll('.label') .style('fill', 'none') .transition() .delay(function (d) { return d.delay[0]; }) .duration(function (d) { return d.duration; }) .style('fill', function () { return color.nodeLabelColor; }) .on('start', function (d) { console.log('#g'+ d.id + '_' +i); pre.select('#g'+ d.id + '_' +i).remove(); console.log(pre.select('#g'+ d.id + '_' +i)); var thisNode = d3.select(this); thisNode.attrs({ transitionStatus: function (d) { d.transitionStatus = 'start'; return d.transitionStatus; } }) }) .on('end', function (d) { var thisNode = d3.select(this); thisNode.attrs({ transitionStatus: function (d) { d.transitionStatus = 'end'; return d.transitionStatus; } }) }); } else { setLabelAttributes(nodes); g.selectAll('.label').attr('transitionStatus', 'end'); } } } function drawLegends() { var legend_g = this.legend_g; if (!legend_g.select('#nontreeLegendText')._groups[0][0]) { var svgHeight = parseFloat(d3.select('.graphDiv').select('svg').attr('height')); var initY = 0; var initX = 0; var legendData = [ { class: 'legend', id: 0, type: 'image', x: initX + 10, y: initY, width: 20, height: 20, link: 'image/star.png', text: 'Influencer' }, { class: 'legend', id: 1, type: 'circle', x: initX + 10, y: initY + 30, r: 10, fill: color.nodeColor, text: 'Cluster' }, { class: 'legend', id: 2, type: 'path', d: 'M' + initX + ' ' + (initY + 60) + 'L' + (initX + 50) + ' ' + (initY + 60), dash: false, stroke: color.edgeColor, opacity: 1, strokeWidth: 3 + px, text: 'Tree Edges', textX: initX + 64, textY: initY + 65, textColor: color.nodeLabelColor }, { class: 'legend', id: 3, type: 'path', d: 'M' + initX + ' ' + (initY + 85) + 'L' + (initX + 50) + ' ' + (initY + 85), dash: true, stroke: color.edgeColor, opacity: 1, disableOpacity: 0.2, strokeWidth: 3 + px, text: 'Nontree Edges', textX: initX + 64, textY: initY + 90, textColor: color.textDisableColor } ] legend_g.selectAll('whatever') .data(legendData) .enter() .append('g') .each(function (d) { var thisG = d3.select(this) thisG.attrs({ id: d.class + d.id, class: d.class + 'G' }); switch (d.type) { case 'image': { thisG.append('image') .attrs({ x: d.x - 10, y: d.y - 10, height: d.height, width: d.width, 'xlink:href': d.link }); thisG.append('text') .attrs({ x: d.x + 20, y: d.y + 5 }) .styles({ fill: color.nodeLabelColor, 'font-family': 'Arial' }) .html(d.text) return 1 } case 'circle': { thisG.append('circle') .attrs({ cx: d.x, cy: d.y, r: d.r }) .styles({ fill: d.fill }); thisG.append('text') .attrs({ x: d.x + 20, y: d.y + 5 }) .styles({ fill: color.nodeLabelColor, 'font-family': 'Arial' }) .html(d.text) return 1 } case 'path': { thisG.append('path') .attrs({ class: function (d) { return d.class; }, id: function (d) { if (d.dash)return 'nontreeLegend'; else return 'treeLegend' }, d: d.d }) .styles({ stroke: d.stroke, 'stroke-width': d.strokeWidth, // 'stroke-dasharray':function(d){ // if(d.dash){ // return 5.5 // } // }, opacity: function (d) { if (d.dash) { return d.disableOpacity } else { return d.opacity } }, cursor: function (d) { if (d.dash) { return 'hand' } } }) .each(function (d) { var thisEdge = d3.select(this); var marker = thisG.append("svg:defs") .append("svg:marker") .attr("id", 'legendMarker') .attr('class', 'legend') .attr("viewBox", "0 0 10 10") .attr("refX", 0) .attr("refY", 4) .attr("markerWidth", 4) .attr("markerHeight", 4) .attr("orient", 'auto') .append("svg:path") .attr('class', 'legend') .attr("d", "M0,0 L0,8 L8,4 L0,0") .style("fill", color.edgeColor); thisEdge.attr('marker-end', 'url(#legendMarker)') }); thisG.append('text') .attrs({ id: function (d) { if (d.dash)return 'nontreeLegendText'; else return 'treeLegendText' }, x: d.textX, y: d.textY }) .styles({ fill: function (d) { return d.textColor }, 'font-family': 'Arial', cursor: function (d) { if (d.dash) { return 'hand' } } }) .on('click', function (d) { if (d.dash) { changeNonTreeEdges(); var thisLegend = d3.select('#nontreeLegendText'); thisLegend.styles({ fill: function (d) { if (d.textColor == color.textDisableColor) { d.textColor = color.nodeLabelColor; return d.textColor; } else { d.textColor = color.textDisableColor; return d.textColor; } } }) } }) .html(d.text) return 1 } } }) } //currentLayer.svg.select('.legendDrawer').attr('transform', 'translate(' + legendTranWidth + ',' + legendTranHeight + ')'); } function changeNonTreeEdges() { if (optionNumber.edgeFilter == 0) { optionNumber.edgeFilter = 1; d3.select('.edgeField').selectAll('path') .each(function (d) { if (d.isNontreeEdge) { d3.select(this).styles({ visibility: 'visible' }) } }) } else { optionNumber.edgeFilter = 0; d3.select('.edgeField').selectAll('path') .each(function (d) { if (d.isNontreeEdge) { d3.select(this).styles({ visibility: 'hidden' }) } }) } } function drawNodes(optionNumber, doTransition, transitionType, dd) { var sizeScale = this.sizeScale; var k = this.zoomK || 1; function dataBundling(d, i, thisNode) { if (d.focused == 'true') { d.imageShift = -10; d.imageSize = 20; thisNode.append('image') .attrs({ type: 'image', class: 'node', x: d.x + d.imageShift / k, y: d.y + d.imageShift / k, cluster: d.oldKey, width: d.imageSize / k + px, height: d.imageSize / k + px, 'xlink:href': function (d) { if (pageStyle == 'dark') return 'image/star.png'; else return 'image/lightStar.png' } }) } else thisNode.append('circle') .attrs({ type: 'circle', class: 'node', cluster: d.oldKey, cx: d.x, cy: d.y, r: function (d) { var size = sizeScale.sizeScale(d.newSize); d.nodeR = size; return d.nodeR / k; } }) } var focusedNodeData; var that = this; var nodes = dd.node; var edges = dd.edge; var focusedID = this.focusedID; var drag = this.drag; // var nodes= []; // var edges=[]; // clone(dd.node,nodes); // clone(dd.edge,edges); dd.subNodeYearData = []; var nonRootNodes = []; nodes.forEach(function (node) { if(getUrlParam('twitter') == '20') { if(node.focused == 'false') { nonRootNodes.push(node); } } else { if(!node.focused) { nonRootNodes.push(node); } } }); var citationDomain = [d3.min(nonRootNodes, function (d) { return d.citation; }), d3.max(nonRootNodes, function (d) { return d.citation; })]; var avgCitationDomain = [d3.min(nonRootNodes, function (d) { return d.citation / d.size; }), d3.max(nonRootNodes, function (d) { return d.citation / d.size; })]; if(parseFloat(getUrlParam('nodeOpacityMin')) >= 0 && parseFloat(getUrlParam('nodeOpacityMin')) <= 1) { nodeOpacityMin = parseFloat(getUrlParam('nodeOpacityMin')); } if(parseFloat(getUrlParam('nodeOpacityMax')) >= 0 && parseFloat(getUrlParam('nodeOpacityMax')) <= 1) { nodeOpacityMax = parseFloat(getUrlParam('nodeOpacityMax')); } var nodeOpacity = { uniform: function (citation) { //do something with citation return 0.8; }, citation: function (citation) { var scale = d3.scaleLinear() .domain(citationDomain) .range([nodeOpacityMin, nodeOpacityMax]); return scale(citation); }, avgCitation: function (avgCitation) { var scale = d3.scaleLinear() .domain(avgCitationDomain) .range([nodeOpacityMin, nodeOpacityMax]); return scale(avgCitation); } }; that.nodeOpacity = nodeOpacity; clone(dd.nodeYearData.data, dd.subNodeYearData); for (var i = 0; i < dd.subNodeYearData.length; i++) { dd.subNodeYearData[i][1] = 0; } var textElem = this.textElem; var relation = this.relation; var edgeLabelElem = this.edgeLabelElem; var pathElem = this.pathElem; var data = this.data; var drawnodes = this.drawnodes; var duration = this.duration; var preYearNode = this.preYearNode; var nodeClick = this.nodeClick; var mouseover = this.mouseover; var mouseout = this.mouseout; var screenPreNodes = data.screenPreviousData[focusedID].node; var g; var pre; var preNodes = {}; if (this.preNodeLayer) { pre = this.preNodeLayer; pre.selectAll('.circle') .each(function (d) { preNodes[d.id] = {nodeR: d.nodeR}; }); //pre.remove(); } g = drawnodes.append('g') .attr('class', 'circleLayer'); this.preNodeLayer = g; var edgeSet = {}; var nodesDic = {}; nodes.forEach(function (node) { node.sourceNodes = []; node.targetNodes = []; nodesDic[node.id] = node; }); edges.forEach(function (edge) { var source = edge.source; var target = edge.target; var key = source + '-' + target; if (!edgeSet[key] && !edge.isNontreeEdge) { edgeSet[key] = 1; var sn = nodesDic[source]; var tn = nodesDic[target]; if (source in nodesDic) { sn.targetNodes.push(tn); } if (target in nodesDic) { tn.sourceNodes.push(sn); } } }); // svg.select('.linearGradientDefs').remove(); if (doTransition) { g.selectAll('node').data(nodes) .enter() .append('g') .attr('id', function (d) { return 'g' + d.id; }) .each(function (d, i) { var thisNode = d3.select(this); if (d.focused == 'true')thisNode.append('image') .attrs({ type: 'image', class: 'node', x: d.x - 10, y: d.y - 10, width: 20 + px, height: 20 + px, 'xlink:href': function (d) { if (pageStyle == 'dark') return 'image/star.png'; else return 'image/lightStar.png' } }); else thisNode.append('circle') .attrs({ type: 'circle', class: 'node', cx: d.x, cy: d.y, r: sizeScale.sizeScale(d.size * d.ratio[0]) }); d.index = 3; var backgroundData = [ { class: 'backgroundNode', delay: d.delay, id: d.id, isBackground: 1, index: 2, x: d.x, y: d.y, //opacity:0.7* d.sizeIncreaseRatio[0], opacity: 0.7, r: sizeScale.sizeScale(d.size * d.ratio[0]) * 0.133 + sizeScale.sizeScale(d.size * d.ratio[0]), fill: color.nodeColor, highlightFill: color.nodeHighlightColor, highlightOpacity: 1 * d.sizeIncreaseRatio[0], duration: d.duration }, { class: 'backgroundNode', delay: d.delay, id: d.id, isBackground: 1, index: 1, x: d.x, y: d.y, //opacity:0.5*d.sizeIncreaseRatio[0], opacity: 0.5, r: sizeScale.sizeScale(d.size * d.ratio[0]) * 0.133 * 2 + sizeScale.sizeScale(d.size * d.ratio[0]), fill: color.nodeColor, highlightFill: color.nodeHighlightColor, highlightOpacity: 1 * d.sizeIncreaseRatio[0], duration: d.duration } ]; thisNode.selectAll('whatever') .data(backgroundData) .enter() .append('circle') .each(function (d) { d3.select(this) .attrs({ id: 'node' + d.id, isBackground: d.isBackground, class: d.class, cx: d.x, cy: d.y, r: d.r, index: d.index }) .styles({ opacity: d.opacity, fill: 'none' }) }); }); } else { g.selectAll('node').data(nodes) .enter() .append('g') .attr('id', function (d) { return 'g' + d.id; }) .attr('cluster', function (d) { return d.oldKey }) .each(function (d, i) { var thisNode = d3.select(this); dataBundling(d, i, thisNode); thisNode.selectAll('*') .attrs({ transitionStatus: 'end' }) }); } preYearNode = false; var defs = g.append('defs').attr('class', 'linearGradientDefs'); defs.selectAll('linearGradient').data(nodes).enter() .append('linearGradient') .attr('class', 'linearGradient') .attr('id', function (d) { return 'linearGradient' + d.id; }) .attrs({ x1: 0, y1: 0, x2: 0, y2: 1 }) .each(function (e) { var thisLG = d3.select(this); var data = [{offset: 0, color: color.nodeGreyColor, opacity: 1}, { offset: 0, color: color.nodeGreyColor, opacity: 1 }, {offset: 0, color: color.nodeColor, opacity: 1}, {offset: 1, color: color.nodeColor, opacity: 1}]; var citation = e.citation; var size = e.size; thisLG.selectAll('stop').data(data).enter() .append('stop') .attrs({ offset: function (d) { return d.offset }, 'stop-color': function (d) { return d.color }, 'stop-opacity': function () { if (nodeOpacityOption == 'citation' || nodeOpacityOption == 'uniform') { console.log(citation); console.log(nodeOpacity[nodeOpacityOption](citation)); console.log(nodeOpacity) console.log(nodeOpacityOption) console.log(nodeOpacity[nodeOpacityOption]) return nodeOpacity[nodeOpacityOption](citation); } else if (nodeOpacityOption == 'avgCitation') { return nodeOpacity[nodeOpacityOption](citation/size); } } }) }); //from line 274 to line 412 //is aim to resolve movie mode pause won't update node fill style //the method is not very well,should be fixed in the future //shit!!! if (transitionType == 'flowMap') { g.selectAll('.node') .data(nodes) .attr('year', function (d) { var dic = d.newNodeYearInfo; var yearString = '' for (var key in d.newNodeYearInfo) { yearString += key + '-' + d.newNodeYearInfo[key] + '_'; } return yearString; }) .attr('id', function (d) { return 'node' + d.id; }) .on('dblclick', doubleClick) .on('click', function (d) { return nodeClick(d, that); }) .on('mouseover', function (d) { return mouseover(d, that); }) .on('mouseout', function (d) { return mouseout(d, that); }) .each(function (d) { d.that = that; }) .call(drag) .styles({ "fill": 'none' }) .transition() .duration(function (d) { return d.duration; }) .delay(function (d) { return d.delay[0]; }) .styles({ "fill": function (d) { return color.nodeColor; }, // 'fill':'rgb(0,220,225)', "opacity": 1, "cursor": "hand" }) .each(function (d, i) { if (d.size == 0) { d3.select(this).remove(); } d.clicked = false; if (d.focused == 'true') { // d3.select(this).attr('stroke','red'); // d3.select(this).attr('stroke-width','2px'); // d3.select(this).attr('class','node clicked'); focusedNodeData = d; } d.edgeLabelElem = []; d.pathElem = []; d.backgroundPathElem = []; d.relatedEdges = []; d.textElem = { textElem: [], id: d.id }; d.self = d3.select(this); if (textElem[d.id])d.textElem.textElem = textElem[d.id].textElem; for (var j = 0; j < relation[d.id].edges.length; j++) { d.edgeLabelElem.push(edgeLabelElem[relation[d.id].edges[j]]); //d.pathElem.push(pathElem[relation[d.id].edges[j]]); } pathElem.forEach(function (e) { //if(!e.isNontreeEdge) { if (e.fatherNode == d.id) { d.pathElem.push(e.self); } if (e.isBackgroundEdge && (e.source == d.id || e.target == d.id)) { d.backgroundPathElem.push(e.self); } if (e.routerClusters) { if (e.routerClusters.indexOf(parseInt(d.id)) != -1) { d.relatedEdges.push(e.self); } } else { if (e.source == d.id || e.target == d.id) { d.relatedEdges.push(e.self); } } //} }) }); } else { g.selectAll('.node') .data(nodes) .attr('year', function (d) { var dic = d.newNodeYearInfo; var yearString = ''; for (var key in d.newNodeYearInfo) { yearString += key + '-' + d.newNodeYearInfo[key] + '_'; } return yearString; }) .attr('id', function (d) { return 'node' + d.id; }) .on('dblclick', doubleClick) .on('click', function (d) { return nodeClick(d, that); }) .on('mouseover', function (d) { return mouseover(d, that); }) .on('mouseout', function (d) { return mouseout(d, that); }) .each(function (d) { d.that = that; }) .call(drag) .styles({ "fill": function (d) { return "url(#linearGradient" + d.id + ")" }, // 'fill':'rgb(0,220,225)', "opacity": 1, "cursor": "hand" }) .transition() .duration(function (d) { if (transitionType == 'flowMap') { return d.duration; } else { return 1; } }) .delay(function (d) { if (transitionType == 'flowMap') { return d.delay[0]; } else { return 1; } }) .styles({ "fill": function (d) { return "url(#linearGradient" + d.id + ")" }, // 'fill':'rgb(0,220,225)', "opacity": 1, "cursor": "hand" }) .each(function (d, i) { if (d.size == 0) { d3.select(this).remove(); } d.clicked = false; if (d.focused == 'true') { // d3.select(this).attr('stroke','red'); // d3.select(this).attr('stroke-width','2px'); // d3.select(this).attr('class','node clicked'); focusedNodeData = d; } d.edgeLabelElem = []; d.pathElem = []; d.backgroundPathElem = []; d.relatedEdges = []; d.textElem = { textElem: [], id: d.id }; d.self = d3.select(this); if (textElem[d.id])d.textElem.textElem = textElem[d.id].textElem; for (var j = 0; j < relation[d.id].edges.length; j++) { d.edgeLabelElem.push(edgeLabelElem[relation[d.id].edges[j]]); //d.pathElem.push(pathElem[relation[d.id].edges[j]]); } pathElem.forEach(function (e) { if (e.fatherNode == d.id) { d.pathElem.push(e.self); } if (e.isBackgroundEdge && (e.source == d.id || e.target == d.id)) { d.backgroundPathElem.push(e.self); } if (e.routerClusters) { if (e.routerClusters.indexOf(parseInt(d.id)) != -1) { d.relatedEdges.push(e.self); } } else { if (e.source == d.id || e.target == d.id) { d.relatedEdges.push(e.self); } } }) }); } if (transitionType == 'flowMap') { var svgNodes = g.selectAll('.node'); console.log(nodes.length); for (var i = 0; i < nodes.length; i++) { if (nodes[i].id == 18) { console.log(1); } var node = d3.select(svgNodes._groups[0][i]); var tmpDelay = []; var tmpRatio = []; var nodeData; node.attr('cx', function (d) { nodeData = d; return d.x; }); clone(nodeData.delay, tmpDelay); clone(nodeData.ratio, tmpRatio); setTransition(node, tmpDelay, tmpRatio); } } else { g.selectAll('.node') .data(nodes) .transition() .duration(function (d) { if (transitionType == 'flowMap') { return d.duration; } else { return 0; } }) .delay(function (d) { if (transitionType == 'flowMap') { return d.delay[0]; } else { return 0; } }) .styles({ "fill": function (d) { return "url(#linearGradient" + d.id + ")" }, 'cursor': 'hand' }) } function setTransition(node, delay, ratio) { var nodeData = node.data()[0]; var nodeID = node.attr('id'); var r; if (ratio.length > 0) { node.transition() .duration(function (d) { return d.duration * 4; }) .delay(function (d) { return delay[0]; }) .ease(d3.easeLinear) .attrs({ 'r': function (d) { if (preNodes[d.id]) { return preNodes[d.id].nodeR / k; } r = sizeScale.sizeScale(d.size * ratio[0]); d.nodeR = r; return d.nodeR / k; } }) .styles({ // "fill":function(d){return 'white'}, "fill": function (d) { return "url(#linearGradient" + d.id + ")" }, 'cursor': 'hand' }) .on('start', function (d) { pre.select('#g' + d.id).remove(); var thisNode = d3.select(this); thisNode.attrs({ transitionStatus: function (d) { d.transitionStatus = 'start'; return d.transitionStatus; } }); d.index = 3; g.select('#g' + nodeID.split('e')[1]) .selectAll('.backgroundNode') .each(function (e, i) { if (e.isBackground) { d3.select(this) .transition() .duration(e.duration * 4) .ease(d3.easeLinear) .attrs({ r: function (e) { var bigR; if (e.index == 2) { bigR = r + 4; } else if (e.index == 1) { bigR = r + 8; } e.bigR = bigR; return e.bigR; } }) .styles({ fill: e.highlightFill, //fill:color.svgColor, 'fill-opacity': function () { var tempOpacity = e.highlightOpacity; e.highlightOpacity /= d.sizeIncreaseRatio[0]; d.sizeIncreaseRatio = d.sizeIncreaseRatio.splice(1, d.ratio.length - 1); e.highlightOpacity *= d.sizeIncreaseRatio[0]; return tempOpacity; } }) .on('start', function (d) { d3.select(this) .attrs({ transitionStatus: 'start' }) }) .on('end', function (d) { d3.select(this) .attrs({ transitionStatus: 'end' }); d3.select(this) .transition() .duration(e.duration * 8) .ease(d3.easeLinear) .style('fill', color.svgColor) .on('end', function (d) { d3.select(this).style('fill', 'none') }) }) } }); g.selectAll('#' + nodeID).sort(function (a, b) { return d3.ascending(a.index, b.index); }) }) .on('end', function (d) { delay = delay.splice(1, delay.length - 1); delay[0] -= d.duration * 4; ratio = ratio.splice(1, ratio.length - 1); setTransition(node, delay, ratio); }); } else { node.attr('transitionStatus', function (d) { d.transitionStatus = 'end'; return d.transitionStatus; }); } } this.focusedNodeData = focusedNodeData; } function drawSize(optionNumber, doTransition, transitionType, d) { var nodes = d.node; var edges = d.edge; // var nodes= []; // var edges=[]; // clone(d.node,nodes); // clone(d.edge,edges); var data = this.data; var that = this; var nodeOpacity = that.nodeOpacity; var k=this.zoomK||1; var drawnodes = this.drawnodes; var nodeClick = this.nodeClick; var mouseover = this.mouseover; var mouseout = this.mouseout; var idElem = this.idElem; var focusedID = this.focusedID; var svg = this.svg; var screenPreNodes = data.screenPreviousData[focusedID].node; var fontSize = dMax/2; var fontFamily = 'Microsoft YaHei'; var drag = this.drag; var pre; var preSizes = {}; if (this.preSizeLayer) { pre = this.preSizeLayer; pre.selectAll('.circle') .each(function (d) { preSizes[d.id] = {size: d.newSize}; }); //pre.remove(); } var g = drawnodes.append('g').attr('class', 'sizeLayer'); this.preSizeLayer = g; nodes.forEach(function (node) { node.fontSize=fontSize; }); if (doTransition) { g.selectAll('node_size') .data(nodes) .enter() .append('text') .attrs({ "x": function (d) { return d.x; }, "y": function (d) { d.nodeSizeTextShiftY=7.5; return d.y + d.nodeSizeTextShiftY/k; }, "id": function (d) { return 'size'+d.id }, "class": 'size' }) } else { g.selectAll('node_size') .data(nodes) .enter() .append('text') .attrs({ "x": function (d) { return d.x; }, "y": function (d) { d.nodeSizeTextShiftY=7; return d.y + d.nodeSizeTextShiftY/k; }, "id": function (d) { return 'size'+d.id }, 'transitionStatus': 'end', "class": function (d) { d.class = 'size'; return d.class; } }) } g.selectAll('.size') .data(nodes) .on('dblclick', doubleClick) .on('click', function (d) { return nodeClick(d, that); }) .on('mouseover', function (d) { return mouseover(d, that); }) .on('mouseout', function (d) { return mouseout(d, that); }) .each(function (d) { d.that = that; }) .call(drag) .each(function (d) { if (d.size == 0 || d.focused == 'true') { d3.select(this).remove(); } idElem[d.id] = d3.select(this); }) .style("opacity", function (d) { if (nodeOpacityOption == 'citation' || nodeOpacityOption == 'uniform') { return nodeOpacity[nodeOpacityOption](d.citation); } else if (nodeOpacityOption == 'avgCitation') { return nodeOpacity[nodeOpacityOption](d.citation/ d.size); } }) .style("cursor", "hand") .styles({ 'font-size': function (d) { return d.fontSize/k; }, 'font-family': 'Microsoft YaHei', fill: color.sizeLabelColor, //'alignment-baseline': 'middle', 'text-anchor': 'middle' }); if (transitionType == 'flowMap') { var sizes = g.selectAll('.size'); for (var i = 0; i < sizes._groups[0].length; i++) { var size = d3.select(sizes._groups[0][i]); var nodeData; var tmpSizeSeries = []; var tmpDelay = []; size.attr('id', function (d) { nodeData = d; return 'size' + d.id; }); clone(nodeData.sizeSeries, tmpSizeSeries); clone(nodeData.sizeDelay, tmpDelay); setSizeTransition(size, 1 ,tmpDelay , tmpSizeSeries); //size.attr('id', function (d) { // d.sizeDelay = tmpDelay; // d.sizeSeries = tmpSizeSeries; // return d.id; //}); } } else { g.selectAll('.size') .html(function (d) { if(preSizes[d.id]) { return preSizes[d.id].size; } //return d.id; return d.newSize; //add old key to help change label //return d.newSize+'-'+ d.oldKey; }); } function setSizeTransition(size, preSize,sizeDelay, sizeSeries) { var nodeData = size.data()[0]; if (sizeSeries.length > 0) { size.transition() .duration(function (d) { return d.duration * 4; }) .delay(function (d) { return sizeDelay[0]; }) .tween("text", function (d) { var that=d3.select(this); var i = d3.interpolateRound(preSize, sizeSeries[0]); preSize = sizeSeries[0]; return function (t) { that.text(i(t)); }; }) .style("opacity", 1) .style("cursor", "hand") .styles({ 'font-size': function (d) { var size = dMax/2; d.fontSize = size; return d.fontSize/k; }, 'font-family': 'Microsoft YaHei', fill: color.sizeLabelColor }) .on('start', function (d) { pre.select('#size'+ d.id).remove(); var thisNode = d3.select(this); thisNode.attrs({ transitionStatus: function (d) { d.transitionStatus = 'start'; return d.transitionStatus; } }) }) .on('end', function (d) { sizeDelay = sizeDelay.splice(1, sizeDelay.length - 1); sizeDelay[0] -= d.duration * 4; sizeSeries = sizeSeries.splice(1, sizeSeries.length - 1); setSizeTransition(size, preSize, sizeDelay, sizeSeries); }) } else { size.attr('transitionStatus', function (d) { d.transitionStatus = 'end'; return d.transitionStatus; }) } } svg.selectAll('.node').each(function (d) { d.idElem = idElem[d.id]; }) } function drawYearAxis(d){ var axisSVG=this.axisSVG; var that=this; var svg=this.svg; var width=parseFloat(axisSVG.style('width')); var height=parseFloat(axisSVG.style('height')); var nodeYearData=d; var padding=30; var dataSet=d.data; var maxYear=d.maxYear; var minYear=d.minYear; var maxCount=d.maxCount; var minCount=d.minCount; var animateMode=this.animateMode; this.xScale = d3.scaleLinear() .domain([minYear,maxYear]) .range([padding,width-padding]); this.yScale = d3.scaleLinear() .domain([0,maxCount]) .range([(height-padding),padding]); var xScale=this.xScale; var yScale=this.yScale; this.xAxis=d3.axisBottom(xScale); this.yAxis=d3.axisLeft(yScale).ticks(3); var xAxis=this.xAxis; var yAxis=this.yAxis; var axisG=axisSVG.append("g") .attr("class","axis") .call(xAxis) .attr("transform","translate(0,"+(height-padding)+")") .append("text") .attr("transform","translate("+(height-padding)+",0)");//指定坐标轴说明的坐标 var yearSliderDuration=(maxYear-minYear)*2000; var timeCircleData=[ { x:xScale(minYear), y:yScale(0), r:7, minYear:minYear, maxYear:maxYear, id:'leftAxisCircle', transitionX:xScale(minYear), duration:yearSliderDuration, rBig:12, filter:'url(#leftOrRight_filter)', index:0 }, { x:xScale(maxYear), y:yScale(0), r:7, minYear:minYear, maxYear:maxYear, id:'rightAxisCircle', transitionX:xScale(maxYear), duration:yearSliderDuration, rBig:12, filter:'url(#leftOrRight_filter)', index:0 }]; this.preYearPath=false; this.drawNodeYearDataSet(dataSet,'yearPath'); axisSVG.selectAll('text') .styles({ 'fill':color.axisTickColor, 'font-family':'Arial', 'font-weight':'bold' }) axisSVG.selectAll('line') .styles({ stroke:color.axisColor }); axisSVG.select('.axis').select('path') .styles({ fill:'none', stroke:color.axisColor }); this.yearSliderDrag = d3.drag() .subject(function(d) { return d; }) .on('drag', yearSliderDragMove) .on('start', yearSliderDragStart) .on('end', yearSliderDragEnd); axisSVG.selectAll('axisCircle').data(timeCircleData).enter() .append('circle') .attrs({ id:function(d){return d.id;}, class:'axisCircle', cx:function(d){return d.x}, cy:function(d){return d.y}, r:function(d){return d.r} }) .style('filter',function(d,i){ return d.filter }) .style('visibility',function(d,i){ if(animateMode==flipBook){ if(i == 0){ return 'hidden' } else{ return 'visible'; } } }) .style('cursor','hand') .each(function(d){ d.that=that; }) .call(this.yearSliderDrag) .on('click',function(){ console.log('clicked') // var thisNode=d3.select(this) // .duration(100) // .ease('linear') // .attr('fill',) }) .on('dblclick',function(d){ var left=axisSVG.select('') }) .on('mouseover',function(){ var thisNode=d3.select(this); thisNode.transition() .duration(100) .ease(d3.easeLinear) .attr('r',function(d){return d.rBig}) // .style('filter','url(#leftOrRight'); }) .on('mouseout',function(){ var thisNode=d3.select(this); var t=d3.transition().duration(100).ease(d3.easeLinear); thisNode.transition(t) .attr('r',function(d){return d.r}) // .style('filter','url(#pause'); }) this.yearPosition={}; for(var year=minYear;year<=maxYear;year++){ this.yearPosition[year]=[xScale(year-0.5),xScale(year+0.5)] } } function yearAxisTransition(start,end,that){ var axisSVG=that.axisSVG; var animateMode=that.animateMode; var xScale=that.xScale; var yScale=that.yScale; var minYear=that.minYear; var maxYear=that.maxYear; var transitionFlag=that.transitionFlag; var yearFilter=that.yearFilter; // var len=arguments.length; axisSVG.select('#leftAxisCircle') .attrs({ cx:function(d){ if(animateMode==flipBook){ // if(len>0){ d.x=xScale(minYear) return xScale(minYear); // } // else return d.x; } else{ d.x=xScale(start) return xScale(start) } } }) .transition() .ease(d3.easeLinear) .duration(function(d){ if(animateMode==flipBook){ // if(len>0){ return (end-start)*2000; // } // else return d.duration; } else{ return (end-start)*2000; } }) .attrs({ cx:function(d){ if(animateMode==flipBook){ d.x=xScale(minYear) return xScale(minYear); } else{ d.x=xScale(start) return xScale(start) } } }); axisSVG.select('#rightAxisCircle') .attrs({ cx:function(d){ if(animateMode==flipBook){ d.x = xScale(start); return xScale(start); } else{ d.x = xScale(end); return xScale(end) } } }) .transition() .ease(d3.easeLinear) .duration(function(d){ return (end-start)*2000; }) .attrs({ cx:function(d){ d.x = xScale(end); return xScale(end) } }) .on('end',function(){ console.log(1); transitionFlag=false; yearFilter=[minYear,maxYear]; var button=axisSVG.select('.controlButton'); if(button.attr('id')=='pause'){ var name=button.attr('name'); changeFilter(button,name); } }); } function drawNodeYearDataSet(dataSet,pathClass){ var axisSVG=this.axisSVG; var svg=this.svg; var xScale=this.xScale; var yScale=this.yScale; function yearPathClick(d){ axisSVG.selectAll('.subYearPath').remove(); var thisPath=d3.select(this); var thisClass=thisPath.attr('class'); var year=thisPath.attr('year'); var nodes=d3.selectAll('.node'); if(thisClass=='yearPath clicked'){ nodes.each(function(){ var thisNode=d3.select(this); var years=thisNode.attr('year').split('_'); var yearsDic={}; var sum=0 for(var i=0;i<years.length;i++){ var nodeYear = years[i].split('-')[0]; var num= parseInt(years[i].split('-')[1]); yearsDic[nodeYear]=num; if(num)sum+=num } if(year in yearsDic){ var ratio=yearsDic[year]/sum; var id=thisNode.attr('id').split('e')[1]; thisNode.style('fill',function(d){return "url(#linearGradient"+ d.id+")"}); var linearGradient=svg.select('#linearGradient'+id) linearGradient.selectAll('stop') .each(function(d,i){ var thisStop=d3.select(this); var curOffset=parseFloat(thisStop.attr('offset')); curOffset-=ratio; if(i==1){ thisStop.attr('offset',curOffset); } else if(i==2){ thisStop.attr('offset',curOffset); } }) } }); thisPath.attr('class','yearPath'); thisPath.style('fill',color.yearPathColor); // thisPath.style('stroke','none'); } else if(thisClass=='yearPath'){ nodes.each(function(){ var thisNode=d3.select(this); var years=thisNode.attr('year').split('_'); var yearsDic={}; var sum=0 for(var i=0;i<years.length;i++){ var nodeYear = years[i].split('-')[0]; var num= parseInt(years[i].split('-')[1]); yearsDic[nodeYear]=num; if(num)sum+=num } if(year in yearsDic){ var ratio=yearsDic[year]/sum; var id=thisNode.attr('id').split('e')[1]; var linearGradient=svg.select('#linearGradient'+id) linearGradient.selectAll('stop') .each(function(d,i){ var thisStop=d3.select(this); var curOffset=parseFloat(thisStop.attr('offset')); curOffset+=ratio; if(i==1){ thisStop.attr('offset',curOffset); } else if(i==2){ thisStop.attr('offset',curOffset); } }) } }); thisPath.attr('class','yearPath clicked'); thisPath.style('fill',color.yearPathHighlightColor); // thisPath.style('stroke',color.yearPathHighLightStroke); } } var subYearPathDataList=[[]]; var yearPathDataList=[]; var k=0; for(var i=0;i<dataSet.length-1;i++){ var yearPathData={}; var p1=[xScale(dataSet[i][0])-1,yScale(0)]; var p2=[xScale(dataSet[i][0])-1,yScale(dataSet[i][1])]; var p3=[xScale(dataSet[i+1][0]),yScale(dataSet[i][1])]; var p4=[xScale(dataSet[i+1][0]),yScale(0)]; if(pathClass=='subYearPath'){ if(dataSet[i][1]!=0){ subYearPathDataList[k].push({i:i, data:dataSet[i]}); } else{ k+=1; subYearPathDataList[k]=[]; } } else{ yearPathData.d='M'+p1[0]+','+p1[1]+' L'+p2[0]+','+p2[1] +' '+p3[0]+','+p3[1]+' '+p4[0]+','+p4[1]; yearPathData.year = dataSet[i][0]; yearPathData.class = pathClass; yearPathData.fill = color.yearPathColor; yearPathData.stroke = 'none'; yearPathDataList.push(yearPathData); } var d; } // console.log(subYearPathDataList); var finalSubYearPathDataList=[]; for(var i=0;i<subYearPathDataList.length;i++){ var len=subYearPathDataList[i].length if(len>0) { var start = subYearPathDataList[i][0].i - 1; var end = subYearPathDataList[i][len - 1].i + 1; if (dataSet[start])subYearPathDataList[i] = [{data:dataSet[start],i:start}].concat(subYearPathDataList[i]); if (dataSet[end])subYearPathDataList[i] = subYearPathDataList[i].concat([{data:dataSet[end],i:end}]); finalSubYearPathDataList.push(subYearPathDataList[i]); } } for(var i=0;i<finalSubYearPathDataList.length;i++){ if(finalSubYearPathDataList[i][0].i==0){ finalSubYearPathDataList[i]=[{i:0,data:[finalSubYearPathDataList[i][0].data[0],0]}].concat(finalSubYearPathDataList[i]) } if(finalSubYearPathDataList[i][finalSubYearPathDataList[i].length-1].i==dataSet.length-1){ finalSubYearPathDataList[i]=finalSubYearPathDataList[i].concat([{i:dataSet.length-1,data:[finalSubYearPathDataList[i][finalSubYearPathDataList[i].length-1].data[0],0]}]) } } for(var i=0;i<finalSubYearPathDataList.length;i++){ for(var j=0;j<finalSubYearPathDataList[i].length;j++){ var p=[xScale(finalSubYearPathDataList[i][j].data[0].toInt()),yScale(finalSubYearPathDataList[i][j].data[1])] finalSubYearPathDataList[i][j]=p; } } for(var i=0;i<finalSubYearPathDataList.length;i++){ var subYear={}; subYear.class = 'subYearPath'; subYear.fill = color.yearPathHighlightColor; subYear.stroke = color.yearPathHighLightStroke; subYear.strokeWidth=2+px; subYear.d = ''; if(finalSubYearPathDataList[i].length>=3){ var tmp=finalSubYearPathDataList[i]; subYear.d+='M'+tmp[0][0]+','+tmp[0][1]+'L'+tmp[1][0]+','+tmp[0][1]+','+tmp[1][0]+','+tmp[1][1]; for(var j=1;j<tmp.length-1;j++){ subYear.d+=','+tmp[j][0]+','+tmp[j][1]+','+tmp[j+1][0]+','+tmp[j][1]+','+tmp[j+1][0]+','+tmp[j+1][1]; } } finalSubYearPathDataList[i]=subYear; } // console.log(finalSubYearPathDataList) if(pathClass == 'subYearPath'){ axisSVG.selectAll('whatever') .data(finalSubYearPathDataList) .enter() .append('path') .each(function(d){ d3.select(this) .attrs({ d: d.d, class: d.class }) .styles({ fill:d.fill, stroke:d.stroke, 'stroke-width': d.strokeWidth }) }) } else{ axisSVG.selectAll('whatever') .data(yearPathDataList) .enter() .append('path') .each(function(d){ d3.select(this) .attrs({ d:d.d, year:d.year, class:d.class }) .styles({ fill: d.fill }) .on('click',yearPathClick) }) } // axisSVG.append('path') // .attr('d',d) // .attr('year',dataSet[i][0]) // .attr('class',pathClass) // .style('fill',function(d){ // if(pathClass=='yearPath'){ // return color.yearPathColor; // } // else if(pathClass=='subYearPath'){ // return color.yearPathHighlightColor; // } // }) // .style('stroke',function(d){ // if(pathClass=='yearPath'){ // return 'none'; // } // else if(pathClass=='subYearPath'){ // return color.yearPathHighLightStroke; // } // }) // .style('stroke-width','3px') // .on('click',yearPathClick) for(var i=0;i<dataSet.length;i++){ if(pathClass!='subYearPath'){ axisSVG.append('text') .attrs({ x:(xScale(dataSet[i][0])+xScale(dataSet[i][0]+1))/2-String(dataSet[i][1]).visualLength()/2+3, y:yScale(dataSet[i][1])-2 }) .styles({ 'font-size':9+px, 'font-family':'Arial', 'color':color.yearPathHighlightColor }) .html(dataSet[i][1]); } } } function axisLayout(d) { this.drawAnimateControlPanel(); this.drawYearAxis(d.nodeYearData); } function getMulEdgeSourceTargetDic(edges) { var dic = {}; for (var i = 0; i < edges.length; i++) { var edge = edges[i]; var source = edge.source; var target = edge.target; var key = source + '_' + target; if (dic[key]) { dic[key].push(edge); } else { dic[key] = [edge]; } } return dic; } function adjustLayer(k,t) { currentLayer.background.style('cursor', '-webkit-grabbing'); var svg = currentLayer.svg; var layer = svg.select('.svgDrawer'); t=t||'translate('+0+','+0+')scale('+width/svgWidth+')'; layer.attr("transform", t); currentLayer.zoomK = k; //layer.select('.mask0').attr("transform","translate("+ t.x+","+ t.y+"),scale("+ parseFloat(1/t.k)+")"); //layer.select('.mask1').attr("transform","translate("+ t.x+","+ t.y+"),scale("+ parseFloat(1/t.k)+")"); layer.selectAll('.node') .attr('r', function (d) { return d.nodeR / k; }) .style('stroke-width', function (d) { return d.strokeWidth / k; }); layer.selectAll('.size') .styles({ 'font-size': function (d) { return d.fontSize / k; } }) .attrs({ y: function (d) { return d.y + d.nodeSizeTextShiftY / t.k; } }); layer.selectAll('.label') .styles({ 'font-size': function (d) { return d.fontSize / k; } }) .each(function (d) { var thisLabel = d3.select(this); var indexStr = thisLabel.attr('index'); var prefix = indexStr.split('_')[0]; var index = indexStr.split('_')[1]; thisLabel.attrs({ y: d.y + d[prefix + 'Y'][index] / initDMax * (dMax+dMin-8) / k }); }); layer.selectAll('image') .attrs({ x: function (d) { return d.x + d.imageShift / k }, y: function (d) { return d.y + d.imageShift / k }, width: function (d) { return d.imageSize / k + px }, height: function (d) { return d.imageSize / k + px } }); layer.select('.edgeField').selectAll('path') .attr('d', function (d) { return pathData(d, d.that, k); }) .styles({ 'stroke-width': function (d) { return d.strokeWidth / k + px } }); } function graphZoom() { var t = d3.event.transform; adjustLayer(t.k,t); } function layout(optionNumber, doTransition, transitionType, d) { var that = this; var zoom = d3.zoom() .scaleExtent([-Infinity, +Infinity]) .on("zoom", graphZoom) .on('end', function () { leftLayer.background.style('cursor', '-webkit-grab'); }); that.svgZoom = zoom; var svg = this.svg; svg.call(zoom); var containers = [svg.svg_g]; var drawnodes = this.drawnodes; var drag = d3.drag() .subject(function (d) { return d; }) .on('drag', dragmove); this.drag = drag; this.currentData = d; this.currentEdgeSourceTargetDic = getMulEdgeSourceTargetDic(d.edge); this.getRelation(d); if (!d.keepAll)this.removeSVGElements(); this.drawBackgroundYear(doTransition); this.drawEdges(optionNumber, doTransition, transitionType, d); this.drawLabels(optionNumber, doTransition, transitionType, d); this.drawNodes(optionNumber, doTransition, transitionType, d); // drawSelfEdge(optionNumber,doTransition,doIncremental,d); this.drawSize(optionNumber, doTransition, transitionType, d); // removeDuplicationLabels(d.node); this.drawLegends(); } function nodePositionToInt(d) { var nodes = d.node; var edges = d.edge; nodes.forEach(function (node) { node.x = parseInt(node.x); node.y = parseInt(node.y); }); //edges.forEach(function (edge) { // if(edge.pathNodeList){ // edge.pathNodeList.forEach(function(node){ // node.x = parseInt(node.x); // node.y = parseInt(node.y); // }) // } //}) } function pathData(d, that, zoomK) { var zoom = zoomK || 1; var sizeScale = that.sizeScale; var svg = that.svg; var focusedID = that.focusedID; var p = d.points; var data = that.data; var nodes = data.postData[focusedID].node; var oriEdgeDic = nodes.edgeDic; var method = that.method; if (d.isNontreeEdge) { d.type = 'L'; } else { d.type = 'curveMonotoneX'; } var flow = d.flow; switch (d.type) { case 'L': { var x1, y1, x2, y2, r1, r2, dis; var len = p.length; len = len - 1; dis = distance(p[0].x, p[0].y, p[len].x, p[len].y); r1 = sizeScale.sizeScale(p[0].size); r2 = sizeScale.sizeScale(p[len].size); x1 = getstart(p[0].x, p[len].x, r1, dis); y1 = getstart(p[0].y, p[len].y, r1, dis); x2 = getend(p[len].x, p[0].x, r2, dis); y2 = getend(p[len].y, p[0].y, r2, dis); return [ 'M', p[0].x, ' ', p[0].y, //' ', (p[0].x+ p[len].x)/2, ' ', (p[0].y+ p[len].y)/2, 'L', p[len].x, ' ', p[len].y ].join(''); //return [ // 'M', x1, ' ', y1, // 'L', x2, ' ', y2 //].join(''); } case 'curveMonotoneX': { var pathD = 'M'; var target = nodes[d.target]; var targetRadius = sizeScale.sizeScale(target.size); var newPathNodeList = []; var regStr; function drawTreeEdge() { var nodeSet = d3.set(); var key = d.source + '_' + d.target + '_background'; nodeSet.add(d.source); nodeSet.add(d.target); d.pathNodeList.forEach(function (nodeId) { var node = nodes[nodeId] if (node.id == d.source) { //newPathNodeList.push(node.move(node,0, node.edgeShiftDic[key].shiftIn)); newPathNodeList.push(node.move(node, 0, node.edgeShiftDic[key].shift / zoom)); if (node.cp1) { var cp = new Point(node.cp1.x, node.cp1.y); newPathNodeList.push(cp.move(0, node.edgeShiftDic[key].shift / zoom)); newPathNodeList.push(cp.move(-1 / zoom, node.edgeShiftDic[key].shift / zoom)); } } else { newPathNodeList.push(node); if (node.cp1) { var cp = new Point(node.cp1.x, node.cp1.y); newPathNodeList.push(cp); newPathNodeList.push(cp.move(-1 / zoom, 0)); } } }); var source = nodes[d.pathNodeDic[d.source]]; var target = nodes[d.pathNodeDic[d.target]]; if (nodeSet.has(d.source)) { source = source.move(source, 0, source.edgeShiftDic[key].shift / zoom); } if (nodeSet.has(d.target)) { target = target.move(target, 0, target.edgeShiftDic[key].shift / zoom); } return regStr = source.x + "," + source.y + "(.*)" + target.x + "," + target.y; } function drawRecoveredTreeEdge() { var nodeSet = d3.set(); var key = d.source + '_' + d.target; d.pathNodeList.forEach(function (node) { nodeSet.add(node.id); }); d.longPathNodes.forEach(function (node) { if (nodeSet.has(node.id)) { newPathNodeList.push(node.move(node, 0, node.edgeShiftDic[key].shiftOut)); if (node.cp1) { var cp = new Point(node.cp1.x, node.cp1.y); newPathNodeList.push(cp.move(0, node.edgeShiftDic[key].shiftOut)); newPathNodeList.push(cp.move(-1, node.edgeShiftDic[key].shiftOut)); } } else { newPathNodeList.push(node); if (node.cp1) { var cp = new Point(node.cp1.x, node.cp1.y); newPathNodeList.push(cp); newPathNodeList.push(cp.move(-1, 0)); } } }); var source = d.pathNodeDic[d.source]; var target = d.pathNodeDic[d.target]; if (nodeSet.has(d.source)) { source = source.move(source, 0, source.edgeShiftDic[key].shiftOut); } if (nodeSet.has(d.target)) { target = target.move(target, 0, target.edgeShiftDic[key].shiftOut); } return regStr = source.x + "," + source.y + "(.*)" + target.x + "," + target.y; } function drawForegroundEdges() { var shift; var sourceShift = 0; var targetShift = 0; for (var i = 0; i < d.longPathNodes.length; i++) { var p = nodes[d.longPathNodes[i]]; if (p.id in d.nodeShiftDic) { shift = d.nodeShiftDic[p.id]; } else { shift = 0; } newPathNodeList.push(p.move(p, 0, shift / zoom)); if (p.cp1) { var cp = new Point(p.cp1.x, p.cp1.y); newPathNodeList.push(cp.move(0, shift / zoom)); newPathNodeList.push(cp.move(-1, shift / zoom)); } } var len = d.pathNodeList.length; //var sourcePartKey = d.pathNodeList[0].id + '_' + d.pathNodeList[1].id; //var targetPartKey = d.pathNodeList[len - 2].id + '_' + d.pathNodeList[len - 1].id; var sourcePartKey = d.pathNodeList[0] + '_' + d.pathNodeList[1]; var targetPartKey = d.pathNodeList[len - 2] + '_' + d.pathNodeList[len - 1]; var source = nodes[d.pathNodeDic[d.source]]; var target = nodes[d.pathNodeDic[d.target]]; //if (sourcePartKey in d.shiftDic) { source = source.move(source, 0, d.nodeShiftDic[d.source] / zoom); //} //if (targetPartKey in d.shiftDic) { target = target.move(target, 0, d.nodeShiftDic[d.target] / zoom); //} return regStr = source.x + "," + source.y + "(.*)" + target.x + "," + target.y; } if (d.isBackgroundEdge) { regStr = drawTreeEdge(); } else if (d.isForegroundTargetEdge) { regStr = drawForegroundEdges(); } else if (d.isForegroundSourceEdge) { regStr = drawForegroundEdges(); } //else if(d.isForegroundEdge){ // console.log(d); // regStr=drawForegroundEdges(); //} if (newPathNodeList.length > 0) { var reg = new RegExp(regStr); var res; svg.append('path') .attr('class', 'monotoneX') .datum(newPathNodeList) .attr('d', d3.line() .curve(d3.curveMonotoneX) .x(function (d) { return d.x; }) .y(function (d) { return d.y; }) ) .styles({ 'stroke': 'yellow', 'stroke-width': '2px', 'fill': 'none' }) .each(function () { res = reg.exec(d3.select(this).attr('d'))[0]; }) .remove(); pathD += res; var tmpPath = svg.append('path') .attr('d', pathD) .style('stroke', 'none') .style('fill', 'none') .each(function () { var thisEdge = d3.select(this); var totalLength = thisEdge.node().getTotalLength(); var asspoint = thisEdge.node().getPointAtLength((totalLength * (1 - targetRadius / totalLength) - 11)); var point = thisEdge.node().getPointAtLength((totalLength * (1 - targetRadius / totalLength) - 10)); pathD += 'M' + asspoint.x + ' ' + asspoint.y + 'M' + point.x + ' ' + point.y }); tmpPath.remove(); } return pathD; } } } function removeDuplicationLabels(nodes) { for (var i = 0; i < nodes.length; i++) { var id = '#label' + nodes[i].id; svg.selectAll(id) .each(function (d, i) { var thisLabel = d3.select(this); if (thisLabel.attr('isBackground')) { thisLabel.remove(); } }); } } function greyBackground() { var svg = this.svg; var svg_g = this.svg_g; // drawnodes.selectAll('.node') // .style('fill','lightgrey'); svg.select('.rectBackground').remove(); var width = svg.attr('width'); var height = svg.attr('height'); //mask设定这么大是因为设置小了在缩放时可能会把后面的漏出来 var maskingOutData = [ { class: 'outer mask0', index: 1, x: -5 * width, y: -5 * height, width: width * 11, height: height * 11, 'fill': color.svgColor, 'opacity': 0.6, rectClass: 'rect' }, { class: 'outer mask1', index: 3, x: -5 * width, y: -5 * height, width: width * 11, height: height * 11, 'fill': color.svgColor, 'opacity': 0.75, rectClass: 'rect' } ]; svg_g.selectAll('whatever') .data(maskingOutData) .enter() .append('g') .attrs({ class: function (d) { return d.class }, index: function (d) { return d.index } }) .each(function (d) { d3.select(this) .append('rect') .attrs({ class: function (d) { return d.rectClass }, x: function (d) { return d.x }, y: function (d) { return d.y }, height: function (d) { return d.height }, width: function (d) { return d.width } }) .styles({ fill: function (d) { return d.fill }, opacity: function (d) { return d.opacity } }) }); // svg_g.append('rect') // .attrs({ // class:'rectBackground', // x:0, // y:0, // width:width, // height:height // }) // .styles({ // 'fill':'rgb(15,40,60)', // 'opacity':0.85 // }); svg.selectAll('path').attr('isBackground', 1); svg.selectAll('.node').attr('isBackground', 1); svg.selectAll('.size').remove(); svg.selectAll('.label').attr('isBackground', 1); this.initFrameIndex(4) } function removeSVGElements() { var animateMode = this.animateMode; var svg_g = this.svg_g; if (animateMode == flipBook) { svg_g.selectAll('g') .each(function (d) { if (d.index > 0)d3.select(this).remove(); }); this.drawnodes = svg_g.select('#nodeG0'); this.drawedges = svg_g.select('#edgeG0'); this.drawnodes.selectAll('*').remove(); this.drawedges.selectAll('*').remove(); } else { svg_g.select('#nodeG2').remove(); svg_g.select('#edgeG2').remove(); this.drawnodes .attr('index', function (d) { d.index = 2; return d.index }) .attr('id', function (d) { return 'nodeG' + d.index }); this.drawedges .attr('index', function (d) { d.index = 2; return d.index }) .attr('id', function (d) { return 'edgeG' + d.index }); this.drawedges.select('.edgeField').selectAll('path') .each(function (d) { d3.select(this) .attrs({ class: function (d) { d.class = 'edgeG2' + d.class.split('G4')[1] return d.class } }) }); this.drawedges.selectAll('.marker') .each(function (d) { d3.select(this) .attrs({ id: function (d) { d.id = 'edgeG2' + d.id.split('G4')[1] return d.id } }) }); this.initFrameIndex(4); svg_g.selectAll('.outer') .sort(function (a, b) { return d3.ascending(a.index, b.index); }); } } function drawAuthorInfo() { var authorDiv = d3.select('.authorDiv'); authorDiv.selectAll('div').remove(); if (focusedID.split('_').length == 2)var tmpID = focusedID.split('_')[0]; if (authorData[tmpID]) { var authorInfo = authorData[tmpID]; } else { var authorInfo = authorData['default']; } for (var i = 0; i < 2; i++) { var authorDivWidth = authorDiv.style('width').split('px')[0] - 2; var authorDivHeight = authorDiv.style('height').split('px')[0]; var authorInfoDiv = authorDiv.append('div').attr('class', 'authorInfoDiv') .styles({ float: 'left', height: authorDivHeight + px, width: authorDivWidth / 2 + px }); var lineRatio = 0.75 if (i == 0) { var lineDiv = authorDiv.append('div').styles({ float: 'left', background: 'rgb(35,78,108)', width: '2px', height: authorDivHeight * lineRatio + px, 'margin-top': authorDivHeight * (1 - lineRatio) / 2 + px }); } var marginRatio = 0.2; var imageRatio = 0.6; authorInfoDiv.append('div').attr('class', 'imageDiv') .styles({ float: 'left', width: authorDivHeight * imageRatio + px, height: authorDivHeight * imageRatio + px, 'margin-left': authorDivHeight * marginRatio + px, 'margin-top': authorDivHeight * marginRatio + px }) .append('img').attr('class', 'img').attr('src', authorInfo[i].image) .styles({ 'border-radius': 5 + px, width: authorDivHeight * imageRatio + px, height: authorDivHeight * imageRatio + px }); d3.select('.ruler').style('font-size', '14px'); var authorTextDiv = authorInfoDiv.append('div').attr('class', 'authorTextDiv') .styles({ float: 'left', width: authorDivWidth / 2 - authorDivHeight * (marginRatio + 0.05) - authorDivHeight * imageRatio + px, height: authorDivHeight * imageRatio + px, 'margin-top': authorDivHeight * marginRatio + px, 'margin-left': authorDivHeight * 0.05 + px }) authorTextDiv.append('div').attr('class', 'authorNameDiv').append('text') .styles({ 'font-family': 'Microsoft YaHei', 'font-size': 14 + px }) .html(function (d) { return authorInfo[i]['author'] + ':'; }) for (var key in authorInfo[i]) { if (key != 'author' && key != 'title' && key != 'image') authorTextDiv.append('div').attr('class', 'authorNameDiv').append('text') .styles({ 'font-family': 'Microsoft YaHei', 'font-size': function (d) { return 11 + px; } }) .html(function (d) { return authorInfo[i][key]; }) } } } function getstart(origin1, origin2, r, d) { if (d != 0) return origin1 + (r / d) * (origin2 - origin1); else return origin1; } function getend(origin1, origin2, r, d) { var ratio = r + 13 / d; // if(d!=0) return origin1*ratio+origin2*(1-ratio); if (d != 0) return origin1 + ((r + 13) / d) * (origin2 - origin1); else return origin1; } function findBoxOfPoints(points) { var maxX = d3.max(points, function (d) { return d.x }) var maxY = d3.max(points, function (d) { return d.y }) var minX = d3.min(points, function (d) { return d.x }) var minY = d3.min(points, function (d) { return d.y }) return { x: minX, y: minY, width: maxX - minX, height: maxY - minY } } function getStrokeWidth(d) { var stroke_width; var that = d.that; var flowScale = that.flowScale; var weightScale = that.weightScale; if (optionNumber.edgeThicknessOption == 1) { stroke_width = flowScale(d.flow); } else if (optionNumber.edgeThicknessOption == 0) { var weightSum = 0; for (var key in d.weight) { weightSum += d.weight[key]; } stroke_width = weightScale(weightSum); } return stroke_width; } function drawTitle() { d3.selectAll('.title').remove(); drawTitles.selectAll('text').data(['1']).enter() .append('text') .attrs({ 'x': '95px', 'y': '50px' }) .text(title); } function findFocusedNode() { for (var i = 0; i < nodes.length; i++) { if (nodes[i].nodes) { for (var j = 0; j < nodes[i].nodes.length; j++) { if (nodes[i].nodes[j].focus == 'focused') { nodes[i].focused = true; } } } } } function SizeScale(maxSize) { this.k = 0; var max = d3.max([minMax, maxSize]); this.sizeScale = function (nodeSize) { var r = (dMax - dMin) * (Math.sqrt(nodeSize) / Math.sqrt(max)) + dMin; return r; }; } function getSelfData(nodes) { for (var i = 0; i < nodes.length; i++) { if (nodes[i].selfEdge) { var size = nodes[i].size; var r = sizeScale.sizeScale(size); var x = nodes[i].x; var y = nodes[i].y; var d = 2; var selfEdgeLabelX = x; var selfEdgeLabelY = y - (5 / 3 * r + d); nodes[i].selfPathStr = selfPathData(x, y, size); nodes[i].selfEdgeLabelX = selfEdgeLabelX; nodes[i].selfEdgeLabelY = selfEdgeLabelY; } } } function selfPathData(x, y, size) { var r = sizeScale.sizeScale(size); var d = 2; var pi = Math.PI; var degree = 25 / 360 * pi; var x1 = x - (r + d) * Math.sin(degree); var x2 = x + (r + d) * Math.sin(degree); var y1 = y - (r + d); var y2 = y - (r + d); var rx = r / 3; var ry = r / 3; return 'M' + x1 + ' ' + y1 + 'A' + rx + ' ' + ry + ' ' + 0 + ' ' + 1 + ' ' + 1 + ' ' + x2 + ' ' + y2; } function getSelfEdgeStrokeWidth(d) { var stroke_width; if (optionNumber.edgeThicknessOption == 1) { stroke_width = flowScale(d.selfEdge); } else if (optionNumber.edgeThicknessOption == 0) { var weight = parseInt(d.selfEdge * d.size); stroke_width = weightScale(weight); } return stroke_width; } function setTransition(div, location, marginLeft, marginTop, isVertical) {//location should be the final place after transition var duration = 500; if (isVertical) { div.transition() .duration(duration) .styles({ height: location + px, 'margin-left': marginLeft + px, 'margin-top': marginTop + px }) } else { div.transition() .duration(duration) .styles({ width: location + px, 'margin-left': marginLeft + px, 'margin-top': marginTop + px }) } } function recoverScreen() { var duration = 500; var bodyDiv = d3.select('.bodyDiv'); var hiddenDivList = { top: ['titleDiv', 'middleTopBarDiv'], bottom: ['authorDiv'], left: ['leftAndTransitionDiv'], right: ['rightDiv'] }; var hiddenElementList = ['div', 'text']; for (var key in hiddenDivList) { for (var i = 0; i < hiddenDivList[key].length; i++) { var thisDiv = bodyDiv.select('.' + hiddenDivList[key][i]); var originWidth = thisDiv.attr('oldWidth').split('px')[0]; var originHeight = thisDiv.attr('oldHeight').split('px')[0]; if (key == 'top') { setTransition(thisDiv, originHeight, 0, 0, true); } else if (key == 'bottom') { setTransition(thisDiv, originHeight, 0, 0, true); } else if (key = 'left') { setTransition(thisDiv, originWidth, 0, 0, false); } else if (key == 'right') { setTransition(thisDiv, originWidth, 0, 0, false); } for (var j = 0, len1 = hiddenElementList.length; j < len1; j++) { thisDiv.selectAll(hiddenElementList[j]) .styles({ display: 'block' }); } } } var middleDiv = d3.select('.middleDiv'); middleDiv.transition() .duration(duration) .styles({ width: middleDiv.attr('oldWidth'), height: middleDiv.attr('oldWidth') }); var top = middleDiv.select('.topControlDiv'); top.transition() .duration(duration).styles({ width: top.attr('oldWidth') }); // var bottom = middleDiv.select('.bottomControlDiv'); bottom.transition() .duration(duration).styles({ width: bottom.attr('oldWidth') }); var svgHeight = usefulHeight - parseFloat(top.style('height').split('px')[0]) - parseFloat(bottom.style('height').split('px')[0]); var graphDiv = middleDiv.select('.graphDiv'); graphDiv.transition() .duration(duration) .styles({ width: graphDiv.attr('oldWidth'), height: graphDiv.attr('oldHeight') }); var middleSVG = middleDiv.select('svg'); middleSVG.transition() .duration(duration) .attrs({ width: svg.attr('oldWidth'), height: svg.attr('oldHeight') }) .each('end', function () { size = { width: svg.attr('oldWidth') * 0.85, height: svg.attr('oldHeight') * 0.7 }; coordinateOffset(data.postData[focusedID]); getCurves(data.postData[focusedID]); // layout(optionNumber, true, 'flowMap', data.postData[focusedID]); }); } function getLength(divClass, type) { return parseFloat(d3.select('.' + divClass).style(type).split('px')[0]); } function fullScreen() { var duration = 500 changeDivList = ['titleDiv', 'middleTopBarDiv', 'authorDiv', 'leftAndTransitionDiv', 'rightDiv', 'middleDiv', 'topControlDiv', 'bottomControlDiv', 'graphDiv']; function storeOldDivData(div) { div.attr('oldWidth', div.style('width')); div.attr('oldHeight', div.style('height')); } for (var i = 0, len = changeDivList.length; i < len; i++) { storeOldDivData(d3.select('.' + changeDivList[i])); } svg.attr('oldWidth', svg.attr('width')); svg.attr('oldHeight', svg.attr('height')); // layout(optionNumber); var bodyDiv = d3.select('.bodyDiv'); var hiddenDivList = { top: ['titleDiv', 'middleTopBarDiv'], bottom: ['authorDiv'], left: ['leftAndTransitionDiv'], right: ['rightDiv'] }; var hiddenElementList = ['div', 'text']; var topHeight = getLength('titleDiv', 'height') + getLength('middleTopBarDiv', 'height'); var bottomHeight = getLength('authorDiv', 'height'); var leftWidth = getLength('leftAndTransitionDiv', 'width'); var rightWidth = getLength('rightDiv', 'width'); for (var key in hiddenDivList) { for (var i = 0; i < hiddenDivList[key].length; i++) { var thisDiv = bodyDiv.select('.' + hiddenDivList[key][i]); if (key == 'top') { setTransition(thisDiv, 0, 0, 0, true); } else if (key == 'bottom') { setTransition(thisDiv, 0, leftWidth, topHeight + bottomHeight, true); } else if (key = 'left') { setTransition(thisDiv, 0, 0, 0, false); } else if (key == 'right') { setTransition(thisDiv, 0, leftWidth + rightWidth, 0, false); } for (var j = 0, len1 = hiddenElementList.length; j < len1; j++) { thisDiv.selectAll(hiddenElementList[j]) .styles({ display: 'none' }); } } } var middleDiv = d3.select('.middleDiv'); middleDiv.transition() .duration(duration) .styles({ width: usefulWidth + px, height: usefulHeight + px }); var top = middleDiv.select('.topControlDiv'); top.transition() .duration(duration).styles({ width: usefulWidth + px }); // var bottom = middleDiv.select('.bottomControlDiv'); bottom.transition() .duration(duration).styles({ width: usefulWidth + px }); var svgHeight = usefulHeight - parseFloat(top.style('height').split('px')[0]) - parseFloat(bottom.style('height').split('px')[0]); middleDiv.select('.graphDiv') .transition() .duration(duration) .styles({ width: usefulWidth + px, height: svgHeight + px }); var middleSVG = middleDiv.select('svg'); middleSVG.transition() .duration(duration) .attrs({ width: usefulWidth, height: svgHeight }) .each('end', function () { size = { width: usefulWidth * 0.85, height: svgHeight * 0.7 }; coordinateOffset(data.postData[focusedID]); getCurves(data.postData[focusedID]); // layout(optionNumber, true, 'flowMap', data.postData[focusedID]); }); } function reLayoutFlowMap(){ var focusedID=this.focusedID; var data=this.data; var newEdges=[]; var edges=data.postData[focusedID].edge; var treeEdges= data.postData[focusedID].deletedTreeEdges; var nonTreeEdges=data.postData[focusedID].deletedNonTreeEdges; for(var i=0;i<edges.length;i++){ if(edges[i].structureType=='originEdge'&&edges[i].ratio==1){ newEdges.push(edges[i]); } // else if(edges[i].structureType=='treeEdge'){ // nonTreeEdges.push(edges[i]); // } // else if(edges[i].structureType=='nontreeEdge'){ // nonTreeEdges.push(edges[i]); // } } data.postData[focusedID].edge=newEdges; this.calculateFlowMap(data.postData[focusedID],true); this.setInitNodeTransition(data.postData[focusedID]); this.setInitEdgeTransition(data.postData[focusedID]); this.getRelation(data.postData[focusedID]); getCurves(data.postData[focusedID]); if(data.postData[focusedID].subNodeYearData){ var subNodeYearData=data.postData[focusedID].subNodeYearData; for (var i=0;i<subNodeYearData.length;i++){ subNodeYearData[i][1]=0; } } this.preLayout(data.postData[focusedID]); d3.select('.edgeField').selectAll('path') .each(function(){ var thisEdge=d3.select(this); var edgeClass=thisEdge.attr('class'); if(parseInt(edgeClass.split('path')[1])>151){ thisEdge.remove() } }); } function clusterSlider(){ var minID=parseInt(focusedID.split('_')[1]); var min=minID/5-1; var max=7; var k=5; $(function(){ $(".clusterSlider").slider({ range:'min', max:max, value:min, slide:function(event,ui){ // console.log(ui.value); reLayoutByCluster(event, ui); } }); $( ".clusterText" ).html( 5*(parseInt($( ".clusterSlider" ).slider("value"))+1)); }) } function reLayoutByCluster(event,ui){ var cluster=5*(ui.value+1); selectedCluster=cluster; var urlID=getUrlParam('id'); var paperID=parseInt(urlID.split('_')[0]); $( ".clusterText" ).html(cluster); var searchID=String(paperID)+'_'+String(cluster); search(searchID); } function yearSlider(){ yearEdgeDic=getYearEdgeRelation(); var min=10000; var max=0; for(var key in yearEdgeDic){ var year=parseInt(key); if(year>max)max = year; if(year<min)min = year; } yearDataHistory={}; var key=String(min)+'-'+String(max); yearDataHistory[key]={ nodes:copy(nodes), edges:copy(edges) }; $(function() { $( "#yearSlider" ).slider({ range: true, min: min, max: max, values: [ min, max ], slide: function( event, ui ) { reLayoutByYear(event,ui); } }); $( ".yearText" ).html( $( "#yearSlider" ).slider( "values", 0 ) + " - " + $( "#yearSlider" ).slider( "values", 1 ) ); }); } function reLayoutByYear(event, ui){ $( ".yearText" ).html(ui.values[ 0 ] + " - " + ui.values[ 1 ] ); var yearRange={ min:ui.values[0], max:ui.values[1] }; dataFilter(yearRange); } function copy(data){ var result=[]; for(var i= 0,len=data.length;i<len;i++){ var ob={}; for(var key in data[i]){ ob[key]=data[i][key]; } result.push(ob); } return result; } function dataFilter(yearRange){ var yearEdgeDic=getYearEdgeRelation(); var currentData=data.postData[focusedID]; var nodes=currentData.node; var edges=currentData.edge; // oldEdges_yearFilter=[]; // var newEdges_yearFilter=[]; // oldNodes_yearFilter=[]; // var newNodes_yearFilter=[]; // var nodesArray=[]; var min=yearRange.min; var max=yearRange.max; var newEdges=[]; var newNodeList=[]; var newNodes=[]; var nodesKey=[]; var nodesKeyDic={}; var num=0; for(var i=0;i<edges.length;i++){ var edgeYear=edges[i].weight; for(var key in edgeYear){ var year=parseInt(key); if(year>=min&&year<=max){ //edge and its source and target should be stored var newEdge={}; var source=edges[i].source; var target=edges[i].target; if(!in_array(source,nodesKey)){ nodesKey.push(source); nodesKeyDic[source]=num; nodes[source].id=nodesKeyDic[source] newNodes.push(nodes[source]); num+=1; } if(!in_array(target,nodesKey)){ nodesKey.push(target); nodesKeyDic[target]=num; nodes[target].id=nodesKeyDic[target] newNodes.push(nodes[target]); num+=1; } clone(edges[i],newEdge); newEdge.source = nodesKeyDic[newEdge.source]; newEdge.target = nodesKeyDic[newEdge.target]; newEdge.nodes[0]=newEdge.source; newEdge.nodes[1]=newEdge.target; newEdges.push(newEdge); break; } } } data.timeData[focusedID]={}; data.timeData[focusedID].node = newNodes; data.timeData[focusedID].edge = newEdges; data.timeData[focusedID].nodeYearData = data.postData[focusedID].nodeYearData; data.timeData[focusedID].subNodeYearData = data.postData[focusedID].subNodeYearData; getRelation(data.timeData[focusedID]); var assistEdge=generateAssistEdge(data.timeData[focusedID]); var newGraph=new Graph(data.timeData[focusedID].edge,assistEdge); reCalculateLayout(newGraph,data.timeData[focusedID]); reverseXY(data.timeData[focusedID]); coordinateOffset(data.timeData[focusedID]); getYearData(data.timeData[focusedID]); if(preFocusedID) { procrustes(data.timeData[preFocusedID],data.timeData[focusedID]); coordinateOffset(data.timeData[focusedID]); coordinateOffset(data.timeData[preFocusedID]); } findCircleEdges(data.postData[focusedID]); getCurves(data.timeData[focusedID]); // drawAuthorInfo(); if(focusedID&&preFocusedID){ var fID=parseInt(focusedID.split('_')[1]); var pID=parseInt(preFocusedID.split('_')[1]); if(fID>pID){ //incremental // var chlData=data.postData[preFocusedID]; // var parData=data.postData[focusedID]; generateTransitionData(data.timeData[focusedID],data.timeData[preFocusedID]); } else if(fID<pID){ //decremental generateTransitionData(data.timeData[preFocusedID],data.timeData[focusedID]); } } if(focusedID&&preFocusedID){ layout(optionNumber,false,false,data.timeData[focusedID]); } else{ layout(optionNumber,false,false,data.timeData[focusedID]); } // yearSlider(); // clusterSlider(); } function compareVersions (v1, v2) { if (v1 === v2) { return 0; } var v1parts = v1.split('_').map(parseFloat); var v2parts = v2.split('_').map(parseFloat); var len = Math.min(v1parts.length, v2parts.length); for (var i = 0; i < len; i++) { if (parseInt(v1parts[i]) > parseInt(v2parts[i])) { return 1; } if (parseInt(v1parts[i]) < parseInt(v2parts[i])) { return -1; } } if (v1parts.length > v2parts.length) { return 1; } if (v1parts.length < v2parts.length) { return -1; } return 0; } var v1='1_0.8690847534228847'; var v2='0_0.11302401181690515_0.11302401181690623_0.11302401181690616'; var v3='0_0.11302401181690515_0.11302401181690623'; var r1=compareVersions(v1,v2); var r2=compareVersions(v2,v3); var r3=compareVersions(v2,v2); console.log(r1) console.log(r2) console.log(r3) function ifPointInCircle(point,circle){ var x=point.x; var y=point.y; var cx=circle.x; var cy=circle.y; var r=circle.r; var dis=getDistance({x:x, y:y},{x:cx, y:cy}); if(dis<=r)return true; else return false; } function ifPointInRect(point,rect){ } function lawOfCosine(p1,p2,p3){ //get angel at p2 var a=getDistance(p1,p2); var b=getDistance(p2,p3); var c=getDistance(p1,p3); return (a*a+b*b-c*c)/(2*a*b); } function getDistance(p1,p2){ var dx=p1.x-p2.x; var dy=p1.y-p2.y; return Math.sqrt(dx*dx+dy*dy); } function ratioPoint(p1,p2,ratio){ var p3={}; p3.x = p1.x*ratio+p2.x*(1-ratio); p3.y = p1.y*ratio+p2.y*(1-ratio); return p3; } function mergeRect(bounds1,bounds2){ var minX1=bounds1.x; var minY1=bounds1.y; var maxX1=bounds1.x+bounds1.width; var maxY1=bounds1.y+bounds1.height; var minX2=bounds2.x; var minY2=bounds2.y; var maxX2=bounds2.x+bounds1.width; var maxY2=bounds2.y+bounds1.height; var minX=d3.min([minX1,minX2]); var minY=d3.min([minY1,minY2]); var maxX=d3.max([maxX1,maxX2]); var maxY=d3.min([maxY1,maxY2]); return { x:minX, y:minY, width:maxX-minX, height:maxY-minY } } function vector3d(x,y,z){ return {x:x, y:y, z:z}; } function vector3dCross(vec1,vec2){ var x=vec1.y*vec2.z-vec1.z*vec2.y; var y=vec2.x*vec1.z-vec2.z*vec1.x; var z=vec1.x*vec2.y-vec1.y*vec2.x; return {x:x, y:y, z:z}; } function vector(p1,p2){ return [p1, p2]; } function getNormalized(vec){ var disX=vec[1].x-vec[0].x; var disY=vec[1].y-vec[0].y; var dist=Math.sqrt(disX*disX+disY*disY); disX/=dist; disY/=dist; return {x:disX,y:disY}; } function absAngleBetween(vector1,vector2){ var angleBetw=angleBetween(vector1,vector2); var vector1Norm=getNormalized(vector1); var vector2Norm=getNormalized(vector2); var dot=-vector1Norm.y*vector2Norm.x+vector1Norm.x*vector2Norm.y; if(dot>=0){ return angleBetw } else{ return 2*Math.PI-angleBetw; } } function angleBetween(vector1,vector2){ var dotValue=dotProduct(vector1,vector2); if(dotValue>=1){ dotValue=1; } else if(dotValue<=-1){ dotValue=-1; } return Math.acos(dotValue); } function dotProduct(vector1,vector2){ var vector1Norm=getNormalized(vector1); var vector2Norm=getNormalized(vector2); return vector1Norm.x*vector2Norm.x+vector1Norm.y*vector2Norm.y; } function get2PointFun(p1,p2){ var x1=p1.x; var y1=p1.y; var x2=p2.x; var y2=p2.y; if(x1!=x2){ var k=(y2-y1)/(x2-x1); var b=y1-k*x1; // return function(x){return k*x+b;} return {k:k, b:b,vertical:false} } else{ return {x:x1, vertical:true} } } function getPointSlopeFun(p,k){ var x0=p.x; var y0=p.y; var b=y0-k*x0; return {k:k, b:b, vertical:false} } function getPointToLineCrossPoint(p1,p2,p3){ //球一点到两点线段垂点的坐标 var x1=p1.x; var x2=p2.x; var x3=p3.x; var y1=p1.y; var y2=p2.y; var y3=p3.y; var line1=get2PointFun(p1, p2); if(line1.vertical){ return {x:x1,y:y3}; } else{ var k1=line1.k; var b1=line1.b; if(k1!=0){ var k2=-1/k1; var line2=getPointSlopeFun(p3, k2); var b2=line2.b; var x=(b2-b1)/(k1-k2); var y=k1*x+b1; return {x:x, y:y}; } else{ return {x:x3, y:y1}; } } } function twoPointIntSquareDistance(p1,p2){ var x1=parseInt(p1.x); var y1=parseInt(p1.y); var x2=parseInt(p2.x); var y2=parseInt(p2.y); return Math.sqrt(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2); } function isPointInLine(point,line){ var p1=line.p1; var p2=line.p2; var maxX=parseInt(d3.max([p1.x, p2.x])); var maxY=parseInt(d3.max([p1.y, p2.y])); var minX=parseInt(d3.min([p1.x, p2.x])); var minY=parseInt(d3.min([p1.y, p2.y])); var x=parseInt(point.x); var y=parseInt(point.y); // var ptop1=twoPointIntSquareDistance(point, p1); // var ptop2=twoPointIntSquareDistance(point, p2); // var p1top2=twoPointIntSquareDistance(p1, p2); // if((ptop1+ptop2)==p1top2){ if((x>=minX&&x<=maxX)&&(y>=minY&&y<=maxY)){ return true; } else return false; } function get2LineCrossPoint(l1,l2){ var p1=l1.p1; var p2=l1.p2; var p3=l2.p1; var p4=l2.p2; var y1=get2PointFun(p1, p2); var y2=get2PointFun(p3, p4); if(!y1.vertical&&!y2.vertical){ var k1=y1.k; var b1=y1.b; var k2=y2.k; var b2=y2.b; var x=(b2-b1)/(k1-k2); var y=k1*x+b1; var point={x:x, y:y}; var isPointInLine1=isPointInLine(point, l1); var isPointInLine2=isPointInLine(point, l2); return {point:point, isPointInLine1:isPointInLine1,isPointInLine2:isPointInLine2}; } else if(y1.vertical&&!y2.vertical){ var x=y1.x; var k=y2.k; var b=y2.b; var y=k*x+b; var point={x:x, y:y}; var isPointInLine1=isPointInLine(point, l1); var isPointInLine2=isPointInLine(point, l2); return {point:point, isPointInLine1:isPointInLine1,isPointInLine2:isPointInLine2}; } else if(!y1.vertical&&y2.vertical){ var x=y2.x; var k=y1.k; var b=y1.b; var y=k*x+b; var point={x:x, y:y}; var isPointInLine1=isPointInLine(point, l1); var isPointInLine2=isPointInLine(point, l2); return {point:point, isPointInLine1:isPointInLine1,isPointInLine2:isPointInLine2}; } else { return false; } } function getRectangleLineCrossPoint(bounds,line){ var x=bounds.x; var y=bounds.y; var width=bounds.width; var height=bounds.height; var p1={x:x, y:y}; var p2={x:x+width, y:y}; var p3={x:x+width, y:y+height}; var p4={x:x, y:y+height}; var line1={p1:p1, p2:p4}; var line2={p1:p3, p2:p4}; var line3={p1:p1, p2:p2}; var line4={p1:p2, p2:p3}; var lines=[line1, line2, line3, line4]; for(var i=0;i<lines.length;i++){ var crossPoint=get2LineCrossPoint(line,lines[i]); if(crossPoint.isPointInLine1&&crossPoint.isPointInLine2){ return crossPoint.point; } } } function moveCircleEdge(e1,e2){ var p1=e1.p1; var p2=e1.p2; var p3=e2.p1; var p4=e2.p2; var pi=Math.PI; var degree; var d=5; if(p1.x==p2.x)degree=pi/2; else { var k=(p1.y-p2.y)/(p1.x-p2.x); degree=Math.atan(k); } var dx=d*Math.sin(degree); var dy=d*Math.cos(degree); moveToLeft(p1, p2, dx, dy); moveToRight(p3, p4, dx, dy); function moveToLeft(p1,p2,dx,dy){ p1.x-=dx; p1.y+=dy; p2.x-=dx; p2.y+=dy; } function moveToRight(p3,p4,dx,dy){ p3.x+=dx; p3.y-=dy; p4.x+=dx; p4.y-=dy; } e1.dx=dx; e1.dy=-dy; e2.dx=-dx; e2.dy=dy; return {e1:e1,e2:e2}; } //import {server,port,errorPort} from '../setting/server'; //import {layoutPapers} from '../searchInteraction/layout'; //import {ajax} from '../processData/request'; function getUrlParam(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r!=null) return unescape(r[2]); return null; //返回参数值 } var px='px'; var usefulWidth= window.innerWidth ||document.body.clientWidth || document.documentElement.clientWidth; var usefulHeight = document.body.clientHeight || document.documentElement.clientHeight || window.innerHeight; initServer(); var body=d3.select('body'); var bodyDiv=body.append('div').attr('class','bodyDiv') // .attrs({ // onkeydown:'keyboardEvent(event.keyCode||event.which);' // }) .styles({ // 'border':'1px solid rgb(50,70,90)', width:usefulWidth+px, height:usefulHeight+px }); body.append('span').attr('id','ruler').attr('class','ruler'); var paperTitle=getUrlParam('title'); var paperID=getUrlParam('id'); var source=getUrlParam('source'); var action=getUrlParam('action'); // var text='Paper List of '+venue; var texts; if(action=='s')texts=['Papers Directly Influenced by: ',paperTitle]; else if(action=='all')texts=['Papers Directly and Indirectly Influenced by: ',paperTitle]; else texts=['Citing List of: ',paperTitle]; var titleData={ class:'title', texts:texts, size:'30', family:'Arial', top:'100', color:'white' }; // titleData['left']=(usefulWidth-titleData.text.visualLength(titleData.family,titleData.size))/2 titleData['left']=200; console.log(titleData); bodyDiv.append('div') .datum(titleData) .each(function(d){ d3.select(this) .attrs({ class: d.class+'Div' }) .styles({ 'margin-left': d.left+px, 'margin-top': d.top+px }); d3.select(this) .append('text') .attrs({ class: d.class+'Text' }) .styles({ 'font-size': d.size+px, 'font-family': d.family, 'color': d.color }) .html(d.texts[0]); d3.select(this) .append('text') .attrs({ class: d.class+'Text' }) .styles({ 'font-size': d.size+px, 'font-family': d.family, 'color': d.color }) .html(d.texts[1]) .on('click',function(d){ var url='graph.html?'; var source='aminerV8'; url+=source+'_id='+ d.id+'&'; url+='selected='+source; url+='&r='+Math.floor(Math.random()*1000000000+1); window.open(url); }) }); var url='http://'+server+':'+port+'/influencedPapers'; // var url='http://'+'127.0.0.1'+':'+3000+'/searchPapers'; var paperListDiv=bodyDiv.append('div') .attrs({ 'class':'paperListDiv' }) .styles({ 'margin-left':titleData.left+px, 'width':'70%', 'height':'auto' }); var success=function(data){ var list=data; list=list.sort(function(a,b){return b.citation- a.citation}); console.log(list); paperListDiv.selectAll('whatever') .data(list) .enter() .append('div') .styles({ 'margin-top':'15px' }) .each(layoutPapers); }; var data={id:paperID,source:source,action:action}; ajax(url,success,data); initLayout(); function getUrlParam(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r!=null) return unescape(r[2]); return null; //返回参数值 } // var r=getUrlParam('r'); // if(!r)window.location='index.html?r='+Math.floor(Math.random()*1000000000+1); function Submit(e) { if(e ==13) { jump(); } } function jump(){ window.location='result.html?searchname='+$('input[name="Text"]').val()+'&r='+Math.floor(Math.random()*1000000000+1); } var px='px'; var usefulWidth= window.innerWidth ||document.body.clientWidth || document.documentElement.clientWidth; var usefulHeight = document.body.clientHeight || document.documentElement.clientHeight || window.innerHeight; initServer(); //var scrollLength=18; //usefulWidth-=scrollLength; //console.log(usefulHeight); var body=d3.select('body'); var bodyDiv=body.append('div').attr('class','bodyDiv') // .attrs({ // onkeydown:'keyboardEvent(event.keyCode||event.which);' // }) .styles({ 'border':'1px solid rgb(50,70,90)', width:usefulWidth+px, height:usefulHeight+px }); body.append('span').attr('id','ruler').attr('class','ruler'); var fontSize=50; var fontFamily='Arial'; var fontWeight='bold'; var text='E I F F E L'; d3.select('.ruler').styles({ 'font-weight':fontWeight }); var textWidth=text.visualLength(fontFamily,fontSize); var textHeight=text.visualHeight(fontFamily,fontSize); var textMarginInput=usefulHeight*0.03; var inputWidth=570; var inputHeight=40; var buttonWidth=60; var buttonHeight=40; var formWidth=634; var formHeight=inputHeight; var indexNameDiv=bodyDiv.append('div').attr('class','indexNameDiv') .styles({ 'width':textWidth+px, 'height':textHeight+px, 'border':'0px solid #000000', 'margin-left':(usefulWidth-textWidth)/2+px, 'margin-top':(usefulHeight-40)/2-textMarginInput-textHeight-18+px // 'margin-top':'100px' }) .append('text').attr('class','indexName') .html(text) .styles({ 'font-size':fontSize+px, 'font-family':fontFamily, 'font-weight':fontWeight, 'color':'white' }); //var indexMainDiv=bodyDiv.append('div').attr('class','indexMain'); //console.log((usefulHeight-inputHeight)/2-textHeight-textMarginInput); var form=bodyDiv.append('div').attr('class','inputForm').attr('autocomplete','on') .styles({ 'width':formWidth+px, 'height':formHeight+px, 'margin-left':(usefulWidth-formWidth)/2+px, 'margin-top':textMarginInput+px }); var input=form.append('div').attr('class','inputDiv') .styles({ width:inputWidth+px, height:inputHeight+px, background:'white' }) .append('input') .attrs({ class:'indexInputBox', type:'text', // onkeydown:'keyboardEvent(event.keyCode||event.which);', id:'echoText', name:'Text', autocomplete:'on' }) .on('keydown',function(d){ if(event.keyCode==13)jump(); // console.log(event) }) .styles({ border:0+px, padding:10+px, width:(inputWidth-20)+px, height:(inputHeight-20)+px }); var button=form.append('div').attr('class','inputButton').append('input') .attrs({ // src:'image/search.png', type:'submit', class:'indexSubmitButton', id:'indexSubmitBtn', name:'submitBtn', onclick:"jump()", target:"view_window", value:'' }) .styles({ border:0+px, padding:0+px, 'background':'url(image/search.png)', 'width':buttonWidth+px, 'height':buttonHeight+px // 'margin-top':'100px' }); // var paperTypeHeight= var paperTypeDiv=bodyDiv.append('div') .attrs({ class:'paperTypeDiv' }) .styles({ 'width':formWidth*2+px, 'height':formHeight+px, 'margin-left':(usefulWidth-formWidth*2)/2+px, 'margin-top':textMarginInput+px }); var paperField=[{text:'Visualization',field:'vis'}]; var textFont=18; var textFontFamily='Arial'; paperTypeDiv.selectAll('whatever') .data(paperField) .enter() .append('div') .attr('class','visualization') .styles({ cursor:'pointer', 'margin-left':function(d){return (formWidth*2- 'Visualization Venues: TVCG, CGF, IEEE VIS, CG&A, InfoVis, ...'.visualLength(textFontFamily,textFont))/2+px;} }) .append('text') .styles({ float:'left', color:'white', 'font-size':textFont+px, 'font-family':textFontFamily }) .on('click',function(d){ window.open('venuelist.html?field='+d.field) }) .html(function(d){return d.text+' Venues:&nbsp;'}); var venueList=[ {text:'TVCG',venue:'IEEE Transactions on Visualization and Computer Graphics',id:1}, {text:'CG&A',venue:'Computer Graphics and Applications',id:17}, {text:'IEEE VIS',venue:'IEEE VIS',id:9}, {text:'VAST',venue:'Visual Analytics Science and Technology',id:0}, {text:'InfoVis',venue:'InfoVis',id:11} ]; var moreVenueList=[ {text:'CG&A',venue:'CG&A'}, {text:'InfoVis',venue:'InfoVis'}, {text:'IEEE Visualization',venue:'IEEE Visualization'}, {text:'VAST',venue:'Visual Analytics Science and Technology'}, ]; paperTypeDiv.selectAll('whatever') .data(venueList) .enter() .append('div') .styles({ cursor:'pointer', // 'margin-left':function(d){return (formWidth- d.text.visualLength(textFontFamily,10))/2+px;} }) .each(function(d,i){ d3.select(this).append('text') .styles({ float:'left', color:'white', 'font-size':18+px, 'font-family':textFontFamily }) .on('click',function(d){ window.open('venuepapers.html?venue='+d.venue+'&id='+d.id) }) .html(function(d){return d.text}); if(i!=4){ d3.select(this).append('text') .styles({ float:'left', color:'white', 'font-size':18+px, 'font-family':textFontFamily }) .html(',&nbsp;') } else{ d3.select(this).append('text') .attrs({ class:'more' }) .styles({ cursor:'pointer', float:'left', color:'white', 'font-size':18+px, 'font-family':textFontFamily }) .html(', ...') .on('click',function(){ window.open('venuelist.html?field=vis'); }) } }); function jump(){ var inputText=$('input[name="Text"]').val(); inputText = inputText.replace(/[\-|\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g,""); inputText=inputText.toLowerCase(); window.location="result.html?searchname="+inputText; } function getUrlParam(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r!=null) return unescape(r[2]); return null; //返回参数值 } function init(){ px='px'; var usefulWidth= window.innerWidth ||document.body.clientWidth || document.documentElement.clientWidth; var usefulHeight = document.body.clientHeight || document.documentElement.clientHeight || window.innerHeight; var body=d3.select('body'); var bodyDiv=body.append('div').attr('class','bodyDiv') .styles({ 'border':'1px solid rgb(50,70,90)', width:usefulWidth+px, height:usefulHeight+px }); body.append('span').attr('id','ruler').attr('class','ruler'); initServer(); var fontSize=50; var fontFamily='Arial'; var fontWeight='bold'; var text='E I F F E L'; d3.select('.ruler').styles({ 'font-weight':fontWeight }); var textWidth=text.visualLength(fontFamily,fontSize); var textHeight=text.visualHeight(fontFamily,fontSize); var textMarginInput=usefulHeight*0.03; var inputWidth=570; var inputHeight=40; var buttonWidth=60; var buttonHeight=40; var formWidth=634; var formHeight=inputHeight; var indexNameDiv=bodyDiv.append('div').attr('class','indexNameDiv') .styles({ 'width':textWidth+px, 'height':textHeight+px, 'border':'0px solid #000000', 'margin-left':(usefulWidth-textWidth)/2+px, 'margin-top':50+px // 'margin-top':'100px' }) .append('text').attr('class','indexName') .html(text) .styles({ 'font-size':fontSize+px, 'font-family':fontFamily, 'font-weight':fontWeight, 'color':'white' }); var form=bodyDiv.append('div').attr('class','inputForm').attr('autocomplete','on') .styles({ 'width':formWidth+px, 'height':formHeight+px, 'margin-left':(usefulWidth-formWidth)/2+px, 'margin-top':textMarginInput+px }); var input=form.append('div').attr('class','inputDiv') .styles({ width:inputWidth+px, height:inputHeight+px, background:'white' }) .append('input') .attrs({ class:'indexInputBox', type:'text', // onkeydown:'keyboardEvent(event.keyCode||event.which);', id:'echoText', name:'Text' // AUTOCOMPLETE:'on' }) .styles({ border:0+px, padding:10+px, width:(inputWidth-20)+px, height:(inputHeight-20)+px }) .on('keydown',function(d){ if(event.keyCode==13)jump(); // console.log(event) }); var button=form.append('div').attr('class','inputButton').append('input') .attrs({ // src:'image/search.png', type:'submit', class:'indexSubmitButton', id:'indexSubmitBtn', name:'submitBtn', onclick:"jump()", target:"view_window", value:'' }) .styles({ border:0+px, padding:0+px, 'background':'url(image/search.png)', 'width':buttonWidth+px, 'height':buttonHeight+px // 'margin-top':'100px' }); var searchName=getUrlParam('searchname'); var input=$('input[name="Text"]'); input.val(searchName); if(searchName!=''){ var url='http://'+server+':'+port+'/searchWords/'; // var url='http://'+'127.0.0.1'+':'+3000+'/searchWords'; var success=function(d){ console.log(d); // pageLayout(d.list); }; var searchData={searchStr:searchName,source:'aminerV8'}; console.log(searchName); console.log(searchData); ajax(url,success,searchData); } function pageLayout(list){ var paperList=list; list.forEach(function(paper,i){ if(paper.id==1182989){ var t=list[0]; list[0]=list[i]; list[i]=list[0]; } }); var paperListDiv=bodyDiv.append('div') .attrs({ class:'paperListDiv' }) .styles({ height:'auto', width:'50%', 'margin-top':20+px, 'margin-left':(usefulWidth-formWidth)/2+px }); paperListDiv.selectAll('whatever') .data(paperList) .enter() .append('div') .styles({ 'margin-top':'15px' }) .each(layoutPapers); } } function paperClick(d){ d3.select(this) .style('color','red') var id= d.id; var link='graph.html?aminerV8_id='+ id+'&selected=aminerV8'+'&r='+Math.floor(Math.random()*1000000000+1); window.open(link); } init(); //import {server,port,errorPort} from '../setting/server'; //import {layoutPapers} from '../searchInteraction/layout'; //import {ajax} from '../processData/request'; function getUrlParam(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r!=null) return unescape(r[2]); return null; //返回参数值 } var px='px'; var usefulWidth= window.innerWidth ||document.body.clientWidth || document.documentElement.clientWidth; var usefulHeight = document.body.clientHeight || document.documentElement.clientHeight || window.innerHeight; var body=d3.select('body'); var bodyDiv=body.append('div').attr('class','bodyDiv') // .attrs({ // onkeydown:'keyboardEvent(event.keyCode||event.which);' // }) .styles({ // 'border':'1px solid rgb(50,70,90)', width:usefulWidth+px, height:usefulHeight+px }); body.append('span').attr('id','ruler').attr('class','ruler'); var field=getUrlParam('field'); var text='the Venue List of '+field; var titleData={ class:'title', text:text, size:'30', family:'Arial', top:'100', color:'white' }; initServer(); titleData['left']=(usefulWidth-titleData.text.visualLength(titleData.family,titleData.size))/2 console.log(titleData) bodyDiv.append('div') .datum(titleData) .each(function(d){ d3.select(this) .attrs({ class: d.class+'Div' }) .styles({ 'margin-left': d.left+px, 'margin-top': d.top+px }) .append('text') .attrs({ class: d.class+'Text' }) .styles({ 'font-size': d.size+px, 'font-family': d.family, 'color': d.color }) .html(d.text) }); var url='http://'+server+':'+port+'/venueList/'; var venueListDiv=bodyDiv.append('div') .attrs({ 'class':'venueListDiv' }) .styles({ 'width':usefulWidth+px, 'height':'auto' }); var success=function(data){ var list=data; list=list.sort(function(a,b){return b.count- a.count}); console.log(list); var size='16'; var family='Arial'; var color='white'; venueListDiv.selectAll('whatever') .data(list) .enter() .append('div') .style('cursor','pointer') .each(function(d){ var totalText= d.venue; // var totalText= d.venue+'( '; // for(var i=0;i< 2;i++){ // totalText+= d.source[i].source+':'+ d.source[i].count+' '; // } // totalText+=')'; console.log(totalText) d3.select(this) .styles({ 'margin-left': (usefulWidth- totalText.visualLength(family,size))/2+px, 'margin-top': 20+px }) .append('text') .styles({ 'font-size':size+px, 'font-family':family, 'color':color }) .on('click',function(d){ window.open('venuepapers.html?venue='+ d.venue+'&id='+ d.id+'&r='+Math.floor(Math.random()*1000000000+1)) }) // .html(d.venue+'(#'+ d.count+')') .html(totalText); // for (var source in d.source){ // console.log(source); // d3.select(this) // .selectAll('whatever') // .data(d.source) // .enter() // .append('text') // .styles({ // 'font-size':size+px, // 'font-family':family, // 'color':color // }) // .on('click',function(e){ // window.open('venuepapers.html?venue='+ d.venue+'&source='+ e.source) // }) // .html(function(e){ // return e.source+':'+ e.count+' '; // }); //// } // d3.select(this) // .append('text') // .styles({ // 'font-size':size+px, // 'font-family':family, // 'color':color // }) // .html(')') }) }; var data={field:field,source:'aminerV8'}; ajax(url,success,data); //import {server,port,errorPort} from '../setting/server'; //import {layoutPapers} from '../searchInteraction/layout'; //import {ajax} from '../processData/request'; function getUrlParam(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r!=null) return unescape(r[2]); return null; //返回参数值 } var px='px'; var usefulWidth= window.innerWidth ||document.body.clientWidth || document.documentElement.clientWidth; var usefulHeight = document.body.clientHeight || document.documentElement.clientHeight || window.innerHeight; var body=d3.select('body'); var bodyDiv=body.append('div').attr('class','bodyDiv') .styles({ width:usefulWidth+px, height:usefulHeight+px }); body.append('span').attr('id','ruler').attr('class','ruler'); var venue=getUrlParam('venue'); var venueID=getUrlParam('id'); var text='Paper List of '+venue; initServer(); var titleData={ class:'title', text:text, size:'30', family:'Arial', top:'100', color:'white' }; titleData['left']=200 console.log(titleData) bodyDiv.append('div') .datum(titleData) .each(function(d){ d3.select(this) .attrs({ class: d.class+'Div' }) .styles({ 'margin-left': d.left+px, 'margin-top': d.top+px }) .append('text') .attrs({ class: d.class+'Text' }) .styles({ 'font-size': d.size+px, 'font-family': d.family, 'color': d.color }) .html(d.text) }); var url='http://'+server+':'+port+'/searchPapers/'; var paperListDiv=bodyDiv.append('div') .attrs({ 'class':'paperListDiv' }) .styles({ 'margin-left':titleData.left+px, 'width':'70%', 'height':'auto' }); var success=function(data){ var list=data; list=list.sort(function(a,b){return b.citation- a.citation}); console.log(list); paperListDiv.selectAll('whatever') .data(list) .enter() .append('div') .styles({ 'margin-top':'15px' }) .each(layoutPapers); }; var data={venueID:venueID,source:'aminerV8'}; ajax(url,success,data); //DirectedGraph.prototype.calculateFlowMap=calculateFlowMap; function calculateFlowMap(d, relayout) { var sizeScale = this.sizeScale; var directedGraph = this.directedGraph; var method = this.method; var edgeDuration = this.edgeDuration; var nodes = d.node; var edges = d.edge; var otherEdges = d.otherEdge; var treeEdges = d.deletedTreeEdges; var nonTreeEdges = d.deletedNonTreeEdges; var that = this; getNodeRelation(nodes, edges); var edgeDic = getEdgeSourceTargetDic(edges); //find root var root; for (var i = 0; i < nodes.length; i++) { if (nodes[i].focused == 'true')root = nodes[i]; } //change jigsaw 210 cluster 106 cluster position root.y = this.svg.attr('height').toFloat() / 2; if(getUrlParam('aminerV8_id') == 1182989 && leftLayer.clusterCount == '20') { var tmp = {x: nodes[13].x, y: nodes[13].y}; nodes[13].x = nodes[19].x; nodes[13].y = nodes[19].y; nodes[19].x = tmp.x; nodes[19].y = tmp.y; } //change twitter function changePosition(n1, n2) { var tmp = {x: n1.x, y: n1.y}; n1.x = n2.x; n1.y = n2.y; n2.x = tmp.x; n2.y = tmp.y; } if(getUrlParam('twitter') == 20 && leftLayer.clusterCount == '20') { changePosition(nodes[11], nodes[16]); changePosition(nodes[4], nodes[15]); changePosition(nodes[1], nodes[17]); changePosition(nodes[11], nodes[1]); nodes[13].y = this.svg.attr('height').toFloat() / 2-20; nodes[4].y += 20; root.y = nodes[11].y; } var cluster = {}; generateCluster(root, cluster); generateNodes(cluster); getClusterBoundAndCenter(cluster); var subClusters = cluster.subClusters; for (var i = 0; i < subClusters.length; i++) { generateAssistNode(root, subClusters[i]); } cluster.isRoot = true; cluster.x = cluster.oriX; cluster.y = cluster.oriY; if (relayout) { useCurrentNodePosition(cluster) } generateBezierNode(cluster); updateNodes(cluster); recoverTreeEdges(d); var flowScale = getEdgeScale(edges, 'flow'); var citationScale = getEdgeScale(edges, 'citation'); var uniformScale = getEdgeScale(edges, 'uniform'); edges.forEach(function (edge) { edge.flowStrokeWidth = flowScale(edge.flow); edge.citationStrokeWidth = citationScale(edge.citation); edge.uniformStrokeWidth = uniformScale(); }); var originEdges = []; var recoveredEdges = []; edges.forEach(function (edge) { if (!edge.recovered) { originEdges.push(edge); } else { recoveredEdges.push(edge); } edge.isForegroundEdge=true; }); var edgeCount = 0; var flowCount = 0; var selfEdgeCount = 0; var selfFlowCount = 0; edges.forEach(function (edge) { flowCount += edge.flow; for (var k in edge.weight) { edgeCount += edge.weight[k]; } if (edge.source === edge.target) { selfFlowCount += edge.flow; for (var k in edge.weight) { selfEdgeCount += edge.weight[k]; } } }); var foregroundSourceEdges=[]; clone(edges,foregroundSourceEdges); var allEdgesSourceDic = getEdgeSourceDic(edges); var foregroundEdgesDic = getEdgeSourceTargetDic(edges); var backgroundEdges = []; clone(originEdges, backgroundEdges); backgroundEdges.forEach(function (edge) { var source=edge.source; var target=edge.target; edge.sourceFatherNode=source; edge.targetFatherNode=target; edge.isBackgroundEdge = true; edge.isForegroundEdge=false; }); var originEdgeDic = getEdgeSourceTargetDic(originEdges); var backgroundEdgesDic = getEdgeSourceTargetDic(backgroundEdges); recoveredEdges.forEach(function (edge) { for (var i = 0; i < edge.routerClusters.length - 1; i++) { var source = edge.routerClusters[i]; var target = edge.routerClusters[i + 1]; var key = source + '_' + target; for(var year in edge.weight){ if(!(year in backgroundEdgesDic[key + '_background'].weight)){ backgroundEdgesDic[key + '_background'].weight[year]=0; } backgroundEdgesDic[key + '_background'].weight[year]+=edge.weight[year]; } backgroundEdgesDic[key + '_background'][edgeThickNessOption] += edge[edgeThickNessOption]; //originEdgeDic[key + '_background'].flowStrokeWidth += edge.flowStrokeWidth; } }); var k = 1; var originEdgeSourceTargetDic = getEdgeSourceTargetDic(originEdges); //generateNodeLevelWeight(cluster); generateMaxWeightEdge(cluster); computeNodeMidTarget(nodes); var pathSet = d3.set(); //sortRecoveredEdges(recoveredEdges); generateFlowMapEdges(backgroundEdges); generateForegroundTargetEdges(edges, originEdges); generateForegroundSourceEdges(foregroundSourceEdges); findForegroundEdgesPath(edges); findForegroundEdgesPath(foregroundSourceEdges); //if (method != 'mst') { recoverNonTreeEdges(d); //} d.edge = backgroundEdges.concat(edges).concat(foregroundSourceEdges); setDelay(cluster); setEdgeDuration(edges); function sortRecoveredEdges(edges) { var treeLevelDic = {}; nodes.forEach(function (node) { treeLevelDic[node.id] = node.treeLevel; }); edges.forEach(function (edge) { edge.treeLevelList = []; edge.routerClusters.forEach(function (nodeId) { edge.treeLevelList.push(treeLevelDic[nodeId]); }); }); //edges.sort(function (a, b) { // return d3.ascending(a.treeLevelList[2], b.treeLevelList[2]); //}) //edges.sort(function (a, b) { // return d3.ascending(a.treeLevelList[1], b.treeLevelList[1]); //}) edges.sort(function (a, b) { return d3.ascending(a.treeLevelList[0], b.treeLevelList[0]); }); edges.sort(function (a, b) { return d3.descending(a.treeLevelList.length, b.treeLevelList.length); }); } function generateNodeLevelWeight(cluster) { var level = 0; var currentClusters = [cluster]; while (currentClusters.length > 0) { var newClusters = []; currentClusters.forEach(function (clus) { if (clus.subClusters) { newClusters = newClusters.concat(clus.subClusters); } nodes[clus.originNodeID].treeLevel = level; }); level += 1; currentClusters = newClusters; } } function generateMaxWeightEdge(cluster) { if (cluster.subClusters) { var maxWeight = 0; var maxIndex = 0; for (var i = 0; i < cluster.subClusters.length; i++) { if (cluster.subClusters[i].weight > maxWeight) { maxWeight = cluster.subClusters[i].weight; maxIndex = i; } } var maxCluster = cluster.subClusters[maxIndex]; var source = cluster.originNodeID; var target = maxCluster.originNodeID; var key = source + '_' + target; if (!(key in originEdgeSourceTargetDic))key += '_background'; var midTargetEdge = originEdgeSourceTargetDic[key]; nodes[source].midTargetEdgeIndex = maxIndex; nodes[source].midTargetEdge = midTargetEdge; midTargetEdge.isMidEdge = true; cluster.subClusters.forEach(function (subCluster) { generateMaxWeightEdge(subCluster); }) } } function findForegroundEdgesPath(edges) { edges.forEach(function (edge) { var pathNodeIds = []; edge.pathNodeList.forEach(function (node) { pathNodeIds.push('_'+node+'_'); }); var regExp = new RegExp(pathNodeIds.join('-')); var pathStrings = pathSet.values(); for (var i = 0; i < pathStrings.length; i++) { var res = regExp.exec(pathStrings[i]); if (res) { var longNodes = []; var uniquePath=pathStrings[i].split('-'); var path=[]; uniquePath.forEach(function (p) { path.push(p.split('_')[1]); }); path.forEach(function (nodeId) { //longNodes.push(nodes[nodeId]); longNodes.push(nodeId); }); edge.longPathNodes = longNodes; break; } } }) } function computeNodeMidTarget(nodes) { nodes.forEach(function (node) { //node.midTargetEdge = null; if (node.midTargetEdge) { var edgeKey = node.midTargetEdge.source + '_' + node.midTargetEdge.target + '_background'; node.topShift += backgroundEdgesDic[edgeKey][edgeThickNessOption] / 2 * k; node.bottomShift += backgroundEdgesDic[edgeKey][edgeThickNessOption] / 2 * k; var targetNode = nodes[node.midTargetEdge.target]; if (!(edgeKey in node.edgeShiftDic))node.edgeShiftDic[edgeKey] = {shiftIn: 0, shiftOut: 0, shift: 0}; if (!(edgeKey in targetNode.edgeShiftDic))targetNode.edgeShiftDic[edgeKey] = {shiftIn: 0, shiftOut: 0}; } }) } function computeShift(source, target, shiftDirection, width, k, f, key) { var edgeKey = key; var shiftDirectionOut = shiftDirection + 'Out'; var shiftDirectionIn = shiftDirection + 'In'; source[shiftDirectionOut] += width * k; target[shiftDirectionIn] += width * k; //source[shiftDirection] += width * k; //target[shiftDirection] += width * k; if (!(edgeKey in source.edgeShiftDic))source.edgeShiftDic[edgeKey] = {shiftIn: 0, shiftOut: 0, shift: 0}; if (!(edgeKey in target.edgeShiftDic))target.edgeShiftDic[edgeKey] = {shiftIn: 0, shiftOut: 0, shift: 0}; source.edgeShiftDic[edgeKey].shiftOut = f * (source[shiftDirectionOut] + width / 2) * k; target.edgeShiftDic[edgeKey].shiftIn = f * (target[shiftDirectionIn] + width / 2) * k; //recovery to origin source.edgeShiftDic[edgeKey].shiftIn = f * (source[shiftDirectionOut] + width / 2) * k; target.edgeShiftDic[edgeKey].shiftOut = f * (target[shiftDirectionIn] + width / 2) * k; source.edgeShiftDic[edgeKey].shift = f * (source[shiftDirection] + width / 2) * k; source[shiftDirection] = (source[shiftDirection] + width) * k; //target.edgeShiftDic[edgeKey].shift = f * (target[shiftDirection] + width / 2) * k; } function generateForegroundSourceEdges(edges){ var edgeTargetDic=getEdgeTargetDic(edges); edges.forEach(function (edge) { edge.isForegroundSourceEdge=true; }); for(var target in edgeTargetDic){ var sourceEdgesDic=edgeTargetDic[target]; var sourceEdges=[]; for(var id in sourceEdgesDic){ var sourceEdge=sourceEdgesDic[id]; if(!sourceEdge.recovered){ sourceEdge.routerLength=2; } else{ sourceEdge.routerLength=sourceEdge.routerClusters.length; } sourceEdges.push(sourceEdge); } sourceEdges.sort(function (a,b) { return d3.descending(a.routerLength, b.routerLength); }); var sumStrokeWidth=d3.sum(sourceEdges, function (d) { return d[edgeThickNessOption]; }); var edgeStrokeWidthDic={}; sourceEdges.forEach(function (edge) { var key; if(!edge.recovered){ key=edge.source+'_'+edge.target; if(!(key in edgeStrokeWidthDic)){ edgeStrokeWidthDic[key]=0; } edgeStrokeWidthDic[key]+=edge[edgeThickNessOption]; } else{ for(var i=0;i<edge.routerClusters.length-1;i++){ key=edge.routerClusters[i]+'_'+edge.routerClusters[i+1]; if(!(key in edgeStrokeWidthDic)){ edgeStrokeWidthDic[key]=0; } edgeStrokeWidthDic[key]+=edge[edgeThickNessOption]; } } }); var edgeStrokeWidthShiftDic={}; for(var key in edgeStrokeWidthDic){ var backgroundEdgeShift=nodes[key.split('_')[0]].edgeShiftDic[key+'_background'].shift; edgeStrokeWidthShiftDic[key]={source:edgeStrokeWidthDic[key]/2+backgroundEdgeShift,target:edgeStrokeWidthDic[key]/2}; } sourceEdges.forEach(function (edge) { edge.nodeShiftDic={}; edge.fatherNode=target; var key; if(!edge.recovered){ key=edge.source+'_'+edge.target; //edge.pathNodeList=[nodes[edge.source],nodes[edge.target]]; edge.pathNodeList=[edge.source,edge.target]; edge.pathNodeDic={}; //edge.pathNodeDic[edge.source]=nodes[edge.source]; //edge.pathNodeDic[edge.target]=nodes[edge.target]; edge.pathNodeDic[edge.source]=edge.source; edge.pathNodeDic[edge.target]=edge.target; edge.nodeShiftDic[edge.source]=edgeStrokeWidthShiftDic[key].source-edge[edgeThickNessOption]/2; edge.nodeShiftDic[edge.target]=edgeStrokeWidthShiftDic[key].target-edge[edgeThickNessOption]/2; edgeStrokeWidthShiftDic[key].source-=edge[edgeThickNessOption]; edgeStrokeWidthShiftDic[key].target-=edge[edgeThickNessOption]; } else{ edge.pathNodeList=[]; edge.pathNodeDic={}; var len=edge.routerClusters.length; for(var i=0;i<len-1;i++){ //edge.pathNodeList.push(nodes[edge.routerClusters[i]]); edge.pathNodeList.push(edge.routerClusters[i]); //edge.pathNodeDic[edge.routerClusters[i]]=nodes[edge.routerClusters[i]]; edge.pathNodeDic[edge.routerClusters[i]]=edge.routerClusters[i]; key=edge.routerClusters[i]+'_'+edge.routerClusters[i+1]; edge.nodeShiftDic[edge.routerClusters[i]]=edgeStrokeWidthShiftDic[key].source-edge[edgeThickNessOption]/2; edge.nodeShiftDic[edge.routerClusters[i+1]]=edgeStrokeWidthShiftDic[key].target-edge[edgeThickNessOption]/2; edgeStrokeWidthShiftDic[key].source-=edge[edgeThickNessOption]; edgeStrokeWidthShiftDic[key].target-=edge[edgeThickNessOption]; } //edge.pathNodeList.push(nodes[edge.routerClusters[len-1]]); //edge.pathNodeDic[edge.routerClusters[len-1]]=nodes[edge.routerClusters[len-1]]; edge.pathNodeList.push(edge.routerClusters[len-1]); edge.pathNodeDic[edge.routerClusters[len-1]]=edge.routerClusters[len-1]; } }); } } function generateForegroundTargetEdges(edges, originEdges) { var edgeSourceDic = getEdgeSourceDic(edges); edges.forEach(function (edge) { edge.isForegroundTargetEdge=true; }) var originEdgeSourceDic = getEdgeSourceDic(originEdges); var originEdgeTargetDic = getEdgeTargetDic(originEdges); //console.log(edgeSourceDic); for (var source in edgeSourceDic) { var targetEdgesDic = edgeSourceDic[source]; var shortEdges = []; var longEdges = []; var subTreeNodeSet = d3.set(); var midNodesSet = d3.set(); for (var id in targetEdgesDic) { if (!targetEdgesDic[id].recovered) { shortEdges.push(targetEdgesDic[id]); subTreeNodeSet.add(targetEdgesDic[id].source); subTreeNodeSet.add(targetEdgesDic[id].target); } else { longEdges.push(targetEdgesDic[id]); targetEdgesDic[id].routerClusters.forEach(function (clusterID) { subTreeNodeSet.add(clusterID); }) } } var currentNode = nodes[source]; var i = 0; while (currentNode.midTargetEdge && subTreeNodeSet.has(currentNode.id)) { midNodesSet.add(currentNode.id); currentNode.sortIndex = i; i += 1; currentNode = nodes[currentNode.midTargetEdge.target]; } if (subTreeNodeSet.has(currentNode.id)) { midNodesSet.add(currentNode.id); currentNode.sortIndex = i; } //已经获取到关键路径的排序,下一步是区分topedge bottomedge,并排序 var topNodesSet = d3.set(); var bottomNodesSet = d3.set(); subTreeNodeSet.values().forEach(function (nodeId) { if (!midNodesSet.has(nodeId)) { var sourceEdgeDic = originEdgeTargetDic[nodeId]; var sourceKey; for (var key in sourceEdgeDic) { sourceKey = key; break; } var sourceNode = nodes[sourceKey]; var thisNode = nodes[nodeId]; var shiftNode = sourceNode.move(sourceNode, 0, 100); //这个角度可以拿出来在一开始全算一遍。。。懒得改了。。。 thisNode.angelToYAxis = lawOfCosine(thisNode, sourceNode, shiftNode); if (thisNode.y <= nodes[sourceNode.midTargetEdge.target].y) { topNodesSet.add(nodeId); } else { bottomNodesSet.add(nodeId); } } }); var topEdges = []; var midEdges = []; var bottomEdges = []; shortEdges.forEach(function (edge) { if (midNodesSet.has(edge.target)) { edge.routerLength = 2; midEdges.push(edge); } else if (topNodesSet.has(edge.target)) { edge.sortCodeList = [nodes[edge.source].sortIndex, nodes[edge.target].angelToYAxis]; topEdges.push(edge); } else { edge.sortCodeList = [nodes[edge.source].sortIndex, nodes[edge.target].angelToYAxis]; bottomEdges.push(edge); } }); longEdges.forEach(function (edge) { if (midNodesSet.has(edge.target)) { edge.routerLength = edge.routerClusters.length; midEdges.push(edge); } else if (topNodesSet.has(edge.target)) { var flag = false; edge.sortCodeList = []; for (var i = 0; i < edge.routerClusters.length - 1; i++) { if (flag) { edge.sortCodeList.push(nodes[edge.routerClusters[i + 1]].angelToYAxis); } if (!flag && midNodesSet.has(edge.routerClusters[i]) && topNodesSet.has(edge.routerClusters[i + 1])) { flag = true; edge.sortCodeList.push(nodes[edge.routerClusters[i]].sortIndex); edge.sortCodeList.push(nodes[edge.routerClusters[i + 1]].angelToYAxis); } } topEdges.push(edge); } else { var flag = false; edge.sortCodeList = []; for (var i = 0; i < edge.routerClusters.length - 1; i++) { if (flag) { edge.sortCodeList.push(nodes[edge.routerClusters[i + 1]].angelToYAxis); } if (!flag && midNodesSet.has(edge.routerClusters[i]) && bottomNodesSet.has(edge.routerClusters[i + 1])) { flag = true; edge.sortCodeList.push(nodes[edge.routerClusters[i]].sortIndex); edge.sortCodeList.push(nodes[edge.routerClusters[i + 1]].angelToYAxis); } } bottomEdges.push(edge); } }); topEdges.sort(function (a, b) { return compareVersions(a.sortCodeList.join('_'), b.sortCodeList.join('_')); }); bottomEdges.sort(function (a, b) { return compareVersions(a.sortCodeList.join('_'), b.sortCodeList.join('_')); }); midEdges.sort(function (a, b) { return d3.descending(a.routerLength, b.routerLength); }); var sortedEdges = []; sortedEdges = sortedEdges.concat(topEdges).concat(midEdges).concat(bottomEdges); var topTotalStrokeWidth = 0; var midTotalStrokeWidth = 0; var bottomTotalStrokeWidth = 0; var edgeStrokeWidthDic={}; sortedEdges.forEach(function (edge) { var key; if(!edge.recovered){ key=edge.source+'_'+edge.target; if(!(key in edgeStrokeWidthDic)){ edgeStrokeWidthDic[key]=0; } edgeStrokeWidthDic[key]+=edge[edgeThickNessOption]; } else{ for(var i=0;i<edge.routerClusters.length-1;i++){ key=edge.routerClusters[i]+'_'+edge.routerClusters[i+1]; if(!(key in edgeStrokeWidthDic)){ edgeStrokeWidthDic[key]=0; } edgeStrokeWidthDic[key]+=edge[edgeThickNessOption]; } } }); //compute shift var edgeStrokeWidthShiftDic={}; for(var key in edgeStrokeWidthDic){ var backgroundEdgeShift=nodes[key.split('_')[0]].edgeShiftDic[key+'_background'].shift; edgeStrokeWidthShiftDic[key]={source:edgeStrokeWidthDic[key]/2+backgroundEdgeShift,target:edgeStrokeWidthDic[key]/2}; } sortedEdges.forEach(function (edge) { edge.fatherNode=source; edge.shiftDic={}; edge.nodeShiftDic={}; var key; if(!edge.recovered){ key=edge.source+'_'+edge.target; edge.shiftDic[key]=edgeStrokeWidthShiftDic[key]-edge[edgeThickNessOption]/2; edge.nodeShiftDic[edge.source]=edgeStrokeWidthShiftDic[key].source-edge[edgeThickNessOption]/2; edge.nodeShiftDic[edge.target]=edgeStrokeWidthShiftDic[key].target-edge[edgeThickNessOption]/2; edgeStrokeWidthShiftDic[key].source-=edge[edgeThickNessOption]; edgeStrokeWidthShiftDic[key].target-=edge[edgeThickNessOption]; //edge.pathNodeList=[nodes[edge.source],nodes[edge.target]]; edge.pathNodeList=[edge.source,edge.target]; edge.pathNodeDic={}; //edge.pathNodeDic[edge.source]=nodes[edge.source]; //edge.pathNodeDic[edge.target]=nodes[edge.target]; edge.pathNodeDic[edge.source]=edge.source; edge.pathNodeDic[edge.target]=edge.target; } else{ edge.pathNodeList=[]; edge.pathNodeDic={}; var len=edge.routerClusters.length; for(var i=0;i<len-1;i++){ //edge.pathNodeList.push(nodes[edge.routerClusters[i]]); edge.pathNodeList.push(edge.routerClusters[i]); //edge.pathNodeDic[edge.routerClusters[i]]=nodes[edge.routerClusters[i]]; edge.pathNodeDic[edge.routerClusters[i]]=edge.routerClusters[i]; key=edge.routerClusters[i]+'_'+edge.routerClusters[i+1]; edge.shiftDic[key]={source:edgeStrokeWidthShiftDic[key].source-edge[edgeThickNessOption]/2,target:edgeStrokeWidthShiftDic[key].target-edge[edgeThickNessOption]/2}; edge.nodeShiftDic[edge.routerClusters[i]]=edgeStrokeWidthShiftDic[key].source-edge[edgeThickNessOption]/2; edge.nodeShiftDic[edge.routerClusters[i+1]]=edgeStrokeWidthShiftDic[key].target-edge[edgeThickNessOption]/2; edgeStrokeWidthShiftDic[key].source-=edge[edgeThickNessOption]; edgeStrokeWidthShiftDic[key].target-=edge[edgeThickNessOption]; } //edge.pathNodeList.push(nodes[edge.routerClusters[len-1]]); //edge.pathNodeDic[edge.routerClusters[len-1]]=nodes[edge.routerClusters[len-1]]; edge.pathNodeList.push(edge.routerClusters[len-1]); edge.pathNodeDic[edge.routerClusters[len-1]]=edge.routerClusters[len-1]; } }); //shortEdges.sort(function (a,b) { // return d3.ascending(nodes[a.target].y,nodes[b.target].y); //}) //shortEdges.forEach(function (edge) { // console.log(edge.source+'_'+edge.target); //}) } } function compareVersions(v1, v2) { if (v1 === v2) { return 0; } var v1parts = v1.split('_').map(parseFloat); var v2parts = v2.split('_').map(parseFloat); var len = Math.min(v1parts.length, v2parts.length); for (var i = 0; i < len; i++) { if (parseInt(v1parts[i]) > parseInt(v2parts[i])) { return 1; } if (parseInt(v1parts[i]) < parseInt(v2parts[i])) { return -1; } } if (v1parts.length > v2parts.length) { return -1; } if (v1parts.length < v2parts.length) { return 1; } return 0; } function generateFlowMapRecoveredEdges(edges) { edges.forEach(function (edge) { var pathNodeDic = {}; var pathNodeList = []; var lastNode = edge.routerClusters[edge.routerClusters.length - 1]; var topShiftSum = 0; var bottomShiftSum = 0; edge.routerClusters.forEach(function (nodeId) { topShiftSum += nodes[nodeId].topShiftIn + nodes[nodeId].topShiftOut; bottomShiftSum += nodes[nodeId].bottomShiftIn + nodes[nodeId].bottomShiftOut; }); var shiftDirection, f; (topShiftSum <= bottomShiftSum) ? shiftDirection = 'topShift' : shiftDirection = 'bottomShift'; (topShiftSum <= bottomShiftSum) ? f = 1 : f = -1; for (var i = 0; i < edge.routerClusters.length - 1; i++) { var nodeId = edge.routerClusters[i]; var nextNodeId = edge.routerClusters[i + 1]; var node = nodes[nodeId]; var nextNode = nodes[nextNodeId]; pathNodeDic[nodeId] = node; pathNodeList.push(node); var key = edge.routerClusters[0] + '_' + edge.routerClusters[edge.routerClusters.length - 1]; computeShift(node, nextNode, shiftDirection, edge[edgeThickNessOption], k, f, key); } pathNodeList.push(nodes[lastNode]); pathNodeDic[lastNode] = nodes[lastNode]; edge.pathNodeDic = pathNodeDic; edge.pathNodeList = pathNodeList; }) } function generateFlowMapEdges(edges) { var keySuffix = ''; if (edges[0].isBackgroundEdge)keySuffix += '_background'; var leafNodeSet = getLeafNodes(edges); var rootNodeSet = getRootNode(edges); var edgeDic = getEdgeSourceTargetDic(edges); var paths = findPathsBetween(rootNodeSet.values()[0], leafNodeSet.values(), edges); var newEdges = []; var newEdgesDic = {}; var keySet = d3.set(); paths.forEach(function (path) { var newEdge = []; for (var i = 0; i < path.length - 1; i++) { var n1 = path[i]; var n2 = path[i + 1]; var originKey = n1 + '_' + n2; var key = originKey + keySuffix; keySet.add(key); var pathNodeDic = {}; var pathNodeList = []; var uniquePath=[]; path.forEach(function (p) { uniquePath.push('_'+p+'_'); }) pathSet.add(uniquePath.join('-')); path.forEach(function (nodeId) { var node = nodes[nodeId]; //pathNodeDic[nodeId] = node; pathNodeDic[nodeId] = nodeId; //pathNodeList.push(node); pathNodeList.push(nodeId); }); edgeDic[key].pathNodeDic = pathNodeDic; edgeDic[key].pathNodeList = pathNodeList; foregroundEdgesDic[originKey].pathNodeDic = pathNodeDic; foregroundEdgesDic[originKey].pathNodeList = pathNodeList; } path.forEach(function (node) { var p = nodes[node]; var p1 = new Point(p.x, p.y); newEdge.push(p1); if (p.cp1) { var cp = new Point(p.cp1.x, p.cp1.y); newEdge.push(cp); newEdge.push(cp.move(-1, 0)); } }); newEdges.push(newEdge); }); } function TreeNode(id) { //this.children=[]; this.father = null; this.id = id; } function findPathsBetween(source, targets, edges) { var edgeSourceDic = getEdgeSourceDic(edges); var edgeDic = getEdgeSourceTargetDic(edges); var keySuffix = ''; if (edges[0].isBackgroundEdge)keySuffix += '_background'; var paths = []; var rootNode = new TreeNode(source); var currentNodes = [rootNode]; var treeNodeDic = {}; treeNodeDic[source] = rootNode; while (currentNodes.length > 0) { var newCurrentNodes = []; currentNodes.forEach(function (node) { if (node.id in edgeSourceDic) { var newTargets = edgeSourceDic[node.id]; var targetNodes = []; for (var target in newTargets) { var newNode = new TreeNode(target); newNode.father = node; newCurrentNodes.push(newNode); treeNodeDic[target] = newNode; targetNodes.push(nodes[target]); } targetNodes .sort(function (a, b) { return d3.ascending(a.y, b.y); }); var l = targetNodes.length; var midEdge = nodes[node.id].midTargetEdge; var mid; for (var i = 0; i < targetNodes.length; i++) { if (targetNodes[i].id == midEdge.target) { mid = i; break } } //var mid = nodes[node.id].midTargetEdgeIndex; //var midKey = node.id + '_' + targetNodes[mid].id; var midFlow = midEdge.flow; //在这里计算可还原边的偏移量,给每个节点两个数组用来标示上半区和下半区共插入了多少边 var thisNode = nodes[node.id]; var targetNode; var edgeKey; var shiftDirection, f, shiftDirectionIn, shiftDirectionOut, edge; var suffixIn = 'In'; var suffixOut = 'Out'; if (mid > 0) { shiftDirection = 'topShift'; f = 1; shiftDirectionIn = shiftDirection + suffixIn; shiftDirectionOut = shiftDirection + suffixOut; var topShift = nodes[node.id].topShift; for (var i = mid - 1; i >= 0; i--) { targetNode = targetNodes[i]; edgeKey = node.id + '_' + targetNode.id + keySuffix; edge = edgeDic[edgeKey]; computeShift(thisNode, targetNode, shiftDirection, edge[edgeThickNessOption], k, f, edgeKey) //edge.shift = (topShift + flowScale(edge.flow) / 2) * k; //topShift += flowScale(edge.flow) * k; } } if (mid < l) { shiftDirection = 'bottomShift'; f = -1; shiftDirectionIn = shiftDirection + suffixIn; shiftDirectionOut = shiftDirection + suffixOut; var bottomShift = nodes[node.id].bottomShift; for (var i = mid + 1; i < l; i++) { targetNode = targetNodes[i]; edgeKey = node.id + '_' + targetNode.id + keySuffix; edge = edgeDic[edgeKey]; computeShift(thisNode, targetNode, shiftDirection, edge[edgeThickNessOption], k, f, edgeKey) //edge.shift = -(bottomShift + flowScale(edge.flow) / 2) * k; //bottomShift += flowScale(edge.flow) * k; } } //.forEach(function(targetNode){ // var edgeKey=node.id+'_'+targetNode.id; //}) } }); currentNodes = newCurrentNodes; } nodes.edgeDic = getEdgeSourceTargetDic(edges); targets.forEach(function (target) { var node = treeNodeDic[target]; var path = []; while (node.father) { path.push(node.id); node = node.father; } path.push(node.id); paths.push(path.reverse()); }); return paths; } function getRootNode(edges) { var allNodeSet = d3.set(); var edgeTargetDic = getEdgeTargetDic(edges); edges.forEach(function (e) { allNodeSet.add(e.source); allNodeSet.add(e.target); }); for (var key in edgeTargetDic) { if (allNodeSet.has(key)) { allNodeSet.remove(key); } } return allNodeSet; } function getLeafNodes(edges) { var allNodeSet = d3.set(); var edgeSourceDic = getEdgeSourceDic(edges); edges.forEach(function (e) { allNodeSet.add(e.source); allNodeSet.add(e.target); }); for (var key in edgeSourceDic) { if (allNodeSet.has(key)) { allNodeSet.remove(key); } } return allNodeSet; } function useCurrentNodePosition(cluster) { if (cluster.subClusters) { cluster.x = cluster.oriX; cluster.y = cluster.oriY; for (var i = 0; i < cluster.subClusters.length; i++) { useCurrentNodePosition(cluster.subClusters[i]) } } } function setEdgeDuration(edges) { for (var i = 0; i < edges.length; i++) { edges[i].duration = edgeDuration; } } function setDelay(cluster) { function setEdgeDelay(cluster) { if (cluster.subClusters) { for (var i = 0; i < cluster.subClusters.length; i++) { var key = cluster.originNodeID + '_' + cluster.subClusters[i].originNodeID; var edge = edgeDic[key]; edge.delay = cluster.delay; setDelay(cluster.subClusters[i]); } } } // console.log(cluster); if (cluster.isRoot) { cluster.delay = 0; var nodeID = parseInt(cluster.originNodeID); nodes[nodeID].delay = cluster.delay; nodes[nodeID].duration = 100; setEdgeDelay(cluster); } else { if (cluster.parentCluster) { cluster.delay = 200 + cluster.parentCluster.delay; var nodeID = parseInt(cluster.originNodeID); nodes[nodeID].delay = cluster.delay; nodes[nodeID].duration = 100; setEdgeDelay(cluster); } } // if(cluster.subClusters){ // for(var i=0;i<cluster.subClusters.le) // } } function updateNodes(cluster) { if (cluster.subClusters) { var nodeID = parseInt(cluster.originNodeID); if (cluster.x && cluster.y) { nodes[nodeID].x = cluster.x; nodes[nodeID].y = cluster.y; nodes[nodeID].cp1 = cluster.cp1; nodes[nodeID].cp2 = cluster.cp2; } for (var i = 0; i < cluster.subClusters.length; i++) { updateNodes(cluster.subClusters[i]); } } } function generateBezierNode(cluster) { var pi = Math.PI; function setAssistNode(edge, p1, p2) { var x1 = p1.x; var x2 = p2.x; var y1 = p1.y; var y2 = p2.y; edge.assists = [[x1, y1], [x2, y2]]; } if (cluster.subClusters) { var sourceID = cluster.originNodeID; var p0 = {x: cluster.x, y: cluster.y}; var maxWeight = 0; var maxCluster; var kNum = 0; for (var i = 0; i < cluster.subClusters.length; i++) { if (cluster.subClusters[i].weight > maxWeight) { maxWeight = cluster.subClusters[i].weight; maxCluster = cluster.subClusters[i]; kNum = i; } } var maxID = maxCluster.originNodeID; var p1 = {} if (maxCluster.nodes) { p1 = {x: maxCluster.x, y: maxCluster.y}; } else if (maxCluster.node) { p1 = {x: maxCluster.oriX, y: maxCluster.oriY}; } var maxCtrlPoint1 = {}; var maxCtrlPoint2 = {}; //if(cluster.parentCluster){ // var preCtrlPoint=cluster.preControlPoint; // var line1=get2PointFun(preCtrlPoint,p0); // // // if(!line1.vertical){ // var k=line1.k; // var angel=Math.atan(k); // var maxControlPoint1Length=getDistance(p0, p1)*cluster.preCtrlPointRatio; // maxCtrlPoint1.x = p0.x+maxControlPoint1Length*Math.cos(angel); // maxCtrlPoint1.y = p0.y+maxControlPoint1Length*Math.sin(angel); // // } // else{ // var maxControlPoint1Length=getDistance(p0, p1)*cluster.preCtrlPointRatio; // maxCtrlPoint1.x = p0.x; // maxCtrlPoint1.y = p0.y+maxControlPoint1Length; // } // maxCtrlPoint2=ratioPoint(p0, p1, 1/3); //} //else{ //rootCluster var cp1; var cp2; if (cluster.subClusters) { cp1 = ratioPoint(p0, p1, 0.77); cp2 = ratioPoint(p0, p1, 0.78); maxCtrlPoint1 = ratioPoint(p0, p1, 2 / 3); maxCtrlPoint2 = ratioPoint(p0, p1, 1 / 3); } //} maxCluster.preControlPoint = maxCtrlPoint2; maxCluster.preCtrlPointRatio = getDistance(maxCtrlPoint2, p1) / getDistance(p0, p1); var vec1 = new vector(p0, p1); var lineVec1 = get2PointFun(p0, p1); var k1 = lineVec1.k; var key = sourceID + '_' + maxID; setAssistNode(edgeDic[key], maxCtrlPoint1, maxCtrlPoint2); var p3 = maxCtrlPoint1; var p4 = {}; for (var i = 0; i < cluster.subClusters.length; i++) { if (i != kNum) { var p2; if (cluster.subClusters[i].nodes) { p2 = {x: cluster.subClusters[i].x, y: cluster.subClusters[i].y}; } else if (cluster.subClusters[i].node) { p2 = {x: cluster.subClusters[i].oriX, y: cluster.subClusters[i].oriY}; } var pt = ratioPoint(p0, p2, 1 / 3); var dist = getDistance(p0, pt); var vec2 = new vector(p0, p2); var lineVec2 = get2PointFun(p0, p2); var k2 = lineVec2.k; var angle = angleBetween(vec1, vec2); var vecToX = new vector({x: 0, y: 0}, {x: 1, y: 0}); var angleToX = angleBetween(vec2, vecToX); var halfAngle = angle / 2; if (k1 == 0) { if (k2 > 0) { p4.x = p0.x + dist * Math.cos(halfAngle); p4.y = p0.y + dist * Math.sin(halfAngle); } else if (k2 < 0) { p4.x = p0.x + dist * Math.cos(halfAngle); p4.y = p0.y - dist * Math.sin(halfAngle); } else { console.log('k1==k2 should not happen') } } else if (k1 > 0) { if (k2 > 0) { if (k2 > k1) { p4.x = p0.x + dist * Math.cos(angleToX - halfAngle); p4.y = p0.y + dist * Math.sin(angleToX - halfAngle); } else if (k2 < k1) { p4.x = p0.x + dist * Math.cos(angleToX + halfAngle); p4.y = p0.y + dist * Math.sin(angleToX + halfAngle); } } else if (k2 <= 0) { p4.x = p0.x + dist * Math.cos(halfAngle - angleToX); p4.y = p0.y + dist * Math.sin(halfAngle - angleToX); } } else if (k1 < 0) { if (k2 >= 0) { p4.x = p0.x + dist * Math.cos(halfAngle - angleToX); p4.y = p0.y + dist * Math.sin(halfAngle - angleToX); } else if (k2 < 0) { if (k2 < k1) { p4.x = p0.x + dist * Math.cos(angleToX - halfAngle); p4.y = p0.y - dist * Math.sin(angleToX - halfAngle); } else if (k2 > k1) { p4.x = p0.x + dist * Math.cos(angleToX - halfAngle); p4.y = p0.y - dist * Math.sin(angleToX + halfAngle); } } } var newKey = sourceID + '_' + cluster.subClusters[i].originNodeID; cluster.cp1 = cp1; cluster.cp2 = cp2; cluster.subClusters[i].preControlPoint = {}; clone(p4, cluster.subClusters[i].preControlPoint); cluster.subClusters[i].preCtrlPointRatio = getDistance(p4, p2) / getDistance(p0, p2); setAssistNode(edgeDic[newKey], p3, p4); } } for (var i = 0; i < cluster.subClusters.length; i++) { generateBezierNode(cluster.subClusters[i]); } } } function generateAssistNode(node, cluster) { if (cluster.subClusters) { //get p0 var p0 = node; //get p1 var maxWeight = 0; var maxCluster; var k = 0; for (var i = 0; i < cluster.subClusters.length; i++) { if (cluster.subClusters[i].weight > maxWeight) { maxWeight = cluster.subClusters[i].weight; maxCluster = cluster.subClusters[i]; k = i; } } var bounds1 = maxCluster.bounds; var line1 = {p1: p0, p2: maxCluster.center}; var p1 = getRectangleLineCrossPoint(bounds1, line1); //get p2 var otherNodesBound = cluster.subClusters[0].bounds; for (var i = 1; i < cluster.subClusters.length; i++) { if (i != k) { otherNodesBound = mergeRect(otherNodesBound, cluster.subClusters[i].bounds); } } var otherNodesCenter = { x: otherNodesBound.x + otherNodesBound.width / 2, y: otherNodesBound.y + otherNodesBound.height / 2 }; var bounds2 = otherNodesBound; var line2 = {p1: p0, p2: otherNodesCenter}; var p2 = getRectangleLineCrossPoint(bounds2, line2); var dist1 = getDistance(p0, p1); var dist2 = getDistance(p0, p2); var JumpCount = {count: 2}; function recurJumpCluster(cluster, count) { var newCount = count; if (cluster.subClusters) { var maxWeight = 0; var maxCluster; for (var i = 0; i < cluster.subClusters.length; i++) { if (cluster.subClusters[i].weight > maxWeight) { maxWeight = cluster.subClusters[i].weight; maxCluster = cluster.subClusters[i]; } } count.count += 1; recurJumpCluster(maxCluster, count) } } recurJumpCluster(cluster, JumpCount); if (JumpCount.count > 2)JumpCount.count -= 1; var shortestDist = d3.min([dist1, dist2]) / JumpCount.count; // var biggerCluster=d3.max([cluster.subCluster1,cluster.subCluster2],function(d){return d.size}); var p3 = maxCluster.center; var biggerDist = getDistance(p0, p3); var bigFraction = parseFloat(shortestDist / biggerDist); var parentFraction = 1 - bigFraction; var x = p0.x * parentFraction + p3.x * bigFraction; var y = p0.y * parentFraction + p3.y * bigFraction; cluster.x = x; cluster.y = y; var newNode = new Node(new Point(x, y)); for (var i = 0; i < cluster.subClusters.length; i++) { generateAssistNode(newNode, cluster.subClusters[i]); } } } function recoverEdges(otherEdge, edges) { function recurSourceNode(sourceNode, targetID) { if (sourceNode.children) { for (var i = 0; i < sourceNode.children.length; i++) { } } } for (var i = 0; i < otherEdge.length; i++) { var sourceID = otherEdge[i].source; var sourceNode = nodes[sourceID]; var targetID = otherEdge[i].target; recurSourceNode(sourceNode, targetID); } // return edges; } function recoverNonTreeEdges(d) { function getLine(sourceID, targetID) { return {p1: nodes[sourceID], p2: nodes[targetID]}; } var edgeSourceTargetDic = directedGraph.edgeSourceTargetDic; var edges = d.edge; var nodes = d.node; var nonTreeEdges = d.deletedNonTreeEdges; var nonCrossEdges = []; for (var i = 0; i < nonTreeEdges.length; i++) { var sourceID = nonTreeEdges[i].source; var targetID = nonTreeEdges[i].target; var line1 = getLine(sourceID, targetID); var crossCount = 0; for (var j = 0; j < edges.length; j++) { var originSourceID = edges[j].source; var originTargetID = edges[j].target; var line2 = getLine(originSourceID, originTargetID); var checkCross = get2LineCrossPoint(line1, line2); if (checkCross.isPointInLine1 && checkCross.isPointInLine2) { crossCount += 1; } } // if(crossCount <=3 ){ nonCrossEdges.push(nonTreeEdges[i]); // } } //console.log(nonCrossEdges); for (var i = 0; i < nonCrossEdges.length; i++) { var source = nonCrossEdges[i].source; var target = nonCrossEdges[i].target; var sourceEdge, targetEdge; if (nodes[source] && nodes[target]) { for (var j = 0; j < edges.length; j++) { if (edges[j].source == source) { sourceEdge = edges[j]; } if (edges[j].target == target) { targetEdge = edges[j]; } } if (sourceEdge && targetEdge) { // if(nodes[source].x<nodes[target].x){ // var newAssistNode=[sourceEdge.assists[0],targetEdge.assists[1]]; // nonCrossEdges[i].assists=newAssistNode; // nonCrossEdges[i].edgeType='dash'; // } // else{ var p1 = ratioPoint(nodes[source], nodes[target], 2 / 3); var p2 = ratioPoint(nodes[source], nodes[target], 1 / 3); nonCrossEdges[i].assists = [[p1.x, p1.y], [p2.x, p2.y]]; nonCrossEdges[i].edgeType = 'dash'; nonCrossEdges[i].isNontreeEdge = true; // } edges.push(nonCrossEdges[i]); } } } } function recoverTreeEdges(d) { var edges = d.edge; var edgeSourceTargetDic = getEdgeSourceTargetDic(edges); var treeEdges = d.deletedTreeEdges; var nontreeEdges = d.deletedNonTreeEdges; var len1, len2; var newDeletedEdges = []; var tmpEdges = []; clone(treeEdges, newDeletedEdges); len1 = newDeletedEdges.length; len2 = tmpEdges.length; while (len1 != len2) { len1 = newDeletedEdges.length; tmpEdges = []; for (var i = 0; i < newDeletedEdges.length; i++) { var flag; var originEdge; var newPath; var originSource; var originTarget; var originKey; if (method == 'recoveryWeight') { originEdge = newDeletedEdges[i].originEdge; newPath = newDeletedEdges[i].newPath; flag = true; originSource = originEdge.source; originTarget = originEdge.target; originKey = originSource + '_' + originTarget; // flag = false; for (var j = 0; j < newPath.edges.length; j++) { var newEdge = newPath.edges[j]; var newSource = newEdge.source; var newTarget = newEdge.target; var newKey = newSource + '_' + newTarget; if (!edgeSourceTargetDic[newKey]) { flag = false; break; } } } else { originEdge = newDeletedEdges[i]; originSource = originEdge.source; originTarget = originEdge.target; originKey = originSource + '_' + originTarget; flag = false; } if (flag == false) { var dijPath; if (method == 'mst')dijPath = directedGraph.maximalSpanningTree.findMaxPathBetween(originSource, originTarget); else dijPath = directedGraph.findMaxPathBetween(originSource, originTarget); if (dijPath[0]) { newPath = dijPath[0]; flag = true; } } if (flag == true) { var assists = []; var routerClusters = [] for (var j = 0; j < newPath.length; j++) { routerClusters.push(newPath.edges[j].source); var source = newPath.edges[j].source; var sourceNode = [nodes[source].x, nodes[source].y]; var target = newPath.edges[j].target; var targetNode = [nodes[target].x, nodes[target].y]; var tmpKey = source + '_' + target; assists.push(sourceNode); for (var k = 0; k < edgeSourceTargetDic[tmpKey].assists.length; k++) { assists.push(edgeSourceTargetDic[tmpKey].assists[k]); } assists.push(targetNode); } routerClusters.push(originEdge.target); assists = assists.slice(1, assists.length); assists = assists.slice(0, assists.length - 1); originEdge.assists = assists; originEdge.TreeEdge = true; originEdge.routerClusters = routerClusters; originEdge.recovered = true; // edgeSourceTargetDic[originKey]=originEdge; edges.push(originEdge); } else { tmpEdges.push(newDeletedEdges[i]); } } newDeletedEdges = []; clone(tmpEdges, newDeletedEdges); len2 = newDeletedEdges.length; } for (var i = 0; i < tmpEdges.length; i++) { nontreeEdges.push(tmpEdges[i].originEdge); } } function generateNodes(cluster) { if (cluster.subClusters) { cluster.nodes = []; for (var i = 0; i < cluster.subClusters.length; i++) { cluster.nodes = cluster.nodes.concat(generateNodes(cluster.subClusters[i])); } //use cluster leaf nodes as weight var weight = 0; for (var j = 0; j < cluster.nodes.length; j++) { weight += cluster.nodes[j].size; } cluster.weight = weight; //use cluster all nodes as weight //var fullWeight = 0; //for (var i = 0; i < cluster.subClusters.length; i++) { // fullWeight+=cluster.subClusters[i].weight; //} //if(cluster.nodes){ // fullWeight+=nodes[cluster.originNodeID].size; //} //cluster.weight=fullWeight; return cluster.nodes; } else { cluster.weight = cluster.node.size; cluster.fullWeight = cluster.node.size; return [cluster.node]; } } function getClusterBoundAndCenter(cluster) { if (cluster.nodes) { var minX = d3.min(cluster.nodes, function (d) { return d.x - sizeScale.sizeScale(d.size) }); var minY = d3.min(cluster.nodes, function (d) { return d.y - sizeScale.sizeScale(d.size) }); var maxX = d3.max(cluster.nodes, function (d) { return d.x + sizeScale.sizeScale(d.size) }); var maxY = d3.max(cluster.nodes, function (d) { return d.y + sizeScale.sizeScale(d.size) }); cluster.bounds = { x: minX, y: minY, width: maxX - minX, height: maxY - minY } cluster.center = { x: minX + (maxX - minX) / 2, y: minY + (maxY - minY) / 2 } for (var i = 0; i < cluster.subClusters.length; i++) { getClusterBoundAndCenter(cluster.subClusters[i]); } } else if (cluster.node) { cluster.bounds = { x: cluster.node.x - sizeScale.sizeScale(cluster.node.size), y: cluster.node.y - sizeScale.sizeScale(cluster.node.size), width: sizeScale.sizeScale(cluster.node.size) * 2, height: sizeScale.sizeScale(cluster.node.size) * 2 } cluster.center = { x: cluster.node.x, y: cluster.node.y } } } function generateCluster(node, cluster) { if (node.children) { cluster.subClusters = []; cluster.originNodeID = node.id; cluster.oriX = node.x; cluster.oriY = node.y; for (var i = 0; i < node.children.length; i++) { var newCluster = {}; newCluster.parentCluster = cluster; cluster.subClusters.push(newCluster); generateCluster(node.children[i], newCluster); } } else { cluster.node = node; cluster.originNodeID = node.id; cluster.oriX = node.x; cluster.oriY = node.y; } } function recurTree(node) { if (node.children) { for (var i = 0; i < node.children.length; i++) { var child = node.children[i]; if (child.children) { var grandChildren = child.children; var maxGrandChild; var maxFlow = 0; for (var j = 0; j < grandChildren.length; j++) { var source = child.id; var target = grandChildren[j].id; var key = String(source) + '_' + String(target); var edge = edgeDic[key]; var flow = edge.flow; if (flow > maxFlow) { maxFlow = flow; maxGrandChild = grandChildren[j]; } } var p1 = {x: node.x, y: node.y}; var p2 = {x: maxGrandChild.x, y: maxGrandChild.y}; var p3 = {x: child.x, y: child.y}; var p4 = getPointToLineCrossPoint(p1, p2, p3); child.x = p4.x; child.y = p4.y; } recurTree(node.children[i]); } } else { return; } } function processEdge(source, target) { if (!source.parentNode) { //this is root need to generate a grandparent var children = source.children; var avgX = 0, avgY = 0; for (var i = 0; i < children.length; i++) { avgX += children[i].x; avgY += children[i].y; } avgX /= children.length; avgY /= children.length; var thisVector = vector({x: source.x, y: source.y}, {x: avgX, y: avgY}); var normalized = getNormalized(thisVector); var reverseNormalized = {x: normalized.x * -1, y: normalized.y * -1}; var x = source.x + 10 * reverseNormalized.x; var y = source.y + 10 * reverseNormalized.y; var grandParent = {x: x, y: y}; } else { grandParent = source.parentNode; } var parent = {x: source.x, y: source.y}; var shiftPoint = false; if (source.parentNode) { var n2 = source.parentNode; var otherEdgeItems; if (source.children) { var sourceID = source.id; var targetID = target.id; if (source.children.length > 1) { var countX = 0, countY = 0; for (var i = 0; i < source.children.length; i++) { if (source.children[i].id != targetID) { countX += source.children[i].x; countY += source.children[i].y; } } countX /= source.children.length - 1; countY /= source.children.length - 1; var thisEdgeVec = vector(source, target); var otherEdgeVec = vector(source, {x: countX, y: countY}); var thisEdgeVec3d = vector3d(getNormalized(thisEdgeVec).x, -1 * getNormalized(thisEdgeVec).y, 0); var otherEdgeVec3d = vector3d(getNormalized(otherEdgeVec).x, -1 * getNormalized(otherEdgeVec).y, 0); var crossResult = vector3dCross(thisEdgeVec3d, otherEdgeVec3d); var grandToParent = vector(grandParent, parent); var shiftX = -1 * getNormalized(grandToParent).y; var shiftY = -1 * getNormalized(grandToParent).x; var shiftDir = {x: shiftX, y: shiftY}; if (crossResult.z < 0) { shiftDir.x *= -1; shiftDir.y *= -1; } } } } var child = {x: target.x, y: target.y}; var grandChild; if (target.children) { var grandChildEdges = target.children; var maxFlow = 0; var maxEdge; for (var i = 0; i < target.children.length; i++) { var key = String(target.id) + '_' + String(target.children[i].id); var tmpEdge = edgeDic[key]; var edgeFLow = tmpEdge.flow; if (edgeFLow > maxFlow) { maxFlow = edgeFLow; maxEdge = tmpEdge; } } grandChild = {x: nodes[maxEdge.target].x, y: nodes[maxEdge.target].y}; } else { var parentToChild = vector(parent, child); var pToCDir = getNormalized(parentToChild); var grandParentToParent = vector(grandParent, parent); var gpToPDir = getNormalized(grandParentToParent); var angleBetween = absAngleBetween(parentToChild, grandParentToParent); var x = pToCDir.x * Math.cos(-angleBetween) - pToCDir.y * Math.sin(-angleBetween); var y = pToCDir.x * Math.sin(-angleBetween) - pToCDir.y * Math.cos(-angleBetween); grandChild = {x: child.x + 10 * x, y: child.y + 10 * y}; } var sourceID = source.id; var targetID = target.id; var key = String(sourceID) + '_' + String(targetID); var edge = edgeDic[key]; var fourPoints = []; fourPoints.push(grandParent); fourPoints.push(parent); fourPoints.push(child); fourPoints.push(grandChild); computeOneSpline(grandParent, parent, child, grandChild, edge, target); var parentGrandDist = getDistance(grandParent, parent); var grandToParent = vector(grandParent, parent); var collX = parentGrandDist * getNormalized(grandToParent).x + parent.x; var collY = parentGrandDist * getNormalized(grandToParent).y + parent.y; var collinShift = {x: collX, y: collY}; // edge.assists[1][0]=collX; // edge.assists[1][1]=collY; // source.x=collX; // source.y=collY; // target.x = edge.assists[2][0]; // target.y = edge.assists[2][1]; } } function computeOneSpline(p0, p1, p2, p3, edge, target) { var ctrlX1 = -p0.x / 6 + p1.x + p2.x / 6; var ctrlX2 = -p1.x / 6 + p2.x + p3.x / 6; var ctrlY1 = -p0.y / 6 + p1.y + p2.y / 6; var ctrlY2 = -p1.y / 6 + p2.y + p3.y / 6; edge.assists = [[p0.x, p0.y], [ctrlX1, ctrlY1], [ctrlX2, ctrlY2], [p3.x, p3.y]]; // edge.assists=[[p0.x,p0.y],[p1.x,p1.y],[p2.x,p2.y],[p3.x,p3.y]]; } function getEdgeSourceTargetDic(edges) { var dic = {}; for (var i = 0; i < edges.length; i++) { var source = edges[i].source; var target = edges[i].target; var key = String(source) + '_' + String(target); if (edges[i].isBackgroundEdge)key += '_background'; dic[key] = edges[i]; } return dic; } function getEdgeSourceDic(edges) { var dic = {}; for (var i = 0; i < edges.length; i++) { var source = edges[i].source; var target = edges[i].target; if (dic[source])dic[source][target] = edges[i]; else { dic[source] = {}; dic[source][target] = edges[i]; } } return dic; } function getEdgeTargetDic(edges) { var dic = {}; for (var i = 0; i < edges.length; i++) { var source = edges[i].source; var target = edges[i].target; if (dic[target])dic[target][source] = edges[i]; else { dic[target] = {}; dic[target][source] = edges[i]; } } return dic; } function getNodeRelation(nodes, edges) { for (var i = 0; i < edges.length; i++) { var source = edges[i].source; var target = edges[i].target; //console.log(source+'->'+target); nodes[target].parentNode = nodes[source]; if (nodes[source].children)nodes[source].children.push(nodes[target]); else nodes[source].children = [nodes[target]]; } } //function method1(d){ // var nodes= d.node; // var edges= d.edge; // //method1 // var newEdgeCount=0; // //find the targets of every node // for(var i=0;i<nodes.length;i++){ // //root find // var tmpTargets=[]; // var nodeID=parseInt(nodes[i].id); // //find all edges that source==nodeID // for(var j=0;j<edges.length;j++){ // if(edges[j].source==nodeID){ // tmpTargets.push(nodes[edges[j].target]) // } // } // nodes[i].targets=tmpTargets; // var clusterResult=hierarchicalClustering(nodes[i]); // nodes[i].clusterResult=clusterResult; // calculateFlowPoint(nodes[i]); // newEdgeCount+=nodes[i].edges.length; // } // console.log(newEdgeCount,edges.length); // updateEdges(d); //} function updateEdges(d) { var nodes = d.node; var edges = d.edge; var newEdges = []; for (var i = 0; i < nodes.length; i++) { newEdges = newEdges.concat(nodes[i].edges); } for (var i = 0; i < newEdges.length; i++) { var points = newEdges[i]; var assists = []; for (var j = 1; j < points.length - 1; j++) { assists.push([points[j].x, points[j].y]); } newEdges.assists = assists; var source = parseInt(newEdges[i][0].id); var target = parseInt(newEdges[i][newEdges[i].length - 1].id); var newEdge = {points: points, assists: assists, source: source, target: target}; newEdges[i] = newEdge; } var edgesDic = {}; for (var i = 0; i < edges.length; i++) { var source = edges[i].source; var target = edges[i].target; var key = String(source) + '_' + String(target); edgesDic[key] = i; } edges.sort(function (a, b) { return a.source - b.source }); edges.sort(function (a, b) { return a.target - b.target }); newEdges.sort(function (a, b) { return a.source - b.source }); newEdges.sort(function (a, b) { return a.target - b.target }); for (var i = 0; i < edges.length; i++) { edges[i].assists = newEdges[i].assists; edges[i].points = newEdges[i].points; } var tmpEdges = []; for (var i = 0; i < edges.length; i++) { var source = edges[i].source; var target = edges[i].target; var key = String(source) + '_' + String(target); var j = edgesDic[key]; tmpEdges[j] = edges[i]; } d.edge = tmpEdges } //function Cluster(thisCLuster,subCluster1,subCluster2){ // this.cluster=thisCLuster; // this.subCluster1=subCluster1; // this.subCluster2=subCluster2; // if(subCluster1&&subCluster2) { // this.type = 'cluster'; // var minX=d3.min([subCluster1.bounds.x, subCluster2.bounds.x]); // var minY=d3.min([subCluster1.bounds.y, subCluster2.bounds.y]); // var maxX=d3.min([subCluster1.bounds.x+subCluster1.bounds.width, subCluster2.bounds.x+subCluster2.bounds.width]); // var maxY=d3.min([subCluster1.bounds.y+subCluster1.bounds.height, subCluster2.bounds.y+subCluster2.bounds.height]); // this.bounds = { // x:minX, // y:minY, // width:maxX-minX, // height:maxY-minY // } // this.center={ // x:minX+(maxX-minX)/2, // y:minY+(maxY-minY)/2 // } // } // else if(!(subCluster1&&subCluster2)){ // if(thisCLuster.isRoot)this.isRoot = true; // else this.isRoot=false; // this.type = 'node'; // this.size= thisCLuster.size; // this.bounds={ // x:thisCLuster.x-sizeScale.sizeScale(thisCLuster.size), // y:thisCLuster.y-sizeScale.sizeScale(thisCLuster.size), // width:sizeScale.sizeScale(thisCLuster.size)*2, // height:sizeScale.sizeScale(thisCLuster.size)*2 // } // this.center={ // x:thisCLuster.x, // y:thisCLuster.y // } // // } // //} function hierarchicalClustering(node) { var root = node; root.isRoot = true; root.equalThis = function (cluster) { if (cluster.type == 'node') { if (cluster.isRoot == true)return true; else return false; } else return false; }; var leafNodes = root.targets; var clusterList = []; var clusterCollection = []; //create init cluster for every node. var rootCluster = new Cluster(root, false, false); var id = 0; rootCluster.id = id; id += 1; clusterList.push(rootCluster); for (var i = 0; i < leafNodes.length; i++) { var targetCluster = new Cluster(leafNodes[i], false, false); targetCluster.id = id; clusterList.push(targetCluster); id += 1; } //do hierarchicalClustering //calculate distance between every two nodes. //O(n)=n*n*n while (clusterList.length > 1) { var distanceList = []; //find closest pair of clusters for (var i = 0; i < clusterList.length; i++) { for (var j = i + 1; j < clusterList.length; j++) { var p1 = clusterList[i].center; var p2 = clusterList[j].center; var distance = getDistance(p1, p2); var distancePair = {distance: distance, cluster1: clusterList[i], cluster2: clusterList[j]}; distanceList.push(distancePair); } } distanceList.sort(function (a, b) { return a.distance - b.distance; }); var closestPair = distanceList[0]; var c1 = closestPair.cluster1; var c2 = closestPair.cluster2; //remove this two clusters var newClusterList = []; for (var i = 0; i < clusterList.length; i++) { if (clusterList[i].id != c1.id && clusterList[i].id != c2.id) { newClusterList.push(clusterList[i]); } } clusterList = newClusterList; //if either of two clusters include root node add another cluster into collection and root as new cluster if (root.equalThis(c1) || root.equalThis(c2)) { var newCluster; if (root.equalThis(c1)) { clusterCollection.push(c2) } else if (root.equalThis(c2)) { clusterCollection.push(c1) } newCluster = rootCluster; } else { newCluster = new Cluster(false, c1, c2); newCluster.id = id; id += 1; } clusterList.push(newCluster); } return clusterCollection; } function calculateFlowPoint(clusterTree) { var rootNode = clusterTree; // console.log(clusterTree); var clusters = clusterTree.clusterResult; clusterTree.edges = []; for (var i = 0; i < clusters.length; i++) { var cluster = clusters[i]; //a cluster only contain one node // if(!(cluster.cluster1||cluster.cluster2)){ //do nothing // } countClusterSize(cluster); processCluster(rootNode, cluster); var edges = clusterTree.edges; var flowEdge = collectFlowPoint(rootNode, cluster); clusterTree.edges = edges.concat(flowEdge); } } function countClusterSize(cluster) { if (cluster.subCluster1 && cluster.subCluster2) { cluster.size = countClusterSize(cluster.subCluster1) + countClusterSize(cluster.subCluster2); return cluster.size; } else { return cluster.size; } } function processCluster(parNode, cluster) { function getNewNode(p0, p1, p2) { var dist1 = getDistance(p0, p1); var dist2 = getDistance(p0, p2); var shortestDist = d3.min([dist1, dist2]) / 2; // var biggerCluster=d3.max([cluster.subCluster1,cluster.subCluster2],function(d){return d.size}); var biggerCluster; if (cluster.subCluster1.size >= cluster.subCluster2.size) { biggerCluster = cluster.subCluster1; } else biggerCluster = cluster.subCluster2; var p3 = biggerCluster.center; var biggerDist = getDistance(p0, p3); var bigFraction = parseFloat(shortestDist / biggerDist); var parentFraction = 1 - bigFraction; var x = p0.x * parentFraction + p3.x * bigFraction; var y = p0.y * parentFraction + p3.y * bigFraction; var newNode = {x: x, y: y, subCluster1: cluster.subCluster1, subCluster2: cluster.subCluster2}; return newNode; } if (cluster.subCluster1 || cluster.subCluster2) { var type1 = cluster.subCluster1.type; var type2 = cluster.subCluster2.type; var typeArray = [type1, type2]; if (in_array('node', typeArray) && !in_array('cluster', typeArray)) { //a cluster only contains nodes var p0 = {x: parNode.x, y: parNode.y}; var p1 = cluster.subCluster1.center; var p2 = cluster.subCluster2.center; var newNode = getNewNode(p0, p1, p2); cluster.nextNode = newNode; cluster.subCluster1 = ''; cluster.subCluster2 = ''; } else if (in_array('cluster', typeArray) && !in_array('node', typeArray)) { //a cluster only contains clusters var p0 = {x: parNode.x, y: parNode.y}; var bounds1 = cluster.subCluster1.bounds; var bounds2 = cluster.subCluster2.bounds; var line1 = {p1: p0, p2: cluster.subCluster1.center}; var line2 = {p1: p0, p2: cluster.subCluster2.center}; var p1 = getRectangleLineCrossPoint(bounds1, line1); var p2 = getRectangleLineCrossPoint(bounds2, line2); var newNode = getNewNode(p0, p1, p2); cluster.nextNode = newNode; processCluster(newNode, cluster.subCluster1); processCluster(newNode, cluster.subCluster2); cluster.subCluster1 = ''; cluster.subCluster2 = ''; } else if (in_array('cluster', typeArray) && in_array('node', typeArray)) { //a cluster contains a node and a cluster if (cluster.subCluster1.type == 'cluster') { var clus = cluster.subCluster1; var node = cluster.subCluster2; } else if (cluster.subCluster1.type == 'node') { var clus = cluster.subCluster2; var node = cluster.subCluster1; } var p0 = {x: parNode.x, y: parNode.y}; var p1 = node.center; var bounds = clus.bounds; var line = {p1: p0, p2: clus.center}; var p2 = getRectangleLineCrossPoint(bounds, line); var newNode = getNewNode(p0, p1, p2); cluster.nextNode = newNode; processCluster(newNode, clus); cluster.subCluster1 = ''; cluster.subCluster2 = ''; } } } function collectFlowPoint(root, cluster) { function recurCluster(cluster) { if (cluster.nextNode) { tmpEdge.push({x: cluster.nextNode.x, y: cluster.nextNode.y}); function judgeCluster(cluster) { if (cluster.type == 'node') { var tmpPoint = {x: cluster.cluster.x, y: cluster.cluster.y, id: cluster.cluster.id}; var edge = []; clone(tmpEdge, edge); edge.push(tmpPoint); flowEdge.push(edge); } else { recurCluster(cluster); } } judgeCluster(cluster.nextNode.subCluster1); judgeCluster(cluster.nextNode.subCluster2); } else { var tmpPoint = {x: cluster.cluster.x, y: cluster.cluster.y, id: cluster.cluster.id}; var edge = []; clone(tmpEdge, edge); edge.push(tmpPoint); flowEdge.push(edge); } } var flowEdge = []; var rootPoint = {x: root.x, y: root.y, id: root.id}; var tmpEdge = []; tmpEdge.push(rootPoint); recurCluster(cluster); return flowEdge; } function Graph(edges,assistEdges){ this.edges=edges; var dotBeginning='digraph{'; var dotEnding='}'; var arrow='->'; var edgeEnding=';'; var dot=''; var invis='[style=invis]'; dot+=dotBeginning; for(var i= 0,len=edges.length;i<len;i++){ var edge=edges[i]; var source=String(edge.source); var target=String(edge.target); var edgeString=source+arrow+target+edgeEnding; dot+=edgeString; } if(assistEdges) { for (var i = 0, len = assistEdges.length; i < len; i++) { var edge = assistEdges[i]; var source = String(edge.source); var target = String(edge.target); var edgeString = source + arrow + target + invis + edgeEnding; dot += edgeString; } } dot+=dotEnding; this.dotString=dot; this.svgGraph=function(){ // console.log(Viz(this.dotString)); var div=d3.select('body').append('tmpDiv').attr('class','tmpDiv'); div.html(Viz(this.dotString)); // .html(Viz(this.dotString)); // document.body.innerHTML +=Viz(this.dotString); } } function reCalculateLayout(graph,graphData){ var nodes=graphData.node; var edges=graphData.edge; if(this.method=='mst'||this.method=='filterFlow'){ maximalSpanningTree(graphData); } // var newGraph=new Graph(graphData.edge, []); graph.svgGraph(); var newSVG=d3.select('.tmpDiv').select('svg'); var svgData=getSVGData(newSVG); newSVG.remove(); d3.select('.tmpDiv').remove(); mergeData(svgData,nodes, edges); // reverseXY(nodes,edges); } function maximalSpanningTree(d){ //find root; var nodes=d.node; var edges= d.edge; d.originEdge=[]; clone(edges,d.originEdge); var root; var newNodes=[]; var newEdges=[]; clone(nodes, newNodes); for(var i=0;i<nodes.length;i++){ if(nodes[i].focused=='true'){ root = nodes[i]; break; } } //remove all the edges to the root node for(var i=0;i<edges.length;i++){ if(edges[i].target!=parseInt(root.id))newEdges.push(edges[i]); } //select top flow of every node var tmpEdge=[]; for(var i=0;i<nodes.length;i++){ if(!(nodes[i].focused=='true')){ var id=parseInt(nodes[i].id); var nodeEdge=[]; var maxEdge={flow:0}; for(var j=0;j<newEdges.length;j++){ if(newEdges[j].target==id){ if(newEdges[j].flow>maxEdge.flow)maxEdge=newEdges[j]; } } tmpEdge.push(maxEdge); } } d.edge = tmpEdge; var edgeDic=getEdgeSourceTargetDic(d.edge); var originEdgeDic=getEdgeSourceTargetDic(d.originEdge); var otherEdge=[]; for(var key in originEdgeDic){ if(!(key in edgeDic)){ otherEdge.push(originEdgeDic[key]) } } d.otherEdge=otherEdge; } function mergeData(data,nodes,edges){ var svgNodes=data.svgNodes; var svgEdges=data.svgEdges; for(var i= 0,len=svgEdges.length;i<len;i++){ var source=svgEdges[i].source; var target=svgEdges[i].target; for(var j= 0,len1=edges.length;j<len;j++){ if(source ==edges[j].source&&target==edges[j].target){ edges[j].assists=svgEdges[i].assists; break; } } } for(var key in svgNodes){ if(nodes[key]){ nodes[key].x = svgNodes[key].x; nodes[key].y = svgNodes[key].y; } } } function getSVGData(svg){ var svgNodes={}; var svgEdges=[]; svg.selectAll('g') .each(function(){ var thisElem=d3.select(this); var thisClass=thisElem.attr('class'); if(thisClass=='edge'){ var edge={}; var edgeValue=thisElem.select('title').text(); edge.source=parseInt(edgeValue.split('->')[0]); edge.target=parseInt(edgeValue.split('->')[1]); edge.assists=[]; var d=thisElem.select('path').attr('d').split('M')[1]; var firstPoint=d.split('C')[0]; var point=[]; point[0]=parseFloat(firstPoint.split(',')[0]); point[1]=parseFloat(firstPoint.split(',')[1]); edge.assists.push(point); var otherPoints=d.split('C')[1].split(' '); for(var i= 0,len=otherPoints.length;i<len;i++){ var tmpPoint=[]; tmpPoint[0]=parseFloat(otherPoints[i].split(',')[0]); tmpPoint[1]=parseFloat(otherPoints[i].split(',')[1]); edge.assists.push(tmpPoint); } svgEdges.push(edge); } else if(thisClass=='node'){ var node={}; var nodeValue=thisElem.select('title').text(); node.id=nodeValue; node.x=parseFloat(thisElem.select('ellipse').attr('cx')); node.y=parseFloat(thisElem.select('ellipse').attr('cy')); svgNodes[nodeValue]=node; } }) return {svgNodes:svgNodes,svgEdges:svgEdges}; } //function getEdgeSourceTargetDic(edges){ // var dic={}; // for (var i= 0,len=edges.length;i<len;i++){ // var source=edges[i].source; // var target=edges[i].target; // if(dic[source]){ // dic[source][target]=edges[i]; // } // else{ // dic[source]={} // dic[source][target]=edges[i]; // } // } // return dic; //} function getNodeDic(nodes){ var dic={}; for(var i= 0,len=nodes.length;i<len;i++){ var key=nodes[i].oldKey dic[key]=nodes[i]; } return dic; } function processIncrementalTree(tree){ var newTree={}; for(var i=0;i<tree.length;i++){ var newGroup={} for(var j=0;j<tree[i].length;j++){ var id=tree[i][j].id; var child=tree[i][j].chd; var parent=tree[i][j].prt; newGroup[id]={child:child, parent:parent}; } var groupID=(i+1)*5; newTree[groupID]=newGroup; } // console.log(newTree); data.incrementalTree=newTree; } function getGraphInfo(nodes,edges){ var result={nodes:0,edges:0,citation:0,flow:0,yearFlow:0}; result.nodes = nodes.length; result.edges = edges.length; result.citation = countCitation(edges); result.flow = countFlow(edges); result.yearFlow = countYearFlow(edges); return result; } function printGraphInfo(info){ console.log('-----------------------------'); for(var key in info){ console.log(key+info[key]); } console.log('-----------------------------'); } function linkPruning(){ /* let the edge with the smallest weight be (i,j). If remove (i,j) does not make the current graph disconnected (here connected means that there is a path from the source to every node), we remove it. If there is a path in the current graph from i to j, we add the weight of the edge to each edge along the path. We update the edge weights and repeat this process. At the end of this process we have a spanning tree */ // 1. build graph structure and functions,node,edge, node parents,node children,add edge,delete edge,graph connection var data=this.data.postData[this.focusedID] var removeSelfEdgeResult=removeSelfEdge(data.edge); data.edge = removeSelfEdgeResult.edge; data.selfEdge = removeSelfEdgeResult.selfEdge; this.directedGraph=new DirectedGraph(data); this.directedGraph.init(); data.originGraphInfo=getGraphInfo(this.directedGraph.nodes,this.directedGraph.edges); var paperCount=0; for(var i=0;i<this.directedGraph.nodes.length;i++){ paperCount+=this.directedGraph.nodes[i].size; } data.originGraphInfo.paperCount=paperCount; if(!this.directedGraph.checkConnection())alert('original graph does not connected'); else{ if(this.method=='filterFlow'){ this.directedGraph.filterTopFlow(1); this.updateData(data,this.directedGraph); } else if(this.method=='recoveryWeight'){ this.directedGraph.generateSpanningTree(); this.updateData(data,this.directedGraph); } else if(this.method=='mst'){ this.directedGraph.generateMaximalSpanningTree(); this.updateData(data,this.directedGraph.maximalSpanningTree); } } } function updateData(data,graph){ data.node=[]; data.edge=[]; clone(graph.nodes,data.node); clone(graph.edges,data.edge); // data.node = graph.nodes; // data.edge = graph.edges; if(this.method=='mst'){ data.deletedTreeEdges=graph.deletedTreeEdges; data.deletedNonTreeEdges=graph.deletedNonTreeEdges; } else{ data.deletedTreeEdges = graph.spanningTree.deletedTreeEdges; data.deletedNonTreeEdges=graph.spanningTree.deletedNonTreeEdges; } this.maxYear=graph.maxYear; this.minYear=graph.minYear; for(var i=0;i<data.node.length;i++){ if(data.node[i].parents){ data.node[i].parents[0]=null; // delete(data.node[i].parents[0]); } if(data.node[i].children){ data.node[i].children=null; // delete(data.node[i].children); } } } function removeSelfEdge(edges){ var newEdges=[]; var selfEdges=[]; for(var i=0;i<edges.length;i++){ if(edges[i].source==edges[i].target){ selfEdges.push(edges[i]); } else{ newEdges.push(edges[i]); } } return {edge:newEdges,selfEdge:selfEdges}; } function linkPruningOld(data){ var removeSelfEdgeResult=removeSelfEdge(data.edge); data.edge = removeSelfEdgeResult.edge; data.selfEdge = removeSelfEdgeResult.selfEdge; directedGraph=new DirectedGraph(data); directedGraph.init(); if(!directedGraph.checkConnection())alert('original graph does not connected'); directedGraph.filterTopFlow(1.5); data.node = directedGraph.nodes; data.edge = directedGraph.edges; data.deletedTreeEdges = directedGraph.spanningTree.deletedTreeEdges; data.deletedNonTreeEdges=directedGraph.spanningTree.deletedNonTreeEdges; maxYear=directedGraph.maxYear; minYear=directedGraph.minYear; for(var i=0;i<data.node.length;i++){ if(data.node[i].parents){ data.node[i].parents[0]=null; // delete(data.node[i].parents[0]); } if(data.node[i].children){ data.node[i].children=null; // delete(data.node[i].children); } } // setNodeWeight(data); // data['edge'].sort(function(a,b){ // return b.flow*b.BFSWeight-a.flow*a.BFSWeight; // }); //// console.log(data); // var k; // for(var key in data['cluster']){ //// console.log('cluster key:'+key); // if(key!='300'){ // k = parseInt(key.split('-')[0])+1; //// console.log('cluster length:'+k); // break; // } // } // var deleted=[]; // while(data['edge'].length>1.5*k){ // deleted.push(data['edge'][data['edge'].length-1]); // data['edge'].pop(); // } //// console.log('prune over'); // // var visitedTree={}; // var treeNum=0; // for(var key in data['cluster']){ // if(!visitedTree[key]){ // var visitedNode=getNodesByAssignRoot(data,key); // for(var i=0;i<visitedNode.length;i++){ // if(!visitedTree[visitedNode[i]]){ // visitedTree[visitedNode[i]] = {nodes:visitedNode,num:treeNum}; // } // } // treeNum+=1; // } // } // var newTree={}; // for (var key in visitedTree){ // newTree[visitedTree[key].num]=visitedTree[key].nodes; // } // visitedTree=newTree; // var rootTree=[]; // var otherTrees=[]; // for(var key in visitedTree){ // for (var i=0;i<visitedTree[key].length;i++){ // if(visitedTree[key][i]=='300') // { // rootTree=visitedTree[key]; // delete visitedTree[key]; // break; // } // // } // } // for (var key in visitedTree){ // otherTrees.push(visitedTree[key]); // } // // // // var visitedNode=getNodes(data); // var reachableEdge=[]; // for(var i= 0,len=data['edge'].length;i<len;i++){ // if(!in_array(data['edge'][i].source,visitedNode)||!in_array(data['edge'][i].target,visitedNode)){ // deleted.push(data['edge'][i]); // } // else{ // reachableEdge.push(data['edge'][i]); // } // } //// data['edge']=reachableEdge; // var nodeStep=[]; // visitedNode=[]; // for(var key in data['cluster']){ // var E=[]; // var S=[]; // var target=key; // for(var i= 0,len=reachableEdge.length;i<len;i++){ // if(reachableEdge[i].target==target&&reachableEdge[i].source!=reachableEdge[i].target){ // S.push(reachableEdge[i]); // } // } // for(var i= 0,len=deleted.length;i<len;i++){ // if(deleted[i].target==target&&deleted[i].source!=deleted[i].target){ // E.push(deleted[i]); // } // } // E.sort(function(a,b){ // return b.flow*b.BFSWeight-a.flow*a.BFSWeight; // }); // if(S.length==0&&E.length>=1){ // for(var i= 0,len=E.length;i<len;i++){ // if(E[i].source!=E[i].target){ // visitedNode=getNodes(data); // if(in_array(E[i].source,visitedNode)){ // data['edge'].push(E[i]); // visitedNode=getNodes(data); // var recovery=String(E[i].source)+'->'+String(E[i].target); //// console.log('recover edge:'+recovery); // break; // } // } // } // } // } // // var newEdge=[]; // for(var i= 0,len=data['edge'].length;i<len;i++){ // if(data['edge'][i].source!=data['edge'][i].target){ // var edge=Edge.newedge(); // for(var key in data['edge'][i]){ // edge[key]=data['edge'][i][key]; // } // newEdge.push(edge); // } // else deleted.push(data['edge'][i]); // } // data['edge']=newEdge; // // //test the top k flow in deleted // deleted.sort(function(a,b){return b.flow*b.BFSWeight-a.flow*a.BFSWeight;}); //// for(var i= 0,count=0;i<deleted.length;i++){ //// if(count==10)break; //// var edge=deleted[i]; //// var source=edge.source; //// var target=edge.target; //// if(in_array(source,visitedNode)&&target!=source){ //// data['edge'].push(edge); //// count+=1; //// } //// //// } // // var tmpEdgeString=[]; // var tmpEdge=[]; // var tmpNode={}; // for(var i=0;i<data['edge'].length;i++){ // var edgeString=data['edge'][i].source+'->'+data['edge'][i].target; // if(!in_array(edgeString,tmpEdgeString)){ // tmpEdge.push(data['edge'][i]); // tmpEdgeString.push(edgeString); // if(!tmpNode[data['edge'][i].source])tmpNode[data['edge'][i].source]=data['cluster'][data['edge'][i].source]; // if(!tmpNode[data['edge'][i].target])tmpNode[data['edge'][i].target]=data['cluster'][data['edge'][i].target]; // } // } // data['edge']=tmpEdge; // data['cluster']=tmpNode; // // console.log('visitedNode:\n'+visitedNode); // visitedNode=getNodes(data); // reachableEdge=[]; // for(var i= 0,len=data['edge'].length;i<len;i++){ // if(!in_array(data['edge'][i].source,visitedNode)||!in_array(data['edge'][i].target,visitedNode)){ // deleted.push(data['edge'][i]); // } // else{ // reachableEdge.push(data['edge'][i]); // } // } // data['edge']=reachableEdge // // deleted.sort(function(a,b){return b.flow-a.flow;}); // for (var key in data['cluster']){ // for (var i=0;i<deleted.length;i++){ // if(deleted[i].source==key&&deleted[i].target==key){ // data['cluster'][key].selfEdge=deleted[i].flow; // } // } // } } function getNodesByAssignRoot(data,root){ data['edge'].sort(function(a,b){ return b.flow- a.flow; }); var nodeStep=[]; var visitedNode=[]; nodeStep.push(root); while(nodeStep[0]){ var newStep=[]; for(var i=0;i<nodeStep.length;i++){ var step=nodeStep[i]; if(!in_array(step,visitedNode)){ visitedNode.push(step); for(var j=0;j<data['edge'].length;j++){ var edge=data['edge'][j]; var source=edge.source; var target=edge.target; if(source==step&&!in_array(target,visitedNode)){ newStep.push(edge.target); } } } } nodeStep=newStep; } return visitedNode; } function getNodes(data){ data['edge'].sort(function(a,b){ return b.flow- a.flow; }); var nodeStep=[]; var visitedNode=[]; var root=300; nodeStep.push(root); while(nodeStep[0]){ var newStep=[]; for(var i=0;i<nodeStep.length;i++){ var step=nodeStep[i]; if(!in_array(step,visitedNode)){ visitedNode.push(step); for(var j=0;j<data['edge'].length;j++){ var edge=data['edge'][j]; var source=edge.source; var target=edge.target; if(source==step&&!in_array(target,visitedNode)){ newStep.push(edge.target); } } } } nodeStep=newStep; } return visitedNode; } function setNodeWeight(data){ data['edge'].sort(function(a,b){ return b.flow- a.flow; }); var nodeStep=[]; var visitedNode=[]; var rootWeight=1; var k=0.1; var level=0; var root=300; nodeStep.push(root); while(nodeStep[0]){ var newStep=[]; for(var i=0;i<nodeStep.length;i++){ var step=nodeStep[i]; if(!in_array(step,visitedNode)){ visitedNode.push(step); if(!data['cluster'][step].BFSWeight)data['cluster'][step].BFSWeight=rootWeight*Math.pow(k, level); for(var j=0;j<data['edge'].length;j++){ if(data['edge'][j].source==step&&!data['edge'][j].BFSWeight)data['edge'][j].BFSWeight=rootWeight*Math.pow(k, level); var edge=data['edge'][j]; var source=edge.source; var target=edge.target; if(source==step&&!in_array(target,visitedNode)){ newStep.push(edge.target); } } } } level+=1 nodeStep=newStep; } return visitedNode; } function linkPruning_su(data){ // console.log(data); data['edge'].sort(function(a,b){ return b.flow-a.flow; }); // console.log(data); var k; for(var key in data['cluster']){ // console.log('cluster key:'+key); if(key!='300'){ k = parseInt(key.split('-')[0])+1; // console.log('cluster length:'+k); break; } } var deleted=[]; while(data['edge'].length>2*k){ deleted.push(data['edge'][data['edge'].length-1]); data['edge'].pop(); } // console.log('prune over'); var visitedNode=getNodes(data); var reachableEdge=[]; for(var i= 0,len=data['edge'].length;i<len;i++){ if(!in_array(data['edge'][i].source,visitedNode)||!in_array(data['edge'][i].target,visitedNode)){ deleted.push(data['edge'][i]); } else{ reachableEdge.push(data['edge'][i]); } } data['edge']=reachableEdge; var nodeStep=[]; visitedNode=[]; for(var key in data['cluster']){ var E=[]; var S=[]; var target=key; for(var i= 0,len=data['edge'].length;i<len;i++){ if(data['edge'][i].target==target&&data['edge'][i].source!=data['edge'][i].target){ S.push(data['edge'][i]); } } for(var i= 0,len=deleted.length;i<len;i++){ if(deleted[i].target==target&&deleted[i].source!=deleted[i].target){ E.push(deleted[i]); } } E.sort(function(a,b){ return b.flow-a.flow; }); if(S.length==0&&E.length>=1){ for(var i= 0,len=E.length;i<len;i++){ if(E[i].source!=E[i].target){ visitedNode=getNodes(data); if(in_array(E[i].source,visitedNode)){ data['edge'].push(E[i]); visitedNode=getNodes(data); var recovery=String(E[i].source)+'->'+String(E[i].target); // console.log('recover edge:'+recovery); break; } } } } } var newEdge=[]; for(var i= 0,len=data['edge'].length;i<len;i++){ if(data['edge'][i].source!=data['edge'][i].target){ var edge=Edge.newedge(); for(var key in data['edge'][i]){ edge[key]=data['edge'][i][key]; } newEdge.push(edge); } } data['edge']=newEdge; //test the top k flow in deleted deleted.sort(function(a,b){return b.flow-a.flow}); for(var i= 0,count=0;i<deleted.length;i++){ if(count==10)break; var edge=deleted[i]; var source=edge.source; var target=edge.target; if(in_array(source,visitedNode)&&target!=source){ data['edge'].push(edge); count+=1; } } var tmpEdgeString=[]; var tmpEdge=[]; var tmpNode={}; for(var i=0;i<data['edge'].length;i++){ var edgeString=data['edge'][i].source+'->'+data['edge'][i].target; if(!in_array(edgeString,tmpEdgeString)){ tmpEdge.push(data['edge'][i]); tmpEdgeString.push(edgeString); if(!tmpNode[data['edge'][i].source])tmpNode[data['edge'][i].source]=data['cluster'][data['edge'][i].source]; if(!tmpNode[data['edge'][i].target])tmpNode[data['edge'][i].target]=data['cluster'][data['edge'][i].target]; } } data['edge']=tmpEdge; data['cluster']=tmpNode; // console.log('visitedNode:\n'+visitedNode); visitedNode=getNodes(data); reachableEdge=[]; for(var i= 0,len=data['edge'].length;i<len;i++){ if(!in_array(data['edge'][i].source,visitedNode)||!in_array(data['edge'][i].target,visitedNode)){ deleted.push(data['edge'][i]); } else{ reachableEdge.push(data['edge'][i]); } } data['edge']=reachableEdge } function updateClusterOption(clusterList) { var clusterOptionID = 1; var optionDiv = d3.select('.optionDiv'); var selectDiv = optionDiv.select('#selectDiv' + clusterOptionID) selectDiv.selectAll('*').remove(); var fontFamily = 'Microsoft YaHei'; var fontSize = 12; var maxLabel = d3.max(clusterList, function (d) { return d.toString().visualLength(fontFamily, fontSize); }); selectDiv.append('cite') .attrs({ class: 'cite', id: 'cite' + clusterOptionID }) .on('click', function () { var thisCite = d3.select(this); var id = thisCite.attr('id').split('cite')[1]; var ul = old$("#ul" + id); var ul_display = d3.select('#ul' + id).style('display'); if (ul.css("display") == "none") { ul.slideDown("fast"); } else { ul.slideUp("fast"); } }) .styles({ width: maxLabel + 30 + px, height: '24px', 'line-height': '24px', 'font-family': 'Microsoft YaHei', 'font-size': 12 + px, color: color.optionTextColor }) .append('a') .styles({ 'margin-left': 10 + px }) .html(function () { return clusterCount || '20'; }); var newUL = selectDiv.append('ul') .attrs({ class: 'ul', id: 'ul' + clusterOptionID }) .styles({ width: maxLabel + 20 + px }); for (var j = 0; j < clusterList.length; j++) { newUL.append('li') .styles({}) .append('a') .styles({ width: maxLabel + px, height: '24px', 'line-height': '24px', 'font-family': 'Microsoft YaHei', 'font-size': 12 + px }) .attrs({ selectId: j, father: clusterOptionID, cluster: clusterList[j] }) .on('click', function () { var id = d3.select(this).attr('father'); var txt = old$(this).text(); var cluster = d3.select(this).attr('cluster'); old$("#cite" + id + ' a').html(txt); var value = old$(this).attr("selectId"); // inputselect.val(value); old$("#ul" + id).hide(); var d = {fatherID: id, selectID: value, cluster: cluster}; changeOption(d); }) .html(clusterList[j]); } } function updateTitle(title) { var titleDiv = d3.select('.titleDiv'); titleDiv.select('text').html(title); } function processData(d) { var clusterList = d.clusterIDList; var title = d.cluster['300'].title; updateTitle(title); updateClusterOption(clusterList); if (this.requestMethod == 'ajax' || this.requestMethod == 'local') { for (var key in d.cluster) { var cluster = d.cluster[key]; var nodeYearInfo = {}; var list = []; if (cluster.nodeidlist) { for (var year in cluster.nodeidlist) { nodeYearInfo[year] = cluster.nodeidlist[year].length; for (var i = 0; i < cluster.nodeidlist[year].length; i++) { list.push(cluster.nodeidlist[year][i]); } } cluster.nodeYearInfo = nodeYearInfo; } else { var sum = 0 for (var day in cluster.nodeYearInfo) { sum += parseInt(cluster.nodeYearInfo[day]); } cluster.size = sum; } cluster.nodeidlist = list; cluster.author = ''; cluster.venue = ''; cluster.author_venue = { author: '', venue: '' } } for (var i = 0; i < d.edge.length; i++) { var edge = d.edge[i]; edge.oldWeight = {}; clone(edge.weight, edge.oldWeight); edge.weight = {}; for (var key in edge.oldWeight) { var years; (key.split('-').length == 2) ? years = key.split('-') : years = key.split('_'); var targetYear = years[1].toInt(); edge.weight[targetYear] = edge.oldWeight[key]; } } } this.fontScale = d3.scaleLinear() .domain([40, 5]) .range([20, 5]); var json_nodes = this.dataPreProcess(d); var json_edges = d.edge; this.data.postData[this.focusedID] = {edge: json_edges, node: json_nodes}; if (this.method != 'origin') { this.linkPruning(); } var assistEdge = []; var newGraph = new Graph(this.data.postData[this.focusedID].edge, assistEdge); this.reCalculateLayout(newGraph, this.data.postData[this.focusedID]); reverseXY(this.data.postData[this.focusedID]); this.getYearData(this.data.postData[this.focusedID]); this.coordinateOffset(this.data.postData[this.focusedID]); if (this.method != 'filterFlow' && this.method != 'origin') { this.calculateFlowMap(this.data.postData[this.focusedID]); } this.temporalSummarization(this.data.postData[this.focusedID]); filterSelfEdge(this.data.postData[this.focusedID]); this.setInitNodeTransition(this.data.postData[this.focusedID]); this.setInitEdgeTransition(this.data.postData[this.focusedID]); this.getRelation(this.data.postData[this.focusedID]); getCurves(this.data.postData[this.focusedID]); if (this.focusedID && this.preFocusedID) { var fID = parseInt(this.focusedID.split('_')[1]); var pID = parseInt(this.preFocusedID.split('_')[1]); if (fID > pID) { generateTransitionData(this.data.postData[this.focusedID], this.data.postData[this.preFocusedID]); } else if (fID < pID) { generateTransitionData(this.data.postData[this.preFocusedID], this.data.postData[this.focusedID]); } } } function edgeAdjustment(d) { var edges = d.edge; for (var i = 0; i < edges.length; i++) { var edge = edges[i]; var p = edge.points; var x1, y1, x2, y2, r1, r2, dis; var last = p.length - 1; dis = distance(p[0].x, p[0].y, p[last].x, p[last].y); r1 = sizeScale.sizeScale(p[0].size); r2 = sizeScale.sizeScale(p[last].size); // x1=getstart(p[0].x,p[last].x,r1,dis); // y1=getstart(p[0].y,p[last].y,r1,dis); x2 = getend(p[last].x, p[0].x, r2, dis); y2 = getend(p[last].y, p[0].y, r2, dis); var adjustList = [p[last - 3], p[last - 2], p[last - 1], p[last]]; var originPoints = adjustPoints(adjustList, {x: x2, y: y2}); edge.originPoints = originPoints; } } function adjustPoints(points, point) { var origin = []; clone(points, origin); var box = findBoxOfPoints(points); points[1].ratioToLeft = (points[1].x - box.x) / box.width; points[1].ratioToTop = (points[1].y - box.y) / box.height; points[2].ratioToLeft = (points[2].x - box.x) / box.width; points[2].ratioToTop = (points[2].y - box.y) / box.height; points[3].x = point.x; points[3].y = point.y; var newBox = findBoxOfPoints(points); points[1].x = newBox.width * points[1].ratioToLeft + newBox.x; points[2].x = newBox.width * points[2].ratioToLeft + newBox.x; points[1].y = newBox.height * points[1].ratioToTop + newBox.y; points[2].y = newBox.height * points[2].ratioToTop + newBox.y; return origin; // svg.selectAll('whatever') // .data(points) // .enter() // .append('circle') // .each(function(d){ // d3.select(this) // .attrs({ // cx:d.x, // cy:d.y, // r:5 // }) // .styles({ // fill:'black' // }) // }) } function filterSelfEdge(d) { var edge = d.edge var newEdge = [] for (var i = 0; i < edge.length; i++) { if (edge[i].source != edge[i].target) { newEdge.push(edge[i]) } } d.edge = newEdge; } function countFlow(edges) { var flow = 0; for (var i = 0; i < edges.length; i++) { flow += edges[i].flow; } return flow; } function countYearFlow(edges) { var flow = 0; for (var i = 0; i < edges.length; i++) { flow += edges[i].flow * edges[i].yearWeight; } return flow; } function countCitation(edges) { var citation = 0; for (var i = 0; i < edges.length; i++) { citation += edges[i].citation; } return citation; } function preLayout(d) { var layoutData = {}; clone(d, layoutData); this.axisLayout(d); this.yearFilter = [this.minYear, this.maxYear]; this.preYear = this.minYear; var newD = this.filterDataByYear(d, [this.yearFilter[0], this.yearFilter[1]]); this.layout(optionNumber, false, false, newD); this.ifInitLayout = false; this.requestTitleList(this.focusedNodeData, 300); } function filterDataByYear(d, yearFilter) { //console.log(yearFilter); var animateMode = this.animateMode; yearFilter[1] -= 1; //过滤完之后需要更新id var nodes = d.node; var edges = d.edge; var newEdges = []; var newNodes = []; var yearDelay = this.yearDelay; var minYear = this.minYear; //filter edges for (var i = 0; i < edges.length; i++) { var edge = edges[i]; //if (animateMode == flipBook) { var years = edge.yearSet.values(); for (var j = 0; j < years.length; j++) { if (years[j] >= yearFilter[0] && years[j] <= yearFilter[1]) { newEdges.push(edge); newEdges[newEdges.length - 1].delay -= yearDelay * (yearFilter[0] - minYear); break; } } edge.ratio = 0; for (var year in edge.yearRatioDic) { if (year >= yearFilter[0] && year <= yearFilter[1]) { edge.ratio += edge.yearRatioDic[year]; } } } for (var i = 0; i < nodes.length; i++) { nodes[i].sourceID = false; nodes[i].targetID = false; } //rebuild the relation between edges and nodes for (var i = 0; i < newEdges.length; i++) { var edge = newEdges[i]; var source = edge.source; var target = edge.target; if (nodes[source].targetID && !in_array(target, nodes[source].targetID)) nodes[source].targetID.push(target); else { nodes[source].targetID = [target.toString()]; } nodes[target].sourceID = source.toString(); } for (var i = 0; i < nodes.length; i++) { var j = 0; var newNodeYearInfo = {}; var len = 0; var preStatus = minYear; if (animateMode == flipBook) { for (var key in nodes[i].nodeYearInfo) { if (key.toInt() < yearFilter[0])preStatus = key.toInt(); else break; } } else if (animateMode == movie) { preStatus = yearFilter[0]; } var k = 0; var newDelay = []; var delaySum = 0; for (var key in nodes[i].nodeYearInfo) { var year = key.toInt(); if (animateMode == flipBook) { if (year >= yearFilter[0] && year <= yearFilter[1]) { newNodeYearInfo[key] = nodes[i].nodeYearInfo[key]; newDelay.push(nodes[i].oriDelay[k]); len += 1; } else if (year < yearFilter[0]) { delaySum += nodes[i].oriDelay[k]; } } else { if (year >= preStatus && year <= yearFilter[1]) { newNodeYearInfo[key] = nodes[i].nodeYearInfo[key]; newDelay.push(nodes[i].oriDelay[k]); len += 1; } else if (year < preStatus) { delaySum += nodes[i].oriDelay[k]; } } k += 1; } if (len > 0) { // setNodeTransition(nodes, preYear); newDelay[0] += delaySum; newNodes.push(nodes[i]); var minKey = 2100; var size = 0; for (var key in newNodeYearInfo) { size += newNodeYearInfo[key]; var year = key.toInt(); if (year < minKey)minKey = year; } if (animateMode == flipBook) { for (var key in nodes[i].nodeYearInfo) { if (!newNodeYearInfo[key])newNodeYearInfo[minKey] += nodes[i].nodeYearInfo[key]; } } newNodes[newNodes.length - 1].newNodeYearInfo = newNodeYearInfo; newNodes[newNodes.length - 1].delay = newDelay; newNodes[newNodes.length - 1].newSize = size; } } this.setNodeTransition(newNodes, yearFilter[0]); var newD = { deletedNonTreeEdges: d.deletedNonTreeEdges, deletedTreeEdges: d.deletedTreeEdges, nodeYearData: d.nodeYearData, originGraphInfo: d.originGraphInfo, selfEdge: d.selfEdge, sunNodeYearData: d.sunNodeYearData }; newD.node = newNodes; newD.edge = newEdges; return newD; } function setNodeTransition(nodes, preYear) { var yearDelay = this.yearDelay; var yearFilter = this.yearFilter; var maxYear = this.maxYear; var minYear = this.minYear; // var thisYear; // var lastYear=minYear; // for(var i=0;i<edges.length;i++){ // var target=edges[i].target; // nodes[target].delay = []; // for(var key in edges[i].weight){ // var year=parseInt(key); // if(lastYear==minYear){ // nodes[target].delay.push({delay:2000*(thisYear-lastYear+1),year:thisYear,}); // } // else{ // nodes[target].delay.push(2000*(thisYear-lastYear)); // } // lastYear=thisYear; // } // } var timeDic = {}; for (var i = 0; i < nodes.length; i++) { if (nodes[i].parentNode) { nodes[i].sourceID = nodes[i].parentNode.id; nodes[i].parentNode = null; // delete(nodes[i].parentNode); } if (nodes[i].children) { nodes[i].targetID = [] for (var j = 0; j < nodes[i].children.length; j++) { nodes[i].targetID.push(nodes[i].children[j].id); } nodes[i].children = null; // delete(nodes[i].children); } var thisYear; var lastYear = preYear; var sum = 0; // nodes[i].delay = []; nodes[i].delay[0] -= yearDelay * (yearFilter[0] - minYear); nodes[i].ratio = []; nodes[i].sizeSeries = []; var j = 0; for (var key in nodes[i].nodeYearInfo) { thisYear = parseInt(key); sum += parseInt(nodes[i].nodeYearInfo[key]); if (thisYear >= yearFilter[0] && thisYear <= yearFilter[1]) { var ratio = parseFloat(sum / nodes[i].size); nodes[i].sizeSeries.push(sum); nodes[i].ratio.push(ratio); lastYear = thisYear; } j += 1; } if (nodes[i].delay[0] < 0) { // for(var j=1;j<nodes[i].delay.length;j++){ nodes[i].delay[1] += nodes[i].delay[0]; // } nodes[i].delay[0] = 0; } nodes[i].sizeRatio = []; nodes[i].sizeDelay = []; // nodes[i].timeSeries = []; nodes[i].timeSeries[0] = nodes[i].delay[0]; for (var j = 1; j < nodes[i].delay.length; j++) { nodes[i].timeSeries[j] = nodes[i].delay[j] + nodes[i].timeSeries[j - 1]; } nodes[i].sizeIncrease = []; nodes[i].sizeIncrease[0] = nodes[i].sizeSeries[0]; nodes[i].sizeIncreaseRatio = []; for (var j = 1; j < nodes[i].sizeSeries.length; j++) { nodes[i].sizeIncrease[j] = nodes[i].sizeSeries[j] - nodes[i].sizeSeries[j - 1]; } for (var j = 0; j < nodes[i].timeSeries.length; j++) { var time = nodes[i].timeSeries[j]; var nodeID = nodes[i].id; var deltaSize = nodes[i].sizeIncrease[j]; if (!(time in timeDic))timeDic[time] = {'sum': 0, 'list': []}; timeDic[time]['list'].push({'id': nodeID, 'size': deltaSize}); timeDic[time]['sum'] += deltaSize; } clone(nodes[i].ratio, nodes[i].sizeRatio); clone(nodes[i].delay, nodes[i].sizeDelay); } var nodesDic = {}; for (var i = 0; i < nodes.length; i++) { id = nodes[i].id; nodesDic[id] = nodes[i]; } for (var time in timeDic) { var obj = timeDic[time]; var sum = obj['sum']; var list = obj['list']; var sizeList = []; for (var i = 0; i < list.length; i++) { sizeList.push(list[i]['size']); } var scale = d3.scaleLinear() .domain([0, d3.max(sizeList)]) .range([0.2, 1]); for (var i = 0; i < list.length; i++) { var id = list[i]['id']; var size = list[i]['size']; var index = nodesDic[id].timeSeries.indexOf(parseInt(time)); var ratio = scale(size); if (ratio < 0.5)ratio = 0.01; nodesDic[id].sizeIncreaseRatio[index] = ratio; list[i]['ratio'] = ratio; } } //console.log(timeDic); } function setInitNodeTransition(d) { var nodes = d.node; for (var i = 0; i < nodes.length; i++) { nodes[i].duration = 100; nodes[i].delay = []; var preStep; preStep = this.minYear; var j = 0 for (var key in nodes[i].nodeYearInfo) { var year = key.toInt(); var delay = this.yearDelay * (year - preStep); if (j == 0)delay += 1000; nodes[i].delay.push(delay); preStep = year; j += 1; } } for (var i = 0; i < nodes.length; i++) { if (nodes[i].focused == 'true') { nodes[i].delay[0] -= 1000; break; } nodes[i].oriDelay = []; clone(nodes[i].delay, nodes[i].oriDelay); } for (var i = 0; i < nodes.length; i++) { nodes[i].oriDelay = []; clone(nodes[i].delay, nodes[i].oriDelay); } // nodes[0].delay[0]-=1000; } function setInitEdgeTransition(d) { var edges = d.edge; //var newEdges = []; var edgeMaxYear = this.maxYear; var edgeMinYear = this.minYear; // for(var i=0;i<edges.length;i++){ // for(var key in edges[i].weight){ // var year=parseInt(key); // if(year>edgeMaxYear)edgeMaxYear=year; // if(year<edgeMinYear)edgeMinYear=year; // } // } for (var i = 0; i < edges.length; i++) { var totalSum = 0; for (var key in edges[i].weight) { totalSum += parseInt(edges[i].weight[key]); } var sum = 0; edges[i].yearRatioDic = {}; edges[i].yearSet = d3.set(); edges[i].flipBookStartYear = edgeMinYear; edges[i].flipBookEndYear = edgeMaxYear; if (edges[i].isBackgroundEdge || edges[i].isForegroundSourceEdge || edges[i].isForegroundTargetEdge) { edges[i].flipBookRatio = {}; for (var j = edgeMinYear; j <= edgeMaxYear; j++) { var partSum = 0; for (var k = edgeMinYear; k <= j; k++) { if (k in edges[i].weight) { partSum += edges[i].weight[k]; } } var ratioKey = edgeMinYear + '_' + j; edges[i].flipBookRatio[ratioKey] = (partSum / totalSum); } } for (var key in edges[i].weight) { edges[i].yearRatioDic[key] = parseFloat(edges[i].weight[key] / totalSum); edges[i].yearSet.add(key); } edges[i].delay = this.yearDelay * (parseInt(key) - edgeMinYear); edges[i].duration = this.edgeDuration; edges[i].id = i; //for (var key in edges[i].weight) { // sum += parseInt(edges[i].weight[key]); // var edge = {}; // // clone(edges[i], edge); // edge.year = parseInt(key); // edge.delay = this.yearDelay * (parseInt(key) - edgeMinYear); // edge.ratio = parseFloat(sum / totalSum); // // edge.duration = this.edgeDuration; // edge.id = i; // if(edge.ratio!=1)edge.isFaker=true; // newEdges.push(edge); // // if(edge.source=='14'&&edge.target == '7'){ // console.log(edge.ratio) // console.log(edge) // } //} } //d.edge = newEdges; } function getYearData(d) { var nodeYearDic = {} for (var i = 0; i < d.node.length; i++) { for (var key in d.node[i].nodeYearInfo) { if (nodeYearDic[key])nodeYearDic[key] += d.node[i].nodeYearInfo[key]; else nodeYearDic[key] = d.node[i].nodeYearInfo[key]; } } // console.log(nodeYearDic); var nodeYearData = [] for (var key in nodeYearDic) { nodeYearData.push([parseInt(key), nodeYearDic[key]]); } // console.log(nodeYearData); this.maxYear = d3.max(nodeYearData, function (d) { return d[0] }); this.minYear = d3.min(nodeYearData, function (d) { return d[0] }); var maxCount = d3.max(nodeYearData, function (d) { return d[1] }); var minCount = d3.min(nodeYearData, function (d) { return d[1] }); for (var i = this.minYear; i <= this.maxYear; i++) { if (!nodeYearDic[i])nodeYearDic[i] = 0; } // if(!requestMethod=='local'){ nodeYearDic[this.maxYear + 1] = 0; this.maxYear += 1; // } var nodeYearData = [] for (var key in nodeYearDic) { nodeYearData.push([parseInt(key), nodeYearDic[key]]); } nodeYearData.sort(function (a, b) { return a[0] - b[0] }); d.nodeYearData = { data: nodeYearData, maxYear: this.maxYear, maxCount: maxCount, minYear: this.minYear, minCount: minCount }; this.yearFilter = [this.minYear, this.maxYear]; } function generateTransitionData(chlData, parData) { //process nodes var fID = parseInt(focusedID.split('_')[1]); var pID = parseInt(preFocusedID.split('_')[1]); var chlNodeIDDic = {}; var parNodeIDDic = {}; var transitionData = {node: [], edge: []}; for (var i = 0; i < chlData.node.length; i++) { chlNodeIDDic[chlData.node[i].oldKey] = i; } for (var i = 0; i < parData.node.length; i++) { parNodeIDDic[parData.node[i].oldKey] = i; } for (var i = 0; i < chlData.node.length; i++) { if (chlData.node[i].oldKey == '300') { transitionData.node[i] = {}; clone(chlData.node[i], transitionData.node[i]); transitionData.node[i].x = parData.node[parNodeIDDic['300']].x; transitionData.node[i].y = parData.node[parNodeIDDic['300']].y; } else { var chlKey = chlData.node[i].oldKey; var parKey = data.incrementalTree[fID][chlKey].parent; transitionData.node[i] = {}; clone(chlData.node[i], transitionData.node[i]); transitionData.node[i].x = parData.node[parNodeIDDic[parKey]].x; transitionData.node[i].y = parData.node[parNodeIDDic[parKey]].y; } } //process edges clone(chlData.edge, transitionData.edge); for (var i = 0; i < transitionData.edge.length; i++) { var source = transitionData.edge[i].source; var target = transitionData.edge[i].target; var sourceX = transitionData.node[source].x; var sourceY = transitionData.node[source].y; var targetX = transitionData.node[target].x; var targetY = transitionData.node[target].y; transitionData.edge[i].points[0].x = sourceX; transitionData.edge[i].points[0].y = sourceY; transitionData.edge[i].points[2].x = targetX; transitionData.edge[i].points[2].y = targetY; } tmpNodes = transitionData.node; tmpCurves = transitionData.edge; } function generateAssistEdge(d) { var clusterCount = parseInt(focusedID.split('_')[1]); var tmpNodeID = clusterCount + 1; var tmpEdges = []; // console.log(d); // console.log(data.incrementalTree); var tree = data.incrementalTree[parseInt(clusterCount) - 5]; //get node id oldid dic var idDic = {} for (var i = 0; i < d.node.length; i++) { idDic[d.node[i].oldKey] = i; } if (clusterCount != 5) { for (var key in tree) { var newNode = tmpNodeID; for (var i = 0; i < tree[key].child.length; i++) { var id = idDic[tree[key].child[i]]; var newEdge = {source: newNode, target: id}; tmpEdges.push(newEdge); } tmpNodeID += 1; } } return tmpEdges; } function procrustes(graph1, graph2) { function getNodeKeyDic(graph) { var dic = {}; for (var i = 0; i < graph.node.length; i++) { var oldKey = graph.node[i].oldKey; dic[oldKey] = i; } return dic; } var graph1NodeDic = getNodeKeyDic(graph1); var graph2NodeDic = getNodeKeyDic(graph2); // console.log(graph1, graph2); // console.log(data.incrementalTree); // if(graph1.node.length<graph2.node.length){ //small graph to large graph //translation var totalX = 0; var totalY = 0; var k = graph1.node.length + graph2.node.length; for (var i = 0; i < graph1.node.length; i++) { totalX += graph1.node[i].x; totalY += graph1.node[i].y; } for (var i = 0; i < graph2.node.length; i++) { totalX += graph2.node[i].x; totalY += graph2.node[i].y; } var avgX = totalX / k; var avgY = totalY / k; for (var i = 0; i < graph1.node.length; i++) { graph1.node[i].x -= avgX; graph1.node[i].y -= avgY; } for (var i = 0; i < graph2.node.length; i++) { graph2.node[i].x -= avgX; graph2.node[i].y -= avgY; } //uniform scaling // } // else{ //large graph to small graph // } } function generateNodesDic(nodes) { var dic = {}; for (var i = 0, len = nodes.length; i < len; i++) { var key = nodes[i].oldKey; var value = nodes[i]; dic[key] = value; } return dic } function generateTmpNodes(oldNodes, newNodes) { var oldNodesDic = generateNodesDic(oldNodes); var newNodesDic = generateNodesDic(newNodes); tmpNodes = []; for (var i = 0, len = newNodes.length; i < len; i++) { var tmp = {}; for (var key in newNodes[i]) { tmp[key] = newNodes[i][key]; } tmpNodes.push(tmp); } var t = 0; for (var key in newNodesDic) { if (!oldNodesDic[key]) { var fatherKey = newNodesDic[key].father; var father = oldNodesDic[fatherKey]; tmpNodes[t].x = father.x; tmpNodes[t].y = father.y; } else { tmpNodes[t].x = oldNodesDic[key].x; tmpNodes[t].y = oldNodesDic[key].y; } t += 1; } } function generateTmpCurves(oldCurves, newCurves) { tmpCurves = []; for (var i = 0, len = newCurves.length; i < len; i++) { var tmp = {} for (var key in newCurves[i]) { tmp[key] = newCurves[i][key]; } tmpCurves.push(tmp); var id = newCurves[i].id; var existFlag = false; for (var j = 0, len1 = oldCurves.length; j < len1; j++) { if (oldCurves[j].id == id) { existFlag = true; tmp.points = oldCurves[j].points; tmp.opacity = 1; newCurves[i].opacity = 1; newCurves[i].delay = 0; newCurves[i].duration = duration; break; } } if (!existFlag) { tmp.opacity = 0; newCurves[i].opacity = 1; newCurves[i].delay = 3 / 4 * duration; newCurves[i].duration = 1 / 10 * duration; } } } function getRelation(d) { var nodes = d.node; var edges = d.edge; this.relation = {}; for (var i = 0; i < nodes.length; i++) { var id = nodes[i].id.toInt(); this.relation[id] = this.relationship.newrelation(); this.relation[id].nodeid = i; for (var j = 0; j < edges.length; j++) { //if(!edges[j].recovered){ if (edges[j].source == id || edges[j].target == id) { this.relation[id].edges.push(j); } //} //else{ // if(edges[j].routerClusters.indexOf(id)!=-1){ // this.relation[id].edges.push(j); // } //} } } } function typeofObj(obj) { return Object.prototype.toString.call(obj); } function cloneArray(fromObj, toObj) { for (var j = 0; j < fromObj.length; j++) { var type = typeofObj(fromObj[j]); if (type == "[object Object]") { toObj[j] = {}; cloneObj(fromObj[j], toObj[j]); } else if (type == "[object Array]") { toObj[j] = []; cloneArray(fromObj[j], toObj[j]) } else { toObj[j] = fromObj[j]; } } } function cloneObj(fromObj, toObj) { for (var i in fromObj) { if (!in_array(i, cloneIngoreList)) { if (typeofObj(fromObj[i]) == "[object Object]") { toObj[i] = {} cloneObj(fromObj[i], toObj[i]); } else if (typeofObj(fromObj[i]) == "[object Array]") { toObj[i] = []; cloneArray(fromObj[i], toObj[i]) } else { toObj[i] = fromObj[i]; } } } } function clone(fromObj, toObj) { if (typeofObj(fromObj) == "[object Object]")cloneObj(fromObj, toObj); else if (typeofObj(fromObj) == "[object Array]")cloneArray(fromObj, toObj); else toObj = fromObj; } function in_array(stringToSearch, arrayToSearch) { for (s = 0; s < arrayToSearch.length; s++) { thisEntry = arrayToSearch[s].toString(); if (thisEntry == stringToSearch) { return true; } } return false; } function dataPreProcess(d) { // if(method=='mst'){ // } this.calculateEdgeCitation(d); var newId = []; var json_nodes = []; var i = 0; this.maxSize = 0; for (var key in d.cluster) { var t = String(i); i += 1; newId[key] = t; if (key == '300') { this.title = d.cluster[key].title; var year = ''; for (var yearKey in d.cluster[key].nodeYearInfo) { year = yearKey; break } if(!d.cluster[key].summary) d.cluster[key].summary = ''; var author = d.cluster[key].summary.replace(/\]/g, ''); author = author.split('[')[0]; d.cluster[key].keywords = [author, year]; d.cluster[key].onegram = [author, year]; d.cluster[key].bigrams = [author, year]; } d.cluster[key].x = parseFloat(d.cluster[key].x); d.cluster[key].y = parseFloat(d.cluster[key].y); d.cluster[key].size = d.cluster[key].nodeidlist.length; if (d.cluster[key].size > this.maxSize)this.maxSize = d.cluster[key].size; d.cluster[key].id = t; d.cluster[key].oldKey = key; json_nodes[t] = d.cluster[key]; } this.sizeScale = new SizeScale(this.maxSize); for (var i = 0; i < d.edge.length; i++) { var source = parseInt(newId[d.edge[i].source]); d.edge[i].source = source; var target = parseInt(newId[d.edge[i].target]); d.edge[i].target = target; } //calculate #citation of edge return json_nodes; } function calculateEdgeCitation(data) { for (var i = 0; i < data['edge'].length; i++) { var edge = data['edge'][i]; var flow = edge.flow; var source = edge.source; var target = edge.target; var sourceNode = data['cluster'][source]; var sourceSize = sourceNode.nodeidlist.length; var targetNode = data['cluster'][target]; var targetSize = targetNode.nodeidlist.length; var citation = parseInt(flow * Math.sqrt(sourceSize * targetSize)); data['edge'][i].citation = citation; } } function initData(nodes, edges) { sortByCitations(nodes); getData(nodes, edges); getRelation(); coordinateOffset(); getCurves(); // splitLabels(nodes, edges); } function draw() { // drawAuthorInfo(); layout(optionNumber, false, false, data.postData[focusedID]); } function sortByCitations(data) { // console.log(data); for (var i = 1; i < data.length; i++) { data[i].nodes.sort(function (a, b) { return parseInt(b.citation_count) - parseInt(a.citation_count); }) } // console.log(data); } //function getRelation(d){ // var nodes=d.node; // var edges=d.edge; // for (var i=0;i<nodes.length;i++) // { // relation[i]=relationship.newrelation(); // relation[i].nodeid=i; // for (var j=0;j<edges.length;j++) // { // if(edges[j].source==i||edges[j].target==i) // { // relation[i].edges.push(j); // } // } // } //} function coordinate(sx, sy, tx, ty) { var d = distance(sx, sy, tx, ty); var mid_x = (sx + tx) / 2; var mid_y = (sy + ty) / 2; var x = mid_x - ((2 - Math.sqrt(3)) / 4) * d; var y = mid_y - ((2 * Math.sqrt(3) - 3) / 4) * d; return [x, y]; } function distance(x1, y1, x2, y2) { return Math.sqrt(Math.pow((y1 - y2), 2) + Math.pow((x1 - x2), 2)); } function coordinateOffset(d) { var nodes = d.node; var edges = d.edge; var screenPreviousData = {}; clone(d, screenPreviousData); this.data.screenPreviousData = {}; this.data.screenPreviousData[this.focusedID] = screenPreviousData; var sizeScale = this.sizeScale; var max_x, max_y, min_x, min_y; max_x = max_y = -100000; min_x = min_y = 100000; for (var i = 0; i < nodes.length; i++) { if (parseInt(nodes[i].x + sizeScale.sizeScale(nodes[i].size)) > max_x) { max_x = parseInt(nodes[i].x + sizeScale.sizeScale(nodes[i].size)); } if (parseInt(nodes[i].y + sizeScale.sizeScale(nodes[i].size) + 50) > max_y) { max_y = parseInt(nodes[i].y + sizeScale.sizeScale(nodes[i].size) + 50); } if (parseInt(nodes[i].x - sizeScale.sizeScale(nodes[i].size)) <= min_x) { min_x = parseInt(nodes[i].x - sizeScale.sizeScale(nodes[i].size)); } if (parseInt(nodes[i].y - sizeScale.sizeScale(nodes[i].size)) <= min_y) { min_y = parseInt(nodes[i].y - sizeScale.sizeScale(nodes[i].size)); } } var x_basic = (this.svg.attr("width") - this.size.width) / 2; var y_basic = (this.svg.attr("height") - this.size.height) / 2; var x_offset = x_basic - min_x; var y_offset = y_basic - min_y; var x_zoom = this.size.width / (max_x - min_x); var y_zoom = this.size.height / (max_y - min_y); for (var i = 0; i < nodes.length; i++) { nodes[i].x += x_offset; nodes[i].y += y_offset; } for (var i = 0; i < edges.length; i++) { for (var j = 0; j < edges[i].assists.length; j++) { // console.log(edges[i].assists[j]); // console.log(edges[i].assists[j][1]); edges[i].assists[j][0] = parseInt(edges[i].assists[j][0]); edges[i].assists[j][1] = parseInt(edges[i].assists[j][1]); edges[i].assists[j][0] += x_offset; edges[i].assists[j][1] += y_offset; } } for (var i = 0; i < nodes.length; i++) { nodes[i].x -= x_basic; nodes[i].y -= y_basic; nodes[i].x *= x_zoom; nodes[i].y *= y_zoom; nodes[i].x += x_basic; nodes[i].y += y_basic; } for (var i = 0; i < edges.length; i++) { for (var j = 0; j < edges[i].assists.length; j++) { edges[i].assists[j][0] -= x_basic; edges[i].assists[j][0] *= x_zoom; edges[i].assists[j][0] += x_basic; edges[i].assists[j][1] -= y_basic; edges[i].assists[j][1] *= y_zoom; edges[i].assists[j][1] += y_basic; } } d.node = nodes; d.edge = edges; } function findCircleEdges(d) { var nodes = d.node; var edges = d.edge; var edgeSourceTargetDic = getEdgeSourceTargetDic(edges); var nodeDic = getNodeDic(nodes); for (var i = 0, len = edges.length; i < len; i++) { var source = edges[i].source; var target = edges[i].target; if (edgeSourceTargetDic[target])if (edgeSourceTargetDic[target][source]) { var edge1 = edges[i]; var edge2 = edgeSourceTargetDic[target][source]; var p1 = {x: nodeDic[nodes[source].oldKey].x, y: nodeDic[nodes[source].oldKey].y}; var p2 = {x: nodeDic[nodes[target].oldKey].x, y: nodeDic[nodes[target].oldKey].y}; var p3 = {x: nodeDic[nodes[source].oldKey].x, y: nodeDic[nodes[source].oldKey].y}; var p4 = {x: nodeDic[nodes[target].oldKey].x, y: nodeDic[nodes[target].oldKey].y}; var e1 = {p1: p1, p2: p2}; var e2 = {p1: p3, p2: p4}; var newEdge = moveCircleEdge(e1, e2); edges[i].dx = e1.dx; edges[i].dy = e1.dy; edgeSourceTargetDic[target][source].dx = e2.dx; edgeSourceTargetDic[target][source].dy = e2.dy; } } } function getCurves(d) { var nodes = d.node; var edges = d.edge; for (var i = 0; i < edges.length; i++) { var dx = 0; var dy = 0; if (edges[i].dx)dx = edges[i].dx; if (edges[i].dy)dy = edges[i].dy; var source_x = parseInt(nodes[edges[i].source].x) + dx; var source_y = parseInt(nodes[edges[i].source].y) + dy; var target_x = parseInt(nodes[edges[i].target].x) + dx; var target_y = parseInt(nodes[edges[i].target].y) + dy; var source_size = parseInt(nodes[edges[i].source].size); var target_size = parseInt(nodes[edges[i].target].size); var source_label = nodes[edges[i].source].label; var target_label = nodes[edges[i].target].label; var flow = edges[i].flow; var edgeType = edges[i].edgeType; var citation = edges[i].citation; var weight = edges[i].weight; var id = edges[i].id; var ratio = edges[i].ratio; var delay = edges[i].delay; var duration = edges[i].duration; var assist = coordinate(source_x, source_y, target_x, target_y); var year = edges[i].year; var structureType; var routerClusters = edges[i].routerClusters; if (edges[i].TreeEdge)structureType = 'treeEdge'; else if (edges[i].isNontreeEdge)structureType = 'nontreeEdge'; else structureType = 'originEdge'; edges[i] = { source: edges[i].source, target: edges[i].target, points: [], nodes: [edges[i].source, edges[i].target], flow: flow, weight: weight, id: id, citation: citation, dx: dx, dy: dy, assists: edges[i].assists, edgeType: edgeType, delay: delay, duration: duration, ratio: ratio, year: year, structureType: structureType, routerClusters: routerClusters, pathNodeDic: edges[i].pathNodeDic, pathNodeList: edges[i].pathNodeList, shift: edges[i].shift, recovered: edges[i].recovered, longPathNodes: edges[i].longPathNodes, flowStrokeWidth: edges[i].flowStrokeWidth, citationStrokeWidth: edges[i].citationStrokeWidth, uniformStrokeWidth: edges[i].uniformStrokeWidth, isBackgroundEdge: edges[i].isBackgroundEdge, isForegroundEdge: edges[i].isForegroundEdge, isForegroundSourceEdge: edges[i].isForegroundSourceEdge, isForegroundTargetEdge: edges[i].isForegroundTargetEdge, isNontreeEdge: edges[i].isNontreeEdge, merged: edges[i].merged, shiftDic: edges[i].shiftDic, nodeShiftDic: edges[i].nodeShiftDic, fatherNode: edges[i].fatherNode, isFaker: edges[i].isFaker, yearRatioDic: edges[i].yearRatioDic, yearSet: edges[i].yearSet, transitionCount: 0, flipBookStartYear: edges[i].flipBookStartYear, flipBookEndYear: edges[i].flipBookEndYear, flipBookRatio: edges[i].flipBookRatio }; var source_text, target_text; edges[i].points.push({x: source_x, y: source_y, size: source_size, text: source_label, id: edges[i].source}); if (drawFlowMap) { for (var j = 0; j < edges[i].assists.length; j++) { edges[i].points.push({x: edges[i].assists[j][0], y: edges[i].assists[j][1], size: 1, text: "", id: -1}); } } edges[i].points.push({x: target_x, y: target_y, size: target_size, text: target_label, id: edges[i].target}); } } function calculateAssistPoint(x1, y1, x2, y2, x3, y3) { var x0, y0;//p1p2中点 var k1, b1;//p1p2直线的斜率与常数项 var k2, b2;// 过p1p2直线中点垂线的斜率与常数项 var a0, b0, c0;//圆与直线相交的二次方程系数 var d;//所需距离 var x4, y4, x5, y5;//解出来的两个点坐标,分列直线左右两侧 var pi = Math.PI; var angle = pi / 6;//角度 var delta;//判别式 x0 = (x1 + x2) / 2; y0 = (y1 + y2) / 2; k1 = (y2 - y1) / (x2 - x1); b1 = y1 - k1 * x1; k2 = (x1 - x2) / (y2 - y1); b2 = (y1 + y2) / 2 + ((x2 - x1) * (x2 + x1)) / (2 * (y2 - y1)); d = Math.tan(angle) * Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) / 2; a0 = 1 + k2 * k2; b0 = 2 * k2 * (b2 - y0) - 2 * x0; c0 = x0 * x0 + (b2 - y0) * (b2 - y0) - d * d; delta = Math.sqrt(b0 * b0 - 4 * a0 * c0); x4 = (-b0 + delta) / (2 * a0); y4 = k2 * x4 + b2; x5 = (-b0 - delta) / (2 * a0); y5 = k2 * x5 + b2; var value3, value4, value5;//判断左右 value3 = k1 * x3 + b1 - y3; value4 = k1 * x4 + b1 - y4; value5 = k1 * x5 + b1 - y5; var right, left; right = left = {}; var p = {}//所需结果 if (value4 > value5) { right.x = x4; right.y = y4; left.x = x5; left.y = y5; } else { left.x = x4; left.y = y4; right.x = x5; right.y = y5; } if (value3 > 0) { return right; //p3点在直线右侧 } else if (value3 < 0) { return left; //p3点在直线左侧 } else { if (k1 >= 0) { return left; } else { return right; } } } function ajax(url,success,data) { console.log(url); console.log(data); $.ajax({ url: url, data: data, async: false, success: success }) } function requestData(){ ids=[]; var layers=[]; if('left' in sourceCheckedStatus)layers.push(leftLayer); if('right' in sourceCheckedStatus)layers.push(rightLayer); layers.forEach(function(layer){ var source=layer.source; var clusterCount=layer.clusterCount; layer.focusedID=source+'_'+clusterCount; //if(!(layer.focusedID in layer.data.sourceData)){ if(source in dataID&&layer.ifLayout){ ids.push({ id:dataID[source], source:source, layer:layer, clusterCount:clusterCount }) } //} }); search(ids); } function search(ids){ var requests=[]; ids.forEach(function(item){ var id=item.layer.focusedID; var data=item.layer.data; if(!(id in data.sourceData)||!data.sourceData[id]){ requests.push(item); } }); if(requests.length==0){ //data all exist, call layout function ids.forEach(function(item){ if(item.layer.ifLayout) { var source = item.source; var tmpData = {}; clone(item.layer.data.sourceData[item.layer.focusedID], tmpData); item.layer.processData(tmpData); if (item.layer.focusedID && item.layer.preFocusedID) { item.layer.layout(optionNumber, true, 'incremental', item.layer.data.postData[item.layer.focusedID]); } else { item.layer.preLayout(item.layer.data.postData[item.layer.focusedID]); } } }); } else{ var url='http://'+server+':'+port+'/InfluenceGraph'; var reqData=[]; requests.forEach(function(item){ reqData.push({ source:item.source, id:item.id, clusterCount:item.clusterCount }); item.layer.focusedID=item.source+'_'+item.clusterCount; }); var success=function(d){ if(d['error']){ var newUrl='http://'+server+':'+errorPort+'/error'; var errorData={ errorCode:1, source:source, errorID:searchID }; var success=function(){ alert('The influence graph is computing in the backend'); }; ajax(newUrl,success,errorData); } else{ console.log(d); function clearCiteseerx(graph){ var clusters=graph.cluster; var edges=graph.edge; var newClusters={}; var newEdges=[]; var yearList=[]; var cluster300IDList=clusters['300'].nodeidlist; var mYear=1980; for(var y in cluster300IDList){ if(y&&parseInt(y)>mYear)mYear=parseInt(y); } for(var key in clusters){ var idYearDic=clusters[key].nodeidlist; var newDic={}; for(var year in idYearDic){ if(year&&parseInt(year)>=mYear){ yearList.push(parseInt(year)); newDic[year]=idYearDic[year]; } } var flag=false; for(var k in newDic){ flag=true; break; } if(flag){ newClusters[key]=clusters[key]; newClusters[key].nodeidlist=newDic; } else{ console.log('cluster '+key+' year is error'); } } //console.log(yearList) if(!('300' in newClusters)){ var cluster300=clusters[300]; var minYear=d3.min(yearList); var id=cluster300.nodeidlist[''][0]; var yearKey=String(minYear-1); cluster300.nodeidlist={}; cluster300.nodeidlist[yearKey]=[id]; newClusters['300']=cluster300; } edges.forEach(function(edge){ var source=edge.source; var target=edge.target; if((source in newClusters)&&(target in newClusters)){ newEdges.push(edge); } }); //fix year data //citeseerx year should <=2014 for(var clusterID in graph.cluster){ var newIDList={}; for(var year in graph.cluster[clusterID].nodeidlist){ if(parseInt(year)>2014){ //console.log(year); if(!('2014' in newIDList))newIDList[String(2014)]=[]; newIDList[String(2014)]=newIDList[String(2014)].concat(graph.cluster[clusterID].nodeidlist[year]); } else{ newIDList[year]=graph.cluster[clusterID].nodeidlist[year]; } } graph.cluster[clusterID].nodeidlist=newIDList; } graph.edge.forEach(function(edge){ var newWeight={}; for(var key in edge.weight){ var sourceYear=key.split('_')[0]; var targetYear=key.split('_')[1]; if(parseInt(sourceYear)>=2014)sourceYear=2014; if(parseInt(targetYear)>=2014)targetYear=2014; var newKey=sourceYear+'_'+targetYear; if(!(newKey in newWeight))newWeight[newKey]=0; newWeight[newKey]+=edge.weight[key]; } edge.weight=newWeight; }); graph.cluster=newClusters; graph.edge=newEdges; } function addFrequencyKeywords(graph){ var clusters=graph.cluster; for(var key in clusters){ if(!('frequencyKeywords' in clusters[key])){ clusters[key].frequencyKeywords=['none','none','none']; } } } //console.log(d.citeseerx); for(var key in d){ if(key.split('_')[0]=='citeseerx'){ clearCiteseerx(d[key]); } addFrequencyKeywords(d[key]); } //if(d.citeseerx){ // clearCiteseerx(d.citeseerx); // //} //console.log(d.citeseerx); ids.forEach(function(item,i){ //if(i==1)return; var source=item.source; if(source=='aminerV8')item.layer.sourceText='AMiner'; else if(source=='citeseerx')item.layer.sourceText='CiteseerX'; var tmpData={}; item.layer.source=item.source; var focused=item.source+'_'+item.clusterCount; item.layer.focusedID=focused; var data=item.layer.data; if(data.sourceData[focused]){ clone(data.sourceData[focused],tmpData); } else{ clone(d[source+'_'+item.clusterCount],tmpData); item.layer.data.sourceData[item.layer.focusedID]= d[source+'_'+item.clusterCount]; } if(item.layer.ifLayout){ item.layer.processData(tmpData); if(item.layer.focusedID&&item.layer.preFocusedID){ item.layer.layout(optionNumber,true, 'incremental',item.layer.data.postData[item.layer.focusedID]); } else{ item.layer.preLayout(item.layer.data.postData[item.layer.focusedID]); } } }); } }; ajax(url,success,{data:reqData}); } } function FSubmit(e){ if(e ==13){ search(); } } function getUrlParam(name){ var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r!=null) return unescape(r[2]); return null; //返回参数值 } function ajax(url, success, data) { console.log(url); console.log(data); $.ajax({ url: url, data: data, async: false, success: success }) } function requestData() { var twitterClusterCount = getUrlParam('twitter'); if (twitterClusterCount) { d3.json('localData/twitter'+twitterClusterCount+'.json', function (data) { console.log(data); var nodeCount = 0; var edgeCount = 0; var flowCount = 0; var selfEdgeCount = 0; var selfFlowCount = 0; for (var key in data.cluster) { for (var year in data.cluster[key].nodeYearInfo) { nodeCount += +data.cluster[key].nodeYearInfo[year]; } } data.edge.forEach(function (edge) { flowCount += edge.flow; for (var k in edge.weight) { edgeCount += edge.weight[k]; } if (edge.source === edge.target) { selfFlowCount += edge.flow; for (var k in edge.weight) { selfEdgeCount += edge.weight[k]; } } }); data.clusterIDList = [5,10,20]; for (var key in data.cluster) { var nodeYearInfo = data.cluster[key].nodeYearInfo; var nodeidlist = {}; for (var year in nodeYearInfo) { nodeidlist[year] = new Array(parseInt(nodeYearInfo[year])); } data.cluster[key].nodeidlist = nodeidlist; data.cluster[key].keywords = ['','','']; data.cluster[key].bigrams = ['','','']; data.cluster[key].onegram = ['','','']; } var k ='twitter_'+twitterClusterCount; var d={}; d[k] = data; ids = [{ source: 'twitter', layer: leftLayer, clusterCount: twitterClusterCount }]; ids.forEach(function (item, i) { //if(i==1)return; var source = item.source; var tmpData = {}; item.layer.source = item.source; var focused = item.source + '_' + item.clusterCount; item.layer.focusedID = focused; var data = item.layer.data; if (data.sourceData[focused]) { clone(data.sourceData[focused], tmpData); } else { var newCluster = {}; for (var key in d[source + '_' + item.clusterCount]['cluster']) { var node = new Node(d[source + '_' + item.clusterCount]['cluster'][key]); newCluster[key] = node; } d[source + '_' + item.clusterCount]['cluster'] = newCluster; clone(d[source + '_' + item.clusterCount], tmpData); item.layer.data.sourceData[item.layer.focusedID] = d[source + '_' + item.clusterCount]; } if (item.layer.ifLayout) { item.layer.processData(tmpData); if (item.layer.focusedID && item.layer.preFocusedID) { item.layer.layout(optionNumber, true, 'incremental', item.layer.data.postData[item.layer.focusedID]); } else { item.layer.preLayout(item.layer.data.postData[item.layer.focusedID]); } } }); }) } else { ids = []; var layers = []; if ('left' in sourceCheckedStatus)layers.push(leftLayer); if ('right' in sourceCheckedStatus)layers.push(rightLayer); layers.forEach(function (layer) { var source = layer.source; var clusterCount = layer.clusterCount; layer.focusedID = source + '_' + clusterCount; //if(!(layer.focusedID in layer.data.sourceData)){ if (source in dataID && layer.ifLayout) { ids.push({ id: dataID[source], source: source, layer: layer, clusterCount: clusterCount }) } }); search(ids); } } function search(ids) { var requests = []; ids.forEach(function (item) { var id = item.layer.focusedID; var data = item.layer.data; if (!(id in data.sourceData) || !data.sourceData[id]) { requests.push(item); } }); if (requests.length == 0) { //data all exist, call layout function ids.forEach(function (item) { if (item.layer.ifLayout) { var source = item.source; var tmpData = {}; clone(item.layer.data.sourceData[item.layer.focusedID], tmpData); item.layer.processData(tmpData); if (item.layer.focusedID && item.layer.preFocusedID) { item.layer.layout(optionNumber, true, 'incremental', item.layer.data.postData[item.layer.focusedID]); } else { item.layer.preLayout(item.layer.data.postData[item.layer.focusedID]); } } }); } else { var url = 'http://' + server + ':' + port + '/InfluenceGraph'; var reqData = []; requests.forEach(function (item) { reqData.push({ source: item.source, id: item.id, clusterCount: item.clusterCount }); item.layer.focusedID = item.source + '_' + item.clusterCount; }); var success = function (d) { if (d['error']) { var newUrl = 'http://' + server + ':' + errorPort + '/error'; var errorData = { errorCode: 1, source: source, errorID: searchID }; var success = function () { alert('The influence graph is computing in the backend'); }; ajax(newUrl, success, errorData); } else { console.log(d); function clearCiteseerx(graph) { var clusters = graph.cluster; var edges = graph.edge; var newClusters = {}; var newEdges = []; var yearList = []; var cluster300IDList = clusters['300'].nodeidlist; var mYear = 1980; for (var y in cluster300IDList) { if (y && parseInt(y) > mYear)mYear = parseInt(y); } for (var key in clusters) { var idYearDic = clusters[key].nodeidlist; var newDic = {}; for (var year in idYearDic) { if (year && parseInt(year) >= mYear) { yearList.push(parseInt(year)); newDic[year] = idYearDic[year]; } } var flag = false; for (var k in newDic) { flag = true; break; } if (flag) { newClusters[key] = clusters[key]; newClusters[key].nodeidlist = newDic; } else { console.log('cluster ' + key + ' year is error'); } } //console.log(yearList) if (!('300' in newClusters)) { var cluster300 = clusters[300]; var minYear = d3.min(yearList); var id = cluster300.nodeidlist[''][0]; var yearKey = String(minYear - 1); cluster300.nodeidlist = {}; cluster300.nodeidlist[yearKey] = [id]; newClusters['300'] = cluster300; } edges.forEach(function (edge) { var source = edge.source; var target = edge.target; if ((source in newClusters) && (target in newClusters)) { newEdges.push(edge); } }); //fix year data //citeseerx year should <=2014 for (var clusterID in graph.cluster) { var newIDList = {}; for (var year in graph.cluster[clusterID].nodeidlist) { if (parseInt(year) > 2014) { //console.log(year); if (!('2014' in newIDList))newIDList[String(2014)] = []; newIDList[String(2014)] = newIDList[String(2014)].concat(graph.cluster[clusterID].nodeidlist[year]); } else { newIDList[year] = graph.cluster[clusterID].nodeidlist[year]; } } graph.cluster[clusterID].nodeidlist = newIDList; } graph.edge.forEach(function (edge) { var newWeight = {}; for (var key in edge.weight) { var sourceYear = key.split('_')[0]; var targetYear = key.split('_')[1]; if (parseInt(sourceYear) >= 2014)sourceYear = 2014; if (parseInt(targetYear) >= 2014)targetYear = 2014; var newKey = sourceYear + '_' + targetYear; if (!(newKey in newWeight))newWeight[newKey] = 0; newWeight[newKey] += edge.weight[key]; } edge.weight = newWeight; }); graph.cluster = newClusters; graph.edge = newEdges; } function addFrequencyKeywords(graph) { var clusters = graph.cluster; for (var key in clusters) { if (!('frequencyKeywords' in clusters[key])) { clusters[key].frequencyKeywords = ['none', 'none', 'none']; } } } //console.log(d.citeseerx); for (var key in d) { var db = key.split('_')[0]; var count = key.split('_')[1]; if (db == 'citeseerx') { clearCiteseerx(d[key]); } addFrequencyKeywords(d[key]); } var clusterCount=leftLayer.clusterCount; var key = 'aminerV8_'+clusterCount; if (d[key]) { var sum = 0; for (var clusterId in d[key].cluster) { var cluster = d[key].cluster[clusterId]; for (var year in cluster.nodeidlist) { sum += cluster.nodeidlist[year].length; } } if(sum<500&&isFirstRequest){ console.log('hi'); isFirstRequest=false; if(clusterCount=='20'){ leftLayer.clusterCount=10; rightLayer.clusterCount=10; d3.selectAll('.dbOption') .each(function (d) { d3.select(this) .select('cite') .html(d.name+'-'+ d.layer.clusterCount); }); requestData(); } else{ ids.forEach(function (item, i) { //if(i==1)return; var source = item.source; if (source == 'aminerV8')item.layer.sourceText = 'AMiner'; else if (source == 'citeseerx')item.layer.sourceText = 'CiteseerX'; var tmpData = {}; item.layer.source = item.source; var focused = item.source + '_' + item.clusterCount; item.layer.focusedID = focused; var data = item.layer.data; if (data.sourceData[focused]) { clone(data.sourceData[focused], tmpData); } else { var newCluster = {}; for (var key in d[source + '_' + item.clusterCount]['cluster']) { var node = new Node(d[source + '_' + item.clusterCount]['cluster'][key]); newCluster[key] = node; } d[source + '_' + item.clusterCount]['cluster'] = newCluster; clone(d[source + '_' + item.clusterCount], tmpData); item.layer.data.sourceData[item.layer.focusedID] = d[source + '_' + item.clusterCount]; } if (item.layer.ifLayout) { item.layer.processData(tmpData); if (item.layer.focusedID && item.layer.preFocusedID) { item.layer.layout(optionNumber, true, 'incremental', item.layer.data.postData[item.layer.focusedID]); } else { item.layer.preLayout(item.layer.data.postData[item.layer.focusedID]); } } }); } } else{ ids.forEach(function (item, i) { //if(i==1)return; var source = item.source; if (source == 'aminerV8')item.layer.sourceText = 'AMiner'; else if (source == 'citeseerx')item.layer.sourceText = 'CiteseerX'; var tmpData = {}; item.layer.source = item.source; var focused = item.source + '_' + item.clusterCount; item.layer.focusedID = focused; var data = item.layer.data; if (data.sourceData[focused]) { clone(data.sourceData[focused], tmpData); } else { var newCluster = {}; for (var key in d[source + '_' + item.clusterCount]['cluster']) { var node = new Node(d[source + '_' + item.clusterCount]['cluster'][key]); newCluster[key] = node; } d[source + '_' + item.clusterCount]['cluster'] = newCluster; clone(d[source + '_' + item.clusterCount], tmpData); item.layer.data.sourceData[item.layer.focusedID] = d[source + '_' + item.clusterCount]; } if (item.layer.ifLayout) { item.layer.processData(tmpData); if (item.layer.focusedID && item.layer.preFocusedID) { item.layer.layout(optionNumber, true, 'incremental', item.layer.data.postData[item.layer.focusedID]); } else { item.layer.preLayout(item.layer.data.postData[item.layer.focusedID]); } } }); } } } }; ajax(url, success, {data: reqData}); } } function FSubmit(e) { if (e == 13) { search(); } } function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象 var r = window.location.search.substr(1).match(reg); //匹配目标参数 if (r != null) return unescape(r[2]); return null; //返回参数值 } function Temporal(data){ this.temporalDic=data; this.temporalList=[]; this.division={}; this.init=function(){ for(var year in this.temporalDic){ var tmp={ year:year, flow:this.temporalDic[year] }; this.temporalList.push(tmp) } this.division[1]=[this.temporalList] }; this.divideYear=function(num){ if(this.division[num]){ return this.division[num]; } else{ var preDivision=this.divideYear(num-1); var newDivision=this.cut(preDivision); this.division[num]=newDivision; return newDivision; } }; this.cut=function(divsion){ var newDivisionList=[]; for(var i=0;i<divsion.length;i++){ var currentPart=divsion[i]; var otherParts=[]; for(var j=0;j<divsion.length;j++){ if(j!=i)otherParts.push(divsion[j]); } var len=currentPart.length; if(len>=4){ for(var j=2;j<len-1;j++){ var part1=[]; var part2=[]; for(var k=0;k<j;k++){ part1.push(currentPart[k]); } for(var k=j;k<len;k++){ part2.push(currentPart[k]); } part1 = this.denseFlow(part1); part2 = this.denseFlow(part2); if(part1.length>1&&part2.length>1){ var newDivision=[]; newDivision.push(part1); newDivision.push(part2); for(var k=0;k<otherParts.length;k++){ newDivision.push(otherParts[k]); } newDivisionList.push(newDivision) } } } } var maxFlow=0; var maxDivision; if(newDivisionList.length>0){ for(var i=0;i<newDivisionList.length;i++){ var division=newDivisionList[i]; var divisionFlow=this.countDivisionFlow(division); if(divisionFlow>maxFlow){ maxDivision=division; maxFlow=divisionFlow; } } return division; } else{ return []; } }; this.sortDivision=function(division){ division.sort(function(a,b){return d3.ascending(a[0].year, b[0].year)}); }; this.countDivisionFlow=function(division){ var sum=0; for(var i=0;i<division.length;i++){ var part=division[i]; var partFlow=this.countPartFlow(part); sum+=partFlow; } division.smoothFlowCount=sum; return sum; }; this.countPartFlow=function(part){ var sum=0; for(var i=0;i<part.length;i++){ sum+=part[i].flow; } sum = this.smoothFlow(sum, part.length); return sum; }; this.denseFlow=function(part){ while(part[0]&&part[0].flow==0){ part = part.slice(1,part.length); } while(part[part.length-1]&&part[part.length-1].flow==0){ part = part.slice(0,part.length-1); } return part; }; this.smoothFlow=function(flow,duration){ var k=0.5; return flow/Math.pow(duration,k) }; this.selectMaxDivision=function(){ var max=0; var maxDivision; for(var key in this.division){ if(key!=1){ if(this.division[key].smoothFlowCount){ if(this.division[key].smoothFlowCount>max){ max = this.division[key].smoothFlowCount; maxDivision=this.division[key]; } } } } this.maxDivision=maxDivision; } } function temporalSummarization(d){ var temporalData=this.getTemporalData(d); this.temporal=new Temporal(temporalData); this.temporal.init(); this.temporal.divideYear(12); this.temporal.selectMaxDivision(); } function getTemporalData(d){ var edges=d.edge; var temporal={}; for(var year=this.minYear;year<=this.maxYear;year++){ temporal[year]=0; } var edgeSumFlow=0 var temporFlow=0; for(var i=0;i<edges.length;i++){ var edge=edges[i]; var flow=edge.flow; edgeSumFlow+=flow; var weight=edge.weight; var totalCitation=edge.citation; for(var year in weight){ var subFlow=(weight[year]/totalCitation)*flow; temporal[year.toInt()]+=subFlow; } } for(var year in temporal){ temporFlow+=temporal[year]; } // console.log(temporFlow,edgeSumFlow); // console.log(temporal); return temporal } var str='M41.08164179104483,302.4C43.678231395542014,307.7846857291704,46.27482100003919,313.1693714583408,48.87141060453637,313.1693714583408C49.20474393786971,313.1693714583408,49.538077271203036,313.1693714583408,49.87141060453637,313.1693714583408C58.23100768625882,313.1693714583408,66.59060476798126,337.43976747453956,74.95020184970372,349.2233541666991C83.02517284222147,360.6057353744069,91.1001438347392,382.71434634472195,99.17511482725695,382.71434634472195C99.50844816059028,382.71434634472195,99.84178149392362,382.71434634472195,100.17511482725695,382.71434634472195C109.27542867925101,382.71434634472195,118.37574253124507,342.360373892397,127.47605638323913,340.5042414171221C144.98467456108426,336.9331211980139,162.4932927389294,337.07257695634183,180.00191091677453,335.14756108845984C197.51052909461967,333.22254522057784,215.01914727246478,330.8198318600074,232.52776545030991,328.95414620983C253.8895177126435,326.67787778854984,275.2512699749771,325.0115953216645,296.6130222373107,323.0130629844527C303.86170497201624,322.3349010682581,311.1103877067217,320.97230025533116,318.35907044142726,320.97230025533116C318.6924037747606,320.97230025533116,319.02573710809395,320.97230025533116,319.35907044142726,320.97230025533116C365.7941962146828,320.97230025533116,412.2293219879384,259.4534228549383,458.66444776119397,197.93454545454546'; var reg=new RegExp('127.47605638323913,343.2110302810014(.*)296.6130222373107,325.172287336565') console.log(reg.exec(str)) function layoutPapers(d){ //pingbi chongfu lunwen if(d.id!=2253750){ //console.log(d3.select(this)); var textColor='rgb(223,209,32)'; var abstractColor='rgb(221, 226, 164)'; var title=d3.select(this).append('div'); title .append('text') .styles({ cursor:'pointer', color:'white', 'font-size':18+px, 'font-family':'Microsoft YaHei' }) .on('mouseover',function(d){ d3.select(this) .styles({ 'text-decoration':'underline' }) }) .on('mouseout',function(d){ d3.select(this) .styles({ 'text-decoration':'' }) }) .on('click',function(d){ var url='graph.html?'; var sourceStr=''; d.ids.forEach(function(item){ var source=item.source; sourceStr+=source+'_'; url+=source+'_id='+item.id+'&'; }); var source='aminerV8'; //url+=source+'_id='+ d.id+'&'; url+='selected='+source; url+='&source='+sourceStr; url+='&r='+Math.floor(Math.random()*1000000000+1); window.open(url); }) .html(d.title); if(d.graphSize){ var graphSizeDatas=[ {text:' [',color:'white'}, {text: d.graphSize,color:'white'}, {text:' papers influenced',color:textColor}, {text:']<br>',color:'white'} ]; title .selectAll('whatever') .data(graphSizeDatas) .enter() .append('text') .styles({ color:function(d){return d.color}, 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .each(function(e,i){ if(i==1){ d3.select(this) .styles({ color:'white', cursor:'pointer' }) .on('mouseover',function(e){ d3.select(this) .styles({ 'text-decoration':'underline' }) }) .on('mouseout',function(e){ d3.select(this) .styles({ 'text-decoration':'' }) }) .on('click',function(e){ var url='citation.html?id='+ d.id+'&action=all&'+'source=aminerV8'+'&title='+ d.title+'&r='+Math.floor(Math.random()*1000000000+1); window.open(url); }) } }) .html(function(e){ return e.text; }); } var summary=d3.select(this).append('div'); summary .append('text') .styles({ color:textColor, 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .html(d.authors+' - '+d.year+' - '); summary .append('text') .styles({ color:textColor, 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .html(d.venue+'<br>') .each(function(){ if(d.venueID){ d3.select(this) .styles({ color:'white', cursor:'pointer' }) .on('mouseover',function(){ d3.select(this) .styles({ 'text-decoration':'underline' }) }) .on('mouseout',function(){ d3.select(this) .styles({ 'text-decoration':'' }) }) .on('click',function(){ var url='venuepapers.html?venue='+d.venue+'&id='+d.venueID+'&r='+Math.floor(Math.random()*1000000000+1); window.open(url); }) } }); if(d.abstract){ var abstract=d3.select(this).append('div') .styles({ height:55+px, 'overflow-y':'hidden' }); abstract.append('text') .styles({ color:abstractColor, 'font-size':10+px, 'font-family':'Microsoft YaHei', }) .html(d.abstract); } var citation=d3.select(this).append('div'); citation .append('text') .styles({ color:textColor, 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .html('Citing '); citation .append('text') .styles({ cursor:'pointer', color:'white', 'font-size':14+px, 'font-family':'Microsoft YaHei', }) .on('mouseover',function(d){ d3.select(this) .styles({ 'text-decoration':'underline' }) }) .on('mouseout',function(d){ d3.select(this) .styles({ 'text-decoration':'' }) }) .on('click',function(d){ var url='citation.html?'; var source='aminerV8'; url+='id='+ d.id+'&'; url+='source='+source; url+='&title='+ d.title; url+='&action=t'; url+='&r='+Math.floor(Math.random()*1000000000+1); window.open(url); }) .html(d.citing); citation .append('text') .styles({ color:textColor, 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .html(' papers'); citation .append('text') .styles({ color:textColor, 'font-size':14+px, 'font-family':'Microsoft YaHei', 'margin-left':50+px }) .html('Cited by '); citation .append('text') .styles({ cursor:'pointer', color:'white', 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .on('mouseover',function(d){ d3.select(this) .styles({ 'text-decoration':'underline' }) }) .on('mouseout',function(d){ d3.select(this) .styles({ 'text-decoration':'' }) }) .on('click',function(d){ var url='citation.html?'; var source='aminerV8'; url+='id='+ d.id+'&'; url+='source='+source; url+='&title='+ d.title; url+='&action=s'; url+='&r='+Math.floor(Math.random()*1000000000+1); window.open(url); }) .html(d.citation); citation .append('text') .styles({ color:textColor, 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .html(' papers'); citation .append('text') .styles({ color:textColor, 'font-size':14+px, 'font-family':'Microsoft YaHei', 'margin-left':50+px }) .html('Source: '); citation .selectAll('whatever') .data(d.ids) .enter() .append('text') .styles({ cursor:'pointer', color:'white', 'font-size':14+px, 'font-family':'Microsoft YaHei' }) .html(function(e,i){ if(i==0)return 'AMiner'; else return ', CiteseerX'; }) .on('mouseover',function(d){ d3.select(this) .styles({ 'text-decoration':'underline' }) }) .on('mouseout',function(d){ d3.select(this) .styles({ 'text-decoration':'' }) }) .on('click',function(e,i){ var url='graph.html?'; d.ids.forEach(function(item){ var source=item.source; url+=source+'_id='+item.id+'&'; }); var source= e.source; //url+=source+'_id='+ e.id+'&'; url+='selected='+source; url+='&r='+Math.floor(Math.random()*1000000000+1); window.open(url); }); } } function layoutSetting(){ drawFlowMap=true; } function initServer(){ SDCloud='211.147.15.14'; server40='192.168.1.40'; localServer='127.0.0.1'; server42='192.168.1.42'; ali='118.190.210.193'; server=ali; port='5002'; errorPort='5003'; }
36.664078
1,362
0.455844
8d52d7f7f2035f81d46b05cbdee67feb245209dd
273
js
JavaScript
src/helpers/Authenticate.js
Duncanian/meetup-api
654ed70b45b0504d10dea4ed95db58bd68c96142
[ "MIT" ]
null
null
null
src/helpers/Authenticate.js
Duncanian/meetup-api
654ed70b45b0504d10dea4ed95db58bd68c96142
[ "MIT" ]
null
null
null
src/helpers/Authenticate.js
Duncanian/meetup-api
654ed70b45b0504d10dea4ed95db58bd68c96142
[ "MIT" ]
null
null
null
import jwt from 'jsonwebtoken'; import dotenv from 'dotenv'; dotenv.config(); class Utils { static generateToken(payload) { const token = jwt.sign(payload, process.env.JWT_PUBLIC_KEY, { expiresIn: 60 * 60 * 24 * 7 }); return token; } } export default Utils;
19.5
97
0.688645
8d52e5b325696ede73b354ae525a477477682d0d
2,846
js
JavaScript
components/randomizer/index.js
wvbraun/aframe-visualizer-test
0e87bf2aba4c830efd9e5a5c0305b3b84839241f
[ "MIT" ]
670
2016-09-18T06:36:42.000Z
2018-11-27T09:42:27.000Z
components/randomizer/index.js
wvbraun/aframe-visualizer-test
0e87bf2aba4c830efd9e5a5c0305b3b84839241f
[ "MIT" ]
175
2016-09-28T14:45:40.000Z
2018-12-01T10:53:29.000Z
components/randomizer/index.js
wvbraun/aframe-visualizer-test
0e87bf2aba4c830efd9e5a5c0305b3b84839241f
[ "MIT" ]
304
2016-09-15T21:25:40.000Z
2018-11-28T17:04:49.000Z
if (typeof AFRAME === 'undefined') { throw new Error('Component attempted to register before AFRAME was available.'); } /** * Set random color within bounds. */ AFRAME.registerComponent('random-color', { schema: { min: {default: {x: 0, y: 0, z: 0}, type: 'vec3'}, max: {default: {x: 1, y: 1, z: 1}, type: 'vec3'} }, update: function () { var data = this.data; var max = data.max; var min = data.min; this.el.setAttribute('material', 'color', '#' + new THREE.Color( Math.random() * max.x + min.x, Math.random() * max.y + min.y, Math.random() * max.z + min.z ).getHexString()); } }); /** * Set random position within bounds. */ AFRAME.registerComponent('random-position', { schema: { min: {default: {x: -10, y: -10, z: -10}, type: 'vec3'}, max: {default: {x: 10, y: 10, z: 10}, type: 'vec3'} }, update: function () { var data = this.data; var max = data.max; var min = data.min; this.el.setAttribute('position', { x: Math.random() * (max.x - min.x) + min.x, y: Math.random() * (max.y - min.y) + min.y, z: Math.random() * (max.z - min.z) + min.z }); } }); /** * Set random position within spherical bounds. */ AFRAME.registerComponent('random-spherical-position', { schema: { radius: {default: 10}, startX: {default: 0}, lengthX: {default: 360}, startY: {default: 0}, lengthY: {default: 360} }, update: function () { var data = this.data; var xAngle = THREE.Math.degToRad(Math.random() * data.lengthX + data.startX); var yAngle = THREE.Math.degToRad(Math.random() * data.lengthY + data.startY); this.el.setAttribute('position', { x: data.radius * Math.cos(xAngle) * Math.sin(yAngle), y: data.radius * Math.sin(xAngle) * Math.sin(yAngle), z: data.radius * Math.cos(yAngle) }); } }); /** * Set random rotation within bounds. */ AFRAME.registerComponent('random-rotation', { schema: { min: {default: {x: 0, y: 0, z: 0}, type: 'vec3'}, max: {default: {x: 360, y: 360, z: 360}, type: 'vec3'} }, update: function () { var data = this.data; var max = data.max; var min = data.min; this.el.setAttribute('rotation', { x: Math.random() * max.x + min.x, y: Math.random() * max.y + min.y, z: Math.random() * max.z + min.z }); } }); /** * Set random scale within bounds. */ AFRAME.registerComponent('random-scale', { schema: { min: {default: {x: 0, y: 0, z: 0}, type: 'vec3'}, max: {default: {x: 2, y: 2, z: 2}, type: 'vec3'} }, update: function () { var data = this.data; var max = data.max; var min = data.min; this.el.setAttribute('scale', { x: Math.random() * max.x + min.x, y: Math.random() * max.y + min.y, z: Math.random() * max.z + min.z }); } });
24.964912
82
0.558679
8d534f3932bd698db44357a8082a5101c095890d
3,323
js
JavaScript
chrome/browser/resources/chromeos/camera/src/js/type.js
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/resources/chromeos/camera/src/js/type.js
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/resources/chromeos/camera/src/js/type.js
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * Photo or video resolution. */ export class Resolution { /** * @param {number} width * @param {number} height */ constructor(width, height) { /** * @type {number} * @const */ this.width = width; /** * @type {number} * @const */ this.height = height; } /** * @return {number} Total pixel number. */ get area() { return this.width * this.height; } /** * Aspect ratio calculates from width divided by height. * @return {number} */ get aspectRatio() { // Approxitate to 4 decimal places to prevent precision error during // comparing. return parseFloat((this.width / this.height).toFixed(4)); } /** * Compares width/height of resolutions, see if they are equal or not. * @param {!Resolution} resolution Resolution to be compared with. * @return {boolean} Whether width/height of resolutions are equal. */ equals(resolution) { return this.width === resolution.width && this.height === resolution.height; } /** * Compares aspect ratio of resolutions, see if they are equal or not. * @param {!Resolution} resolution Resolution to be compared with. * @return {boolean} Whether aspect ratio of resolutions are equal. */ aspectRatioEquals(resolution) { return this.width * resolution.height === this.height * resolution.width; } /** * Create Resolution object from string. * @param {string} s * @return {!Resolution} */ static fromString(s) { return new Resolution(...s.split('x').map(Number)); } /** * @override */ toString() { return `${this.width}x${this.height}`; } } /** * Capture modes. * @enum {string} */ export const Mode = { PHOTO: 'photo', VIDEO: 'video', SQUARE: 'square', PORTRAIT: 'portrait', }; /** * Camera facings. * @enum {string} */ export const Facing = { USER: 'user', ENVIRONMENT: 'environment', EXTERNAL: 'external', NOT_SET: '(not set)', UNKNOWN: 'unknown', }; // The types here are used only in jsdoc and are required to be explicitly // exported in order to be referenced by closure compiler. // TODO(inker): Exports/Imports these jsdoc only types by closure compiler // comment syntax. The implementation of syntax is tracked here: // https://github.com/google/closure-compiler/issues/3041 /** * @typedef {{ * hasError: (boolean|undefined), * resolution: (Resolution|undefined), * }} */ export let PerfInformation; /** * @typedef {{ * width: number, * height: number, * maxFps: number, * }} */ export let VideoConfig; /** * @typedef {{ * minFps: number, * maxFps: number, * }} */ export let FpsRange; /** * A list of resolutions. * @typedef {Array<!Resolution>} */ export let ResolutionList; /** * Map of all available resolution to its maximal supported capture fps. The key * of the map is the resolution and the corresponding value is the maximal * capture fps under that resolution. * @typedef {Object<(!Resolution|string), number>} */ export let MaxFpsInfo; /** * List of supported capture fps ranges. * @typedef {Array<!FpsRange>} */ export let FpsRangeList;
21.718954
80
0.643094
8d5453d02c7a651b5be0474446a33d84472403f1
242
js
JavaScript
book/example/gio/file-load-contents/big5.js
foreachsam/book-lang-javascript-gjs
3f83c147cb58b48115fe16d4b04eded68a6d4648
[ "CC0-1.0" ]
1
2017-03-16T14:08:50.000Z
2017-03-16T14:08:50.000Z
book/example/gio/file-load-contents/big5.js
foreachsam/book-lang-javascript-gjs
3f83c147cb58b48115fe16d4b04eded68a6d4648
[ "CC0-1.0" ]
null
null
null
book/example/gio/file-load-contents/big5.js
foreachsam/book-lang-javascript-gjs
3f83c147cb58b48115fe16d4b04eded68a6d4648
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/gjs const Gio = imports.gi.Gio; var file = Gio.File.new_for_path("big5.txt"); try { var [ok, data, etag] = file.load_contents(null); if (ok) { print(data.toString('big5')); } } catch (e) { print("Error: ", e.message); }
14.235294
49
0.61157
8d54726cc1eb934c44a39a9b5bb2ebab74fa74ee
431
js
JavaScript
src/heapify.js
Aveek-Saha/js-data-structs
30dffd2b3a3c03d3cd28a26fa176b2928347f8af
[ "MIT" ]
5
2019-05-06T03:21:59.000Z
2021-04-23T02:18:08.000Z
src/heapify.js
Aveek-Saha/js-data-structs
30dffd2b3a3c03d3cd28a26fa176b2928347f8af
[ "MIT" ]
13
2020-10-08T19:44:26.000Z
2021-10-02T12:07:52.000Z
src/heapify.js
Aveek-Saha/js-data-structs
30dffd2b3a3c03d3cd28a26fa176b2928347f8af
[ "MIT" ]
2
2020-04-23T05:44:40.000Z
2020-10-10T16:29:33.000Z
export default function heapify(array, n, i) { let largest = i; let l = 2 * i + 1; // left child let r = 2 * i + 2; // right child if (r < n && array[i].key < array[r].key) largest = r; if (l < n && array[largest].key < array[l].key) largest = l; if (largest != i) { var temp = array[i]; array[i] = array[largest]; array[largest] = temp; heapify(array, n, largest); } }
28.733333
64
0.515081
8d54c6073022aabf600e2dcf81a0113087d0e262
153
js
JavaScript
workshop/static/en/api-reference/search/enumvalues_3.js
amanzw/aws-iot-edukit-tutorials
c4f0824e7bcb6be7be356ba74398a8bbb4e8c37b
[ "MIT-0" ]
null
null
null
workshop/static/en/api-reference/search/enumvalues_3.js
amanzw/aws-iot-edukit-tutorials
c4f0824e7bcb6be7be356ba74398a8bbb4e8c37b
[ "MIT-0" ]
null
null
null
workshop/static/en/api-reference/search/enumvalues_3.js
amanzw/aws-iot-edukit-tutorials
c4f0824e7bcb6be7be356ba74398a8bbb4e8c37b
[ "MIT-0" ]
null
null
null
var searchData= [ ['release_344',['RELEASE',['../button_8h.html#afeb311a4a42fcf0fd31c24acc64621b1ad590443978dc58d64aed5001f56efcdf',1,'button.h']]] ];
30.6
131
0.771242
8d54da76a2733b2b8a979c1ae4fd1f2d1ee86f05
9,479
js
JavaScript
util/attendance-function.js
ClassManagementRFIDandCam/Rest-backend-RDFI
a96318bcae686debe0e39371c38e52a0430509cf
[ "MIT" ]
null
null
null
util/attendance-function.js
ClassManagementRFIDandCam/Rest-backend-RDFI
a96318bcae686debe0e39371c38e52a0430509cf
[ "MIT" ]
null
null
null
util/attendance-function.js
ClassManagementRFIDandCam/Rest-backend-RDFI
a96318bcae686debe0e39371c38e52a0430509cf
[ "MIT" ]
1
2022-03-19T08:12:11.000Z
2022-03-19T08:12:11.000Z
const Course = require('../models/course'); const Student = require('../models/student'); const Lecturer = require('../models/lecturer'); const Attendance = require('../models/attendance'); const { createError } = require('./error-handler'); const convertToWeekday = require('./weekday-converter'); exports.getAttendanceAggregationGroupByStudent = async () => { const courses = await Course.find() .select('subjectId weekday periods roomId classType') .populate('subjectId', '-_id id name') .populate('roomId', '-_id code'); const students = await Student.find() .select('id name'); const resultPromises = courses.map(async course => { const attendanceDateAgg = await Attendance.aggregate([ { $match: { courseId: course._id } }, { $group: { _id: { $dateToString: { date: "$createdAt", format: "%Y/%m/%d" } } } }, { $sort: { _id: 1 } }, ]); return { courseId: course._id, checkDates: attendanceDateAgg.map(date => date._id) }; }); const datesGroupByCourse = await Promise.all(resultPromises); /* datesGroupByCourse = [ { courseId, checkDates: ['YYYY/MM/DD']} ] */ const attendanceGrpByStudentCourseAgg = await Attendance.aggregate([ { $group: { _id: { studentId: '$studentId', courseId: '$courseId' }, attendances: { $push: { date: { $dateToString: { format: "%Y/%m/%d", date: "$createdAt" } }, hour: { $dateToString: { format: "%H:%M", date: "$createdAt", timezone: 'Asia/Ho_Chi_Minh' } } } } } } ]); /* attendanceGrpByStudentCourseAgg = [ { _id: { courseId, studentId }, attendances: [{date, hour}] } ] */ const flatAggregation = attendanceGrpByStudentCourseAgg.map(a => { const fullDates = datesGroupByCourse.find(c => c.courseId.toString() === a._id.courseId.toString()); const fullAttendances = fullDates.checkDates.map(date => { const checkDate = a.attendances.find(attendance => attendance.date === date); return checkDate ? { date: checkDate.date.split('/').reverse().slice(0, -1).join('/'), hour: checkDate.hour } : { date: date.split('/').reverse().slice(0, -1).join('/'), hour: null }; }); return { courseId: a._id.courseId, studentId: a._id.studentId, attendances: fullAttendances }; }); /* flatAggregation = [ { courseId, studentId, attendances: [ { date, hour: null if not check } ] } ] */ const reducedAggregationOnStudentId = flatAggregation.reduce((results, agg) => { (results[agg.studentId] = results[agg.studentId] || []).push({ courseId: agg.courseId, attendances: agg.attendances }); return results; }, {}); /* reducedAggregationOnStudentId = { 'studentId': [ { courseId, attendances } ] } */ let studentList = []; for (const [key, values] of Object.entries(reducedAggregationOnStudentId)) { // key: studentId; value: [ { courseId, attendances } ] const student = students.find(s => s._id.toString() === key); const attendCourses = values.map(v => { const course = courses.find(c => c._id.toString() === v.courseId.toString()); return { ...v, subjectId: course.subjectId.id, subjectName: course.subjectId.name, roomCode: course.roomId.code, periods: course.periods, weekday: convertToWeekday(course.weekday), classType: course.classType === '1' ? 'Laboratory' : 'Theory', courseCode: `${course.classType === '1' ? 'Lab' : 'Theory'}-${course.subjectId.name}`, }; }); studentList.push({ studentName: student.name.split(' ').slice(-2).join(' '), studentId: student.id, studentEmail: student.id + '@student.hcmiu.edu.vn', courses: attendCourses }); } /* studentList = [ { studentName, Id, Email, courses: [{ courseData, attendances }] } ] */ return studentList; } exports.getAttendanceAggregationGroupByLecturer = async () => { // get lecturers' ids const lecturers = await Lecturer.find().select('_id name courseIds'); const attendanceGrpByDateCourseAgg = await Attendance.aggregate([ { $group: { _id: { date: { $dateToString: { format: "%Y/%m/%d", date: "$createdAt" } }, courseId: '$courseId' }, studentCount: { $sum: 1 // or $push: '$studentId' } } }, { $sort: { _id: 1 } }, ]); const attendanceGrpByDateCourseLecturer = attendanceGrpByDateCourseAgg.map(a => { const lecturerId = lecturers.find(l => l.courseIds.includes(a._id.courseId))._id; return { ...a, lecturerId }; }); const attendanceAggregation = attendanceGrpByDateCourseLecturer.map(a => { return { ...a, _id: { ...a._id, date: a._id.date.split('/').reverse().slice(0, -1).join('/') } }; }); const reducedAggregationOnLecturerId = attendanceAggregation.reduce((results, agg) => { (results[agg.lecturerId] = results[agg.lecturerId] || []).push({ date: agg._id.date, courseId: agg._id.courseId, studentCount: agg.studentCount }); return results; }, {}); for (const [key, value] of Object.entries(reducedAggregationOnLecturerId)) { reducedAggregationOnLecturerId[key] = value.reduce((results, agg) => { (results[agg.courseId] = results[agg.courseId] || []).push({ date: agg.date, studentCount: agg.studentCount }); return results; }, {}); } for (const [k, v] of Object.entries(reducedAggregationOnLecturerId)) { const resultPromises = Object.entries(reducedAggregationOnLecturerId[k]).map(async value => { // value[0]: courseId, value[1]: {date,studentCount} const course = await Course.findById(value[0]) .select('subjectId weekday periods roomId classType regStudentIds') .populate('subjectId', '-_id id name') .populate('roomId', '-_id code'); return { courseId: course._id, subjectId: course.subjectId.id, subjectName: course.subjectId.name, roomCode: course.roomId.code, periods: course.periods, studentNumber: course.regStudentIds.length, weekday: convertToWeekday(course.weekday), classType: course.classType === '1' ? 'Laboratory' : 'Theory', attendances: value[1] }; }); const results = await Promise.all(resultPromises); reducedAggregationOnLecturerId[k] = results; } const resPromises = Object.entries(reducedAggregationOnLecturerId).map(async value => { // value[0]: lecturerId, value[1]: [array of courses] const lecturer = await Lecturer.findById(value[0]).select('name email'); return { lecturerId: lecturer._id, lecturerName: lecturer.name.split(' ').slice(-2).join(' '), lecturerEmail: lecturer.email, courses: value[1] }; }); const res = await Promise.all(resPromises); return res; } exports.getAttendanceReport = async (courseId) => { const course = await Course .findById(courseId, 'periods classType weekday roomId lecturerId subjectId') .populate('subjectId', '-_id name id') .populate('roomId', '-_id code') .populate('lecturerId', '-_id name'); if (!course) throw createError('Course not found D:', 404); const attendanceDateAgg = await Attendance.aggregate([ { $match: { courseId: course._id } }, { $group: { _id: { $dateToString: { date: "$createdAt", format: "%Y/%m/%d" } } } }, { $sort: { _id: 1 } }, ]); const dates = attendanceDateAgg.map(d => d._id.split('/').reverse().join('/')); const attendancesGroupByStudentId = await Attendance.aggregate([ { $match: { courseId: course._id } }, { $group: { _id: "$studentId", attendances: { $addToSet: { date: { $dateToString: { date: "$createdAt", format: "%d/%m/%Y" } }, hour: { $dateToString: { format: "%H:%M", date: "$createdAt", timezone: 'Asia/Ho_Chi_Minh' } } } } } } ]); const populatedAttendances = await Student.populate(attendancesGroupByStudentId, { path: '_id', select: 'name id' }); const studentAttendances = populatedAttendances.map(a => { let attendances = []; dates.forEach(date => { let isAttend = a.attendances.find(a => a.date === date) if (isAttend) attendances.push(isAttend.hour); else attendances.push(false); }); return { id: a._id.id, name: a._id.name, attendances: attendances }; }); const result = { course: { courseId: course._id, subjectId: course.subjectId.id, subjectName: course.subjectId.name, lecturer: course.lecturerId.name, room: course.roomId.code, classType: course.classType, weekday: course.weekday, periods: course.periods }, dates: dates, studentAttendances: studentAttendances }; return result; };
28.127596
106
0.578331
8d55efc60f9b0709200b68a7fc4507feee64a874
1,110
js
JavaScript
_build/html/searchindex.js
ronyman-com/webpres-docs
161258f2642576eea03e264a1804b9dde8b7a19e
[ "MIT" ]
null
null
null
_build/html/searchindex.js
ronyman-com/webpres-docs
161258f2642576eea03e264a1804b9dde8b7a19e
[ "MIT" ]
null
null
null
_build/html/searchindex.js
ronyman-com/webpres-docs
161258f2642576eea03e264a1804b9dde8b7a19e
[ "MIT" ]
null
null
null
Search.setIndex({docnames:["amazons3","error_solved","getstarted","index","installapps"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":4,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":3,"sphinx.domains.rst":2,"sphinx.domains.std":2,sphinx:56},filenames:["amazons3.rst","error_solved.rst","getstarted.rst","index.rst","installapps.rst"],objects:{},objnames:{},objtypes:{},terms:{"error solv":1,"get start":2,_getstart:[],amazons3:0,app:[0,1,2,3],builder:[0,1,2,3,4],cm:2,document:[0,1,2,4],error:[0,2,3,4],error_solv:[],free:2,get:[0,1,3,4],getstart:[],index:[3,4],instal:[0,1,2,3],installapp:[],modul:[],opensourc:2,org:[0,1,2,3,4],orphan:3,page:[0,1,2,3,4],search:[0,1,2,3,4],site:2,solv:[0,2,3,4],start:[0,1,3,4],storag:[1,2,3,4],webpr:[0,1,2,4]},titles:["Storage","Error Solved","Get Started.","WebPres\u2019s documentation!","Install Apps"],titleterms:{app:4,content:[0,1,2,3,4],doc:[],document:3,error:1,get:2,indic:[],instal:4,s:3,solv:1,start:2,storag:0,tabl:[],webpr:3,welcom:[]}})
1,110
1,110
0.694595
8d55f12718e606bc8efcc1d2d478942917d19ab5
377
js
JavaScript
lib/util.js
KnowledgeGarden/Meteor4BacksideServlet
30e86b8ff77e6024ef5aadcd06248d42c2119367
[ "Apache-2.0" ]
null
null
null
lib/util.js
KnowledgeGarden/Meteor4BacksideServlet
30e86b8ff77e6024ef5aadcd06248d42c2119367
[ "Apache-2.0" ]
null
null
null
lib/util.js
KnowledgeGarden/Meteor4BacksideServlet
30e86b8ff77e6024ef5aadcd06248d42c2119367
[ "Apache-2.0" ]
null
null
null
/** a place for stuff */ Meteor.methods({ replaceAll: function(word, char1, replaceChar){ console.log("ReplaceAll "+word); var myword = word; //word.valueOf(); return myword.replace(new RegExp(char1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(replaceChar?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):replaceChar); } });
34.272727
197
0.549072
8d5672e6e921df30460117603798a4bee7351b85
4,378
js
JavaScript
src/frontlib/components/ExampaperProduct/Components/AddSubject/Controls/EvaluationEngine.js
zhangxu003/react-dva-bizcharts
b575e9fb0de0fee38ee9eb2be0d6a307f7d926bf
[ "MIT" ]
3
2020-01-16T03:12:48.000Z
2020-01-16T03:17:46.000Z
src/frontlib/components/ExampaperProduct/Components/AddSubject/Controls/EvaluationEngine.js
zhangxu003/react-dva-bizcharts
b575e9fb0de0fee38ee9eb2be0d6a307f7d926bf
[ "MIT" ]
null
null
null
src/frontlib/components/ExampaperProduct/Components/AddSubject/Controls/EvaluationEngine.js
zhangxu003/react-dva-bizcharts
b575e9fb0de0fee38ee9eb2be0d6a307f7d926bf
[ "MIT" ]
null
null
null
/** * @Author tina * @DateTime 2018-10-18 * @copyright 评分引擎 */ import React, { Component } from 'react'; import { Select } from 'antd'; import styles from './index.less'; const Option = Select.Option; import {queryEvaluationEngine} from '@/services/api'; import { formatMessage,FormattedMessage,defineMessages} from 'umi/locale'; const messages = defineMessages({ AssessmentEngine: { id: 'app.assessment.engine', defaultMessage: '评分引擎', }, }); class EvaluationEngine extends Component { constructor(props) { super(props); const { subIndex,patternType } = this.props; const{data,showData,index2} = this.props; var evaluationEngineInfo={}; var defaultEvaluationEngine='' //渲染数据 const editData = showData&&showData.data const mainIndex=index2=='all'?'1':index2; if(editData&&editData.patternType=="NORMAL"&&editData.mainQuestion.evaluationEngineInfo) { evaluationEngineInfo=editData.mainQuestion.evaluationEngineInfo defaultEvaluationEngine=editData.mainQuestion.evaluationEngineInfo.evaluationEngine } else if(editData&&editData.patternType=="TWO_LEVEL"&&editData.subQuestion[subIndex].evaluationEngineInfo) { evaluationEngineInfo=editData.subQuestion[subIndex].evaluationEngineInfo defaultEvaluationEngine=editData.subQuestion[subIndex].evaluationEngineInfo.evaluationEngine } else if(editData&&editData.patternType=="COMPLEX"&&editData.groups[mainIndex].data) { if(editData.groups[mainIndex].data.patternType=="NORMAL"&&editData.groups[mainIndex].data.mainQuestion.evaluationEngineInfo!=null) { evaluationEngineInfo=editData.groups[index2].data.mainQuestion.evaluationEngineInfo defaultEvaluationEngine=editData.groups[index2].data.mainQuestion.evaluationEngineInfo.evaluationEngine } if(editData.groups[mainIndex].data.patternType=="TWO_LEVEL"&&editData.groups[mainIndex].data.subQuestion[subIndex].evaluationEngineInfo!=null) { evaluationEngineInfo=editData.groups[index2].data.subQuestion[subIndex].evaluationEngineInfo defaultEvaluationEngine=editData.groups[index2].data.subQuestion[subIndex].evaluationEngineInfo.evaluationEngine } } this.state = { visible: true, evaluationEngineType:[], defaultEvaluationEngine:defaultEvaluationEngine?defaultEvaluationEngine:props.data.params.defaultEvaluationEngine, evaluationEngineInfo:defaultEvaluationEngine?evaluationEngineInfo: { "evaluationEngine":props.data.params.defaultEvaluationEngine, "fourDimensionEvaluationMode":props.data.params.fourDimensionEvaluationMode, } }; } handleChange=(value)=>{ const { subIndex,patternType,data,index2 } = this.props; this.setState({ defaultEvaluationEngine:value, evaluationEngineInfo:{ "evaluationEngine":value, "fourDimensionEvaluationMode":data.params.fourDimensionEvaluationMode, } }) this.props.saveEvaluationEngineInfo({ "evaluationEngine":value, "fourDimensionEvaluationMode":data.params.fourDimensionEvaluationMode, },subIndex,patternType,index2) } componentDidMount() { const { subIndex,patternType,index2 } = this.props; this.props.saveEvaluationEngineInfo(this.state.evaluationEngineInfo,subIndex,patternType,index2) //获取评分引擎 queryEvaluationEngine().then((res)=> { if (res.responseCode == '200') { this.setState({ evaluationEngineType:res.data }) } }).catch(err => { }); } render() { const { evaluationEngineType,key} = this.state; const { data,subIndex,index2 } = this.props; return ( <div className="demon"> <h1> <span>*</span>{formatMessage(messages.AssessmentEngine)} </h1> {evaluationEngineType.length>0&&<Select onChange={this.handleChange} value={this.state.defaultEvaluationEngine?this.state.defaultEvaluationEngine:evaluationEngineType[0].code} key={subIndex+index2} disabled={data.params.evaluationEngineOptional=='N'?true:false} > {evaluationEngineType.map((item)=>{ return <Option value={item.code} key={item.code}>{item.value}</Option> })} </Select>} </div> ); } } export default EvaluationEngine;
39.441441
151
0.703746
8d569401770fcd989fcd6e8da0c4bda73a3df77c
1,796
js
JavaScript
built/base/StringHelper.js
ShimizuShiori/MockSql
629721885c3acb25f7639447c898225f42ede791
[ "MIT" ]
1
2021-05-03T01:18:56.000Z
2021-05-03T01:18:56.000Z
built/base/StringHelper.js
ShimizuShiori/MockSql
629721885c3acb25f7639447c898225f42ede791
[ "MIT" ]
null
null
null
built/base/StringHelper.js
ShimizuShiori/MockSql
629721885c3acb25f7639447c898225f42ede791
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class StringHelper { /** * 重复一个字符串 * @param str 目标字符串 * @param count 重复的次数 */ static Repeat(str, count) { let result = []; for (let i = 0; i < count; i++) result.push(str); return result.join(""); } static SplitByIndexes(str, indexes) { let result = []; let currentIndex = 0; let currentIndexIndex = 0; let currentArray = []; var length = str.length; while (currentIndex < length) { if (currentIndex === 0) { currentArray.push(str[currentIndex]); } else if (currentIndex === indexes[currentIndexIndex]) { result.push(currentArray.join("")); currentArray = [str[currentIndex]]; currentIndexIndex++; } else { currentArray.push(str[currentIndex]); } currentIndex++; } if (currentArray.length !== 0) result.push(currentArray.join("")); return result; } static Insert(str, index, paddingStr) { let array = StringHelper.SplitByIndexes(str, [index]); return array.join(paddingStr); } static ReplaceRange(str, startIndex, count, paddingString) { let endIndex = startIndex + count; let array = StringHelper.SplitByIndexes(str, [startIndex, endIndex]); array[1] = paddingString; return array.join(""); } static PaddingLeft(str, paddingStr, length) { let result = str; while (result.length < length) { result = paddingStr + result; } return result; } } exports.StringHelper = StringHelper;
30.965517
77
0.541759
8d57315b08533a98da8c318646a9a29e6691093b
396
js
JavaScript
nutrif-web/lib/angular/docs/ptore2e/example-example68/default_test.js
LADOSSIFPB/nutrif
232f519b708cef199dcc2ef3485240cacf57612c
[ "Apache-2.0" ]
3
2017-09-22T14:33:54.000Z
2020-07-05T20:01:13.000Z
nutrif-web/lib/angular/docs/ptore2e/example-example68/default_test.js
LADOSSIFPB/nutrif
232f519b708cef199dcc2ef3485240cacf57612c
[ "Apache-2.0" ]
2
2017-05-26T23:15:30.000Z
2021-12-14T21:05:56.000Z
nutrif-web/lib/angular/docs/ptore2e/example-example68/default_test.js
LADOSSIFPB/nutrif
232f519b708cef199dcc2ef3485240cacf57612c
[ "Apache-2.0" ]
2
2016-06-02T23:45:41.000Z
2020-07-05T20:01:24.000Z
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-example68/index.html"); }); it('should check ng-click', function() { expect(element(by.binding('count')).getText()).toMatch('0'); element(by.css('button')).click(); expect(element(by.binding('count')).getText()).toMatch('1'); }); });
30.461538
69
0.628788
8d577a0939e843887d7470517de917c1dc99c89c
200
js
JavaScript
src/plugins/iam/screens/list-all-roles/schemas.js
triniti/cms-js
cf6a170d0ae09bf1c73805f3be77f337c3cb7a36
[ "Apache-2.0" ]
4
2019-11-08T21:00:34.000Z
2021-09-17T22:35:08.000Z
src/plugins/iam/screens/list-all-roles/schemas.js
triniti/cms-js
cf6a170d0ae09bf1c73805f3be77f337c3cb7a36
[ "Apache-2.0" ]
133
2019-10-03T19:26:45.000Z
2022-03-30T23:28:09.000Z
src/plugins/iam/screens/list-all-roles/schemas.js
triniti/cms-js
cf6a170d0ae09bf1c73805f3be77f337c3cb7a36
[ "Apache-2.0" ]
1
2020-02-07T17:49:08.000Z
2020-02-07T17:49:08.000Z
import ListAllRolesRequestV1Mixin from '@gdbots/schemas/gdbots/iam/mixin/list-all-roles-request/ListAllRolesRequestV1Mixin'; export default { listAllRoles: ListAllRolesRequestV1Mixin.findOne(), };
33.333333
124
0.83
8d57b2366367af2ef3ead9e18896b8620d899eb4
8,003
js
JavaScript
web/pluguin/bootstrap-switch2/bootstrap-switch.js
rafik83/unicef4
bff78d1380382afbd2ac51b979877a47a03339bc
[ "MIT" ]
null
null
null
web/pluguin/bootstrap-switch2/bootstrap-switch.js
rafik83/unicef4
bff78d1380382afbd2ac51b979877a47a03339bc
[ "MIT" ]
null
null
null
web/pluguin/bootstrap-switch2/bootstrap-switch.js
rafik83/unicef4
bff78d1380382afbd2ac51b979877a47a03339bc
[ "MIT" ]
null
null
null
!function($){$.fn["bootstrapSwitch"]=function(method){var inputSelector='input[type!="hidden"]';var methods={init:function(){return this.each(function(){var $element=$(this),$div,$switchLeft,$switchRight,$label,$form=$element.closest("form"),myClasses="",classes=$element.attr("class"),color,moving,onLabel="ON",offLabel="OFF",icon=false,textLabel=false;$.each(["switch-mini","switch-small","switch-large"],function(i,el){if(classes.indexOf(el)>=0){myClasses=el;}});$element.addClass("has-switch");if($element.data("on")!==undefined){color="switch-"+$element.data("on");}if($element.data("on-label")!==undefined){onLabel=$element.data("on-label");}if($element.data("off-label")!==undefined){offLabel=$element.data("off-label");}if($element.data("label-icon")!==undefined){icon=$element.data("label-icon");}if($element.data("text-label")!==undefined){textLabel=$element.data("text-label");}$switchLeft=$("<span>").addClass("switch-left").addClass(myClasses).addClass(color).html(""+onLabel+"");color="";if($element.data("off")!==undefined){color="switch-"+$element.data("off");}$switchRight=$("<span>").addClass("switch-right").addClass(myClasses).addClass(color).html(""+offLabel+"");$label=$("<label>").html("&nbsp;").addClass(myClasses).attr("for",$element.find(inputSelector).attr("id"));if(icon){$label.html('<i class="icon '+icon+'"></i>');}if(textLabel){$label.html(""+textLabel+"");}$div=$element.find(inputSelector).wrap($("<div>")).parent().data("animated",false);if($element.data("animated")!==false){$div.addClass("switch-animate").data("animated",true);}$div.append($switchLeft).append($label).append($switchRight);$element.find(">div").addClass($element.find(inputSelector).is(":checked")?"switch-on":"switch-off");if($element.find(inputSelector).is(":disabled")){$(this).addClass("deactivate");}var changeStatus=function($this){if($element.parent("label").is(".label-change-switch")){}else{$this.siblings("label").trigger("mousedown").trigger("mouseup").trigger("click");}};$element.on("keydown",function(e){if(e.keyCode===32){e.stopImmediatePropagation();e.preventDefault();changeStatus($(e.target).find("span:first"));}});$switchLeft.on("click",function(e){changeStatus($(this));});$switchRight.on("click",function(e){changeStatus($(this));});$element.find(inputSelector).on("change",function(e,skipOnChange){var $this=$(this),$element=$this.parent(),thisState=$this.is(":checked"),state=$element.is(".switch-off");e.preventDefault();$element.css("left","");if(state===thisState){if(thisState){$element.removeClass("switch-off").addClass("switch-on");}else{$element.removeClass("switch-on").addClass("switch-off");}if($element.data("animated")!==false){$element.addClass("switch-animate");}if(typeof skipOnChange==="boolean"&&skipOnChange){return;}$element.parent().trigger("switch-change",{"el":$this,"value":thisState});}});$element.find("label").on("mousedown touchstart",function(e){var $this=$(this);moving=false;e.preventDefault();e.stopImmediatePropagation();$this.closest("div").removeClass("switch-animate");if($this.closest(".has-switch").is(".deactivate")){$this.unbind("click");}else{if($this.closest(".switch-on").parent().is(".radio-no-uncheck")){$this.unbind("click");}else{$this.on("mousemove touchmove",function(e){var $element=$(this).closest(".make-switch"),relativeX=(e.pageX||e.originalEvent.targetTouches[0].pageX)-$element.offset().left,percent=(relativeX/$element.width())*100,left=25,right=75;moving=true;if(percent<left){percent=left;}else{if(percent>right){percent=right;}}$element.find(">div").css("left",(percent-right)+"%");});$this.on("click touchend",function(e){var $this=$(this),$myInputBox=$this.siblings("input");e.stopImmediatePropagation();e.preventDefault();$this.unbind("mouseleave");if(moving){$myInputBox.prop("checked",!(parseInt($this.parent().css("left"))<-25));}else{$myInputBox.prop("checked",!$myInputBox.is(":checked"));}moving=false;$myInputBox.trigger("change");});$this.on("mouseleave",function(e){var $this=$(this),$myInputBox=$this.siblings("input");e.preventDefault();e.stopImmediatePropagation();$this.unbind("mouseleave mousemove");$this.trigger("mouseup");$myInputBox.prop("checked",!(parseInt($this.parent().css("left"))<-25)).trigger("change");});$this.on("mouseup",function(e){e.stopImmediatePropagation();e.preventDefault();$(this).trigger("mouseleave");});}}});if($form.data("bootstrapSwitch")!=="injected"){$form.bind("reset",function(){setTimeout(function(){$form.find(".make-switch").each(function(){var $input=$(this).find(inputSelector);$input.prop("checked",$input.is(":checked")).trigger("change");});},1);});$form.data("bootstrapSwitch","injected");}});},toggleActivation:function(){var $this=$(this);$this.toggleClass("deactivate");$this.find(inputSelector).prop("disabled",$this.is(".deactivate"));},isActive:function(){return!$(this).hasClass("deactivate");},setActive:function(active){var $this=$(this);if(active){$this.removeClass("deactivate");$this.find(inputSelector).removeAttr("disabled");}else{$this.addClass("deactivate");$this.find(inputSelector).attr("disabled","disabled");}},toggleState:function(skipOnChange){var $input=$(this).find(":checkbox");$input.prop("checked",!$input.is(":checked")).trigger("change",skipOnChange);},toggleRadioState:function(skipOnChange){var $radioinput=$(this).find(":radio");$radioinput.not(":checked").prop("checked",!$radioinput.is(":checked")).trigger("change",skipOnChange);},toggleRadioStateAllowUncheck:function(uncheck,skipOnChange){var $radioinput=$(this).find(":radio");if(uncheck){$radioinput.not(":checked").trigger("change",skipOnChange);}else{$radioinput.not(":checked").prop("checked",!$radioinput.is(":checked")).trigger("change",skipOnChange);}},setState:function(value,skipOnChange){$(this).find(inputSelector).prop("checked",value).trigger("change",skipOnChange);},setOnLabel:function(value){var $switchLeft=$(this).find(".switch-left");$switchLeft.html(value);},setOffLabel:function(value){var $switchRight=$(this).find(".switch-right");$switchRight.html(value);},setOnClass:function(value){var $switchLeft=$(this).find(".switch-left");var color="";if(value!==undefined){if($(this).attr("data-on")!==undefined){color="switch-"+$(this).attr("data-on");}$switchLeft.removeClass(color);color="switch-"+value;$switchLeft.addClass(color);}},setOffClass:function(value){var $switchRight=$(this).find(".switch-right");var color="";if(value!==undefined){if($(this).attr("data-off")!==undefined){color="switch-"+$(this).attr("data-off");}$switchRight.removeClass(color);color="switch-"+value;$switchRight.addClass(color);}},setAnimated:function(value){var $element=$(this).find(inputSelector).parent();if(value===undefined){value=false;}$element.data("animated",value);$element.attr("data-animated",value);if($element.data("animated")!==false){$element.addClass("switch-animate");}else{$element.removeClass("switch-animate");}},setSizeClass:function(value){var $element=$(this);var $switchLeft=$element.find(".switch-left");var $switchRight=$element.find(".switch-right");var $label=$element.find("label");$.each(["switch-mini","switch-small","switch-large"],function(i,el){if(el!==value){$switchLeft.removeClass(el);$switchRight.removeClass(el);$label.removeClass(el);}else{$switchLeft.addClass(el);$switchRight.addClass(el);$label.addClass(el);}});},status:function(){return $(this).find(inputSelector).is(":checked");},destroy:function(){var $element=$(this),$div=$element.find("div"),$form=$element.closest("form"),$inputbox;$div.find(":not(input)").remove();$inputbox=$div.children();$inputbox.unwrap().unwrap();$inputbox.unbind("change");if($form){$form.unbind("reset");$form.removeData("bootstrapSwitch");}return $inputbox;}};if(methods[method]){return methods[method].apply(this,Array.prototype.slice.call(arguments,1));}else{if(typeof method==="object"||!method){return methods.init.apply(this,arguments);}else{$.error("Method "+method+" does not exist!");}}};}(jQuery);(function($){$(function(){$(".make-switch")["bootstrapSwitch"]();});})(jQuery);
2,667.666667
8,001
0.721729
8d57f138f402c44e09521ab4ee8ac8f0a110a055
97
js
JavaScript
tooEasy/recreatingAbsFunction.js
DobroTora/Edabit-Solution
ce88cb6ef41de024f73538ee6534397d9df7328b
[ "MIT" ]
1
2021-04-19T11:22:04.000Z
2021-04-19T11:22:04.000Z
tooEasy/recreatingAbsFunction.js
DobroTora/Edabit-Solution
ce88cb6ef41de024f73538ee6534397d9df7328b
[ "MIT" ]
null
null
null
tooEasy/recreatingAbsFunction.js
DobroTora/Edabit-Solution
ce88cb6ef41de024f73538ee6534397d9df7328b
[ "MIT" ]
1
2021-06-05T12:00:11.000Z
2021-06-05T12:00:11.000Z
function absolute(n) { if (n<0) { return -n; }else{ return n; } }
13.857143
23
0.402062
8d58ab02f001906b9d93ec9ae0b93d29dbde994b
939
js
JavaScript
src/1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.1699/1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.1699.js
jiangshanmeta/meta
8f9d084cda91988d42208ac7a029612e9edc693b
[ "MIT" ]
221
2018-10-26T07:05:12.000Z
2022-03-30T03:23:10.000Z
src/1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.1699/1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.1699.js
ralap18/meta
82d660a6eabb15e398a7dcc2a0fa99342143bb12
[ "MIT" ]
23
2018-09-24T14:50:58.000Z
2020-09-17T14:23:45.000Z
src/1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.1699/1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.1699.js
ralap18/meta
82d660a6eabb15e398a7dcc2a0fa99342143bb12
[ "MIT" ]
45
2019-03-29T03:36:19.000Z
2022-03-25T20:57:13.000Z
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var numTriplets = function (nums1, nums2) { const map1 = Object.create(null); const map2 = Object.create(null); for (let i = 0; i < nums1.length; i++) { const multi = nums1[i] * nums1[i]; map1[multi] = (map1[multi] || 0) + 1; } for (let i = 0; i < nums2.length; i++) { const multi = nums2[i] * nums2[i]; map2[multi] = (map2[multi] || 0) + 1; } let result = 0; for (let i = 0; i < nums2.length; i++) { for (let j = i + 1; j < nums2.length; j++) { const multi = nums2[i] * nums2[j]; if (map1[multi]) { result += map1[multi]; } } } for (let i = 0; i < nums1.length; i++) { for (let j = i + 1; j < nums1.length; j++) { result += (map2[nums1[i] * nums1[j]] || 0); } } return result; };
28.454545
55
0.458999
8d5a2257076ffb9b75013586a9c47fdd21ca9c9c
2,083
js
JavaScript
src/components/purchaseForm/styleForm.js
AlexKozzlov/test-task-involve
59f90d3e0a98ee5e2c977b247a21cfc5e3540df1
[ "MIT" ]
null
null
null
src/components/purchaseForm/styleForm.js
AlexKozzlov/test-task-involve
59f90d3e0a98ee5e2c977b247a21cfc5e3540df1
[ "MIT" ]
null
null
null
src/components/purchaseForm/styleForm.js
AlexKozzlov/test-task-involve
59f90d3e0a98ee5e2c977b247a21cfc5e3540df1
[ "MIT" ]
null
null
null
import styled from "styled-components"; const SelectLabel = styled.div` margin: 28px 32px; & h3 { font-family: "Roboto-700"; font-style: normal; font-weight: bold; font-size: 48px; line-height: 56px; } `; const InputContainer = styled.div` width: 313px; height: 46px; margin-top: 20px; display: flex; flex-direction: row; justify-content: space-between; border: 1px solid #cbcbcb; border-radius: 5px; & input { width: 313px; height: 44px; padding-left: 20px; border: none; border-radius: 5px; outline: none; display: block; font-family: "Roboto-400"; font-size: 16px; font-style: normal; font-weight: 400; line-height: 19px; letter-spacing: 0em; text-align: left; } `; const customStyles = { option: (provided, state) => { return { ...provided, padding: 5, fontSize: 18, fontFamily: "Roboto-500", fontStyle: "normal", fontWeight: 500, textAlign: "left", }; }, control: (provided, state) => { return { border: state.menuIsOpen ? "1px solid #58B4AE" : "1px solid #CBCBCB", borderRadius: 4, width: 313, height: 46, display: "flex", flexDirection: "row", justifyContent: "space-between", fontSize: 18, fontFamily: "Roboto-500", fontStyle: "normal", fontWeight: 500, textAlign: "left", }; }, menu: (provided, state) => { return { ...provided, width: 313, boxShadow: "0px 4px 8px rgba(0, 0, 0, 0.16)", borderRadius: 4, color: state.selectProps.menuColor, padding: 5, }; }, singleValue: (provided, state) => { const opacity = state.isDisabled ? 0.5 : 1; const transition = "opacity 300ms"; return { ...provided, opacity, transition, }; }, dropdownIndicator: (base, state) => ({ ...base, transition: "all .2s ease", transform: state.selectProps.menuIsOpen ? "rotate(180deg)" : null, }), }; export { SelectLabel, customStyles, InputContainer };
21.474227
75
0.582813
8d5b321267c01e0ac17153a0b1ebcf0639c83db5
7,762
js
JavaScript
app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Dropdown_onOptionChange_spec.js
primathon-sarthak/appsmith
01f01cd56553dcceb14ef4cad191f3a4ae4f2cfb
[ "Apache-2.0" ]
null
null
null
app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Dropdown_onOptionChange_spec.js
primathon-sarthak/appsmith
01f01cd56553dcceb14ef4cad191f3a4ae4f2cfb
[ "Apache-2.0" ]
null
null
null
app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/FormWidgets/Dropdown_onOptionChange_spec.js
primathon-sarthak/appsmith
01f01cd56553dcceb14ef4cad191f3a4ae4f2cfb
[ "Apache-2.0" ]
null
null
null
const commonlocators = require("../../../../locators/commonlocators.json"); const formWidgetsPage = require("../../../../locators/FormWidgets.json"); const widgetLocators = require("../../../../locators/Widgets.json"); const publish = require("../../../../locators/publishWidgetspage.json"); const dsl = require("../../../../fixtures/newFormDsl.json"); const data = require("../../../../fixtures/example.json"); const apiPage = require("../../../../locators/ApiEditor.json"); const datasource = require("../../../../locators/DatasourcesEditor.json"); const modalWidgetPage = require("../../../../locators/ModalWidget.json"); describe("Dropdown Widget Functionality", function() { before(() => { cy.addDsl(dsl); }); it("Dropdown-AlertModal Validation", function() { cy.SearchEntityandOpen("Dropdown1"); cy.testJsontext("options", JSON.stringify(data.input)); //creating the Alert Modal and verify Modal name cy.createModal("Alert Modal", this.data.AlertModalName); cy.PublishtheApp(); // Changing the option to verify the success message cy.get(formWidgetsPage.selectWidget) .find(widgetLocators.dropdownSingleSelect) .click({ force: true }); cy.get(commonlocators.singleSelectMenuItem) .contains("Option 2") .click({ force: true }); cy.wait(1000); cy.get(modalWidgetPage.modelTextField).should( "have.text", this.data.AlertModalName, ); }); it("Dropdown-FromModal Validation", function() { cy.openPropertyPane("dropdownwidget"); //creating the Alert Modal and verify Modal name cy.updateModal("Form Modal", this.data.FormModalName); cy.PublishtheApp(); // Changing the option to verify the success message cy.get(formWidgetsPage.selectWidget) .find(widgetLocators.dropdownSingleSelect) .click({ force: true }); cy.get(commonlocators.singleSelectMenuItem) .contains("Option 2") .click({ force: true }); cy.get(modalWidgetPage.modelTextField).should( "have.text", this.data.FormModalName, ); }); it("Dropdown-Call-Api Validation", function() { //creating an api and calling it from the onOptionChangeAction of the Dropdown widget. // Creating the api cy.NavigateToAPI_Panel(); cy.CreateAPI("dropdownApi"); cy.log("Creation of buttonApi Action successful"); cy.enterDatasourceAndPath(this.data.paginationUrl, "users?page=4&size=3"); cy.SaveAndRunAPI(); // Going to HomePage where the button widget is located and opeing it's property pane. cy.get(formWidgetsPage.NavHomePage).click({ force: true }); cy.reload(); cy.SearchEntityandOpen("Dropdown1"); // Adding the api in the onClickAction of the button widget. cy.addAPIFromLightningMenu("dropdownApi"); // Filling the messages for success/failure in the onClickAction of the button widget. cy.onClickActions("Success", "Error", "onoptionchange"); cy.PublishtheApp(); // Changing the option to verify the success message cy.get(formWidgetsPage.selectWidget) .find(widgetLocators.dropdownSingleSelect) .click({ force: true }); cy.get(commonlocators.singleSelectMenuItem) .contains("Option 3") .click({ force: true }); cy.get(formWidgetsPage.apiCallToast).should("have.text", "Success"); }); it("Dropdown-Call-Query Validation", function() { //creating a query and calling it from the onOptionChangeAction of the Dropdown widget. // Creating a mock query // cy.CreateMockQuery("Query1"); let postgresDatasourceName; cy.startRoutesForDatasource(); cy.NavigateToDatasourceEditor(); cy.get(datasource.PostgreSQL).click(); cy.generateUUID().then((uid) => { postgresDatasourceName = uid; cy.get(".t--edit-datasource-name").click(); cy.get(".t--edit-datasource-name input") .clear() .type(postgresDatasourceName, { force: true }) .should("have.value", postgresDatasourceName) .blur(); }); cy.wait("@saveDatasource").should( "have.nested.property", "response.body.responseMeta.status", 200, ); cy.fillPostgresDatasourceForm(); cy.saveDatasource(); cy.CreateMockQuery("Query1"); // Going to HomePage where the button widget is located and opeing it's property pane. cy.get(formWidgetsPage.NavHomePage).click({ force: true }); cy.reload(); cy.openPropertyPane("dropdownwidget"); // Adding the query in the onClickAction of the button widget. cy.addQueryFromLightningMenu("Query1"); // Filling the messages for success/failure in the onClickAction of the button widget. cy.onClickActions("Success", "Error", "onoptionchange"); cy.PublishtheApp(); // Changing the option to verify the success message cy.get(formWidgetsPage.selectWidget) .find(widgetLocators.dropdownSingleSelect) .click({ force: true }); cy.get(commonlocators.singleSelectMenuItem) .contains("Option 2") .click({ force: true }); cy.get(formWidgetsPage.apiCallToast).should("have.text", "Success"); }); it("Toggle JS - Dropdown-Call-Query Validation", function() { //creating an api and calling it from the onOptionChangeAction of the button widget. // calling the existing api cy.SearchEntityandOpen("Dropdown1"); cy.get(formWidgetsPage.toggleOnOptionChange).click({ force: true }); cy.testJsontext( "onoptionchange", "{{Query1.run(() => showAlert('Success','success'), () => showAlert('Error','error'))}}", ); cy.PublishtheApp(); // Changing the option to verify the success message cy.get(formWidgetsPage.selectWidget) .find(widgetLocators.dropdownSingleSelect) .click({ force: true }); cy.get(commonlocators.singleSelectMenuItem) .contains("Option 2") .click({ force: true }); cy.get(formWidgetsPage.apiCallToast).should("have.text", "Success"); }); it("Toggle JS - Dropdown-CallAnApi Validation", function() { //creating an api and calling it from the onOptionChangeAction of the button widget. // calling the existing api cy.SearchEntityandOpen("Dropdown1"); cy.testJsontext( "onoptionchange", "{{dropdownApi.run(() => showAlert('Success','success'), () => showAlert('Error','error'))}}", ); cy.PublishtheApp(); // Changing the option to verify the success message cy.get(formWidgetsPage.selectWidget) .find(widgetLocators.dropdownSingleSelect) .click({ force: true }); cy.get(commonlocators.singleSelectMenuItem) .contains("Option 1") .click({ force: true }); cy.get(formWidgetsPage.apiCallToast).should("have.text", "Success"); cy.get(publish.backToEditor).click(); cy.openPropertyPane("dropdownwidget"); // Click on onOptionChange JS button cy.get(formWidgetsPage.toggleOnOptionChange).click({ force: true }); cy.get(commonlocators.dropdownSelectButton) .eq(0) .click(); cy.get(commonlocators.chooseAction) .children() .contains("No Action") .click(); }); it("Dropdown Widget Functionality to Verify On Option Change Action", function() { // Open property pane cy.SearchEntityandOpen("Dropdown1"); // Dropdown On Option Change cy.addAction("Option Changed"); cy.PublishtheApp(); // Change the Option cy.get(formWidgetsPage.selectWidget) .find(widgetLocators.dropdownSingleSelect) .click({ force: true }); cy.get(commonlocators.singleSelectMenuItem) .contains("Option 3") .click({ force: true }); // Verify Option is changed cy.validateToastMessage("Option Changed"); cy.get(publish.backToEditor).click(); }); }); afterEach(() => { cy.goToEditFromPublish(); });
37.497585
100
0.675213
8d5bb549977d24836ea0d671b152d086bd613e58
2,321
js
JavaScript
src/empirler/old/AST.js
TarVK/Empirler-V2
8c545dfe7718de97fe6218219642b59c7e9ad13e
[ "MIT" ]
1
2018-12-02T16:46:51.000Z
2018-12-02T16:46:51.000Z
src/empirler/old/AST.js
TarVK/Empirler-V2
8c545dfe7718de97fe6218219642b59c7e9ad13e
[ "MIT" ]
null
null
null
src/empirler/old/AST.js
TarVK/Empirler-V2
8c545dfe7718de97fe6218219642b59c7e9ad13e
[ "MIT" ]
null
null
null
export default class AST { constructor(input, root) { this.input = input; this.root = root; } highlight(part) { if (!part) part = this.root; let out = ""; console.log(part); let lastIndex = part.match.range.start; part.match.parts.forEach((childPart, index) => { if (childPart) { const childStart = (childPart.match.range || childPart.range) .start; if (index > 0 && lastIndex != childStart) { out += "<span class=error style=color:darkred;background-color:pink>" + escapeHtml( this.input.substring(lastIndex, childStart) ) + "</span>"; } if (childPart.match.parts) { if (childPart.match.parts.length > 0) { out += this.highlight(childPart); lastIndex = childPart.match.range.end; } } else { const def = part.definition.pattern[index]; if (def.color) { out += "<span style=color:" + def.color + ">" + escapeHtml( this.input.substring( childPart.range.start, childPart.range.end ) ) + "</span>"; } else { out += escapeHtml( this.input.substring( childPart.range.start, childPart.range.end ) ); } lastIndex = childPart.range.end; } } }); return out; } } function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); }
34.641791
88
0.353727
8d5ccd2837892cc3d160a4fd3f9795e8eb8d3f32
1,296
js
JavaScript
ocsinventory-reports/ocsreports/js/tooltip.js
himynameismax/codeigniter
cf1b6cecf2730975ffd75fa95439401807a0071d
[ "MIT" ]
null
null
null
ocsinventory-reports/ocsreports/js/tooltip.js
himynameismax/codeigniter
cf1b6cecf2730975ffd75fa95439401807a0071d
[ "MIT" ]
null
null
null
ocsinventory-reports/ocsreports/js/tooltip.js
himynameismax/codeigniter
cf1b6cecf2730975ffd75fa95439401807a0071d
[ "MIT" ]
null
null
null
/* * * tx to Damien ALEXANDRE * http://damienalexandre.fr/Info-Bulle-en-Javascript.html * * * */ var i=false; // visible or not? function GetId(id) { return document.getElementById(id); } function move(e) { if(i) { // calcul the position if (navigator.appName!="Microsoft Internet Explorer") { // IE or other? GetId("mouse_pointer").style.left=e.pageX + 5+"px"; GetId("mouse_pointer").style.top=e.pageY + 10+"px"; } else { // TeDeum Modif if(document.documentElement.clientWidth>0) { GetId("mouse_pointer").style.left=20+event.x+document.documentElement.scrollLeft+"px"; GetId("mouse_pointer").style.top=10+event.y+document.documentElement.scrollTop+"px"; } else { GetId("mouse_pointer").style.left=20+event.x+document.body.scrollLeft+"px"; GetId("mouse_pointer").style.top=10+event.y+document.body.scrollTop+"px"; } } } } function show_me(text) { if(i==false) { GetId("mouse_pointer").style.visibility="visible"; // show tooltip. GetId("mouse_pointer").innerHTML = text; // copy the text in html i=true; } } function hidden_me() { if(i==true) { GetId("mouse_pointer").style.visibility="hidden"; // hidden tooltip i=false; } } document.onmousemove=move; // when mouse move, calcul again the mouse pointer. //-->
24.923077
88
0.673611
8d5d1d8f80fd0e8d4ceef251cc4db91707775c90
3,146
js
JavaScript
src/electron-app/main.js
simlu/notebag
ce4aacbc176587c489d4ad8c909a3986278116c8
[ "MIT" ]
141
2020-10-27T21:56:09.000Z
2022-03-18T21:44:51.000Z
src/electron-app/main.js
raykyri/notebag
e8d1af7d3d34f1efd57626844c559bf746e01ac8
[ "MIT" ]
5
2020-10-29T03:09:31.000Z
2021-01-08T08:45:34.000Z
src/electron-app/main.js
raykyri/notebag
e8d1af7d3d34f1efd57626844c559bf746e01ac8
[ "MIT" ]
25
2020-10-28T12:32:11.000Z
2022-03-20T09:08:38.000Z
/* eslint-disable */ "use strict"; const fs = require("fs"); const { app, ipcMain, globalShortcut, nativeTheme, dialog, Menu } = require("electron"); const ElectronStore = require("electron-store"); const mv = require("mv"); const keytar = require("keytar"); const { makeAccelerator } = require("./utilities/makeAccelerator"); const { createApplicationMenu } = require("./menu"); const { toggleWindow, createWindow } = require("./mainWindow"); const { setTrayTheme, createTray } = require("./tray"); let electronStore = new ElectronStore({ watch: true }); Menu.setApplicationMenu(createApplicationMenu()); if (!electronStore.get("preferences.showDock", true)) { app.dock.hide(); } app.on("ready", async () => { const theme = nativeTheme.shouldUseDarkColors ? "dark" : "light"; const accelerator = makeAccelerator(electronStore.get("preferences.shortcuts.showHideWindow", [17, 18, 32])); createTray(theme); createWindow(); globalShortcut.register(accelerator, toggleWindow); }); app.on("window-all-closed", () => {}); app.on("activate", () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if(!global.mainWindow) { createWindow(); } }); app.on("will-quit", () => { globalShortcut.unregisterAll(); }); ipcMain.on("valid-license", async (_, licenseKey) => { await keytar.setPassword(app.name, app.name, licenseKey); }); ipcMain.on("deactivate-license", async () => { await keytar.deletePassword(app.name, app.name); }); ipcMain.on("shortcut-changed:showHideWindow", (event , oldKeys, newKeys) => { const oldAccelerator = makeAccelerator(oldKeys); const accelerator = makeAccelerator(newKeys); globalShortcut.unregister(oldAccelerator); globalShortcut.register(accelerator, toggleWindow); }); ipcMain.on("shortcut-suspended:showHideWindow", (event , oldKeys) => { const oldAccelerator = makeAccelerator(oldKeys); globalShortcut.unregister(oldAccelerator); }); ipcMain.on("toggle-dock", (event, showDock) => { if (showDock) { app.dock.show(); return; } app.dock.hide(); }); ipcMain.on("note-path-changed", (event , oldPath, newPath) => { const oldFile = `${oldPath}/notebag.json`; const newFile = `${newPath}/notebag.json`; try { if (fs.existsSync(newFile)) { app.relaunch(); app.exit(); return; } } catch (err) { dialog.showMessageBoxSync({ type: "error", title: "Error changing file location", message: `Notebag was not able to change the location of your notes file. Please try again with another path. Error: ${err}`, buttons: ["OK"], icon: null, }); return; } mv(oldFile, newFile, function(err) { if (err) { dialog.showMessageBoxSync({ type: "error", title: "Error changing file location", message: `Notebag was not able to change the location of your notes file. Please try again with another path. Error: ${err}`, buttons: ["OK"], icon: null, }); return; } app.relaunch(); app.exit(); }); }); nativeTheme.on("updated", () => { const newTheme = nativeTheme.shouldUseDarkColors ? "dark" : "light"; setTrayTheme(newTheme); });
25.370968
129
0.681818
8d5d72636f618eccaba3f0c95e2501089d5ceb6b
2,051
js
JavaScript
script.js
draceel07/SCROLL-TO-ACCEPT
03c1969e323176aa8145f2104424e4400a3b2f60
[ "MIT" ]
1
2020-10-01T17:10:05.000Z
2020-10-01T17:10:05.000Z
script.js
draceel07/SCROLL-TO-ACCEPT
03c1969e323176aa8145f2104424e4400a3b2f60
[ "MIT" ]
3
2020-10-01T17:05:24.000Z
2020-10-01T17:23:28.000Z
script.js
draceel07/SCROLL-TO-ACCEPT
03c1969e323176aa8145f2104424e4400a3b2f60
[ "MIT" ]
1
2020-10-01T17:10:14.000Z
2020-10-01T17:10:14.000Z
console.log('100%........................'); //first i will capture the terms and condition div // function scrollToaccept() { // const termsCondition = document.querySelector('.terms-and-conditions'); // console.log(termsCondition); // it works // if(!termsCondition) { // return; // quit this function if it's not present on the page. // } // termsCondition.addEventListener('scroll', (e) => { // console.log(e.currentTarget.scrollTop); //1475 : it will measure height from the top // console.log(e.currentTarget.scrollHeight); //2010 both can be might change : total height of scroll // }) // } // scrollToaccept() //second i will listen to the scroll event inside terms and conditions // in case if termsCondition is not present we can pass some if statements for prevention by making a function const termsCondition = document.querySelector('.terms-and-conditions'); const watch = document.querySelector('.watch'); const button = document.querySelector('.accept'); //Intersection Observer :- //callback function function callbackForIntersection(payload) { // console.log(payload); // console.log(payload[0].isIntersecting); ///output either true or false console.log(payload[0].intersectionRatio); if(payload[0].intersectionRatio === 1) { button.disabled = false // console.log('REMOVING OBSERVER'); // observer.unobserve(termsCondition.lastElementChild); } else { button.disabled = true; } } const observer = new IntersectionObserver(callbackForIntersection, { root: termsCondition, threshold:1, // for getting 1 threshold we have to add image or any element in the end }); //inside intersection observer function we need to give callback function as argument. we can also optionmethod inside intersection function //working: // observer.observe(watch); // now i will observe the last paragraph termsCondition observer.observe(termsCondition.lastElementChild);
39.442308
142
0.683569
8d5d7ffd2324d1f4e6596116bf237630552befc1
6,766
js
JavaScript
test/aria/utils/Path.js
mathbruyen/ariatemplates
2ca1f40338754c6d82a41fba9516ebc4d11cb295
[ "Apache-2.0" ]
null
null
null
test/aria/utils/Path.js
mathbruyen/ariatemplates
2ca1f40338754c6d82a41fba9516ebc4d11cb295
[ "Apache-2.0" ]
null
null
null
test/aria/utils/Path.js
mathbruyen/ariatemplates
2ca1f40338754c6d82a41fba9516ebc4d11cb295
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012 Amadeus s.a.s. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Test case for aria.utils.Path */ Aria.classDefinition({ $classpath : "test.aria.utils.Path", $extends : "aria.jsunit.TestCase", $dependencies : ["aria.utils.Path"], $prototype : { /** * Test the parse method */ test_parse : function () { var path = "data.test.elem[0][\"par'a:m\\\"1\"].param2['0']"; var parsedPath = aria.utils.Path.parse(path); this.assertTrue(parsedPath[0] == "data"); this.assertTrue(parsedPath[1] == "test"); this.assertTrue(parsedPath[2] == "elem"); this.assertTrue(parsedPath[3] == "0"); this.assertTrue(parsedPath[4] == "par'a:m\"1"); this.assertTrue(parsedPath[5] == "param2"); this.assertTrue(parsedPath[6] == "0"); }, /** * Test the resolve method */ test_resolve : function () { // method has two signature, with string and array var pathStr = "param1[0]['param3']"; var pathArray = ["param1", 0, "param4"]; var obj = { param1 : [{ param3 : 13, param4 : false }] }; this.assertTrue(aria.utils.Path.resolve(pathStr, obj) == 13); this.assertTrue(aria.utils.Path.resolve(pathArray, obj) === false); }, /** * test test pathArrayToString method */ test_pathArrayToString : function () { var path = "data.test.elem[0][\"par'a:m\\\"1\"].param2['0']"; var parsedPath = aria.utils.Path.parse(path); this.assertTrue(aria.utils.Path.pathArrayToString(parsedPath) == 'data["test"]["elem"]["0"]["par\'a:m\\\"1"]["param2"]["0"]'); }, testSetValue : function () { var obj = {}; aria.utils.Path.setValue(obj, "first", 10); aria.utils.Path.setValue(obj, "second", { "nested" : { "reality" : true, "imagination" : false } }); aria.utils.Path.setValue(obj, "second['nested'].reality", "better than imagination"); aria.utils.Path.setValue(obj, "third.deep.inside", null); aria.utils.Path.setValue(obj, "fourth[0].something", "number"); aria.utils.Path.setValue(obj, "will.be.cancelled", true); aria.utils.Path.setValue(obj, "will.be.cancelled.by.me", true); aria.utils.Path.setValue(obj, "number['0']['1']", 2); aria.utils.Path.setValue(obj, "number1.second2", 3); aria.utils.Path.setValue(obj, "array", "not really an array"); aria.utils.Path.setValue(obj, "array[1]", "array"); aria.utils.Path.setValue(obj, "array[0][1][2]", "now it is"); var expected = { first : 10, second : { nested : { reality : "better than imagination", imagination : false } }, third : { deep : { inside : null } }, fourth : [{ something : "number" }], will : { be : { cancelled : { by : { me : true } } } }, number : { 0 : { 1 : 2 } }, number1 : { second2 : 3 }, array : [[], "array"] }; expected.array[0][1] = []; expected.array[0][1][2] = "now it is"; this.assertTrue(aria.utils.Json.equals(obj, expected), "Build object different from expected"); }, testDescribe : function () { var obj = {}, got, expected; got = aria.utils.Path.describe(obj, "a"); this.assertEquals(got, null, "single path in empty object should be null"); got = aria.utils.Path.describe(obj, "a.b.c"); this.assertEquals(got, null, "multiple path in empty object should be null"); obj = { a : "empty", b : ["a", "b", "c", { f : "something" }], c : { a : "object", b : false, c : { one : 1 } } }; got = aria.utils.Path.describe(obj, "a"); expected = { container : obj, property : "a", value : "empty" }; this.assertTrue(aria.utils.Json.equals(got, expected), "describe 'a' is wrong"); got = aria.utils.Path.describe(obj, "a.b"); this.assertEquals(got, null, "a.b in object should be null"); got = aria.utils.Path.describe(obj, "b[1]"); expected = { container : obj.b, property : 1, value : "b" }; this.assertTrue(aria.utils.Json.equals(got, expected), "describe 'b[1]' is wrong"); got = aria.utils.Path.describe(obj, "b[3].f"); expected = { container : obj.b[3], property : "f", value : "something" }; this.assertTrue(aria.utils.Json.equals(got, expected), "describe 'b[3].f' is wrong"); got = aria.utils.Path.describe(obj, "c['c'].one"); expected = { container : obj.c.c, property : "one", value : 1 }; this.assertTrue(aria.utils.Json.equals(got, expected), "describe 'c['c'].one' is wrong"); } } });
35.610526
138
0.44768
8d5dbb4f73d70bc9ac78206d0b761f726ae23c17
1,016
js
JavaScript
src/pages/new/add/index.js
princessJoanna/ant-adminYr1.0
27b322ba43adf535c766b058fcd3ec93639cace2
[ "MIT" ]
null
null
null
src/pages/new/add/index.js
princessJoanna/ant-adminYr1.0
27b322ba43adf535c766b058fcd3ec93639cace2
[ "MIT" ]
null
null
null
src/pages/new/add/index.js
princessJoanna/ant-adminYr1.0
27b322ba43adf535c766b058fcd3ec93639cace2
[ "MIT" ]
null
null
null
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Upload, Button, Icon, Select,Input } from 'antd' const { TextArea } = Input; const Option = Select.Option const Add = ({ newDetail }) => { const Option = Select.Option const handleChange=(value)=>{ console.log(`selected ${value}`); } return (<div className="content-inner"> <div> <label>请选择新闻的分类:</label> <Select defaultValue="请选择分类" style={{ width: 120 }} onChange={handleChange}> <Option value="1">公司动态</Option> <Option value="2">行业动态</Option> <Option value="3">客户动态</Option> </Select> </div> <div> <div style={{ margin: '10px 0' }}> <Input placeholder="请输入资讯标题" /> </div> <TextArea placeholder="请输入资讯内容" autosize={{ minRows: 6, maxRows: 1}} /> </div> </div>) } Add.propTypes = { NewDetail: PropTypes.object, } export default connect(({ addNew, loading }) => ({ addNew, loading:loading.models.AddNew }))(Add)
26.736842
97
0.615157
8d5e76168351389112e526ad200dd940a01520d3
1,053
js
JavaScript
docs/cpp/structoperations__research_1_1_state_info.js
matbesancon/or-tools
b37d9c786b69128f3505f15beca09e89bf078a89
[ "Apache-2.0" ]
1
2021-07-06T13:01:46.000Z
2021-07-06T13:01:46.000Z
docs/cpp/structoperations__research_1_1_state_info.js
matbesancon/or-tools
b37d9c786b69128f3505f15beca09e89bf078a89
[ "Apache-2.0" ]
null
null
null
docs/cpp/structoperations__research_1_1_state_info.js
matbesancon/or-tools
b37d9c786b69128f3505f15beca09e89bf078a89
[ "Apache-2.0" ]
1
2021-07-24T22:52:41.000Z
2021-07-24T22:52:41.000Z
var structoperations__research_1_1_state_info = [ [ "StateInfo", "structoperations__research_1_1_state_info.html#ae04b0c2ce0cbd0cd96639fd3d6cd817a", null ], [ "StateInfo", "structoperations__research_1_1_state_info.html#a9f2db1d22ae290ba55364fed1223079d", null ], [ "StateInfo", "structoperations__research_1_1_state_info.html#a7800f35338d1e2efe1b078ecaa5d4978", null ], [ "StateInfo", "structoperations__research_1_1_state_info.html#a3e34449ce0fbcc62500f5fcd902682e4", null ], [ "depth", "structoperations__research_1_1_state_info.html#acb5ba97551079e0b072c62c21d784ac5", null ], [ "int_info", "structoperations__research_1_1_state_info.html#abb70bfb0cc441145e74c3e1f080433ab", null ], [ "left_depth", "structoperations__research_1_1_state_info.html#af40da30f99ec5fe6e1659d25909a2161", null ], [ "ptr_info", "structoperations__research_1_1_state_info.html#adb10c3ea3e6b70866bed78424ed1136c", null ], [ "reversible_action", "structoperations__research_1_1_state_info.html#a133ce5a301ebbf5352db94f502f12fa7", null ] ];
87.75
117
0.822412
8d5e8107be07c9ffd572e6a82dbf616598ca2d59
1,952
js
JavaScript
packages/strapi-plugin-content-manager/admin/src/components/SelectMany/ListItem.js
mhelmetag/strapi
504c7cda275ddf0cad59ffb7c922a52a59728587
[ "MIT" ]
7
2020-01-07T04:30:05.000Z
2022-01-22T08:36:46.000Z
packages/strapi-plugin-content-manager/admin/src/components/SelectMany/ListItem.js
mhelmetag/strapi
504c7cda275ddf0cad59ffb7c922a52a59728587
[ "MIT" ]
4
2021-05-12T00:02:48.000Z
2022-02-26T02:08:52.000Z
packages/strapi-plugin-content-manager/admin/src/components/SelectMany/ListItem.js
mhelmetag/strapi
504c7cda275ddf0cad59ffb7c922a52a59728587
[ "MIT" ]
4
2020-06-19T07:29:54.000Z
2021-05-13T09:52:15.000Z
import React, { memo, useEffect } from 'react'; import PropTypes from 'prop-types'; import { useDrag, useDrop } from 'react-dnd'; import { getEmptyImage } from 'react-dnd-html5-backend'; import pluginId from '../../pluginId'; import ItemTypes from '../../utils/ItemTypes'; import { Li } from './components'; import Relation from './Relation'; function ListItem({ data, findRelation, mainField, moveRelation, nextSearch, onRemove, source, targetModel, }) { const to = `/plugins/${pluginId}/${targetModel}/${data.id}?source=${source}&redirectUrl=${nextSearch}`; const originalIndex = findRelation(data.id).index; const [{ isDragging }, drag, preview] = useDrag({ item: { type: ItemTypes.RELATION, id: data.id, originalIndex, data, mainField, }, collect: monitor => ({ isDragging: monitor.isDragging(), }), }); const [, drop] = useDrop({ accept: ItemTypes.RELATION, canDrop: () => false, hover({ id: draggedId }) { if (draggedId !== data.id) { const { index: overIndex } = findRelation(data.id); moveRelation(draggedId, overIndex); } }, }); useEffect(() => { preview(getEmptyImage(), { captureDraggingState: true }); }, [preview]); const opacity = isDragging ? 0.2 : 1; return ( <Li ref={node => drag(drop(node))} style={{ opacity }}> <Relation mainField={mainField} onRemove={onRemove} data={data} to={to} /> </Li> ); } ListItem.defaultProps = { findRelation: () => {}, moveRelation: () => {}, nextSearch: '', onRemove: () => {}, targetModel: '', }; ListItem.propTypes = { data: PropTypes.object.isRequired, findRelation: PropTypes.func, mainField: PropTypes.string.isRequired, moveRelation: PropTypes.func, nextSearch: PropTypes.string, onRemove: PropTypes.func, source: PropTypes.string.isRequired, targetModel: PropTypes.string, }; export default memo(ListItem);
24.098765
105
0.634734
8d5f2a5973fbf4c5f47decc585491a571ecea05a
273
js
JavaScript
api/v1/utils/passwords.js
TheDrizzyWay/Questioner
2db953f444357642510cc1a34fd4f60af9122de7
[ "MIT" ]
null
null
null
api/v1/utils/passwords.js
TheDrizzyWay/Questioner
2db953f444357642510cc1a34fd4f60af9122de7
[ "MIT" ]
null
null
null
api/v1/utils/passwords.js
TheDrizzyWay/Questioner
2db953f444357642510cc1a34fd4f60af9122de7
[ "MIT" ]
4
2019-01-04T10:07:00.000Z
2019-08-29T07:53:06.000Z
import bcrypt from 'bcryptjs'; export default class Hash { static hashPassword(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(10)); } static comparePassword(password, hashPassword) { return bcrypt.compareSync(password, hashPassword); } }
22.75
61
0.74359
8d5f41a02ae4f5f339fa9126ff8ba44d1c0856d9
1,449
js
JavaScript
javascript/chapter07/util/Graph.js
Kiandr/crackingcodinginterview
b499f5bc704ce24f8826d5facfaf6a3cc996a86a
[ "Apache-2.0" ]
null
null
null
javascript/chapter07/util/Graph.js
Kiandr/crackingcodinginterview
b499f5bc704ce24f8826d5facfaf6a3cc996a86a
[ "Apache-2.0" ]
null
null
null
javascript/chapter07/util/Graph.js
Kiandr/crackingcodinginterview
b499f5bc704ce24f8826d5facfaf6a3cc996a86a
[ "Apache-2.0" ]
null
null
null
var Graph = function() { this.nodes = {}; }; Graph.prototype.addEdge = function(node, edge) { if (this.nodes[node] === undefined) { return 'node does not exist'; } else if (this.nodes[node][edge]) { return `edge ${node}-${edge} already exists`; } else { this.nodes[node][edge] = true; } }; Graph.prototype.addNode = function(value) { if (this.nodes[value] !== undefined) { return `node of value ${value} already exists`; } else { this.nodes[value] = {}; } }; Graph.prototype.findEdges = function(node) { if (this.nodes[node] === undefined) { return 'node does not exist'; } else { return this.nodes[node]; } }; Graph.prototype.hasEdge = function(node, edge) { if (this.nodes[node] === undefined) { return false; } else { return this.nodes[node][edge] !== undefined; } }; Graph.prototype.hasNode = function(node) { return this.nodes[node] !== undefined; }; Graph.prototype.removeEdge = function(node, edge) { if (this.nodes[node] === undefined) { return 'node does not exist'; } else { delete this.nodes[node][edge]; } }; Graph.prototype.removeNode = function(node) { if (this.nodes[node] === undefined) { return 'node does not exist'; } else { delete this.nodes[node]; for (var currNode in this.nodes) { if (this.nodes[currNode][node] !== undefined) { delete this.nodes[currNode][node]; } } } }; module.exports = Graph;
22.640625
53
0.615597
8d5fd1cf145b28ae33e97897b1dbcd03f3404b24
341
js
JavaScript
src/components/Icon/styleds.js
steedems/sd-gatsby
c4eb149694bb23af972340c738cac629aba1b994
[ "MIT" ]
null
null
null
src/components/Icon/styleds.js
steedems/sd-gatsby
c4eb149694bb23af972340c738cac629aba1b994
[ "MIT" ]
13
2020-01-01T15:35:50.000Z
2022-02-26T12:35:22.000Z
src/components/Icon/styleds.js
steedems/sd-gatsby
c4eb149694bb23af972340c738cac629aba1b994
[ "MIT" ]
null
null
null
/** * Created by Stefano Demurtas on 06/02/2018. */ import styled from 'styled-components'; import { colors } from '../../utils/styles'; export const IconWrapper = styled.div` font-size: ${props => props.size}rem; padding: 12px 12px 12px 0; cursor: ${props => (props.onClick ? 'pointer' : '')}; color: ${colors.highlight}; `;
20.058824
55
0.642229
8d60084e3e3eb99b7020ae069b8c4010914cb46f
441
js
JavaScript
js/index.js
lakerphan4life/beer-pour
4b1def2a81513f54ac4fda021bd1098eee8f0d6e
[ "MIT" ]
null
null
null
js/index.js
lakerphan4life/beer-pour
4b1def2a81513f54ac4fda021bd1098eee8f0d6e
[ "MIT" ]
null
null
null
js/index.js
lakerphan4life/beer-pour
4b1def2a81513f54ac4fda021bd1098eee8f0d6e
[ "MIT" ]
null
null
null
$(document).ready(function() { $('.pour') //Pour Me Another Drink, Bartender! .delay(2000) .animate({ height: '360px' }, 1500) .delay(1600) .slideUp(500); $('#liquid') // I Said Fill 'Er Up! .delay(3400) .animate({ height: '250px' }, 2500); $('.beer-foam') // Keep that Foam Rollin' Toward the Top! Yahooo! .delay(3400) .animate({ bottom: '250px' }, 2500); });
20.045455
67
0.514739
8d60546c4f49c141e9a7c86e175644118862ec07
102
js
JavaScript
node_modules/polyfill-library/polyfills/__dist/Math.clz32/min.js
vladermakov12345/Test1
6c228a7f600c44445475218e6c32a7be575d8b33
[ "MIT" ]
1
2019-09-20T08:12:15.000Z
2019-09-20T08:12:15.000Z
node_modules/polyfill-library/polyfills/__dist/Math.clz32/min.js
vladermakov12345/Test1
6c228a7f600c44445475218e6c32a7be575d8b33
[ "MIT" ]
1
2022-03-02T05:39:38.000Z
2022-03-02T05:39:38.000Z
node_modules/polyfill-library/polyfills/__dist/Math.clz32/min.js
vladermakov12345/Test1
6c228a7f600c44445475218e6c32a7be575d8b33
[ "MIT" ]
null
null
null
CreateMethodProperty(Math,"clz32",function(t){var r=ToUint32(t);return r?32-r.toString(2).length:32});
102
102
0.764706
8d606d3d8c550930cd83b49364d48f4f72fb9579
232
js
JavaScript
grunt/ftp-deploy.js
dereksheppard/egov
5eecbb5f318f78b9c2f747959052a72b7caaab81
[ "MIT" ]
null
null
null
grunt/ftp-deploy.js
dereksheppard/egov
5eecbb5f318f78b9c2f747959052a72b7caaab81
[ "MIT" ]
null
null
null
grunt/ftp-deploy.js
dereksheppard/egov
5eecbb5f318f78b9c2f747959052a72b7caaab81
[ "MIT" ]
null
null
null
module.exports = { build: { auth: { host: 'webupload.kingcounty.gov', port: 21, authKey: 'key1' }, src: ['<%= public %>/' ], dest: 'kcproto/bs3/', exclusions: ['<%= public %>/html',''] } };
17.846154
41
0.465517
8d60be1be609e1d5ac4cf8540d5d252d707159d0
1,846
js
JavaScript
languages/javascript/sprite_runtime.js
CSnap/waterbear
04424330483e7e6cb1990512d51f2072252704c2
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
languages/javascript/sprite_runtime.js
CSnap/waterbear
04424330483e7e6cb1990512d51f2072252704c2
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
languages/javascript/sprite_runtime.js
CSnap/waterbear
04424330483e7e6cb1990512d51f2072252704c2
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
// Sprite Routines function RectSprite(size,pos,color){ this.x = pos.x; this.y = pos.y; this.w = size.w; this.h = size.h; this.collisionRect = this; this.color = color; }; window.RectSprite = RectSprite; RectSprite.prototype.draw = function(ctx){ ctx.save(); ctx.fillStyle = this.color; ctx.fillRect(this.x, this.y, this.w, this.h); ctx.restore(); }; RectSprite.prototype.collides = function(sprite){ var self = this.collisionRect; var that = sprite.collisionRect; if ((self.x + self.w) < that.x) return false; if ((self.y + self.h) < that.y) return false; if (self.x > (that.x + that.w)) return false; if (self.y > (that.y + that.h)) return false; return true; }; RectSprite.prototype.toString = function(){ return '<RectSprite ' + this.x + ' ' + this.y + ' ' + this.w + ' ' + this.h + ' ' + this.color + '>'; }; function Vector2(dx,dy){ this.dx = dx || 0; this.dy = dy || 0; } Vector2.fromAngle = function(radians, magnitude){ if (magnitude <= 0) magnitude = 1.0; return new Vector(Math.cos(radians) * magnitude, Math.sin(radians) * magnitude); } Vector2.prototype.magnitude = function(){ return Math.sqrt(this.dx * this.dx + this.dy * this.dy); } Vector2.prototype.add = function(v){ return new Vector2(this.dx + v.dx, this.dy + v.dy); } Vector2.prototype.subtract = function(v){ return new Vector2(this.dx - v.dx, this.dy - v.dy); } Vector2.prototype.reflect = function(rx, ry){ return new Vector2(rx ? -this.dx: this.dx, ry ? -this.dy : this.dy); } Vector2.prototype.angle = function(){ // angle of vector in radians return Math.atan2(this.dy, this.dx); } Vector2.prototype.rotate = function(radians){ var mag = this.magnitude(); var theta = this.angle(); return Vector.fromAngle(theta + radians, mag); }
26.753623
106
0.631636
8d61f42e0d3c8cdc1c97549da52affdedf4a6d00
2,660
js
JavaScript
www/resources/js/core/service/user-service.js
12130010/nongnghiep
53dc221389abfa5d15d76739c8f80e36ca39f295
[ "Apache-2.0" ]
null
null
null
www/resources/js/core/service/user-service.js
12130010/nongnghiep
53dc221389abfa5d15d76739c8f80e36ca39f295
[ "Apache-2.0" ]
null
null
null
www/resources/js/core/service/user-service.js
12130010/nongnghiep
53dc221389abfa5d15d76739c8f80e36ca39f295
[ "Apache-2.0" ]
null
null
null
'use strict'; app.service('userService', ['$q', 'commonService', 'connectorService', function($q, commonService, connectorService) { function UserService(){ this.userDetail = {}; } UserService.prototype.isAuthenticated = function isAuthenticated(){ return !$.isEmptyObject(this.userDetail); } /* Use to login. userLoginModel = { username: String, password: String } */ UserService.prototype.login = function login(userLoginModel){ var self = this; var deferred = $q.defer(); connectorService.get( { actionName: "USER_LOGIN", actionParams : [userLoginModel.username, userLoginModel.password] } ).then(function success(response){ //login success: response.data = {"tag":"login","success":1,"error":0,"uid":"59a75a560d5a72.74818691","user":{"name":"seval","email":"seval@test.com","created_at":"2017-08-31 07:37:42","updated_at":null}} //login fail: response.data = {"tag":"login","success":0,"error":1,"error_msg":"Incorrect email or password!"} if(response.data.success === 1){ //login success commonService.copyValueFromOther(response.data.user, self.userDetail); deferred.resolve(self.userDetail); } else { // login fail deferred.reject(response.data); } }, function error(response){ deferred.reject(response.data); }); return deferred.promise; } UserService.prototype.logout = function logout(){ var self = this; var deferred = $q.defer(); commonService.cleanAllProperty(this.userDetail); //TODO clean all data return $q.when({}); } UserService.prototype.refresh = function refresh(){ var self = this; var deferred = $q.defer(); return deferred.promise; } //load user have login UserService.prototype.loadUserDetail = function loadUserDetail(){ return {}; } UserService.prototype.register = function register(user){ var self = this; var deferred = $q.defer(); connectorService.post( { actionName: "USER_CREATE_NEW_USER", actionParams : [], data: user } ).then(function success(response){ deferred.resolve(response); }, function error(response){ deferred.reject(response); }); return deferred.promise; } UserService.prototype.checkUserIsExist = function checkUserIsExist(username){ var self = this; var deferred = $q.defer(); connectorService.get( { actionName: "USER_CHECK_USER_IS_EXIST", actionParams : [username] } ).then(function success(response){ deferred.resolve(response); }, function error(response){ deferred.reject(response); }); return deferred.promise; } return new UserService(); }]);
25.576923
207
0.67406
8d627a835045d95f7680553cac7357b2a3c18abf
1,357
js
JavaScript
src/59.spiral-matrix-ii.js
jiadi0801/leetcode
d5d60e9d9136323b4aaf4321156eba195bf9688e
[ "MIT" ]
null
null
null
src/59.spiral-matrix-ii.js
jiadi0801/leetcode
d5d60e9d9136323b4aaf4321156eba195bf9688e
[ "MIT" ]
null
null
null
src/59.spiral-matrix-ii.js
jiadi0801/leetcode
d5d60e9d9136323b4aaf4321156eba195bf9688e
[ "MIT" ]
null
null
null
/** * @param {number} n * @return {number[][]} */ var generateMatrix = function(n) { let martrix = []; for (let i = 0; i < n; i++) { let row = []; for (let j = 0; j < n; j++) { row.push(0); } martrix.push(row); } let count = n * n; let row = 0, col = 0; let direction = 1; // 右1 下2 左3 上4 for (let i = 0; i < count; i++) { martrix[row][col] = i + 1; if (direction === 1) { if (col + 1 < n && !martrix[row][col + 1]) { col++; } else { direction = 2; row++; }; } else if (direction === 2) { if (row + 1 < n && !martrix[row + 1][col]) { row++; } else { direction = 3; col--; }; } else if (direction === 3) { if (col - 1 > -1 && !martrix[row][col - 1]) { col--; } else { direction = 4; row--; }; } else if (direction === 4) { if (row - 1 > -1 && !martrix[row - 1][col]) { row--; } else { direction = 1; col++; }; } } return martrix; }; module.exports = generateMatrix;
24.232143
57
0.328666
8d62d3646ad91e0f37522e713136bb6cf37160af
709
js
JavaScript
src/components/Layout.js
FrankcoMiguel/Portfolio
933c0c7e8e9c357a7a3741dc45df73513add8f66
[ "RSA-MD" ]
1
2022-03-01T21:30:30.000Z
2022-03-01T21:30:30.000Z
src/components/Layout.js
FrankcoMiguel/Portfolio
933c0c7e8e9c357a7a3741dc45df73513add8f66
[ "RSA-MD" ]
6
2020-07-21T16:35:52.000Z
2022-01-02T09:07:58.000Z
src/components/Layout.js
FrankcoMiguel/Portfolio
933c0c7e8e9c357a7a3741dc45df73513add8f66
[ "RSA-MD" ]
1
2020-10-29T11:02:37.000Z
2020-10-29T11:02:37.000Z
import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css' import Navbar from './Navbar' import Footer from './Footer' import { Helmet } from 'react-helmet' import navbar from '../data/navbar.json' const Layout = ({children, title, page}) => { return ( <div className="Application"> <Helmet> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{title}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devicons/devicon@latest/devicon.min.css" /> </Helmet> <Navbar option={page} items={navbar}/> {children} <Footer /> </div> ) } export default Layout
26.259259
108
0.633286
8d630bef3ee093b364e0cab3d08d978f43ae3edf
1,210
js
JavaScript
lib/provider/camunda/parts/implementation/External.js
prithviraj-maurya/bpmn-js-properties-panel
ffc99ae13a1e7b8381cb57a91e8c4fb3950446aa
[ "MIT" ]
210
2015-08-22T13:49:51.000Z
2022-03-16T09:42:53.000Z
lib/provider/camunda/parts/implementation/External.js
prithviraj-maurya/bpmn-js-properties-panel
ffc99ae13a1e7b8381cb57a91e8c4fb3950446aa
[ "MIT" ]
519
2015-06-23T08:44:54.000Z
2022-03-31T15:44:15.000Z
lib/provider/camunda/parts/implementation/External.js
prithviraj-maurya/bpmn-js-properties-panel
ffc99ae13a1e7b8381cb57a91e8c4fb3950446aa
[ "MIT" ]
200
2015-07-08T07:14:29.000Z
2022-03-23T03:55:41.000Z
'use strict'; var entryFactory = require('../../../../factory/EntryFactory'), cmdHelper = require('../../../../helper/CmdHelper'); module.exports = function(element, bpmnFactory, options, translate) { var getImplementationType = options.getImplementationType, getBusinessObject = options.getBusinessObject; function isExternal(element) { return getImplementationType(element) === 'external'; } var topicEntry = entryFactory.textField(translate, { id: 'externalTopic', label: translate('Topic'), modelProperty: 'externalTopic', get: function(element, node) { var bo = getBusinessObject(element); return { externalTopic: bo.get('camunda:topic') }; }, set: function(element, values, node) { var bo = getBusinessObject(element); return cmdHelper.updateBusinessObject(element, bo, { 'camunda:topic': values.externalTopic }); }, validate: function(element, values, node) { return isExternal(element) && !values.externalTopic ? { externalTopic: translate('Must provide a value') } : {}; }, hidden: function(element, node) { return !isExternal(element); } }); return [ topicEntry ]; };
26.888889
118
0.657851
8d63e095efdd2d8e8b88c45e2f82d20eb37e649a
2,705
js
JavaScript
ios/versioned-react-native/ABI32_0_0/Libraries/Core/Devtools/symbolicateStackTrace.js
ThakurKarthik/expo
ed78ed4f07c950184a59422ebd95645253f44e3d
[ "Apache-2.0", "MIT" ]
12
2019-04-08T17:10:41.000Z
2021-12-24T18:57:59.000Z
ios/versioned-react-native/ABI32_0_0/Libraries/Core/Devtools/symbolicateStackTrace.js
ThakurKarthik/expo
ed78ed4f07c950184a59422ebd95645253f44e3d
[ "Apache-2.0", "MIT" ]
19
2020-04-07T07:36:24.000Z
2022-03-26T09:32:12.000Z
ios/versioned-react-native/ABI32_0_0/Libraries/Core/Devtools/symbolicateStackTrace.js
ThakurKarthik/expo
ed78ed4f07c950184a59422ebd95645253f44e3d
[ "Apache-2.0", "MIT" ]
2
2019-05-04T06:30:20.000Z
2019-05-04T06:37:46.000Z
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ 'use strict'; const getDevServer = require('./getDevServer'); const {SourceCode} = require('../../BatchedBridge/NativeModules'); // Avoid requiring fetch on load of this module; see symbolicateStackTrace let fetch; import type {StackFrame} from './parseErrorStack'; function isSourcedFromDisk(sourcePath: string): boolean { return !/^http/.test(sourcePath) && /[\\/]/.test(sourcePath); } async function symbolicateStackTrace( stack: Array<StackFrame>, ): Promise<Array<StackFrame>> { // RN currently lazy loads whatwg-fetch using a custom fetch module, which, // when called for the first time, requires and re-exports 'whatwg-fetch'. // However, when a dependency of the project tries to require whatwg-fetch // either directly or indirectly, whatwg-fetch is required before // RN can lazy load whatwg-fetch. As whatwg-fetch checks // for a fetch polyfill before loading, it will in turn try to load // RN's fetch module, which immediately tries to import whatwg-fetch AGAIN. // This causes a circular require which results in RN's fetch module // exporting fetch as 'undefined'. // The fix below postpones trying to load fetch until the first call to symbolicateStackTrace. // At that time, we will have either global.fetch (whatwg-fetch) or RN's fetch. if (!fetch) { fetch = global.fetch || require('../../Network/fetch').fetch; } const devServer = getDevServer(); if (!devServer.bundleLoadedFromServer) { throw new Error('Bundle was not loaded from the packager'); } let stackCopy = stack; if (SourceCode.scriptURL) { let foundInternalSource: boolean = false; stackCopy = stack.map((frame: StackFrame) => { // If the sources exist on disk rather than appearing to come from the packager, // replace the location with the packager URL until we reach an internal source // which does not have a path (no slashes), indicating a switch from within // the application to a surrounding debugging environment. if (!foundInternalSource && isSourcedFromDisk(frame.file)) { // Copy frame into new object and replace 'file' property return {...frame, file: SourceCode.scriptURL}; } foundInternalSource = true; return frame; }); } const response = await fetch(devServer.url + 'symbolicate', { method: 'POST', body: JSON.stringify({stack: stackCopy}), }); const json = await response.json(); return json.stack; } module.exports = symbolicateStackTrace;
35.12987
96
0.704251
8d6498f45d2b9c4ee03b7299ff3a3cce1d441e9f
2,772
js
JavaScript
Script/JAX/sortable-tree.js
Jaxboards/Jaxboards
28bba7f621f3b00f83d6026ad23991d3d799079f
[ "MIT" ]
3
2018-08-26T05:01:04.000Z
2021-06-20T18:11:50.000Z
Script/JAX/sortable-tree.js
Jaxboards/Jaxboards
28bba7f621f3b00f83d6026ad23991d3d799079f
[ "MIT" ]
70
2018-08-01T23:44:05.000Z
2019-07-08T01:37:25.000Z
Script/JAX/sortable-tree.js
Jaxboards/Jaxboards
28bba7f621f3b00f83d6026ad23991d3d799079f
[ "MIT" ]
2
2018-09-14T03:28:42.000Z
2021-07-23T19:12:22.000Z
import Drag from './drag'; import { insertBefore, insertAfter, isChildOf } from './el'; function parsetree(tree, prefix) { const nodes = Array.from(tree.querySelectorAll('li')); const order = {}; let gotsomethin = 0; nodes.forEach(node => { if (node.className !== 'seperator' && node.parentNode === tree) { gotsomethin = 1; const [sub] = node.getElementsByTagName('ul'); order[`_${node.id.substr(prefix.length)}`] = sub !== undefined ? parsetree(sub, prefix) : 1; } }); return gotsomethin ? order : 1; } export default function(tree, prefix, formfield) { const listItems = Array.from(tree.querySelectorAll('li')); const items = []; const seperators = []; items.push(...listItems.filter(li => li.className !== 'title')); items.forEach(item => { const tmp = document.createElement('li'); tmp.className = 'seperator'; seperators.push(tmp); insertBefore(tmp, item); }); const drag = new Drag().noChildActivation(); drag.drops(seperators.concat(items)).addListener({ ondragover(a) { a.droptarget.style.border = '1px solid #000'; }, ondragout(a) { a.droptarget.style.border = 'none'; }, ondrop(a) { const next = a.droptarget.nextSibling; let tmp; const parentlock = a.el.className === 'parentlock'; const nofirstlevel = a.el.className === 'nofirstlevel'; if (a.droptarget) { a.droptarget.style.border = 'none'; } if (a.droptarget.className === 'seperator') { if (parentlock && a.droptarget.parentNode !== a.el.parentNode) { return drag.reset(a.el); } if (nofirstlevel && a.droptarget.parentNode.className === 'tree') { return drag.reset(a.el); } if (isChildOf(a.droptarget, a.el) || a.el === next) { return drag.reset(a.el); } if (next.className === 'spacer') { next.parentNode.removeChild(next); } if (next.className !== 'spacer') { insertAfter(a.el.previousSibling, a.droptarget); } else { a.el.previousSibling.parentNode.removeChild(a.el.previousSibling); } insertAfter(a.el, a.droptarget); } else if (!parentlock && a.droptarget.tagName === 'LI') { [tmp] = a.droptarget.getElementsByTagName('ul'); if (!tmp) { tmp = document.createElement('ul'); a.droptarget.appendChild(tmp); } tmp.appendChild(a.el.previousSibling); tmp.appendChild(a.el); a.droptarget.appendChild(tmp); } drag.reset(a.el); if (formfield) { formfield.value = JSON.stringify(parsetree(tree, prefix)); } return null; } }); items.forEach(item => drag.apply(item)); }
31.5
76
0.588745
8d64a2e5ac3d3022066c33d7d63fd4b4b89a0921
801
js
JavaScript
server.js
rafin-rahman/portal-esl
4eb14416a8aa2a4485179e5dd5c8507cf0581841
[ "MIT" ]
1
2021-03-30T23:48:17.000Z
2021-03-30T23:48:17.000Z
server.js
ElizabethSchoolofLondon/portal
4eb14416a8aa2a4485179e5dd5c8507cf0581841
[ "MIT" ]
3
2021-02-28T16:15:27.000Z
2021-03-24T15:06:19.000Z
server.js
ElizabethSchoolofLondon/portal
4eb14416a8aa2a4485179e5dd5c8507cf0581841
[ "MIT" ]
4
2021-02-04T13:04:30.000Z
2021-03-25T11:50:10.000Z
const express = require('express') const connectDB = require('./config/db') const app = express() // Connect database connectDB() // Init Middleware app.use(express.json({ extended: false })) // Test get request app.get('/', (req, res) => res.send('API Running')) // Routes app.use('/api/auth', require('./routes/api/auth')) app.use('/api/clients', require('./routes/api/clients')) app.use('/api/sfe', require('./routes/api/sfe')) app.use('/api/university', require('./routes/api/university')) app.use('/api/course', require('./routes/api/course')) app.use('/api/users', require('./routes/api/users')) // If there's no environment, it runs on port 5000 const PORT = process.env.PORT || 5000 // Callback once it connects to the PORT app.listen(PORT, () => console.log(`Server started on ${PORT}`))
32.04
64
0.679151
8d64d9286497c5ab43c83eefd047f91ffe35ba5a
158
js
JavaScript
docs/doxygen/html/search/classes_7.js
kost13/cars-evolution
2e95fdd17d4a4ff9b18f0c0b919808cb69fb4d02
[ "MIT" ]
null
null
null
docs/doxygen/html/search/classes_7.js
kost13/cars-evolution
2e95fdd17d4a4ff9b18f0c0b919808cb69fb4d02
[ "MIT" ]
null
null
null
docs/doxygen/html/search/classes_7.js
kost13/cars-evolution
2e95fdd17d4a4ff9b18f0c0b919808cb69fb4d02
[ "MIT" ]
null
null
null
var searchData= [ ['randomgenerator',['RandomGenerator',['../db/dd6/classcer_1_1evolution_1_1math_1_1_random_generator.html',1,'cer::evolution::math']]] ];
31.6
136
0.753165
8d6640e2178171faa60cc3196f89e7a6a6a3bc6d
3,101
js
JavaScript
server/router/User/Insert/SubmitInsert.js
asyncfinkd/quiz
064762c0b2ed552c23c3c9955896607d7dca5bd1
[ "MIT" ]
27
2021-03-31T19:41:09.000Z
2022-03-08T12:05:41.000Z
server/router/User/Insert/SubmitInsert.js
asyncfinkd/quiz
064762c0b2ed552c23c3c9955896607d7dca5bd1
[ "MIT" ]
21
2021-05-03T07:39:29.000Z
2021-09-01T21:26:10.000Z
server/router/User/Insert/SubmitInsert.js
asyncfinkd/quiz
064762c0b2ed552c23c3c9955896607d7dca5bd1
[ "MIT" ]
2
2021-05-03T07:51:30.000Z
2021-05-03T07:52:17.000Z
const router = require("express").Router(); const UserSubmitSchema = require("../../../schema/User/SubmitUser"); const nodemailer = require("nodemailer"); const env = require("../../../env.json"); router.route("/insertSubmitUser").post(async (req, res) => { const result = req.body.result; const points = req.body.points; const identifyPoints = []; // first section if (points[0].extravert >= points[0].introvert) { identifyPoints.push("Extravert"); } else if (points[0].extravert <= points[0].introvert) { identifyPoints.push("Introvert"); } // second section if (points[0].sensing >= points[0].intuitive) { identifyPoints.push("Sensing"); } else if (points[0].sensing <= points[0].intuitive) { identifyPoints.push("Intuitive"); } // third section if (points[0].rational >= points[0].feeling) { identifyPoints.push("Rational"); } else if (points[0].rational <= points[0].feeling) { identifyPoints.push("Feeling"); } // four section if (points[0].reasonable >= points[0].spontaneous) { identifyPoints.push("Reasonable"); } else if (points[0].reasonable <= points[0].spontaneous) { identifyPoints.push("Spontaneous"); } let mailList = [ `od@deeptan.com.ua`, `mickey@kkc-group.com`, `zuckdeveloper@gmail.com`, ]; const firstElementSplit = identifyPoints[0][0].toLocaleLowerCase(); if (identifyPoints[1][0].toLocaleLowerCase() == "s") { var secondElementSplit = "s"; } else if (identifyPoints[1][0].toLocaleLowerCase() == "i") { var secondElementSplit = "n"; } if (identifyPoints[2][0].toLocaleLowerCase() == "r") { var thirdElementSplit = "t"; } else if (identifyPoints[2][0].toLowerCase() == "f") { var thirdElementSplit = "f"; } if (identifyPoints[3][0].toLowerCase() == "r") { var fourElementSplit = "j"; } else if (identifyPoints[3][0].toLowerCase() == "s") { var fourElementSplit = "p"; } var fullElementSplited = firstElementSplit + secondElementSplit + thirdElementSplit + fourElementSplit; const renderAttachment = []; renderAttachment.push({ filename: `${fullElementSplited.toUpperCase()}.docx`, path: `./router/User/Insert/path/${fullElementSplited.toUpperCase()}.docx`, }); let transporter = nodemailer.createTransport({ service: "gmail", auth: { user: `${env.user}`, pass: `${env.pass}`, }, }); let mailOptions = { from: `${env.user}`, to: mailList, subject: "Result", text: ` Hello, This is your Result: ${result.map((item) => { return "Question: " + item.question + "\n" + "Answer: " + item.value + "\n"; })} Status: ${identifyPoints.map((item) => { return item; })}`, attachments: renderAttachment, }; transporter.sendMail(mailOptions, function (err, data) { if (err) { console.log("error occurs: ", err); } else { console.log("email sent"); } }); const insertUserSchema = new UserSubmitSchema({ result: result, points: points, }); insertUserSchema.save(); res.json("insert"); }); module.exports = router;
27.936937
79
0.629797
8d66a81750e3046146d4f924b850c72d7e8fe7ac
296
js
JavaScript
src/views/Sections/index.js
offmausam/patchchain
774e53c8e2b4f528fc7cb661ef20fe9a5a46db48
[ "MIT" ]
null
null
null
src/views/Sections/index.js
offmausam/patchchain
774e53c8e2b4f528fc7cb661ef20fe9a5a46db48
[ "MIT" ]
null
null
null
src/views/Sections/index.js
offmausam/patchchain
774e53c8e2b4f528fc7cb661ef20fe9a5a46db48
[ "MIT" ]
null
null
null
export { default as Roadmap } from "./Roadmap"; export { default as FAQ } from "./FAQ"; export { default as Portfolio } from "./Portfolio"; export { default as Technology } from "./Technology"; export { default as Tokenomics } from "./Tokenomics"; export { default as Clients } from "./Clients";
42.285714
53
0.695946
8d66d675f302c2ada6a38fafc3a79c93fa206592
1,625
js
JavaScript
www/map.js
proller/leaftest
a470106c84d9132365cdde08f00389d46a588beb
[ "MIT" ]
null
null
null
www/map.js
proller/leaftest
a470106c84d9132365cdde08f00389d46a588beb
[ "MIT" ]
null
null
null
www/map.js
proller/leaftest
a470106c84d9132365cdde08f00389d46a588beb
[ "MIT" ]
null
null
null
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var config = JSON.parse(xmlhttp.responseText); loadmap(config); } } xmlhttp.open("GET", "conf.json", true); xmlhttp.overrideMimeType("application/json"); //to silence browser warnings when started without a server xmlhttp.send(); function loadmap(config) { var mapsize = config.mapsize; var spawn = config.spawn; var zoommin = config.zoommin; var xb= 0-spawn.x+mapsize/2; var yb= 0-spawn.y-mapsize/2-256; var bnd = new L.LatLngBounds(); bnd.extend(L.latLng([spawn.x-mapsize/2, spawn.y-mapsize/2])); bnd.extend(L.latLng([spawn.x+mapsize/2, spawn.y+mapsize/2])); var map = L.map('map', { maxZoom:26, minZoom:zoommin, maxNativeZoom:20, fullscreenControl: true, //maxBounds: bnd, //commented out until it works... crs: /*L.CRS.Simple*/L.extend({}, L.CRS, { projection: { project: function (latlng) { return new L.Point(latlng.lat+xb, latlng.lng+yb); }, unproject: function (point) { return new L.LatLng(point.x-xb, point.y-yb); } }, transformation: new L.Transformation(1, 0, -1, 0), scale: function (zoom) { return Math.pow(2, zoom-20); } }) }).setView([0,0], 22); map.setView([spawn.x,spawn.y]); L.tileLayer('tiles/{z}/map_{x}_{y}.png', { maxZoom: 26, maxNativeZoom: 20, tileSize: 256, continuousWorld: true }).addTo(map); map.on('mousemove click', function(e) { window.mousemove.innerHTML = e.latlng.lat.toFixed(1) + ', ' + e.latlng.lng.toFixed(1); }); var hash = L.hash(map); }
29.017857
105
0.652308
8d66dc7c37d27cf5b3534e9e617a905cf84e87b5
1,925
js
JavaScript
owncloud/apps/firstrunwizard/l10n/ru.js
ay1741/ay1741.github.io
3021c6814c228a3c9487cd4d5632f5cdb65f4b18
[ "Apache-2.0" ]
null
null
null
owncloud/apps/firstrunwizard/l10n/ru.js
ay1741/ay1741.github.io
3021c6814c228a3c9487cd4d5632f5cdb65f4b18
[ "Apache-2.0" ]
null
null
null
owncloud/apps/firstrunwizard/l10n/ru.js
ay1741/ay1741.github.io
3021c6814c228a3c9487cd4d5632f5cdb65f4b18
[ "Apache-2.0" ]
null
null
null
OC.L10N.register( "firstrunwizard", { "Welcome to %s" : "Добро пожаловать в %s", "Your personal web services. All your files, contacts, calendar and more, in one place." : "Ваши персональные веб сервисы. Все файлы, контакты, календарь и многое другое в одном месте.", "Get the apps to sync your files" : "Получить приложения для синхронизации ваших файлов", "Desktop client" : "Клиент для ПК", "Android app" : "Android приложение", "iOS app" : "iOS приложение", "Connect your desktop apps to %s" : "Подключите приложения с компьютера к %s", "Connect your Calendar" : "Подключите свой календарь", "Connect your Contacts" : "Подключите свои контакты", "Access files via WebDAV" : "Доступ к файлам через WebDAV", "Documentation" : "Документация", "There’s more information in the <a target=\"_blank\" href=\"%s\">documentation</a> and on our <a target=\"_blank\" href=\"http://owncloud.org\">website</a>." : "Более подробная информация в <a target=\"_blank\" href=\"%s\">документации</a> и на нашем <a target=\"_blank\" href=\"http://owncloud.org\">сайте</a>.", "If you like ownCloud,\n\t<a href=\"mailto:?subject=ownCloud\n\t\t&body=ownCloud is a great open software to sync and share your files. \n\t\tYou can freely get it from http://owncloud.org\">\n\t\trecommend it to your friends</a>\n\tand <a href=\"http://owncloud.org/promote\"\n\t\ttarget=\"_blank\">spread the word</a>!" : "Если Вам нравится ownCloud,\n\t<a href=\"mailto:?subject=ownCloud\n\t\t&body=ownCloud – открытое программное обеспечение для синхронизации и совместного использования ваших файлов. \n\t\tВы можете скачать его бесплатно на http://owncloud.org\">\n\t\tпорекомендуйте его друзьям</a>\n\tи <a href=\"http://owncloud.org/promote\"\n\t\ttarget=\"_blank\">расскажите всем</a>!" }, "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);");
101.315789
699
0.684675
8d66ea9d67c76c0274fedaf53bb1666e59390d63
207
js
JavaScript
tests/test262/15.2/15.2.3/15.2.3.3/15.2.3.3-2-23.js
aliahsan07/safe-development
542e4ebe5142912ad212a8517051462633bede2c
[ "BSD-3-Clause" ]
2
2021-11-25T12:53:02.000Z
2022-02-01T23:29:49.000Z
tests/test262/15.2/15.2.3/15.2.3.3/15.2.3.3-2-23.js
aliahsan07/safe-development
542e4ebe5142912ad212a8517051462633bede2c
[ "BSD-3-Clause" ]
null
null
null
tests/test262/15.2/15.2.3/15.2.3.3/15.2.3.3-2-23.js
aliahsan07/safe-development
542e4ebe5142912ad212a8517051462633bede2c
[ "BSD-3-Clause" ]
1
2021-06-03T21:38:53.000Z
2021-06-03T21:38:53.000Z
function testcase() { var obj = { "1e-7" : 1 }; var desc = Object.getOwnPropertyDescriptor(obj, 0.0000001); return desc.value === 1; } { var __result1 = testcase(); var __expect1 = true; }
14.785714
61
0.608696
8d671f837335952b71103ab8dafe09d8d59f9841
1,814
js
JavaScript
components/Header.js
vaibhavdighole06/Smart_Contract_Management
ec5aa800ad009a9e69e20854c1b8846f21c181fe
[ "MIT" ]
null
null
null
components/Header.js
vaibhavdighole06/Smart_Contract_Management
ec5aa800ad009a9e69e20854c1b8846f21c181fe
[ "MIT" ]
1
2021-08-13T02:49:37.000Z
2021-08-13T02:49:37.000Z
components/Header.js
vaibhavdighole06/Smart_Contract_Management
ec5aa800ad009a9e69e20854c1b8846f21c181fe
[ "MIT" ]
null
null
null
import React,{Component} from 'react'; import {Menu,Button} from 'semantic-ui-react'; import {Link} from '../routes'; import web3 from '../ethereum/web3'; import {Router} from '../routes'; class Header extends Component{ clickMeToView=async event=> { var accounts; var add; Promise.all( accounts= await web3.eth.getAccounts(), add=accounts[0] ); Router.pushRoute(`/AssignedToMe/${add}`); } clickMe=async event=> { var accounts; var add; Promise.all( accounts= await web3.eth.getAccounts(), add=accounts[0] ); Router.pushRoute(`/${add}`); } clickAll=async event=> { var accounts; var add; Promise.all( accounts= await web3.eth.getAccounts(), add=accounts[0] ); Router.pushRoute(`/All/${add}`); } clickViewProfile=async event=> { var accounts; var add; Promise.all( accounts= await web3.eth.getAccounts(), add=accounts[0] ); Router.pushRoute(`/showProfiles/${add}`); } render(){ return ( <Menu style={{marginTop:'10px'}}> <Link route="/"> <a className="item"> SSV_Contracts </a> </Link> <Menu.Menu position="right"> <Button className="item" onClick={this.clickMeToView} content="Assigned" primary /> <Button className="item" onClick={this.clickMe} content="Created" primary /> <Button className="item" onClick={this.clickAll} content="All" primary /> <Button className="item" onClick={this.clickViewProfile} content="View Profiles" primary /> <Link route="/"> <a className="item"> Global Contracts </a> </Link> <Link route="/contracts/new"> <a className="item"> + </a> </Link> </Menu.Menu> </Menu> )} } export default Header;
21.855422
60
0.596472
8d67b6d2029788e0d587dc15a15b179d6a38cc67
1,609
js
JavaScript
src/app.js
marcusthelin/slack-gitlab-unfurler
f978e47688355e85111622ea1acd70ed7fa0a06f
[ "MIT" ]
null
null
null
src/app.js
marcusthelin/slack-gitlab-unfurler
f978e47688355e85111622ea1acd70ed7fa0a06f
[ "MIT" ]
null
null
null
src/app.js
marcusthelin/slack-gitlab-unfurler
f978e47688355e85111622ea1acd70ed7fa0a06f
[ "MIT" ]
null
null
null
const express = require('express'); const { isEmpty } = require('lodash'); const { reduce } = require('async'); const getDataFromUrl = require('./helpers/extract-data-from-url'); const bot = require('./helpers/bot'); const app = express(); const unfurlHandlers = { merge_requests: require('./handlers/merge-requests'), pipelines: require('./handlers/pipelines'), }; app.use(express.json()); app.post('/unfurl', async (req, res) => { /** * If body has a challenge field we just want to return * that data. This is a verifaction process from Slack. */ if (req.body.challenge) { return res.send(req.body.challenge); } const { links = [] } = req.body.event; const { event } = req.body; const unfurlData = {}; for await (const link of links) { const urlData = getDataFromUrl(link.url); if (!urlData) { return; } const { projectFullPath, type, id, rest } = urlData; const handler = unfurlHandlers[type]; let unfurlBlocks; if (handler) { unfurlBlocks = await handler(projectFullPath, id, rest); unfurlData[link.url] = { blocks: unfurlBlocks }; } } if (!isEmpty(unfurlData)) { await bot.chat .unfurl({ channel: event.channel, ts: event.message_ts, unfurls: unfurlData, }) .catch(console.log); } res.status(500); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is listening on port ${port}`); });
26.377049
68
0.573027
8d68486554f9df88a151b959ec5469d9d9b015d6
775
js
JavaScript
src/assets/theme-dark/components/stepper/index.js
NaveedAhmad0/Danerob-admin-panel
f7536276175f884e039db36071fb5727b2653763
[ "MIT" ]
null
null
null
src/assets/theme-dark/components/stepper/index.js
NaveedAhmad0/Danerob-admin-panel
f7536276175f884e039db36071fb5727b2653763
[ "MIT" ]
null
null
null
src/assets/theme-dark/components/stepper/index.js
NaveedAhmad0/Danerob-admin-panel
f7536276175f884e039db36071fb5727b2653763
[ "MIT" ]
null
null
null
import colors from "assets/theme-dark/base/colors"; import borders from "assets/theme-dark/base/borders"; import boxShadows from "assets/theme-dark/base/boxShadows"; import pxToRem from "assets/theme-dark/functions/pxToRem"; import linearGradient from "assets/theme-dark/functions/linearGradient"; const { transparent, gradients } = colors; const { borderRadius } = borders; const { colored } = boxShadows; const stepper = { styleOverrides: { root: { background: linearGradient(gradients.info.main, gradients.info.state), padding: `${pxToRem(24)} 0 ${pxToRem(16)}`, borderRadius: borderRadius.lg, boxShadow: colored.info, "&.MuiPaper-root": { backgroundColor: transparent.main, }, }, }, }; export default stepper;
27.678571
76
0.700645
8d68862b476ab258579ce5bc3ba16f97d22c75eb
5,638
js
JavaScript
packages/wdio-devtools-service/src/auditor.js
nkyazhin/webdriverio
199d36e09a527a0ebbede92ed750185378051d09
[ "MIT" ]
1
2021-01-27T10:25:15.000Z
2021-01-27T10:25:15.000Z
packages/wdio-devtools-service/src/auditor.js
nkyazhin/webdriverio
199d36e09a527a0ebbede92ed750185378051d09
[ "MIT" ]
null
null
null
packages/wdio-devtools-service/src/auditor.js
nkyazhin/webdriverio
199d36e09a527a0ebbede92ed750185378051d09
[ "MIT" ]
null
null
null
import Diagnostics from 'lighthouse/lighthouse-core/audits/diagnostics' import MainThreadWorkBreakdown from 'lighthouse/lighthouse-core/audits/mainthread-work-breakdown' import Metrics from 'lighthouse/lighthouse-core/audits/metrics' import ServerResponseTime from 'lighthouse/lighthouse-core/audits/server-response-time' import CumulativeLayoutShift from 'lighthouse/lighthouse-core/audits/metrics/cumulative-layout-shift' import FirstContentfulPaint from 'lighthouse/lighthouse-core/audits/metrics/first-contentful-paint' import LargestContentfulPaint from 'lighthouse/lighthouse-core/audits/metrics/largest-contentful-paint' import SpeedIndex from 'lighthouse/lighthouse-core/audits/metrics/speed-index' import InteractiveMetric from 'lighthouse/lighthouse-core/audits/metrics/interactive' import TotalBlockingTime from 'lighthouse/lighthouse-core/audits/metrics/total-blocking-time' import ReportScoring from 'lighthouse/lighthouse-core/scoring' import defaultConfig from 'lighthouse/lighthouse-core/config/default-config' import logger from '@wdio/logger' const log = logger('@wdio/devtools-service:Auditor') const SHARED_AUDIT_CONTEXT = { settings: { throttlingMethod: 'devtools' }, LighthouseRunWarnings: false, computedCache: new Map() } export default class Auditor { constructor (traceLogs, devtoolsLogs) { this.devtoolsLogs = devtoolsLogs this.traceLogs = traceLogs this.url = traceLogs.pageUrl this.loaderId = traceLogs.loaderId } _audit (AUDIT, params = {}) { const auditContext = { options: { ...AUDIT.defaultOptions }, ...SHARED_AUDIT_CONTEXT } try { return AUDIT.audit({ traces: { defaultPass: this.traceLogs }, devtoolsLogs: { defaultPass: this.devtoolsLogs }, TestedAsMobileDevice: true, ...params }, auditContext) } catch (e) { log.error(e) return {} } } /** * an Auditor instance is created for every trace so provide an updateCommands * function to receive the latest performance metrics with the browser instance */ updateCommands (browser, customFn) { const commands = Object.getOwnPropertyNames(Object.getPrototypeOf(this)).filter( fnName => fnName !== 'constructor' && fnName !== 'updateCommands' && !fnName.startsWith('_')) commands.forEach(fnName => browser.addCommand(fnName, customFn || ::this[fnName])) } async getMainThreadWorkBreakdown () { const result = await this._audit(MainThreadWorkBreakdown) return result.details.items.map( ({ group, duration }) => ({ group, duration }) ) } async getDiagnostics () { const result = await this._audit(Diagnostics) /** * return null if Audit fails */ if (!Object.prototype.hasOwnProperty.call(result, 'details')) { return null } return result.details.items[0] } async getMetrics () { const serverResponseTime = await this._audit(ServerResponseTime, { URL: this.url }) const result = await this._audit(Metrics) const metrics = result.details.items[0] || {} return { estimatedInputLatency: metrics.estimatedInputLatency, /** * keeping TTFB for backwards compatibility */ timeToFirstByte: Math.round(serverResponseTime.numericValue, 10), serverResponseTime: Math.round(serverResponseTime.numericValue, 10), domContentLoaded: metrics.observedDomContentLoaded, firstVisualChange: metrics.observedFirstVisualChange, firstPaint: metrics.observedFirstPaint, firstContentfulPaint: metrics.firstContentfulPaint, firstMeaningfulPaint: metrics.firstMeaningfulPaint, largestContentfulPaint: metrics.largestContentfulPaint, lastVisualChange: metrics.observedLastVisualChange, firstCPUIdle: metrics.firstCPUIdle, firstInteractive: metrics.interactive, load: metrics.observedLoad, speedIndex: metrics.speedIndex, totalBlockingTime: metrics.totalBlockingTime, cumulativeLayoutShift: metrics.cumulativeLayoutShift, } } async getPerformanceScore() { const auditResults = {} auditResults['speed-index'] = await this._audit(SpeedIndex) auditResults['first-contentful-paint'] = await this._audit(FirstContentfulPaint) auditResults['largest-contentful-paint'] = await this._audit(LargestContentfulPaint) auditResults['cumulative-layout-shift'] = await this._audit(CumulativeLayoutShift) auditResults['total-blocking-time'] = await this._audit(TotalBlockingTime) auditResults.interactive = await this._audit(InteractiveMetric) if (!auditResults.interactive || !auditResults['cumulative-layout-shift'] || !auditResults['first-contentful-paint'] || !auditResults['largest-contentful-paint'] || !auditResults['speed-index'] || !auditResults['total-blocking-time']) { log.info('One or multiple required metrics couldn\'t be found, setting performance score to: null') return null } const scores = defaultConfig.categories.performance.auditRefs.filter((auditRef) => auditRef.weight).map((auditRef) => ({ score: auditResults[auditRef.id].score, weight: auditRef.weight, })) return ReportScoring.arithmeticMean(scores) } }
43.705426
128
0.678609
8d6925cd207190473c8513045a45df1acd69bb7f
2,668
js
JavaScript
src/pages/Account/Settings/GeographicView.js
mannguyen1102/ant
38127877d4a94a6b2e409cb4c89e9a10d613d8dc
[ "MIT" ]
8
2018-10-31T02:11:42.000Z
2021-01-08T07:36:00.000Z
src/pages/Account/Settings/GeographicView.js
mannguyen1102/ant
38127877d4a94a6b2e409cb4c89e9a10d613d8dc
[ "MIT" ]
2
2018-11-15T16:23:13.000Z
2018-11-16T21:01:47.000Z
src/pages/Account/Settings/GeographicView.js
mannguyen1102/ant
38127877d4a94a6b2e409cb4c89e9a10d613d8dc
[ "MIT" ]
2
2019-05-05T02:54:08.000Z
2020-03-11T17:00:29.000Z
import React, { PureComponent } from 'react'; import { Select, Spin } from 'antd'; import { connect } from 'dva'; import styles from './GeographicView.less'; const { Option } = Select; const nullSlectItem = { label: '', key: '', }; export default @connect(({ geographic }) => { const { province, isLoading, city } = geographic; return { province, city, isLoading, }; }) class GeographicView extends PureComponent { componentDidMount = () => { const { dispatch } = this.props; dispatch({ type: 'geographic/fetchProvince', }); }; componentDidUpdate(props) { const { dispatch, value } = this.props; if (!props.value && !!value && !!value.province) { dispatch({ type: 'geographic/fetchCity', payload: value.province.key, }); } } getProvinceOption() { const { province } = this.props; return this.getOption(province); } getCityOption = () => { const { city } = this.props; return this.getOption(city); }; getOption = list => { if (!list || list.length < 1) { return ( <Option key={0} value={0}> 没有找到选项 </Option> ); } return list.map(item => ( <Option key={item.id} value={item.id}> {item.name} </Option> )); }; selectProvinceItem = item => { const { dispatch, onChange } = this.props; dispatch({ type: 'geographic/fetchCity', payload: item.key, }); onChange({ province: item, city: nullSlectItem, }); }; selectCityItem = item => { const { value, onChange } = this.props; onChange({ province: value.province, city: item, }); }; conversionObject() { const { value } = this.props; if (!value) { return { province: nullSlectItem, city: nullSlectItem, }; } const { province, city } = value; return { province: province || nullSlectItem, city: city || nullSlectItem, }; } render() { const { province, city } = this.conversionObject(); const { isLoading } = this.props; return ( <Spin spinning={isLoading} wrapperClassName={styles.row}> <Select className={styles.item} value={province} labelInValue showSearch onSelect={this.selectProvinceItem} > {this.getProvinceOption()} </Select> <Select className={styles.item} value={city} labelInValue showSearch onSelect={this.selectCityItem} > {this.getCityOption()} </Select> </Spin> ); } }
20.84375
63
0.546852
8d69531ded23d8ecf2181920c90a3314d9439ae2
10,053
js
JavaScript
dist_org/service/service.module.js
retailinco/vendure-core
9b76db5a795c9b14649047661c35e61fd9f6712f
[ "MIT" ]
null
null
null
dist_org/service/service.module.js
retailinco/vendure-core
9b76db5a795c9b14649047661c35e61fd9f6712f
[ "MIT" ]
null
null
null
dist_org/service/service.module.js
retailinco/vendure-core
9b76db5a795c9b14649047661c35e61fd9f6712f
[ "MIT" ]
null
null
null
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var ServiceModule_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.ServiceModule = exports.ServiceCoreModule = void 0; const common_1 = require("@nestjs/common"); const typeorm_1 = require("@nestjs/typeorm"); const cache_module_1 = require("../cache/cache.module"); const config_module_1 = require("../config/config.module"); const config_service_1 = require("../config/config.service"); const typeorm_logger_1 = require("../config/logger/typeorm-logger"); const event_bus_module_1 = require("../event-bus/event-bus.module"); const job_queue_module_1 = require("../job-queue/job-queue.module"); const active_order_service_1 = require("./helpers/active-order/active-order.service"); const config_arg_service_1 = require("./helpers/config-arg/config-arg.service"); const custom_field_relation_service_1 = require("./helpers/custom-field-relation/custom-field-relation.service"); const external_authentication_service_1 = require("./helpers/external-authentication/external-authentication.service"); const fulfillment_state_machine_1 = require("./helpers/fulfillment-state-machine/fulfillment-state-machine"); const list_query_builder_1 = require("./helpers/list-query-builder/list-query-builder"); const locale_string_hydrator_1 = require("./helpers/locale-string-hydrator/locale-string-hydrator"); const order_calculator_1 = require("./helpers/order-calculator/order-calculator"); const order_merger_1 = require("./helpers/order-merger/order-merger"); const order_modifier_1 = require("./helpers/order-modifier/order-modifier"); const order_state_machine_1 = require("./helpers/order-state-machine/order-state-machine"); const password_cipher_1 = require("./helpers/password-cipher/password-cipher"); const payment_state_machine_1 = require("./helpers/payment-state-machine/payment-state-machine"); const refund_state_machine_1 = require("./helpers/refund-state-machine/refund-state-machine"); const shipping_calculator_1 = require("./helpers/shipping-calculator/shipping-calculator"); const slug_validator_1 = require("./helpers/slug-validator/slug-validator"); const translatable_saver_1 = require("./helpers/translatable-saver/translatable-saver"); const verification_token_generator_1 = require("./helpers/verification-token-generator/verification-token-generator"); const initializer_service_1 = require("./initializer.service"); const administrator_service_1 = require("./services/administrator.service"); const asset_service_1 = require("./services/asset.service"); const auth_service_1 = require("./services/auth.service"); const channel_service_1 = require("./services/channel.service"); const collection_service_1 = require("./services/collection.service"); const country_service_1 = require("./services/country.service"); const customer_group_service_1 = require("./services/customer-group.service"); const customer_service_1 = require("./services/customer.service"); const facet_value_service_1 = require("./services/facet-value.service"); const facet_service_1 = require("./services/facet.service"); const fulfillment_service_1 = require("./services/fulfillment.service"); const global_settings_service_1 = require("./services/global-settings.service"); const history_service_1 = require("./services/history.service"); const order_testing_service_1 = require("./services/order-testing.service"); const order_service_1 = require("./services/order.service"); const payment_method_service_1 = require("./services/payment-method.service"); const payment_service_1 = require("./services/payment.service"); const product_option_group_service_1 = require("./services/product-option-group.service"); const product_option_service_1 = require("./services/product-option.service"); const product_variant_service_1 = require("./services/product-variant.service"); const product_service_1 = require("./services/product.service"); const promotion_service_1 = require("./services/promotion.service"); const role_service_1 = require("./services/role.service"); const search_service_1 = require("./services/search.service"); const session_service_1 = require("./services/session.service"); const shipping_method_service_1 = require("./services/shipping-method.service"); const stock_movement_service_1 = require("./services/stock-movement.service"); const tag_service_1 = require("./services/tag.service"); const tax_category_service_1 = require("./services/tax-category.service"); const tax_rate_service_1 = require("./services/tax-rate.service"); const user_service_1 = require("./services/user.service"); const zone_service_1 = require("./services/zone.service"); const transactional_connection_1 = require("./transaction/transactional-connection"); const services = [ administrator_service_1.AdministratorService, asset_service_1.AssetService, auth_service_1.AuthService, channel_service_1.ChannelService, collection_service_1.CollectionService, country_service_1.CountryService, customer_group_service_1.CustomerGroupService, customer_service_1.CustomerService, facet_service_1.FacetService, facet_value_service_1.FacetValueService, fulfillment_service_1.FulfillmentService, global_settings_service_1.GlobalSettingsService, history_service_1.HistoryService, order_service_1.OrderService, order_testing_service_1.OrderTestingService, payment_service_1.PaymentService, payment_method_service_1.PaymentMethodService, product_option_group_service_1.ProductOptionGroupService, product_option_service_1.ProductOptionService, product_service_1.ProductService, product_variant_service_1.ProductVariantService, promotion_service_1.PromotionService, role_service_1.RoleService, search_service_1.SearchService, session_service_1.SessionService, shipping_method_service_1.ShippingMethodService, stock_movement_service_1.StockMovementService, tag_service_1.TagService, tax_category_service_1.TaxCategoryService, tax_rate_service_1.TaxRateService, user_service_1.UserService, zone_service_1.ZoneService, ]; const helpers = [ translatable_saver_1.TranslatableSaver, password_cipher_1.PasswordCipher, order_calculator_1.OrderCalculator, order_state_machine_1.OrderStateMachine, fulfillment_state_machine_1.FulfillmentStateMachine, order_merger_1.OrderMerger, order_modifier_1.OrderModifier, payment_state_machine_1.PaymentStateMachine, list_query_builder_1.ListQueryBuilder, shipping_calculator_1.ShippingCalculator, verification_token_generator_1.VerificationTokenGenerator, refund_state_machine_1.RefundStateMachine, config_arg_service_1.ConfigArgService, slug_validator_1.SlugValidator, external_authentication_service_1.ExternalAuthenticationService, transactional_connection_1.TransactionalConnection, custom_field_relation_service_1.CustomFieldRelationService, locale_string_hydrator_1.LocaleStringHydrator, active_order_service_1.ActiveOrderService, ]; let defaultTypeOrmModule; /** * The ServiceCoreModule is imported internally by the ServiceModule. It is arranged in this way so that * there is only a single instance of this module being instantiated, and thus the lifecycle hooks will * only run a single time. */ let ServiceCoreModule = class ServiceCoreModule { }; ServiceCoreModule = __decorate([ common_1.Module({ imports: [config_module_1.ConfigModule, event_bus_module_1.EventBusModule, cache_module_1.CacheModule, job_queue_module_1.JobQueueModule], providers: [...services, ...helpers, initializer_service_1.InitializerService], exports: [...services, ...helpers], }) ], ServiceCoreModule); exports.ServiceCoreModule = ServiceCoreModule; /** * The ServiceModule is responsible for the service layer, i.e. accessing the database * and implementing the main business logic of the application. * * The exported providers are used in the ApiModule, which is responsible for parsing requests * into a format suitable for the service layer logic. */ let ServiceModule = ServiceModule_1 = class ServiceModule { static forRoot() { if (!defaultTypeOrmModule) { defaultTypeOrmModule = typeorm_1.TypeOrmModule.forRootAsync({ imports: [config_module_1.ConfigModule], useFactory: (configService) => { const { dbConnectionOptions } = configService; const logger = ServiceModule_1.getTypeOrmLogger(dbConnectionOptions); return Object.assign(Object.assign({}, dbConnectionOptions), { logger }); }, inject: [config_service_1.ConfigService], }); } return { module: ServiceModule_1, imports: [defaultTypeOrmModule], }; } static forPlugin() { return { module: ServiceModule_1, imports: [typeorm_1.TypeOrmModule.forFeature()], }; } static getTypeOrmLogger(dbConnectionOptions) { if (!dbConnectionOptions.logger) { return new typeorm_logger_1.TypeOrmLogger(dbConnectionOptions.logging); } else { return dbConnectionOptions.logger; } } }; ServiceModule = ServiceModule_1 = __decorate([ common_1.Module({ imports: [ServiceCoreModule], exports: [ServiceCoreModule], }) ], ServiceModule); exports.ServiceModule = ServiceModule; //# sourceMappingURL=service.module.js.map
53.190476
150
0.763155
8d69baf0158cf7ff3590089bfdaee704d3f805a2
4,576
js
JavaScript
public/component---src-pages-404-js-64c2e5b2e75db97f8463.js
MadLabDesign/madlabcms
104cf50fb811ed3fca784c6c5486090d0a1f2b5c
[ "MIT" ]
null
null
null
public/component---src-pages-404-js-64c2e5b2e75db97f8463.js
MadLabDesign/madlabcms
104cf50fb811ed3fca784c6c5486090d0a1f2b5c
[ "MIT" ]
8
2021-03-09T08:18:28.000Z
2022-02-26T11:48:12.000Z
public/component---src-pages-404-js-64c2e5b2e75db97f8463.js
MadLabDesign/madlabcms
104cf50fb811ed3fca784c6c5486090d0a1f2b5c
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[3],{164:function(e,t,n){"use strict";n.r(t);var a=n(0),r=n.n(a),i=n(172),o=n(184),u=n(6),l=n.n(u),c=n(185),s=n.n(c);function d(e){var t=e.description,n=e.lang,a=e.meta,i=e.title,u=o.data.site,l=t||u.siteMetadata.description;return r.a.createElement(s.a,{htmlAttributes:{lang:n},title:i,titleTemplate:"%s | "+u.siteMetadata.title,meta:[{name:"description",content:l},{property:"og:title",content:i},{property:"og:description",content:l},{property:"og:type",content:"website"},{name:"twitter:card",content:"summary"},{name:"twitter:creator",content:u.siteMetadata.author},{name:"twitter:title",content:i},{name:"twitter:description",content:l}].concat(a)})}d.defaultProps={lang:"en",meta:[],description:""},d.propTypes={description:l.a.string,lang:l.a.string,meta:l.a.arrayOf(l.a.object),title:l.a.string.isRequired};var p=d;t.default=function(){return r.a.createElement(i.a,null,r.a.createElement(p,{title:"404: Not found"}),r.a.createElement("h1",null,"NOT FOUND"),r.a.createElement("p",null,"You just hit a route that doesn't exist... the sadness."))}},167:function(e,t,n){"use strict";n.d(t,"b",function(){return d});var a=n(0),r=n.n(a),i=n(6),o=n.n(i),u=n(40),l=n.n(u);n.d(t,"a",function(){return l.a});n(168);var c=r.a.createContext({});function s(e){var t=e.staticQueryData,n=e.data,a=e.query,i=e.render,o=n?n.data:t[a]&&t[a].data;return r.a.createElement(r.a.Fragment,null,o&&i(o),!o&&r.a.createElement("div",null,"Loading (StaticQuery)"))}var d=function(e){var t=e.data,n=e.query,a=e.render,i=e.children;return r.a.createElement(c.Consumer,null,function(e){return r.a.createElement(s,{data:t,query:n,render:a||i,staticQueryData:e})})};d.propTypes={data:o.a.object,query:o.a.string.isRequired,render:o.a.func,children:o.a.func}},168:function(e,t,n){var a;e.exports=(a=n(170))&&a.default||a},169:function(e){e.exports={data:{allWordpressWpApiMenusMenusItems:{edges:[{node:{name:"Main Menu",items:[{title:"Home",object_slug:"home"},{title:"Portfolio",object_slug:"portfolio"}]}}]}}}},170:function(e,t,n){"use strict";n.r(t);n(41);var a=n(0),r=n.n(a),i=n(6),o=n.n(i),u=n(64),l=function(e){var t=e.location,n=e.pageResources;return n?r.a.createElement(u.a,Object.assign({location:t,pageResources:n},n.json)):null};l.propTypes={location:o.a.shape({pathname:o.a.string.isRequired}).isRequired},t.default=l},171:function(e){e.exports={data:{allWordpressSiteMetadata:{edges:[{node:{name:"MadLab",description:"MadLab design portfolio"}}]}}}},172:function(e,t,n){"use strict";var a=n(165),r=n.n(a),i=n(0),o=n.n(i),u=n(169),l=n(167),c=n(166),s=(n(173),n(171));function d(){var e=r()(["\n flex-grow: 1;\n"]);return d=function(){return e},e}var p=c.b.div(d()),m=function(){return o.a.createElement(o.a.Fragment,null,o.a.createElement(l.b,{query:"3211208128",render:function(e){return o.a.createElement(p,null,o.a.createElement("div",null,e.allWordpressSiteMetadata.edges[0].node.name),o.a.createElement("div",null,e.allWordpressSiteMetadata.edges[0].node.description))},data:s}))};function f(){var e=r()(["\n color: #fff;\n padding: 0.8rem;\n display: block;\n text-decoration: none;\n"]);return f=function(){return e},e}function g(){var e=r()(["\n display: flex;\n background-color: #000;\n color: #fff;\n"]);return g=function(){return e},e}var y=c.b.div(g()),b=Object(c.b)(l.a)(f()),v=function(){return o.a.createElement(o.a.Fragment,null,o.a.createElement(l.b,{query:"548580337",render:function(e){return o.a.createElement(y,null,o.a.createElement(m,null),e.allWordpressWpApiMenusMenusItems.edges[0].node.items.map(function(e){return o.a.createElement(b,{to:e.object_slug,key:e.title},e.title)}))},data:u}))};n(174);function E(){var e=r()(["\n max-width: 960px;\n margin: 0 auto;\n"]);return E=function(){return e},e}function h(){var e=r()(["\n@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');\nbody{\n font-family: \"metropolis-regular\";\n margin: 0 !important;\n padding: 0 !important;\n\n}\n"]);return h=function(){return e},e}var w=Object(c.a)(h()),M=c.b.div(E());t.a=function(e){var t=e.children;return o.a.createElement(o.a.Fragment,null,o.a.createElement(w,null),o.a.createElement(v,null),o.a.createElement(M,null,t))}},184:function(e){e.exports={data:{site:{siteMetadata:{title:"Gatsby Default Starter",description:"Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.",author:"@gatsbyjs"}}}}}}]); //# sourceMappingURL=component---src-pages-404-js-64c2e5b2e75db97f8463.js.map
2,288
4,498
0.70979
ac63cba3213e47b504fb1bc9ebbf3658cbf76fb3
2,638
js
JavaScript
web-vue/src/utils/time.js
viliamjrb/drissi1990
df3b4e65a56dbc768b4ada3684f04150303246b1
[ "MIT" ]
1
2022-03-16T02:04:05.000Z
2022-03-16T02:04:05.000Z
web-vue/src/utils/time.js
viliamjrb/drissi1990
df3b4e65a56dbc768b4ada3684f04150303246b1
[ "MIT" ]
1
2022-03-01T08:42:28.000Z
2022-03-01T08:42:28.000Z
web-vue/src/utils/time.js
viliamjrb/drissi1990
df3b4e65a56dbc768b4ada3684f04150303246b1
[ "MIT" ]
null
null
null
/** * 转换时间函数 * @param {*} time * @param {*} cFormat */ export function parseTime(time, cFormat) { if (arguments.length === 0) { return "-"; } if (!time) { return "-"; } // 处理 time 参数 if (isNaN(Number(time)) === false) { time = Number(time); } const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}"; let date; if (typeof time === "object") { date = time; } else { if (("" + time).length === 10) time = parseInt(time) * 1000; date = new Date(time); } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay(), }; const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => { let value = formatObj[key]; // Note: getDay() returns 0 on Sunday if (key === "a") { return ["日", "一", "二", "三", "四", "五", "六"][value]; } if (result.length > 0 && value < 10) { value = "0" + value; } return value || 0; }); return time_str; } /** * 格式化文件大小 * @param {*} value * @returns */ export function renderSize(value) { if (null == value || value == "") { return "-"; } var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"); var index = 0; var srcsize = parseFloat(value); index = Math.floor(Math.log(srcsize) / Math.log(1024)); var size = srcsize / Math.pow(1024, index); size = size.toFixed(2); //保留的小数位数 return size + unitArr[index]; } // export function itemGroupBy(arr, groupKey, key, dataKey) { key = key || "type"; dataKey = dataKey || "data"; let newArr = [], types = {}, // newItem, i, j, cur; for (i = 0, j = arr.length; i < j; i++) { cur = arr[i]; if (!(cur[groupKey] in types)) { types[cur[groupKey]] = { [key]: cur[groupKey], [dataKey]: [] }; newArr.push(types[cur[groupKey]]); } types[cur[groupKey]][dataKey].push(cur); } return newArr; } /** * 格式化时长 * @param {String} ms * @param {String} seg 分割符 * @param {String} levelCount 格式化个数 * @returns */ export function formatDuration(ms, seg, levelCount) { if (isNaN(new Number(ms))) { return ms; } seg = seg || ""; levelCount = levelCount || 5; if (ms < 0) ms = -ms; const time = { 天: Math.floor(ms / 86400000), 小时: Math.floor(ms / 3600000) % 24, 分钟: Math.floor(ms / 60000) % 60, 秒: Math.floor(ms / 1000) % 60, 毫秒: Math.floor(ms) % 1000, }; return Object.entries(time) .filter((val) => val[1] !== 0) .map(([key, val]) => `${val}${key}`) .splice(0, levelCount) .join(seg); }
22.93913
83
0.530705
ac63d8221df9e67c5f1342074d1f7af979fbd9ff
1,800
js
JavaScript
js/views/HomeView.js
vincentbeaudoin/UMovie
02122bc358f52075394aaf89afa25a28227b87f7
[ "Apache-2.0" ]
null
null
null
js/views/HomeView.js
vincentbeaudoin/UMovie
02122bc358f52075394aaf89afa25a28227b87f7
[ "Apache-2.0" ]
null
null
null
js/views/HomeView.js
vincentbeaudoin/UMovie
02122bc358f52075394aaf89afa25a28227b87f7
[ "Apache-2.0" ]
null
null
null
define(['jquery', 'backbone', 'text!js/templates/HomeTemplate.html', 'slick', 'bootstrap'], function ($, Backbone, HomeTemplate) { var HomeView = Backbone.View.extend({ initialize: function () { this.template = HomeTemplate; }, el: '.page', events: { 'click .view-movie': 'viewMovie', 'click .view-tvshow': 'viewTvShow', 'click .view-actor': 'viewActor' }, viewMovie: function (ev) { ev.preventDefault(); var id = $(ev.currentTarget).data('movie-id'); Backbone.history.navigate('/movie/' + id, {trigger: true}); }, viewTvShow: function (event) { event.preventDefault(); var id = $(event.currentTarget).data('tvshow-id'); Backbone.history.navigate('/tvshow/' + id, {trigger: true}); }, viewActor: function (event) { var id = $(event.currentTarget).data('actor-id'); Backbone.history.navigate('/actor/' + id, {trigger: true}); }, render: function () { var self = this; $(self.el).html(self.template); $('.carousel').carousel({ interval: 5000 }); $('.multiple-items').slick({ infinite: true, slidesToShow: 4, slidesToScroll: 3, arrows: true, dots: true, centerMode: true, focusOnSelect: true, variableWidth: true }); } }); return HomeView; } );
36
91
0.435
ac63ee5bf02cee307b2fade12254d1247bd3e715
456
js
JavaScript
js/pages/services-page.js
wycka0214/16-grupe-personal
a18e69b34c8a9811c1ecde92f2fc34084f50cbaf
[ "MIT" ]
null
null
null
js/pages/services-page.js
wycka0214/16-grupe-personal
a18e69b34c8a9811c1ecde92f2fc34084f50cbaf
[ "MIT" ]
35
2020-08-05T15:45:20.000Z
2020-10-06T05:52:18.000Z
js/pages/services-page.js
wycka0214/16-grupe-personal
a18e69b34c8a9811c1ecde92f2fc34084f50cbaf
[ "MIT" ]
3
2020-08-07T17:52:49.000Z
2020-10-08T08:40:59.000Z
"use strict"; import { Header } from '../components/Header.js'; import { Services } from '../components/Services.js'; import { Footer } from '../components/Footer.js'; import { Newsletter } from '../components/Newsletter.js'; new Header({ selector: '#main_header' }); new Services('#services_list', 'services.json'); new Footer({ selector: '#main_footer' }); new Newsletter({ selector: '#footer_newsletter', insertPosition: 'beforeend' });
26.823529
57
0.679825
ac646bf05a30ee2842b10ba70e257fd8cfcaa97d
516
js
JavaScript
src/helloworld.js
mbetances805/dwReact
2e5f021c12a5339a79e1f6eeef29151e0eca3d30
[ "MIT" ]
null
null
null
src/helloworld.js
mbetances805/dwReact
2e5f021c12a5339a79e1f6eeef29151e0eca3d30
[ "MIT" ]
null
null
null
src/helloworld.js
mbetances805/dwReact
2e5f021c12a5339a79e1f6eeef29151e0eca3d30
[ "MIT" ]
null
null
null
//import react, because we want to build off a React component import React, { Component } from 'react'; //Example HelloWorld Component class HelloWorld extends Component { //this is where you put the JSX to render on the page render() { return <h1><img className='logo' src='assets/wsj-logo.svg' /></h1>; } }; //this is where you can define fallbacks for any props that don't get sent HelloWorld.defaultProps = { message: '' }; //export this, or other files can't use this export default HelloWorld;
27.157895
74
0.715116
ac6498e86505fef0b4b2091b1dcbed9454139b0d
2,957
js
JavaScript
src/pages/services/portfolio.js
LeDjinn/gatsby_templates_Lead_Collector
23ae45631207a91d550d646abe964e862d274bbb
[ "RSA-MD" ]
null
null
null
src/pages/services/portfolio.js
LeDjinn/gatsby_templates_Lead_Collector
23ae45631207a91d550d646abe964e862d274bbb
[ "RSA-MD" ]
null
null
null
src/pages/services/portfolio.js
LeDjinn/gatsby_templates_Lead_Collector
23ae45631207a91d550d646abe964e862d274bbb
[ "RSA-MD" ]
null
null
null
import React from 'react'; import { StaticImage } from 'gatsby-plugin-image'; import Seo from '../../components/Seo'; import Layout from '../../components/Layout'; import HeroServices from '../../components/HeroService'; import AnimationRevealPage from '../../components/AnimationRevealPage'; export default function Portfolio() { return ( <Layout> <Seo title="Création de porfolio, le miroir de vos créations" description="un excellent moyen de présenter votre art à travers le canal digital" /> <AnimationRevealPage> <HeroServices /> <section className="md:p-10 m-10 h-full flex flex-wrap sm:flex-col"> <div className="md:flex md:items-center flex-row text-center text-xl font-bold"> <div className="h-52 w-52 relative cursor-pointer mb-8 ml-5"> <div className="absolute inset-0 bg-white opacity-25 rounded-lg shadow-2xl"></div> <div className="absolute inset-0 transform origin-left hover:-translate-y-10 transition duration-300"> <div className="h-full w-full bg-white rounded-lg shadow-2xl text-center text-xl font-bold"> <StaticImage src="../../images/portfolio.webp" quality={95} placeholder="blurred" formats={['AUTO', 'WEBP', 'AVIF']} alt="Partagez vos créations artistiques" className="object-cover object-center h-52 w-52 rounded-lg shadow-2xl" /> Portfolio </div> </div> </div> <StaticImage src="../../images/undraw_portfolio_website_lidw.svg" width={400} placeholder="tracedSVG" quality={95} formats={['AUTO', 'WEBP', 'AVIF']} alt="Otos Lab - L'ensemble de vos oeuvres en un clique" className="object-cover object-center rounded-lg shadow-2xl md:ml-10" /> </div> <p className="mt-10 sm:flex-col text-bol text-xl md:px-8"> <h1 className="font-bold text-purple-700 text-center md:text-left"> Création de site Portfolio - Agence web Otos Lab </h1> <br /> Créateur de mode, photographe, dessinateur, musicien... Vous voulez un espace où vos travaux sont réunis et mis en valeur ? Nous vous proposons de créer un portfolio qui a de la classe, qui vous ressemble, pour vous permettre de partager votre univers avec le public. Vous pourrez disposer de votre site internet pour exposer vos travaux graphiques, artistiques ou tout autre (statiques, machine learning, ingénierie etc.) Présentez-vous au monde de la meilleure des façons, celle qui vous correspond. </p> </section> </AnimationRevealPage> </Layout> ); }
47.693548
116
0.591478
ac6518192f9c0b8be7bce399af46a048742e973d
13,464
js
JavaScript
src/matrix/e2ee/Account.js
terrorizer1980/hydrogen-web
dacdc1aec6cfe01cf473b5cae120a71fd0be5078
[ "Apache-2.0" ]
null
null
null
src/matrix/e2ee/Account.js
terrorizer1980/hydrogen-web
dacdc1aec6cfe01cf473b5cae120a71fd0be5078
[ "Apache-2.0" ]
null
null
null
src/matrix/e2ee/Account.js
terrorizer1980/hydrogen-web
dacdc1aec6cfe01cf473b5cae120a71fd0be5078
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import anotherjson from "another-json"; import {SESSION_E2EE_KEY_PREFIX, OLM_ALGORITHM, MEGOLM_ALGORITHM} from "./common.js"; // use common prefix so it's easy to clear properties that are not e2ee related during session clear const ACCOUNT_SESSION_KEY = SESSION_E2EE_KEY_PREFIX + "olmAccount"; const DEVICE_KEY_FLAG_SESSION_KEY = SESSION_E2EE_KEY_PREFIX + "areDeviceKeysUploaded"; const SERVER_OTK_COUNT_SESSION_KEY = SESSION_E2EE_KEY_PREFIX + "serverOTKCount"; async function initiallyStoreAccount(account, pickleKey, areDeviceKeysUploaded, serverOTKCount, storage) { const pickledAccount = account.pickle(pickleKey); const txn = await storage.readWriteTxn([ storage.storeNames.session ]); try { // add will throw if the key already exists // we would not want to overwrite olmAccount here txn.session.add(ACCOUNT_SESSION_KEY, pickledAccount); txn.session.add(DEVICE_KEY_FLAG_SESSION_KEY, areDeviceKeysUploaded); txn.session.add(SERVER_OTK_COUNT_SESSION_KEY, serverOTKCount); } catch (err) { txn.abort(); throw err; } await txn.complete(); } export class Account { static async load({olm, pickleKey, hsApi, userId, deviceId, olmWorker, txn}) { const pickledAccount = await txn.session.get(ACCOUNT_SESSION_KEY); if (pickledAccount) { const account = new olm.Account(); const areDeviceKeysUploaded = await txn.session.get(DEVICE_KEY_FLAG_SESSION_KEY); account.unpickle(pickleKey, pickledAccount); const serverOTKCount = await txn.session.get(SERVER_OTK_COUNT_SESSION_KEY); return new Account({pickleKey, hsApi, account, userId, deviceId, areDeviceKeysUploaded, serverOTKCount, olm, olmWorker}); } } static async adoptDehydratedDevice({olm, dehydratedDevice, pickleKey, hsApi, userId, olmWorker, storage}) { const account = dehydratedDevice.adoptUnpickledOlmAccount(); const oneTimeKeys = JSON.parse(account.one_time_keys()); // only one algorithm supported by olm atm, so hardcode its name const oneTimeKeysEntries = Object.entries(oneTimeKeys.curve25519); const serverOTKCount = oneTimeKeysEntries.length; const areDeviceKeysUploaded = true; await initiallyStoreAccount(account, pickleKey, areDeviceKeysUploaded, serverOTKCount, storage); return new Account({ pickleKey, hsApi, account, userId, deviceId: dehydratedDevice.deviceId, areDeviceKeysUploaded, serverOTKCount, olm, olmWorker }); } static async create({olm, pickleKey, hsApi, userId, deviceId, olmWorker, storage}) { const account = new olm.Account(); if (olmWorker) { await olmWorker.createAccountAndOTKs(account, account.max_number_of_one_time_keys()); } else { account.create(); account.generate_one_time_keys(account.max_number_of_one_time_keys()); } const areDeviceKeysUploaded = false; const serverOTKCount = 0; if (storage) { await initiallyStoreAccount(account, pickleKey, areDeviceKeysUploaded, serverOTKCount, storage); } return new Account({pickleKey, hsApi, account, userId, deviceId, areDeviceKeysUploaded, serverOTKCount, olm, olmWorker}); } constructor({pickleKey, hsApi, account, userId, deviceId, areDeviceKeysUploaded, serverOTKCount, olm, olmWorker}) { this._olm = olm; this._pickleKey = pickleKey; this._hsApi = hsApi; this._account = account; this._userId = userId; this._deviceId = deviceId; this._areDeviceKeysUploaded = areDeviceKeysUploaded; this._serverOTKCount = serverOTKCount; this._olmWorker = olmWorker; this._identityKeys = JSON.parse(this._account.identity_keys()); } get identityKeys() { return this._identityKeys; } setDeviceId(deviceId) { this._deviceId = deviceId; } async uploadKeys(storage, isDehydratedDevice, log) { const oneTimeKeys = JSON.parse(this._account.one_time_keys()); // only one algorithm supported by olm atm, so hardcode its name const oneTimeKeysEntries = Object.entries(oneTimeKeys.curve25519); if (oneTimeKeysEntries.length || !this._areDeviceKeysUploaded) { const payload = {}; if (!this._areDeviceKeysUploaded) { log.set("identity", true); const identityKeys = JSON.parse(this._account.identity_keys()); payload.device_keys = this._deviceKeysPayload(identityKeys); } if (oneTimeKeysEntries.length) { log.set("otks", true); payload.one_time_keys = this._oneTimeKeysPayload(oneTimeKeysEntries); } const dehydratedDeviceId = isDehydratedDevice ? this._deviceId : undefined; const response = await this._hsApi.uploadKeys(dehydratedDeviceId, payload, {log}).response(); this._serverOTKCount = response?.one_time_key_counts?.signed_curve25519; log.set("serverOTKCount", this._serverOTKCount); // TODO: should we not modify this in the txn like we do elsewhere? // we'd have to pickle and unpickle the account to clone it though ... // and the upload has succeed at this point, so in-memory would be correct // but in-storage not if the txn fails. await this._updateSessionStorage(storage, sessionStore => { if (oneTimeKeysEntries.length) { this._account.mark_keys_as_published(); sessionStore?.set(ACCOUNT_SESSION_KEY, this._account.pickle(this._pickleKey)); sessionStore?.set(SERVER_OTK_COUNT_SESSION_KEY, this._serverOTKCount); } if (!this._areDeviceKeysUploaded) { this._areDeviceKeysUploaded = true; sessionStore?.set(DEVICE_KEY_FLAG_SESSION_KEY, this._areDeviceKeysUploaded); } }); } } async generateOTKsIfNeeded(storage, log) { // We need to keep a pool of one time public keys on the server so that // other devices can start conversations with us. But we can only store // a finite number of private keys in the olm Account object. // To complicate things further then can be a delay between a device // claiming a public one time key from the server and it sending us a // message. We need to keep the corresponding private key locally until // we receive the message. // But that message might never arrive leaving us stuck with duff // private keys clogging up our local storage. // So we need some kind of engineering compromise to balance all of // these factors. // Check how many keys we can store in the Account object. const maxOTKs = this._account.max_number_of_one_time_keys(); // Try to keep at most half that number on the server. This leaves the // rest of the slots free to hold keys that have been claimed from the // server but we haven't recevied a message for. // If we run out of slots when generating new keys then olm will // discard the oldest private keys first. This will eventually clean // out stale private keys that won't receive a message. const keyLimit = Math.floor(maxOTKs / 2); // does the server have insufficient OTKs? if (this._serverOTKCount < keyLimit) { const oneTimeKeys = JSON.parse(this._account.one_time_keys()); const oneTimeKeysEntries = Object.entries(oneTimeKeys.curve25519); const unpublishedOTKCount = oneTimeKeysEntries.length; // we want to end up with maxOTKs / 2 key on the server, // so generate any on top of the remaining ones on the server and the unpublished ones // (we have generated before but haven't uploaded yet for some reason) // to get to that number. const newKeyCount = keyLimit - unpublishedOTKCount - this._serverOTKCount; if (newKeyCount > 0) { await log.wrap("generate otks", log => { log.set("max", maxOTKs); log.set("server", this._serverOTKCount); log.set("unpublished", unpublishedOTKCount); log.set("new", newKeyCount); log.set("limit", keyLimit); this._account.generate_one_time_keys(newKeyCount); this._updateSessionStorage(storage, sessionStore => { sessionStore.set(ACCOUNT_SESSION_KEY, this._account.pickle(this._pickleKey)); }); }); } // even though we didn't generate any keys, we still have some unpublished ones that should be published return true; } return false; } createInboundOlmSession(senderKey, body) { const newSession = new this._olm.Session(); try { newSession.create_inbound_from(this._account, senderKey, body); return newSession; } catch (err) { newSession.free(); throw err; } } async createOutboundOlmSession(theirIdentityKey, theirOneTimeKey) { const newSession = new this._olm.Session(); try { if (this._olmWorker) { await this._olmWorker.createOutboundOlmSession(this._account, newSession, theirIdentityKey, theirOneTimeKey); } else { newSession.create_outbound(this._account, theirIdentityKey, theirOneTimeKey); } return newSession; } catch (err) { newSession.free(); throw err; } } writeRemoveOneTimeKey(session, txn) { // this is side-effecty and will have applied the change if the txn fails, // but don't want to clone the account for now // and it is not the worst thing to think we have used a OTK when // decrypting the message that actually used it threw for some reason. this._account.remove_one_time_keys(session); txn.session.set(ACCOUNT_SESSION_KEY, this._account.pickle(this._pickleKey)); } writeSync(deviceOneTimeKeysCount, txn, log) { // we only upload signed_curve25519 otks const otkCount = deviceOneTimeKeysCount.signed_curve25519 || 0; if (Number.isSafeInteger(otkCount) && otkCount !== this._serverOTKCount) { txn.session.set(SERVER_OTK_COUNT_SESSION_KEY, otkCount); log.set("otkCount", otkCount); return otkCount; } } afterSync(otkCount) { // could also be undefined if (Number.isSafeInteger(otkCount)) { this._serverOTKCount = otkCount; } } _deviceKeysPayload(identityKeys) { const obj = { user_id: this._userId, device_id: this._deviceId, algorithms: [OLM_ALGORITHM, MEGOLM_ALGORITHM], keys: {} }; for (const [algorithm, pubKey] of Object.entries(identityKeys)) { obj.keys[`${algorithm}:${this._deviceId}`] = pubKey; } this.signObject(obj); return obj; } _oneTimeKeysPayload(oneTimeKeysEntries) { const obj = {}; for (const [keyId, pubKey] of oneTimeKeysEntries) { const keyObj = { key: pubKey }; this.signObject(keyObj); obj[`signed_curve25519:${keyId}`] = keyObj; } return obj; } async _updateSessionStorage(storage, callback) { if (storage) { const txn = await storage.readWriteTxn([ storage.storeNames.session ]); try { await callback(txn.session); } catch (err) { txn.abort(); throw err; } await txn.complete(); } else { await callback(undefined); } } signObject(obj) { const sigs = obj.signatures || {}; const unsigned = obj.unsigned; delete obj.signatures; delete obj.unsigned; sigs[this._userId] = sigs[this._userId] || {}; sigs[this._userId]["ed25519:" + this._deviceId] = this._account.sign(anotherjson.stringify(obj)); obj.signatures = sigs; if (unsigned !== undefined) { obj.unsigned = unsigned; } } pickleWithKey(key) { return this._account.pickle(key); } dispose() { this._account.free(); this._account = undefined; } }
42.473186
125
0.630496
ac661c3118c3827f5d44fb3c5988ac990d969fb7
941
js
JavaScript
VoteRevealer.user.js
LunarWatcher/userscripts
7623b229dbbbdbd898987a965d633d0aab5e69df
[ "MIT" ]
4
2018-06-14T12:19:52.000Z
2020-10-12T05:00:41.000Z
VoteRevealer.user.js
LunarWatcher/userscripts
7623b229dbbbdbd898987a965d633d0aab5e69df
[ "MIT" ]
1
2019-03-22T18:06:10.000Z
2019-03-24T11:29:25.000Z
VoteRevealer.user.js
LunarWatcher/userscripts
7623b229dbbbdbd898987a965d633d0aab5e69df
[ "MIT" ]
3
2018-08-07T07:07:46.000Z
2019-03-22T17:52:23.000Z
// ==UserScript== // @name Show me the votes // @namespace https://github.com/LunarWatcher/userscripts // @version 1.0.0 // @description Automatically shows votes on posts where the score is 0 (see https://meta.stackoverflow.com/q/390178/6296561) // @author Olivia Zoe // @include /^https?:\/\/\w*.?(stackoverflow|stackexchange|serverfault|superuser|askubuntu|stackapps)\.com\/(questions|posts|review|tools)\/(?!tagged\/|new\/).*/ // @grant none // @downloadURL https://github.com/LunarWatcher/userscripts/raw/master/VoteRevealer.user.js // @updateURL https://github.com/LunarWatcher/userscripts/raw/master/VoteRevealer.user.js // ==/UserScript== (function() { 'use strict'; $(document).ajaxComplete(function() { let objs = $(".js-vote-count"); for (let i = 0; i < objs.length; i++) if (objs[i].innerHTML == "0") setTimeout(() => { objs[i].click(); }, 1100 * i); }); })();
47.05
166
0.64187
ac667faeeed7bbebd9d7f613cca23b98fd753896
2,084
js
JavaScript
web/site/src/components/seo.js
NLeRoy917/indcovid
cbc94ad3e9993364743fae92f553ef2d154bee18
[ "Apache-2.0" ]
null
null
null
web/site/src/components/seo.js
NLeRoy917/indcovid
cbc94ad3e9993364743fae92f553ef2d154bee18
[ "Apache-2.0" ]
null
null
null
web/site/src/components/seo.js
NLeRoy917/indcovid
cbc94ad3e9993364743fae92f553ef2d154bee18
[ "Apache-2.0" ]
1
2021-03-24T15:46:19.000Z
2021-03-24T15:46:19.000Z
import React from "react"; import PropTypes from "prop-types"; import Helmet from "react-helmet"; import og_image from '../images/landing-screenshot.png'; const siteUrl = 'https://indcovid.com' function SEO({ description, lang, meta, title }) { return ( <Helmet htmlAttributes={{ lang, }} title="Indiana COVID-19 & Health Equity" meta={[ { name: `description`, content: 'On this site, we investigate how people from communities who historically face health disparities are disproportionately affected by the COVID-19 pandemic.', }, { property: `og:type`, content: `website`, }, { name: `twitter:card`, content: `summary`, }, { name: `twitter:creator`, content: `Nathan LeRoy and Barnabas-Obeng-Gyasi`, }, { name: `twitter:title`, content: `Indiana COVID-19 & Health Equity`, }, { name: `twitter:description`, content: `On this site, we investigate how people from communities who historically face health disparities are disproportionately affected by the COVID-19 pandemic.`, }, { name: `og:title`, content: `Indiana COVID-19 & Health Equity` }, { name: `og:description`, content: `On this site, we investigate how people from communities who historically face health disparities are disproportionately affected by the COVID-19 pandemic.` }, { name: `og:url`, content: `https://indcovid.com` }, { name: `og:image`, content: `${siteUrl}${og_image}` } ].concat(meta)} > </Helmet> ) } SEO.defaultProps = { lang: `en`, meta: 'Indiana COVID-19 & Health Equity', description: ``, } SEO.propTypes = { description: PropTypes.string, lang: PropTypes.string, meta: PropTypes.arrayOf(PropTypes.object), title: PropTypes.string.isRequired, } export default SEO
27.064935
177
0.578695
ac677f7004a9b4d51205d41bb5974f4fbe75994c
1,414
js
JavaScript
api/services/Queue.js
communcom/payment-service
de97ca9e276359aa9ae56e26895a94b960dcd415
[ "MIT" ]
null
null
null
api/services/Queue.js
communcom/payment-service
de97ca9e276359aa9ae56e26895a94b960dcd415
[ "MIT" ]
null
null
null
api/services/Queue.js
communcom/payment-service
de97ca9e276359aa9ae56e26895a94b960dcd415
[ "MIT" ]
null
null
null
const mq = require('amqplib'); const core = require('cyberway-core-service'); const { Service } = core.services; const { Logger } = core.utils; const env = require('../data/env'); const QUEUE_NAME = env.GLS_QUEUE_NAME; class Queue extends Service { constructor() { super(); this._mq = null; this._channel = null; } async start() { await super.start(); this._mq = await mq.connect(env.GLS_MQ_CONNECT); this._mq.on('error', err => { if (this._stopping) { return; } Logger.error('Critical Error: Message queue connection error:', err); process.exit(1); }); this._channel = await this._mq.createChannel(); this._channel.on('close', () => { if (this._stopping) { return; } Logger.error('Critical Error: Message queue channel closed'); process.exit(1); }); await this._channel.assertQueue(QUEUE_NAME, { durable: true, }); } send(data) { this._channel.sendToQueue(QUEUE_NAME, Buffer.from(JSON.stringify(data)), { persistent: true, }); } async stop() { this._stopping = true; try { this._mq.close(); } catch (err) {} await super.stop(); } } module.exports = Queue;
21.424242
82
0.521924
ac687810ecd7bbf48d62d9bc71b997a4ff40452b
521
js
JavaScript
app/components/widget.component.js
mdwagner/angularjs-dom-testing
14086dcaa5105b998a86803f7c9482494991ce8d
[ "MIT" ]
1
2019-02-20T22:51:02.000Z
2019-02-20T22:51:02.000Z
app/components/widget.component.js
mdwagner/angularjs-dom-testing
14086dcaa5105b998a86803f7c9482494991ce8d
[ "MIT" ]
null
null
null
app/components/widget.component.js
mdwagner/angularjs-dom-testing
14086dcaa5105b998a86803f7c9482494991ce8d
[ "MIT" ]
null
null
null
const config = { bindings: { myName: '<' }, template: ` <div> Name: {{$ctrl.myName}} <button data-testid="clickme" ng-click="$ctrl.clickme()">Click Me!</button> <span>Life: {{$ctrl.life}}</span> </div> `, controller: WidgetController }; WidgetController.$inject = []; function WidgetController() { const vm = this; vm.life = 0; vm.clickme = ClickMe; function ClickMe() { vm.life = 100; } } module.exports.componentName = 'widget'; module.exports.config = config;
17.965517
81
0.602687
ac68a3938b33b1d9a570adb6a549b161c534fa1f
1,388
js
JavaScript
lib/block/extra/math/mathPreview.js
alants56/muya
7dc3660ce29187ed6400dbf606aaa23c339d1924
[ "MIT" ]
null
null
null
lib/block/extra/math/mathPreview.js
alants56/muya
7dc3660ce29187ed6400dbf606aaa23c339d1924
[ "MIT" ]
null
null
null
lib/block/extra/math/mathPreview.js
alants56/muya
7dc3660ce29187ed6400dbf606aaa23c339d1924
[ "MIT" ]
null
null
null
import katex from 'katex' import 'katex/dist/contrib/mhchem.min.js' import Parent from '@/block/base/parent' class MathPreview extends Parent { static blockName = 'math-preview' static create (muya, state) { const mathBlock = new MathPreview(muya, state) return mathBlock } constructor (muya, { text }) { super(muya) this.tagName = 'div' this.math = text this.classList = ['mu-math-preview'] this.attributes = { spellcheck: 'false' } this.createDomNode() this.attachDOMEvents() this.update() } attachDOMEvents () { const { eventCenter } = this.muya eventCenter.attachDOMEvent(this.domNode, 'click', this.clickHandler.bind(this)) } clickHandler (event) { event.preventDefault() event.stopPropagation() this.parent.firstContentInDescendant().setCursor(0, 0) } update (math = this.math) { if (this.math !== math) { this.math = math } if (math) { try { const html = katex.renderToString(math, { displayMode: true }) this.domNode.innerHTML = html } catch (err) { this.domNode.innerHTML = '<div class="mu-math-error">&lt; Invalid Mathematical Formula &gt;</div>' } } else { this.domNode.innerHTML = '<div class="mu-empty">&lt; Empty Mathematical Formula &gt;</div>' } } } export default MathPreview
22.754098
106
0.626801
ac68c04e2acce79d21208293674439b8d0efe993
38,755
js
JavaScript
client/legacy/index.c58055d8.js
jakecoffman/jakecoffman.github.io
2ae0dd152f17ab059876fa159d50c17c88e85522
[ "Apache-2.0" ]
null
null
null
client/legacy/index.c58055d8.js
jakecoffman/jakecoffman.github.io
2ae0dd152f17ab059876fa159d50c17c88e85522
[ "Apache-2.0" ]
null
null
null
client/legacy/index.c58055d8.js
jakecoffman/jakecoffman.github.io
2ae0dd152f17ab059876fa159d50c17c88e85522
[ "Apache-2.0" ]
null
null
null
import{_ as e,a as t,b as a,c as n,i as r,s as o,d as i,S as s,e as c,f as l,t as h,g as f,h as u,j as m,k as d,l as g,m as p,n as v,o as y,p as w,q as k,r as b,u as I,v as E,w as j,x as S,y as x,z as A,A as P,B as L,C as D,D as R,E as $,F as T,G as C,H as G}from"./client.297b976d.js";function M(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function H(e){var t,a,n,r,o,i,s,k,b,I,E;return{c:function(){t=c("section"),a=c("canvas"),n=l(),r=c("img"),o=l(),i=c("div"),s=c("h1"),k=h("Jake Coffman"),b=l(),I=c("span"),E=h("Software Developer"),this.h()},l:function(e){t=f(e,"SECTION",{id:!0,class:!0});var c=u(t);a=f(c,"CANVAS",{id:!0,class:!0}),u(a).forEach(m),n=d(c),r=f(c,"IMG",{alt:!0,src:!0,id:!0,class:!0}),o=d(c),i=f(c,"DIV",{class:!0});var l=u(i);s=f(l,"H1",{class:!0});var h=u(s);k=g(h,"Jake Coffman"),h.forEach(m),b=d(l),I=f(l,"SPAN",{class:!0});var p=u(I);E=g(p,"Software Developer"),p.forEach(m),l.forEach(m),c.forEach(m),this.h()},h:function(){p(a,"id","canvas"),p(a,"class","svelte-1o42sq9"),p(r,"alt","Jake Coffman"),r.src!=="logo.png"&&p(r,"src","logo.png"),p(r,"id","logo"),p(r,"class","svelte-1o42sq9"),p(s,"class","svelte-1o42sq9"),p(I,"class","tagline svelte-1o42sq9"),p(i,"class","heroic svelte-1o42sq9"),p(t,"id","hero"),p(t,"class","svelte-1o42sq9")},m:function(e,c){v(e,t,c),y(t,a),y(t,n),y(t,r),y(t,o),y(t,i),y(i,s),y(s,k),y(i,b),y(i,I),y(I,E)},p:w,i:w,o:w,d:function(e){e&&m(t)}}}function _(e){return k((function(){var e=document.getElementById("canvas"),t=document.getElementById("hero"),a=e.width=t.clientWidth,n=e.height=t.clientHeight,r=e.getContext("webgl",{preserveDrawingBuffer:!0}),o={},i=2,s=1.5,c=.5,l=3,h=3,f=.03,u=-.2,m=.995,d=1,g=.2,p=25,v=10,y=10,w=.3,k=.1/360;o.vertexShaderSource="\nuniform int u_mode;\nuniform vec2 u_res;\nattribute vec4 a_data;\nvarying vec4 v_color;\n\nvec3 h2rgb( float h ){\n\treturn clamp( abs( mod( h * 6. + vec3( 0, 4, 2 ), 6. ) - 3. ) -1., 0., 1. );\n}\nvoid clear(){\n\tgl_Position = vec4( a_data.xy, 0, 1 );\n\tv_color = vec4( 0, 0, 0, a_data.w );\n}\nvoid draw(){\n\tgl_Position = vec4( vec2( 1, -1 ) * ( ( a_data.xy / u_res ) * 2. - 1. ), 0, 1 );\n\tv_color = vec4( h2rgb( a_data.z ), a_data.w );\n}\nvoid main(){\n\tif( u_mode == 0 )\n\t\tdraw();\n\telse\n\t\tclear();\n}\n",o.fragmentShaderSource="\nprecision mediump float;\nvarying vec4 v_color;\n\nvoid main(){\n\tgl_FragColor = v_color;\n}\n",o.vertexShader=r.createShader(r.VERTEX_SHADER),r.shaderSource(o.vertexShader,o.vertexShaderSource),r.compileShader(o.vertexShader),o.fragmentShader=r.createShader(r.FRAGMENT_SHADER),r.shaderSource(o.fragmentShader,o.fragmentShaderSource),r.compileShader(o.fragmentShader),o.shaderProgram=r.createProgram(),r.attachShader(o.shaderProgram,o.vertexShader),r.attachShader(o.shaderProgram,o.fragmentShader),r.linkProgram(o.shaderProgram),r.useProgram(o.shaderProgram),o.dataAttribLoc=r.getAttribLocation(o.shaderProgram,"a_data"),o.dataBuffer=r.createBuffer(),r.enableVertexAttribArray(o.dataAttribLoc),r.bindBuffer(r.ARRAY_BUFFER,o.dataBuffer),r.vertexAttribPointer(o.dataAttribLoc,4,r.FLOAT,!1,0,0),o.resUniformLoc=r.getUniformLocation(o.shaderProgram,"u_res"),o.modeUniformLoc=r.getUniformLocation(o.shaderProgram,"u_mode"),r.viewport(0,0,a,n),r.uniform2f(o.resUniformLoc,a,n),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),r.enable(r.BLEND),r.lineWidth(s),o.data=[],o.clear=function(){r.uniform1i(o.modeUniformLoc,1);var e=.1;o.data=[-1,-1,0,e,1,-1,0,e,-1,1,0,e,-1,1,0,e,1,-1,0,e,1,1,0,e],o.draw(r.TRIANGLES),r.uniform1i(o.modeUniformLoc,0),o.data.length=0},o.draw=function(e){r.bufferData(r.ARRAY_BUFFER,new Float32Array(o.data),r.STATIC_DRAW),r.drawArrays(e,0,o.data.length/4)};for(var b=[],I=[],E=[],j=v+y,S=2*Math.PI,x=0;x<j;++x)I[x]=Math.sin(S*x/j),E[x]=Math.cos(S*x/j);function A(){this.reset(),this.shards=[];for(var e=0;e<j;++e)this.shards.push(new P(this))}function P(e){this.parent=e}A.prototype.reset=function(){var e=-Math.PI/2+(Math.random()-.5)*c,t=l+h*Math.random();this.mode=0,this.vx=t*Math.cos(e),this.vy=t*Math.sin(e),this.x=Math.random()*a,this.y=n,this.hue=Math.random()},A.prototype.step=function(){if(0===this.mode){var e=this.hue,t=this.x,a=this.y;if(this.hue+=k,this.x+=this.vx*=m,this.y+=this.vy+=f,o.data.push(t,a,e,.2*i,this.x,this.y,this.hue,.2*i),this.vy>=u){this.mode=1,this.shardAmount=v+y*Math.random()|0;for(var n=Math.random()*S,r=Math.cos(n),s=Math.sin(n),c=I[this.shardAmount],l=E[this.shardAmount],h=0;h<this.shardAmount;++h){var p=d+g*Math.random();this.shards[h].reset(r*p,s*p);var w=r;r=r*l-s*c,s=s*l+w*c}}}else if(1===this.mode){this.ph=this.hue,this.hue+=k;for(var b=!0,j=0;j<this.shardAmount;++j){var x=this.shards[j];x.dead||(x.step(),b=!1)}b&&this.reset()}},P.prototype.reset=function(e,t){this.x=this.parent.x,this.y=this.parent.y,this.vx=this.parent.vx*w+e,this.vy=this.parent.vy*w+t,this.dead=!1,this.tick=1},P.prototype.step=function(){this.tick+=.05;var e=this.x,t=this.y;this.x+=this.vx*=m,this.y+=this.vy+=f,o.data.push(e,t,this.parent.ph,i/this.tick,this.x,this.y,this.parent.hue,i/this.tick),this.y>n&&(this.dead=!0)},function e(){window.requestAnimationFrame(e),o.clear(),b.length<p&&b.push(new A),b.map((function(e){e.step()})),o.draw(r.LINES)}(),window.addEventListener("resize",(function(){a=e.width=t.clientWidth,n=e.height=t.clientHeight,r.viewport(0,0,a,n),r.uniform2f(o.resUniformLoc,a,n)}))})),[]}var W=function(t){e(c,s);var a=M(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,_,H,o,{}),t}return c}();function O(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function B(e,t,a){var n=e.slice();return n[5]=t[a],n}function N(e){var t,a;return{c:function(){t=c("img"),this.h()},l:function(e){t=f(e,"IMG",{class:!0,alt:!0,src:!0,loading:!0}),this.h()},h:function(){p(t,"class","p-img svelte-mf3imf"),p(t,"alt",e[0]),t.src!==(a=e[1])&&p(t,"src",a),p(t,"loading","lazy")},m:function(e,a){v(e,t,a)},p:function(e,n){1&n&&p(t,"alt",e[0]),2&n&&t.src!==(a=e[1])&&p(t,"src",a)},d:function(e){e&&m(t)}}}function U(e){var t,a,n;return{c:function(){t=c("video"),a=c("source"),this.h()},l:function(e){t=f(e,"VIDEO",{class:!0,playsinline:!0,autoplay:!0,muted:!0,loop:!0});var n=u(t);a=f(n,"SOURCE",{src:!0,type:!0}),n.forEach(m),this.h()},h:function(){a.src!==(n=e[2])&&p(a,"src",n),p(a,"type","video/mp4"),p(t,"class","p-img svelte-mf3imf"),t.playsInline=!0,t.autoplay=!0,t.muted=!0,t.loop=!0},m:function(e,n){v(e,t,n),y(t,a)},p:function(e,t){4&t&&a.src!==(n=e[2])&&p(a,"src",n)},d:function(e){e&&m(t)}}}function q(e){var t,a,n,r,o,i=e[5].name+"";return{c:function(){t=c("li"),a=c("a"),n=h(i),o=l(),this.h()},l:function(e){t=f(e,"LI",{class:!0});var r=u(t);a=f(r,"A",{href:!0,target:!0,rel:!0,class:!0});var s=u(a);n=g(s,i),s.forEach(m),o=d(r),r.forEach(m),this.h()},h:function(){p(a,"href",r=e[5].href),p(a,"target","_blank"),p(a,"rel","noopener"),p(a,"class","btn svelte-mf3imf"),p(t,"class","svelte-mf3imf")},m:function(e,r){v(e,t,r),y(t,a),y(a,n),y(t,o)},p:function(e,t){8&t&&i!==(i=e[5].name+"")&&b(n,i),8&t&&r!==(r=e[5].href)&&p(a,"href",r)},d:function(e){e&&m(t)}}}function F(e){for(var t,a,n,r,o,i,s,k,j,S,x,A,P=e[1]&&N(e),L=e[2]&&U(e),D=e[3],R=[],$=0;$<D.length;$+=1)R[$]=q(B(e,D,$));return{c:function(){t=c("div"),a=c("a"),P&&P.c(),n=l(),L&&L.c(),r=l(),o=c("div"),i=c("h3"),s=h(e[0]),k=l(),j=c("p"),S=h(e[4]),x=l(),A=c("ul");for(var f=0;f<R.length;f+=1)R[f].c();this.h()},l:function(c){t=f(c,"DIV",{class:!0});var l=u(t);a=f(l,"A",{class:!0,href:!0});var h=u(a);P&&P.l(h),n=d(h),L&&L.l(h),h.forEach(m),r=d(l),o=f(l,"DIV",{class:!0});var p=u(o);i=f(p,"H3",{class:!0});var v=u(i);s=g(v,e[0]),v.forEach(m),k=d(p),j=f(p,"P",{class:!0});var y=u(j);S=g(y,e[4]),y.forEach(m),p.forEach(m),x=d(l),A=f(l,"UL",{class:!0});for(var w=u(A),b=0;b<R.length;b+=1)R[b].l(w);w.forEach(m),l.forEach(m),this.h()},h:function(){p(a,"class","card-link svelte-mf3imf"),p(a,"href",e[5]),p(i,"class","svelte-mf3imf"),p(j,"class","grow svelte-mf3imf"),p(o,"class","project-text svelte-mf3imf"),p(A,"class","links svelte-mf3imf"),p(t,"class","card svelte-mf3imf")},m:function(e,c){v(e,t,c),y(t,a),P&&P.m(a,null),y(a,n),L&&L.m(a,null),y(t,r),y(t,o),y(o,i),y(i,s),y(o,k),y(o,j),y(j,S),y(t,x),y(t,A);for(var l=0;l<R.length;l+=1)R[l].m(A,null)},p:function(e,t){var r=I(t,1)[0];if(e[1]?P?P.p(e,r):((P=N(e)).c(),P.m(a,n)):P&&(P.d(1),P=null),e[2]?L?L.p(e,r):((L=U(e)).c(),L.m(a,null)):L&&(L.d(1),L=null),32&r&&p(a,"href",e[5]),1&r&&b(s,e[0]),16&r&&b(S,e[4]),8&r){var o;for(D=e[3],o=0;o<D.length;o+=1){var i=B(e,D,o);R[o]?R[o].p(i,r):(R[o]=q(i),R[o].c(),R[o].m(A,null))}for(;o<R.length;o+=1)R[o].d(1);R.length=D.length}},i:w,o:w,d:function(e){e&&m(t),P&&P.d(),L&&L.d(),E(R,e)}}}function J(e,t,a){var n=t.title,r=t.link,o=t.image,i=t.video,s=t.links,c=t.text;return e.$$set=function(e){"title"in e&&a(0,n=e.title),"link"in e&&a(5,r=e.link),"image"in e&&a(1,o=e.image),"video"in e&&a(2,i=e.video),"links"in e&&a(3,s=e.links),"text"in e&&a(4,c=e.text)},[n,o,i,s,c,r]}var V=function(t){e(c,s);var a=O(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,J,F,o,{title:0,link:5,image:1,video:2,links:3,text:4}),t}return c}();function Y(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function Q(e,t,a){var n=e.slice();return n[1]=t[a],n}function z(e){for(var t,a,n=[e[1]],r={},o=0;o<n.length;o+=1)r=C(r,n[o]);return t=new V({props:r}),{c:function(){j(t.$$.fragment)},l:function(e){S(t.$$.fragment,e)},m:function(e,n){x(t,e,n),a=!0},p:function(e,a){var r=1&a?A(n,[P(e[1])]):{};t.$set(r)},i:function(e){a||(L(t.$$.fragment,e),a=!0)},o:function(e){D(t.$$.fragment,e),a=!1},d:function(e){R(t,e)}}}function X(e){for(var t,a,n,r,o,i,s,w,k,b,j,S,x,A,P=e[0],R=[],C=0;C<P.length;C+=1)R[C]=z(Q(e,P,C));var G=function(e){return D(R[e],1,1,(function(){R[e]=null}))};return{c:function(){t=c("section"),a=c("h2"),n=h("Projects"),r=l(),o=c("p"),i=h("This is a small selection of projects that I have worked on to learn new skills\n or scratch an itch."),s=l(),w=c("p"),k=h("There are many more projects over at my Github:\n "),b=c("a"),j=h("https://github.com/jakecoffman"),S=l(),x=c("div");for(var e=0;e<R.length;e+=1)R[e].c();this.h()},l:function(e){t=f(e,"SECTION",{id:!0,class:!0});var c=u(t);a=f(c,"H2",{class:!0});var l=u(a);n=g(l,"Projects"),l.forEach(m),r=d(c),o=f(c,"P",{});var h=u(o);i=g(h,"This is a small selection of projects that I have worked on to learn new skills\n or scratch an itch."),h.forEach(m),s=d(c),w=f(c,"P",{});var p=u(w);k=g(p,"There are many more projects over at my Github:\n "),b=f(p,"A",{href:!0});var v=u(b);j=g(v,"https://github.com/jakecoffman"),v.forEach(m),p.forEach(m),S=d(c),x=f(c,"DIV",{class:!0});for(var y=u(x),I=0;I<R.length;I+=1)R[I].l(y);y.forEach(m),c.forEach(m),this.h()},h:function(){p(a,"class","svelte-x645cm"),p(b,"href","https://github.com/jakecoffman"),p(x,"class","cards svelte-x645cm"),p(t,"id","projects"),p(t,"class","svelte-x645cm")},m:function(e,c){v(e,t,c),y(t,a),y(a,n),y(t,r),y(t,o),y(o,i),y(t,s),y(t,w),y(w,k),y(w,b),y(b,j),y(t,S),y(t,x);for(var l=0;l<R.length;l+=1)R[l].m(x,null);A=!0},p:function(e,t){var a=I(t,1)[0];if(1&a){var n;for(P=e[0],n=0;n<P.length;n+=1){var r=Q(e,P,n);R[n]?(R[n].p(r,a),L(R[n],1)):(R[n]=z(r),R[n].c(),L(R[n],1),R[n].m(x,null))}for($(),n=P.length;n<R.length;n+=1)G(n);T()}},i:function(e){if(!A){for(var t=0;t<P.length;t+=1)L(R[t]);A=!0}},o:function(e){R=R.filter(Boolean);for(var t=0;t<R.length;t+=1)D(R[t]);A=!1},d:function(e){e&&m(t),E(R,e)}}}function K(e){return[[{title:"Tree Game",link:"https://trees.jakecoffman.com",image:"trees.png",text:"2-Player web-based game where you try to outgrow your opponent. Play against a bot I wrote for the CodinGame Spring 2021 Challenge.",links:[{href:"https://trees.jakecoffman.com",name:"Play"}]},{title:"STL Devs",link:"https://stldevs.com",image:"stldevs.png",text:"This is a site for discovering what open source work developers are doing in the Greater St. Louis region by harvesting public information from Github.",links:[{href:"https://stldevs.com",name:"Visit"}]},{title:"Tank Game",link:"https://github.com/jakecoffman/tanks-unity/releases",image:"tanks.png",text:"A multi-player game created with Unity. Think Wii Tanks but online, and with mouse and keyboard.",links:[{href:"https://github.com/jakecoffman/tanks-unity/releases",name:"Download"},{href:"http://github.com/jakecoffman/tanks-unity",name:"Source"}]},{title:"Tanklets",link:"https://github.com/jakecoffman/tanklets/releases",image:"tanklets.png",text:"Another Tank Game but written from scratch in Go. I used no game engine, had to learn OpenGL and ported Chipmunk2D for this project.",links:[{href:"https://github.com/jakecoffman/tanklets/releases",name:"Download"},{href:"http://github.com/jakecoffman/tanklets",name:"Source"}]},{title:"fam",link:"https://github.com/jakecoffman/fam",video:"fam.mp4",text:"Another OpenGL game I am making to play with the kiddos.",links:[{href:"https://github.com/jakecoffman/fam",name:"Source"}]},{title:"Chipmunk Port",link:"https://www.jakecoffman.com/cp-ebiten/",image:"cp.gif",text:"Go port of the excellent Chipmunk2D, originally in C.",links:[{href:"https://www.jakecoffman.com/cp-ebiten/",name:"Demo"},{href:"https://github.com/jakecoffman/cp",name:"Source"}]},{title:"Matchtown",link:"https://set.jakecoffman.com",image:"setgame.png",text:"Online multi-player set finding card game.",links:[{href:"https://set.jakecoffman.com",name:"Play"},{href:"https://github.com/jakecoffman/set-game",name:"Source"}]},{title:"Colors",link:"https://www.jakecoffman.com/colors",image:"coloretto.png",text:"Local multi-player color matching game.",links:[{href:"http://www.jakecoffman.com/colors",name:"Play"},{href:"https://github.com/jakecoffman/colors",name:"Source"}]},{title:"Memory",link:"https://www.jakecoffman.com/memory",image:"memory.png",text:"Local multi-player kid's game.",links:[{href:"http://www.jakecoffman.com/memory",name:"Play"},{href:"https://github.com/jakecoffman/memory",name:"Source"}]},{title:"Spy Game",link:"https://resistance.jakecoffman.com",image:"resistance.png",text:"Multi-player game of intrigue. This is a good game to play over web-chat during a pandemic.",links:[{href:"https://resistance.jakecoffman.com",name:"Play"},{href:"http://github.com/jakecoffman/resistance",name:"Source"}]},{title:"Carman",link:"https://www.jakecoffman.com/carman/",image:"carman.jpg",text:"Local multi-player pacman style game. Plug in 4 controllers! Built with Phaserjs.",links:[{href:"https://www.jakecoffman.com/carman/",name:"Play"},{href:"https://github.com/jakecoffman/carman",name:"Source"}]},{title:"Spring Challenge",link:"https://www.codingame.com/contests/spring-challenge-2020/leaderboard/global?column=keyword&value=jke",image:"pacman.gif",text:"Placed 112th out of 5,000 in an AI Pathfinding competition. This was my first time programming AI and my first coding competition.",links:[{href:"https://www.codingame.com/contests/spring-challenge-2020/leaderboard/global?column=keyword&value=jke",name:"Leaderboard"}]},{title:"Trusted Friend",link:"https://github.com/jakecoffman/trusted-friend",image:"trustedfriend.png",text:"Trusted Friend is an Android app no longer in Google Play, but it allowed you to friend people and request their location.",links:[{href:"http://github.com/jakecoffman/trusted-friend",name:"Source"}]},{title:"camcontrol",link:"http://github.com/jakecoffman/camcontrol",image:"camcontrol.png",text:"camcontrol is a Qt app with embedded VLC player to open and control multiple Amcrest cameras at once",links:[{href:"http://github.com/jakecoffman/camcontrol",name:"Source"}]},{title:"Arduino Security",link:"http://youtu.be/lfOxgK1-5HM",image:"arduino.jpg",text:"One of my first open source contributions, an Arduino emailed me when my door opened",links:[{href:"http://youtu.be/lfOxgK1-5HM",name:"Watch"},{href:"https://github.com/jakecoffman/arduino-security-system",name:"Source"}]},{title:"Gorunner",link:"http://github.com/jakecoffman/gorunner",image:"gorunner.png",text:"I used to be obsessed with making a better Jenkins. This was an early attempt\n using Go, with AngularJS on the frontend.",links:[{href:"http://github.com/jakecoffman/gorunner",name:"Source"}]},{title:"Video Tutorials",link:"https://www.youtube.com/user/calicoJake/playlists",image:"tutorials.png",text:"A long time ago I made programming video tutorials. It was a little experiment\n to see if I could make money off of it. Turns out no, but it was fun and I seemed to help a lot of people.",links:[{href:"https://www.youtube.com/playlist?list=PL0DA14EB3618A3507",name:"Flask"},{href:"https://www.youtube.com/playlist?list=PLXbwrYvH4U89KwOnk79AA8j-s2nmDbWDk",name:"Go/Angular"}]}]]}var Z=function(t){e(c,s);var a=Y(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,K,X,o,{}),t}return c}();function ee(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function te(e){var t,a,n,r,o,i,s,k,b,I,E,j,S,x,A,P,L,D,R,$,T,C,G,M,H,_,W,O,B,N,U,q,F;return{c:function(){t=c("section"),a=c("h2"),n=h("Hello, world!"),r=l(),o=c("p"),i=h("Hi, I'm Jake Coffman and I am a Software Developer in St. Louis Missouri."),s=l(),k=c("p"),b=h("I have a Bachelors in Computer Science and have worked professionally in C++, Python, JavaScript,\n Java, Groovy, Ruby, Go, and C#."),I=l(),E=c("h3"),j=h("Experience"),S=l(),x=c("p"),A=h("I started out working on low level security libraries and various security related GUIs at Cerner."),P=l(),L=c("p"),D=h("Then I moved on to doing low level network programming on a 3-D distributed simulation of fighter jets\n at Boeing. I started to pick up web development while I was there, too."),R=l(),$=c("p"),T=h('Next I worked at a startup called Appistry where I helped create an ETL system that took HL7 data and\n transformed it into SQL. I created a search interface for that data and various other "Big Data" web interfaces.'),C=l(),G=c("p"),M=h("Now I am at World Wide Technology where I am the principal developer behind the ATC Lab Gateway."),H=l(),_=c("h3"),W=h("Interests"),O=l(),B=c("p"),N=h("I like game development and have been working on games in my free time. Game development is\n refreshing and completely unlike web development which I have been doing for my day job. Working in 2D and\n 3D with physics engines is a fun challenge."),U=l(),q=c("p"),F=h("I also like web development as a way to expose what I do to potentially billions of people."),this.h()},l:function(e){t=f(e,"SECTION",{id:!0});var c=u(t);a=f(c,"H2",{});var l=u(a);n=g(l,"Hello, world!"),l.forEach(m),r=d(c),o=f(c,"P",{});var h=u(o);i=g(h,"Hi, I'm Jake Coffman and I am a Software Developer in St. Louis Missouri."),h.forEach(m),s=d(c),k=f(c,"P",{});var p=u(k);b=g(p,"I have a Bachelors in Computer Science and have worked professionally in C++, Python, JavaScript,\n Java, Groovy, Ruby, Go, and C#."),p.forEach(m),I=d(c),E=f(c,"H3",{class:!0});var v=u(E);j=g(v,"Experience"),v.forEach(m),S=d(c),x=f(c,"P",{});var y=u(x);A=g(y,"I started out working on low level security libraries and various security related GUIs at Cerner."),y.forEach(m),P=d(c),L=f(c,"P",{});var w=u(L);D=g(w,"Then I moved on to doing low level network programming on a 3-D distributed simulation of fighter jets\n at Boeing. I started to pick up web development while I was there, too."),w.forEach(m),R=d(c),$=f(c,"P",{});var J=u($);T=g(J,'Next I worked at a startup called Appistry where I helped create an ETL system that took HL7 data and\n transformed it into SQL. I created a search interface for that data and various other "Big Data" web interfaces.'),J.forEach(m),C=d(c),G=f(c,"P",{});var V=u(G);M=g(V,"Now I am at World Wide Technology where I am the principal developer behind the ATC Lab Gateway."),V.forEach(m),H=d(c),_=f(c,"H3",{class:!0});var Y=u(_);W=g(Y,"Interests"),Y.forEach(m),O=d(c),B=f(c,"P",{});var Q=u(B);N=g(Q,"I like game development and have been working on games in my free time. Game development is\n refreshing and completely unlike web development which I have been doing for my day job. Working in 2D and\n 3D with physics engines is a fun challenge."),Q.forEach(m),U=d(c),q=f(c,"P",{});var z=u(q);F=g(z,"I also like web development as a way to expose what I do to potentially billions of people."),z.forEach(m),c.forEach(m),this.h()},h:function(){p(E,"class","svelte-127iawm"),p(_,"class","svelte-127iawm"),p(t,"id","intro")},m:function(e,c){v(e,t,c),y(t,a),y(a,n),y(t,r),y(t,o),y(o,i),y(t,s),y(t,k),y(k,b),y(t,I),y(t,E),y(E,j),y(t,S),y(t,x),y(x,A),y(t,P),y(t,L),y(L,D),y(t,R),y(t,$),y($,T),y(t,C),y(t,G),y(G,M),y(t,H),y(t,_),y(_,W),y(t,O),y(t,B),y(B,N),y(t,U),y(t,q),y(q,F)},p:w,i:w,o:w,d:function(e){e&&m(t)}}}var ae=function(t){e(c,s);var a=ee(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,null,te,o,{}),t}return c}();function ne(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function re(e){var t,a,n,r,o,i,s,k,b,I,E,j,S,x,A,P,L,D,R,$,T,C,G,M,H,_,W,O,B,N,U,q,F,J,V,Y,Q,z,X,K,Z,ee,te,ae,ne,re,oe,ie,se,ce,le,he,fe,ue,me,de,ge,pe,ve,ye,we,ke,be,Ie,Ee,je,Se,xe,Ae,Pe,Le;return{c:function(){t=c("section"),a=c("h2"),n=h("Q & A"),r=l(),o=c("h3"),i=h("What are your general thoughts about programming?"),s=l(),k=c("ul"),b=c("li"),I=h("Statically typed languages got a bad reputation and now we are paying the price for having large dynamically typed applications that are difficult to refactor."),E=l(),j=c("li"),S=h("Just as pure OOP is not the answer, pure functional is not either."),x=l(),A=c("li"),P=h("Don't use Mongo unless you are using it to store documents that have no relationship, nor ever will have relationships."),L=l(),D=c("li"),R=h("ORMs will break down, be prepared to write queries by hand."),$=l(),T=c("li"),C=h("Don't rewrite your codebase or re-architect unless it's really a problem. You work for a business, add value."),G=l(),M=c("h3"),H=h("What are your general thoughts about managing developers?"),_=l(),W=c("ul"),O=c("li"),B=h("Most meetings are a waste of time, instead write an email or message in a chat. Asynchronous communication should be preferred."),N=l(),U=c("li"),q=h("The reason you are calling so many meetings is probably because you don't write enough down."),F=l(),J=c("li"),V=h("Project managers aren't above developers, nor the other way around. We are equals and need to decide what gets done next. You manage customer expectations and I'll get things done."),Y=l(),Q=c("li"),z=h("Ideas are worthless without execution. Don't hire idea people if they can't bring the idea to reality."),X=l(),K=c("h3"),Z=h("Why do you use Go so much?"),ee=l(),te=c("p"),ae=h("I like to use Go for my personal projects because it's simple to start a new project and code is easy, the syntax\n is simple is much easier than any other programming language out there. There definitely are some rough spots in the language such as lack of generics, but I find the trade-off is worth it."),ne=l(),re=c("h3"),oe=h("How do you feel about language X or framework Y?"),ie=l(),se=c("p"),ce=h("I think most languages and frameworks have redeeming factors so you won't hear me say I hate any particular one. The most challenging part of software is choosing the right stack for the problem at hand."),le=l(),he=c("p"),fe=h("I also think it's important to not limit your learning to just a single language or framework. You can learn so much more about your favorite language just by learning a different one."),ue=l(),me=c("h3"),de=h("Favorite OS for developing?"),ge=l(),pe=c("p"),ve=h("I have used Mac, Windows, and Linux desktops successfully in developing cross platform applications."),ye=l(),we=c("p"),ke=h("I personally prefer Windows due to the low cost of hardware and have found WSL to be quite nice in filling in the gaps."),be=l(),Ie=c("p"),Ee=h("Typically my Linux desktops last about 6 months before I do an upgrade that breaks everything and I go back to Windows.\n Linux on the Desktop is still to immature and tends to be more of a hobby than an OS."),je=l(),Se=c("h3"),xe=h("Thoughts on testing?"),Ae=l(),Pe=c("p"),Le=h("Code that will go to production should always be tested, but I don't think every function should be tested in\n isolation. I prefer testing functionality (or behaviors), APIs, exported functions, and testing against a real\n database. These kinds of tests are much more valuable and won't break when you go to change the implementation,\n but gives a sense of security that things are still working."),this.h()},l:function(e){t=f(e,"SECTION",{id:!0});var c=u(t);a=f(c,"H2",{});var l=u(a);n=g(l,"Q & A"),l.forEach(m),r=d(c),o=f(c,"H3",{});var h=u(o);i=g(h,"What are your general thoughts about programming?"),h.forEach(m),s=d(c),k=f(c,"UL",{});var p=u(k);b=f(p,"LI",{});var v=u(b);I=g(v,"Statically typed languages got a bad reputation and now we are paying the price for having large dynamically typed applications that are difficult to refactor."),v.forEach(m),E=d(p),j=f(p,"LI",{});var y=u(j);S=g(y,"Just as pure OOP is not the answer, pure functional is not either."),y.forEach(m),x=d(p),A=f(p,"LI",{});var w=u(A);P=g(w,"Don't use Mongo unless you are using it to store documents that have no relationship, nor ever will have relationships."),w.forEach(m),L=d(p),D=f(p,"LI",{});var De=u(D);R=g(De,"ORMs will break down, be prepared to write queries by hand."),De.forEach(m),$=d(p),T=f(p,"LI",{});var Re=u(T);C=g(Re,"Don't rewrite your codebase or re-architect unless it's really a problem. You work for a business, add value."),Re.forEach(m),p.forEach(m),G=d(c),M=f(c,"H3",{});var $e=u(M);H=g($e,"What are your general thoughts about managing developers?"),$e.forEach(m),_=d(c),W=f(c,"UL",{});var Te=u(W);O=f(Te,"LI",{});var Ce=u(O);B=g(Ce,"Most meetings are a waste of time, instead write an email or message in a chat. Asynchronous communication should be preferred."),Ce.forEach(m),N=d(Te),U=f(Te,"LI",{});var Ge=u(U);q=g(Ge,"The reason you are calling so many meetings is probably because you don't write enough down."),Ge.forEach(m),F=d(Te),J=f(Te,"LI",{});var Me=u(J);V=g(Me,"Project managers aren't above developers, nor the other way around. We are equals and need to decide what gets done next. You manage customer expectations and I'll get things done."),Me.forEach(m),Y=d(Te),Q=f(Te,"LI",{});var He=u(Q);z=g(He,"Ideas are worthless without execution. Don't hire idea people if they can't bring the idea to reality."),He.forEach(m),Te.forEach(m),X=d(c),K=f(c,"H3",{});var _e=u(K);Z=g(_e,"Why do you use Go so much?"),_e.forEach(m),ee=d(c),te=f(c,"P",{});var We=u(te);ae=g(We,"I like to use Go for my personal projects because it's simple to start a new project and code is easy, the syntax\n is simple is much easier than any other programming language out there. There definitely are some rough spots in the language such as lack of generics, but I find the trade-off is worth it."),We.forEach(m),ne=d(c),re=f(c,"H3",{});var Oe=u(re);oe=g(Oe,"How do you feel about language X or framework Y?"),Oe.forEach(m),ie=d(c),se=f(c,"P",{});var Be=u(se);ce=g(Be,"I think most languages and frameworks have redeeming factors so you won't hear me say I hate any particular one. The most challenging part of software is choosing the right stack for the problem at hand."),Be.forEach(m),le=d(c),he=f(c,"P",{});var Ne=u(he);fe=g(Ne,"I also think it's important to not limit your learning to just a single language or framework. You can learn so much more about your favorite language just by learning a different one."),Ne.forEach(m),ue=d(c),me=f(c,"H3",{});var Ue=u(me);de=g(Ue,"Favorite OS for developing?"),Ue.forEach(m),ge=d(c),pe=f(c,"P",{});var qe=u(pe);ve=g(qe,"I have used Mac, Windows, and Linux desktops successfully in developing cross platform applications."),qe.forEach(m),ye=d(c),we=f(c,"P",{});var Fe=u(we);ke=g(Fe,"I personally prefer Windows due to the low cost of hardware and have found WSL to be quite nice in filling in the gaps."),Fe.forEach(m),be=d(c),Ie=f(c,"P",{});var Je=u(Ie);Ee=g(Je,"Typically my Linux desktops last about 6 months before I do an upgrade that breaks everything and I go back to Windows.\n Linux on the Desktop is still to immature and tends to be more of a hobby than an OS."),Je.forEach(m),je=d(c),Se=f(c,"H3",{});var Ve=u(Se);xe=g(Ve,"Thoughts on testing?"),Ve.forEach(m),Ae=d(c),Pe=f(c,"P",{});var Ye=u(Pe);Le=g(Ye,"Code that will go to production should always be tested, but I don't think every function should be tested in\n isolation. I prefer testing functionality (or behaviors), APIs, exported functions, and testing against a real\n database. These kinds of tests are much more valuable and won't break when you go to change the implementation,\n but gives a sense of security that things are still working."),Ye.forEach(m),c.forEach(m),this.h()},h:function(){p(t,"id","qa")},m:function(e,c){v(e,t,c),y(t,a),y(a,n),y(t,r),y(t,o),y(o,i),y(t,s),y(t,k),y(k,b),y(b,I),y(k,E),y(k,j),y(j,S),y(k,x),y(k,A),y(A,P),y(k,L),y(k,D),y(D,R),y(k,$),y(k,T),y(T,C),y(t,G),y(t,M),y(M,H),y(t,_),y(t,W),y(W,O),y(O,B),y(W,N),y(W,U),y(U,q),y(W,F),y(W,J),y(J,V),y(W,Y),y(W,Q),y(Q,z),y(t,X),y(t,K),y(K,Z),y(t,ee),y(t,te),y(te,ae),y(t,ne),y(t,re),y(re,oe),y(t,ie),y(t,se),y(se,ce),y(t,le),y(t,he),y(he,fe),y(t,ue),y(t,me),y(me,de),y(t,ge),y(t,pe),y(pe,ve),y(t,ye),y(t,we),y(we,ke),y(t,be),y(t,Ie),y(Ie,Ee),y(t,je),y(t,Se),y(Se,xe),y(t,Ae),y(t,Pe),y(Pe,Le)},p:w,i:w,o:w,d:function(e){e&&m(t)}}}var oe=function(t){e(c,s);var a=ne(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,null,re,o,{}),t}return c}();function ie(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function se(e){var t,a,n,r,o,i,s,k,b,I,E,j,S,x,A,P,L,D,R,$,T,C,G,M,H,_,W,O,B,N;return{c:function(){t=c("section"),a=c("h2"),n=h("Contact"),r=l(),o=c("div"),i=c("div"),s=c("span"),k=c("img"),b=l(),I=c("ul"),E=c("li"),j=c("a"),S=c("img"),x=l(),A=c("span"),P=h("@nill"),L=l(),D=c("li"),R=c("a"),$=c("img"),T=l(),C=c("span"),G=h("jakecoffman"),M=l(),H=c("li"),_=c("a"),W=c("img"),O=l(),B=c("span"),N=h("jake@jakecoffman.com"),this.h()},l:function(e){t=f(e,"SECTION",{id:!0,class:!0});var c=u(t);a=f(c,"H2",{class:!0});var l=u(a);n=g(l,"Contact"),l.forEach(m),r=d(c),o=f(c,"DIV",{class:!0});var h=u(o);i=f(h,"DIV",{class:!0});var p=u(i);s=f(p,"SPAN",{class:!0});var v=u(s);k=f(v,"IMG",{class:!0,src:!0,alt:!0}),v.forEach(m),b=d(p),I=f(p,"UL",{class:!0});var y=u(I);E=f(y,"LI",{});var w=u(E);j=f(w,"A",{href:!0,class:!0});var U=u(j);S=f(U,"IMG",{src:!0,alt:!0,class:!0}),x=d(U),A=f(U,"SPAN",{class:!0});var q=u(A);P=g(q,"@nill"),q.forEach(m),U.forEach(m),w.forEach(m),L=d(y),D=f(y,"LI",{});var F=u(D);R=f(F,"A",{href:!0,class:!0});var J=u(R);$=f(J,"IMG",{src:!0,alt:!0,class:!0}),T=d(J),C=f(J,"SPAN",{class:!0});var V=u(C);G=g(V,"jakecoffman"),V.forEach(m),J.forEach(m),F.forEach(m),M=d(y),H=f(y,"LI",{});var Y=u(H);_=f(Y,"A",{href:!0,class:!0});var Q=u(_);W=f(Q,"IMG",{src:!0,alt:!0,class:!0}),O=d(Q),B=f(Q,"SPAN",{class:!0});var z=u(B);N=g(z,"jake@jakecoffman.com"),z.forEach(m),Q.forEach(m),Y.forEach(m),y.forEach(m),p.forEach(m),h.forEach(m),c.forEach(m),this.h()},h:function(){p(a,"class","svelte-lodrle"),p(k,"class","logo svelte-lodrle"),k.src!=="logo.png"&&p(k,"src","logo.png"),p(k,"alt","Jake Coffman"),p(s,"class","center svelte-lodrle"),S.src!=="twitter.svg"&&p(S,"src","twitter.svg"),p(S,"alt","twitter"),p(S,"class","center svelte-lodrle"),p(A,"class","svelte-lodrle"),p(j,"href","https://twitter.com/nill"),p(j,"class","svelte-lodrle"),$.src!=="github.svg"&&p($,"src","github.svg"),p($,"alt","github"),p($,"class","svelte-lodrle"),p(C,"class","svelte-lodrle"),p(R,"href","https://github.com/jakecoffman"),p(R,"class","svelte-lodrle"),W.src!=="email.svg"&&p(W,"src","email.svg"),p(W,"alt","email"),p(W,"class","svelte-lodrle"),p(B,"class","svelte-lodrle"),p(_,"href","mailto:jake@jakecoffman.com"),p(_,"class","svelte-lodrle"),p(I,"class","svelte-lodrle"),p(i,"class","card svelte-lodrle"),p(o,"class","container svelte-lodrle"),p(t,"id","contact"),p(t,"class","svelte-lodrle")},m:function(e,c){v(e,t,c),y(t,a),y(a,n),y(t,r),y(t,o),y(o,i),y(i,s),y(s,k),y(i,b),y(i,I),y(I,E),y(E,j),y(j,S),y(j,x),y(j,A),y(A,P),y(I,L),y(I,D),y(D,R),y(R,$),y(R,T),y(R,C),y(C,G),y(I,M),y(I,H),y(H,_),y(_,W),y(_,O),y(_,B),y(B,N)},p:w,i:w,o:w,d:function(e){e&&m(t)}}}var ce=function(t){e(c,s);var a=ie(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,null,se,o,{}),t}return c}();function le(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function he(e){var t,a,n,r,o,i,s,k,b,I,E,j,S,x,A,P,L,D,R,$,T,C,G,M,H,_,W;return{c:function(){t=c("header"),a=c("a"),n=h("jakecoffman.com"),r=l(),o=c("div"),i=l(),s=c("nav"),k=c("ul"),b=c("li"),I=c("a"),E=h("Intro"),j=l(),S=c("li"),x=c("a"),A=h("Projects"),P=l(),L=c("li"),D=c("a"),R=h("Q&A"),$=l(),T=c("li"),C=c("a"),G=h("Contact"),M=l(),H=c("li"),_=c("a"),W=h("Blog"),this.h()},l:function(e){t=f(e,"HEADER",{class:!0});var c=u(t);a=f(c,"A",{class:!0,href:!0});var l=u(a);n=g(l,"jakecoffman.com"),l.forEach(m),r=d(c),o=f(c,"DIV",{class:!0}),u(o).forEach(m),i=d(c),s=f(c,"NAV",{});var h=u(s);k=f(h,"UL",{class:!0});var p=u(k);b=f(p,"LI",{class:!0});var v=u(b);I=f(v,"A",{href:!0,class:!0});var y=u(I);E=g(y,"Intro"),y.forEach(m),v.forEach(m),j=d(p),S=f(p,"LI",{class:!0});var w=u(S);x=f(w,"A",{href:!0,class:!0});var O=u(x);A=g(O,"Projects"),O.forEach(m),w.forEach(m),P=d(p),L=f(p,"LI",{class:!0});var B=u(L);D=f(B,"A",{href:!0,class:!0});var N=u(D);R=g(N,"Q&A"),N.forEach(m),B.forEach(m),$=d(p),T=f(p,"LI",{class:!0});var U=u(T);C=f(U,"A",{href:!0,class:!0});var q=u(C);G=g(q,"Contact"),q.forEach(m),U.forEach(m),M=d(p),H=f(p,"LI",{class:!0});var F=u(H);_=f(F,"A",{href:!0,class:!0});var J=u(_);W=g(J,"Blog"),J.forEach(m),F.forEach(m),p.forEach(m),h.forEach(m),c.forEach(m),this.h()},h:function(){p(a,"class","jakecoffman svelte-1ij6ygm"),p(a,"href","https://jakecoffman.com"),p(o,"class","grow"),p(I,"href","#intro"),p(I,"class","svelte-1ij6ygm"),p(b,"class","svelte-1ij6ygm"),p(x,"href","#projects"),p(x,"class","svelte-1ij6ygm"),p(S,"class","svelte-1ij6ygm"),p(D,"href","#qa"),p(D,"class","svelte-1ij6ygm"),p(L,"class","svelte-1ij6ygm"),p(C,"href","#contact"),p(C,"class","svelte-1ij6ygm"),p(T,"class","svelte-1ij6ygm"),p(_,"href","https://www.jakecoffman.com/blog"),p(_,"class","svelte-1ij6ygm"),p(H,"class","svelte-1ij6ygm"),p(k,"class","svelte-1ij6ygm"),p(t,"class","svelte-1ij6ygm")},m:function(e,c){v(e,t,c),y(t,a),y(a,n),y(t,r),y(t,o),y(t,i),y(t,s),y(s,k),y(k,b),y(b,I),y(I,E),y(k,j),y(k,S),y(S,x),y(x,A),y(k,P),y(k,L),y(L,D),y(D,R),y(k,$),y(k,T),y(T,C),y(C,G),y(k,M),y(k,H),y(H,_),y(_,W)},p:w,i:w,o:w,d:function(e){e&&m(t)}}}var fe=function(t){e(c,s);var a=le(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,null,he,o,{}),t}return c}();function ue(e){var n=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,o=t(e);if(n){var i=t(this).constructor;r=Reflect.construct(o,arguments,i)}else r=o.apply(this,arguments);return a(this,r)}}function me(e){var t,a,n,r,o,i,s,h,g,p,k,b,I,E;return a=new fe({}),o=new W({}),s=new ae({}),g=new Z({}),k=new oe({}),I=new ce({}),{c:function(){t=l(),j(a.$$.fragment),n=l(),r=c("article"),j(o.$$.fragment),i=l(),j(s.$$.fragment),h=l(),j(g.$$.fragment),p=l(),j(k.$$.fragment),b=l(),j(I.$$.fragment),this.h()},l:function(e){G('[data-svelte="svelte-4bkk3f"]',document.head).forEach(m),t=d(e),S(a.$$.fragment,e),n=d(e),r=f(e,"ARTICLE",{});var c=u(r);S(o.$$.fragment,c),i=d(c),S(s.$$.fragment,c),h=d(c),S(g.$$.fragment,c),p=d(c),S(k.$$.fragment,c),b=d(c),S(I.$$.fragment,c),c.forEach(m),this.h()},h:function(){document.title="Jake Coffman"},m:function(e,c){v(e,t,c),x(a,e,c),v(e,n,c),v(e,r,c),x(o,r,null),y(r,i),x(s,r,null),y(r,h),x(g,r,null),y(r,p),x(k,r,null),y(r,b),x(I,r,null),E=!0},p:w,i:function(e){E||(L(a.$$.fragment,e),L(o.$$.fragment,e),L(s.$$.fragment,e),L(g.$$.fragment,e),L(k.$$.fragment,e),L(I.$$.fragment,e),E=!0)},o:function(e){D(a.$$.fragment,e),D(o.$$.fragment,e),D(s.$$.fragment,e),D(g.$$.fragment,e),D(k.$$.fragment,e),D(I.$$.fragment,e),E=!1},d:function(e){e&&m(t),R(a,e),e&&m(n),e&&m(r),R(o),R(s),R(g),R(k),R(I)}}}var de=function(t){e(c,s);var a=ue(c);function c(e){var t;return n(this,c),t=a.call(this),r(i(t),e,null,me,o,{}),t}return c}();export default de;
19,377.5
38,754
0.659347
ac69ce1880be5517c34bed633126aafc9ed44a87
738
js
JavaScript
__tests__/ServiceContainer.test.js
viczam/event-dispatcher
38e6080fdb30fa0b21eaca7677cf5b69bd04610e
[ "MIT" ]
7
2016-04-28T21:16:54.000Z
2016-08-20T23:41:59.000Z
__tests__/ServiceContainer.test.js
viczam/event-dispatcher
38e6080fdb30fa0b21eaca7677cf5b69bd04610e
[ "MIT" ]
21
2016-05-09T23:09:54.000Z
2016-09-18T19:53:33.000Z
__tests__/ServiceContainer.test.js
viczam/event-dispatcher
38e6080fdb30fa0b21eaca7677cf5b69bd04610e
[ "MIT" ]
null
null
null
import { ServiceBus, MessageBus, ServiceContainer, decorators } from '../src'; const { service } = decorators; class Test extends ServiceContainer { @service() sayHello(name) { return `Hello, ${name}!`; } } describe('ServiceContainer', () => { let messageBus; let serviceBus; let testService; beforeEach(() => { messageBus = new MessageBus(); serviceBus = new ServiceBus(); serviceBus.connect(messageBus); testService = serviceBus.register(new Test()); }); describe('something', () => { it('should work', async () => { expect(await testService.sayHello('John')).toBe('Hello, John!'); expect(await serviceBus.send('Test.sayHello', 'John')).toBe('Hello, John!'); }); }); });
23.806452
82
0.630081
ac6a13295a7eda0c9d811182f2482ce5ab76eecc
473
js
JavaScript
server/tools/dbs/dropTriggers.js
JEstradaTbot/tbotx
6c0a19dc0242a31a083593b5b9b379d02f7e1743
[ "MIT" ]
1
2022-02-24T17:16:19.000Z
2022-02-24T17:16:19.000Z
server/tools/dbs/dropTriggers.js
JEstradaTbot/tbotx
6c0a19dc0242a31a083593b5b9b379d02f7e1743
[ "MIT" ]
null
null
null
server/tools/dbs/dropTriggers.js
JEstradaTbot/tbotx
6c0a19dc0242a31a083593b5b9b379d02f7e1743
[ "MIT" ]
null
null
null
'use strict'; const { sequelize } = require('../../db/models'); const drops = ` DROP TRIGGER IF EXISTS create_verificationcode_after_user ON "Users"; DROP TRIGGER IF EXISTS update_userlevel_after_verify ON "VerificationCodes"; `; sequelize .query(drops, { raw: true }) .then(() => { console.log('Triggers and functions are successfully dropped'); process.exit(0); }) .catch((err) => { console.error('Error', err.message); process.exit(1); });
24.894737
76
0.668076
ac6a560ed970031368fb05c11b7ea79dcfbe0b2d
2,823
js
JavaScript
generatedata/plugins/dataTypes/SIRET/SIRET.js
novikor/sqlc
3d7cb86a2b2652251c8fa8000d28ca3d013d90d8
[ "BSD-3-Clause" ]
1
2021-02-12T08:56:25.000Z
2021-02-12T08:56:25.000Z
generatedata/plugins/dataTypes/SIRET/SIRET.js
novikor/sqlc
3d7cb86a2b2652251c8fa8000d28ca3d013d90d8
[ "BSD-3-Clause" ]
null
null
null
generatedata/plugins/dataTypes/SIRET/SIRET.js
novikor/sqlc
3d7cb86a2b2652251c8fa8000d28ca3d013d90d8
[ "BSD-3-Clause" ]
1
2017-10-25T10:29:14.000Z
2017-10-25T10:29:14.000Z
/*global $:false*/ define([ "manager", "constants", "lang", "generator" ], function(manager, C, L, generator) { "use strict"; var MODULE_ID = "data-type-SIRET"; var LANG = L.dataTypePlugins.SIRET; var _init = function() { var subscriptions = {}; subscriptions[C.EVENT.DATA_TABLE.ROW.EXAMPLE_CHANGE + "__" + MODULE_ID] = _exampleChange; manager.subscribe(MODULE_ID, subscriptions); }; var _exampleChange = function(msg) { console.log("input[name='dtOption_" + msg.rowID + "'][value='" + msg.value + "']"); $("input[name='dtOption_" + msg.rowID + "'][value='" + msg.value + "']").prop('checked', true); }; /** * Called when the user submits the form to generate some data. If the selected data set contains * one or more rows of this data type, this function is called with the list of row numbers. Note that * the row numbers passed are the *original* row numbers of the rows on creation. It's possible that the * user has re-sorted or deleted some rows. So to get the visible row number for a row, call * gen._getVisibleRowOrderByRowNum(row) */ var _validate = function(rows) { var visibleProblemRows = []; var problemFields = []; for (var i=0; i<rows.length; i++) { if ($("#dtOption_" + rows[i]).val() === "") { var visibleRowNum = generator.getVisibleRowOrderByRowNum(rows[i]); visibleProblemRows.push(visibleRowNum); problemFields.push($("#dtOption_" + rows[i])); } } var errors = []; if (visibleProblemRows.length) { errors.push({ els: problemFields, error: LANG.incomplete_fields + " <b>" + visibleProblemRows.join(", ") + "</b>"}); } return errors; }; /** * Called when the user saves a form. This function is passed the row number of the row to * save. It should return a JSON object (of whatever structure is relevant). */ var _saveRow = function(rowNum) { return { "example": $("#dtExample_" + rowNum).val(), "option": $("#dtOption_" + rowNum).val() }; }; /** * Called when a form is loaded that contains this data type. This is passed the row number and * the custom data type data to populate the fields. loadRow functions all must return an array * with two indexes - both functions: * [0] code to execute (generally inserting data into fields) * [1] a boolean test to determine WHEN the content has been inserted. */ var _loadRow = function(rowNum, data) { return { execute: function() { }, isComplete: function() { if ($("#dtOption_" + rowNum).length) { $("#dtExample_" + rowNum).val(data.example); $("#dtOption_" + rowNum).val(data.option); return true; } else { return false; } } }; }; // register our module manager.registerDataType(MODULE_ID, { init: _init, validate: _validate, loadRow: _loadRow, saveRow: _saveRow }); });
30.684783
119
0.655685
ac6a9ece9a9973dc85891eb913af2d72f6b8c3cb
8,454
js
JavaScript
lib/index.spec.js
GiladShoham/graphql-apollo-errors
1457a12245b53b81baae2712ef41d5141365bed5
[ "MIT" ]
47
2017-01-16T19:31:46.000Z
2020-09-24T19:11:19.000Z
lib/index.spec.js
GiladShoham/graphql-apollo-errors
1457a12245b53b81baae2712ef41d5141365bed5
[ "MIT" ]
9
2017-02-21T20:44:00.000Z
2021-05-09T23:20:35.000Z
lib/index.spec.js
GiladShoham/graphql-apollo-errors
1457a12245b53b81baae2712ef41d5141365bed5
[ "MIT" ]
6
2017-04-04T11:01:54.000Z
2018-03-13T07:54:13.000Z
import chai from 'chai'; import chaiAsPromised from "chai-as-promised"; import 'regenerator-runtime/runtime'; // var rewire = require("rewire"); // var index = rewire("./index.js"); import { initSevenBoom, SevenBoom, formatErrorGenerator } from './index'; chai.use(chaiAsPromised); chai.use(require('sinon-chai')); import sinon from 'sinon'; const expect = chai.expect; // Most of this tests are taken from the Boom repo // In order to make sure that you can just replace all Boom with SevenBoom describe('Init seven boom', () => { it('uses the default seven boom argsDefs - guid generator and timeThrown with errorCode arg', (done) => { const opts = [ { name : 'errorCode', order: 1 }, { name : 'timeThrown', order: 2, default: null }, { name : 'guid', order: 3, default: null } ]; initSevenBoom(opts); const error = SevenBoom.badRequest('my message', {'key': 'val'}, 'myErrCode'); expect(error.output.payload.guid).to.be.a('string'); // expect(error.output.payload.timeThrown).to.be.a.dateString(); expect(error.message).to.equal('my message'); expect(error.output.statusCode).to.equal(400); expect(error.output.payload).to.include({ statusCode: 400, error: 'Bad Request', message: 'my message', errorCode: 'myErrCode' }); expect(error.data).to.include({'key': 'val'}); done(); }); it('I can override the default seven-boom args', (done) => { const opts = [ { name : 'myCustomField', order: 1 } ]; initSevenBoom(opts); const error = SevenBoom.badRequest('my message', {'key': 'val'}, 'myCustomFieldValue'); expect(error.message).to.equal('my message'); expect(error.output.statusCode).to.equal(400); expect(error.output.payload).to.include({ statusCode: 400, error: 'Bad Request', message: 'my message', myCustomField: 'myCustomFieldValue' }); expect(error.data).to.include({'key': 'val'}); done(); }); }); describe('Format error', () => { it('Send all data object in default', (done) => { const formatError = formatErrorGenerator(); const errData = {'key': 'val'}; const error = SevenBoom.badRequest('my message', errData, 'myErrCode'); const err = _simulateGraphqlWrapping(error); const finalError = formatError(err); expect(finalError.data).to.equal(errData); done(); }); it('Send only publicPath data', (done) => { const fromatErrorOpts = { publicDataPath: 'public' } const formatError = formatErrorGenerator(fromatErrorOpts); const publicData = {'myPublic': 'data'}; const errData = {'key': 'val', public:publicData}; const error = SevenBoom.badRequest('my message', errData, 'myErrCode'); const err = _simulateGraphqlWrapping(error); const finalError = formatError(err); expect(finalError.data).to.equal(publicData); done(); }); it('Hooks are called', (done) => { const onOriginalError = sinon.spy(); const onProcessedError = sinon.spy(); const onFinalError = sinon.spy(); const hooks = { onOriginalError, onProcessedError, onFinalError } const fromatErrorOpts = { hooks } const formatError = formatErrorGenerator(fromatErrorOpts); // const errData = {'key': 'val'}; // const originalError = new Error('my message', errData, 'myErrCode'); const originalError = new Error('my message'); const processedError = SevenBoom.wrap(originalError, 500); const err = _simulateGraphqlWrapping(originalError); const finalError = formatError(err); expect( onOriginalError.calledWith(originalError) ).to.be.true; expect( onProcessedError.calledWith(processedError) ).to.be.true; expect( onFinalError.calledWith(finalError) ).to.be.true; done(); }); it('Transform regular error to SevenBoom error', (done) => { const formatError = formatErrorGenerator(); const error = new Error('my message'); const err = _simulateGraphqlWrapping(error); const finalError = formatError(err); expect( finalError.statusCode ).to.equal(500); expect( finalError.message ).to.equal('An internal server error occurred'); done(); }); it('Add the locations and path if requested', (done) => { const fromatErrorOpts = { showLocations: true, showPath: true } const formatError = formatErrorGenerator(fromatErrorOpts); const PATH = 'My path to the future'; const LOCATIONS = 'In a great place'; const error = new Error('my message'); const err = _simulateGraphqlWrapping(error, LOCATIONS, PATH); const finalError = formatError(err); expect( finalError.path ).to.equal(PATH); expect( finalError.locations ).to.equal(LOCATIONS); done(); }); it('Default hide sensitive data from internal error', (done) => { const argsDef = [ { name : 'errorCode', order: 1 },{ name : 'timeThrown', order: 3, default: null }, { name : 'guid', order: 4, default: null } ]; initSevenBoom(argsDef); const formatError = formatErrorGenerator(); const sensitiveData = {'secret': 'SevenBoom'}; const internalError = SevenBoom.internal('Technial message which client should not see', sensitiveData, 'myErrCode'); const err = _simulateGraphqlWrapping(internalError); const finalError = formatError(err); expect( finalError.data ).to.be.empty; expect( finalError.statusCode ).to.equal(500); expect( finalError.message ).to.equal('An internal server error occurred'); done(); }); it('Do not hide sensitive data from internal error when specifically asked', (done) => { const argsDef = [ { name : 'errorCode', order: 1 },{ name : 'timeThrown', order: 3, default: null }, { name : 'guid', order: 4, default: null } ]; initSevenBoom(argsDef); const formatError = formatErrorGenerator({hideSensitiveData: false}); const sensitiveData = {'secret': 'SevenBoom'}; const internalError = SevenBoom.internal('Technial message which client should not see', sensitiveData, 'myErrCode'); const err = _simulateGraphqlWrapping(internalError); const finalError = formatError(err); expect( finalError.data ).to.include(sensitiveData); expect( finalError.statusCode ).to.equal(500); expect( finalError.message ).to.equal('An internal server error occurred'); done(); }); }); // Code taken from grpahql implemantation here (with some changes): // https://github.com/graphql/graphql-js/blob/44f315d1ff72ab32b794937fd11a7f8e792fd873/src/error/GraphQLError.js#L66-L69 function _simulateGraphqlWrapping(originalError, locations, path, nodes, source, positions){ var resultError = new Error(); Object.defineProperties(resultError, { message: { value: originalError.message, // By being enumerable, JSON.stringify will include `message` in the // resulting output. This ensures that the simplist possible GraphQL // service adheres to the spec. enumerable: true, writable: true }, locations: { // Coercing falsey values to undefined ensures they will not be included // in JSON.stringify() when not provided. value: locations || [ { "line": 5, "column": 12, "field": "email" // HERE } ], // By being enumerable, JSON.stringify will include `locations` in the // resulting output. This ensures that the simplist possible GraphQL // service adheres to the spec. enumerable: true }, path: { // Coercing falsey values to undefined ensures they will not be included // in JSON.stringify() when not provided. value: path || "Some path", // By being enumerable, JSON.stringify will include `path` in the // resulting output. This ensures that the simplist possible GraphQL // service adheres to the spec. enumerable: true }, nodes: { value: nodes || 'Nodes' }, source: { value: source || 'Source', }, positions: { value: positions || 'Positions', }, originalError: { value: originalError } }); return resultError; }
32.267176
121
0.635439