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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b9807e3f2eb364c94bb67a4b21fabae5f49f490a | 2,128 | js | JavaScript | src/views/retrieval/mixin/useTable.js | Jangchain/manage-platform | 7f8fc3c96d4890448072d3aa0d2e877865cb2839 | [
"MIT"
] | null | null | null | src/views/retrieval/mixin/useTable.js | Jangchain/manage-platform | 7f8fc3c96d4890448072d3aa0d2e877865cb2839 | [
"MIT"
] | null | null | null | src/views/retrieval/mixin/useTable.js | Jangchain/manage-platform | 7f8fc3c96d4890448072d3aa0d2e877865cb2839 | [
"MIT"
] | null | null | null |
import { reactive, toRefs } from '@vue/composition-api'
import { download, deleteRetrieval } from '@/api/table.js'
export function useTable(ctx, { detail }) {
const state = reactive({
selected: [],
detail: detail ?? 'NaturalDetail'
})
// 处理勾选
const handleSelectionChange = val => {
console.log('handleSelectionChange', val)
state.selected = val
}
// 查看
const handleViewRow = params => {
console.log('查看')
ctx.root.$router.push({
name: state.detail,
params: { ...params, type: state.detail }
})
}
// 下载
const handleDownloadRow = row => {
download(row.name).then(res => {
const { downloadPath, errorDesc } = res
if (downloadPath) {
window.open(downloadPath)
} else {
ctx.root.$message({
type: 'error',
message: errorDesc
})
}
})
}
// 删除
const deleteRow = name => {
console.log('删除成功---', name)
deleteRetrieval(name).then(res => {
console.log('res', res)
if (res) {
ctx.emit('delete', '')
ctx.root.$message({
type: 'success',
message: '删除成功!'
})
} else {
ctx.root.$message({
type: 'error',
message: '删除失败!'
})
}
})
}
// 删除
const handleDeleteRow = row => {
console.log('删除', row)
ctx.root
.$confirm(
'一旦删除该条信息,将无法恢复, 是否继续?',
'确认要删除这条信息吗?',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
customClass: 'retrieval-table-message-box',
center: true
}
)
.then(() => {
deleteRow(row.name)
})
.catch(() => {
ctx.root.$message({
type: 'info',
message: '已取消删除'
})
})
}
// 点击单元格
const handleCellClick = (row, column) => {
if (column.property === 'name') {
handleViewRow(state.detail, { name: row.name })
}
}
return {
...toRefs(state),
handleDeleteRow,
handleDownloadRow,
handleViewRow,
handleSelectionChange,
handleCellClick
}
}
| 20.660194 | 58 | 0.514568 |
b980e3a17f81d9fb9fd0288142dca42c929c00b7 | 1,406 | js | JavaScript | features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/devportal/source/Tests/Integration/setup.js | natechols/carbon-apimgt | 321b0f4f0e3103e8011bfde6b3aa1feb56900872 | [
"Apache-2.0"
] | 5 | 2021-05-04T10:35:47.000Z | 2022-03-17T08:31:54.000Z | features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/devportal/source/Tests/Integration/setup.js | natechols/carbon-apimgt | 321b0f4f0e3103e8011bfde6b3aa1feb56900872 | [
"Apache-2.0"
] | 125 | 2018-12-25T06:32:19.000Z | 2021-06-29T05:16:45.000Z | features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/devportal/source/Tests/Integration/setup.js | natechols/carbon-apimgt | 321b0f4f0e3103e8011bfde6b3aa1feb56900872 | [
"Apache-2.0"
] | 60 | 2021-05-04T10:35:50.000Z | 2022-03-31T09:08:56.000Z | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
const puppeteer = require('puppeteer');
const fs = require('fs');
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');
const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
module.exports = async function () {
console.log('\nSetup Puppeteer');
const browser = await puppeteer.launch({
// headless: false,
});
// This global is not available inside tests but only in global teardown
// eslint-disable-next-line no-underscore-dangle
global.__BROWSER_GLOBAL__ = browser;
// Instead, we expose the connection details via file system to be used in tests
mkdirp.sync(DIR);
fs.writeFileSync(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
};
| 37 | 84 | 0.709815 |
b98158d3fbafdd6622005ec3579c0c6231060d8d | 383 | js | JavaScript | bin/xperf.js | X-Profiler/xperf | c9499df6aa4718ea33078f1a240d1a7533408547 | [
"BSD-2-Clause"
] | 1 | 2021-07-07T01:53:57.000Z | 2021-07-07T01:53:57.000Z | bin/xperf.js | X-Profiler/xperf | c9499df6aa4718ea33078f1a240d1a7533408547 | [
"BSD-2-Clause"
] | null | null | null | bin/xperf.js | X-Profiler/xperf | c9499df6aa4718ea33078f1a240d1a7533408547 | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/env node
'use strict';
const xargs = require('../lib/xargs');
const args = xargs
.usage('xperf start [script.js] [options]')
.command('start', script => (/^.*\.js$/.test(script)), 'script must be js!')
.option('start-cpu-profiling').boolean()
.option('start-gc-profiling').boolean()
.option('start-heap-profling').boolean()
.argv;
console.log(12333, args); | 25.533333 | 78 | 0.644909 |
b982140fd8521316f8820833803d059d745ff82f | 12,690 | js | JavaScript | companion/tracking.spec.js | Th3Un1q3/toggl-watch-app | fbee397e7ea47ee601355cf295d18d99fee059ed | [
"MIT"
] | 1 | 2021-07-27T04:28:55.000Z | 2021-07-27T04:28:55.000Z | companion/tracking.spec.js | Th3Un1q3/toggl-watch-app | fbee397e7ea47ee601355cf295d18d99fee059ed | [
"MIT"
] | 120 | 2020-04-15T14:52:17.000Z | 2022-02-09T09:05:01.000Z | companion/tracking.spec.js | Th3Un1q3/toggl-watch-app | fbee397e7ea47ee601355cf295d18d99fee059ed | [
"MIT"
] | null | null | null | import _ from 'lodash';
import faker from 'faker';
import {
ENTRIES_REFRESH_INTERVAL,
NO_PROJECT_COLOR, NO_PROJECT_INFO,
OPTIMAL_TEXTS_LENGTH, timeEntryDetails,
Tracking,
} from './tracking';
import {API} from './api';
import {Transmitter} from '../common/transmitter';
import flushPromises from 'flush-promises';
import {MESSAGE_TYPE} from '../common/message-types';
import {timeEntryBody} from '../utils/factories/time-entries';
import {projectBody} from '../utils/factories/projects';
import {gettext} from '../__mocks__/i18n';
jest.mock('../common/transmitter');
jest.mock('./api');
describe('Tracking', () => {
let tracking;
let api;
beforeEach(async () => {
api = new API();
tracking = new Tracking({api, transmitter: new Transmitter()});
await flushPromises();
jest.clearAllMocks();
});
const assertRefreshesCurrentEntry = () => {
it('should make tracking.refreshCurrentEntry', () => {
expect(tracking.refreshCurrentEntry)
.toHaveBeenCalledTimes(1);
});
};
describe('commands handling', () => {
let currentEntry;
let entryInLog;
beforeEach(async () => {
currentEntry = timeEntryBody({stop: faker.date.past()});
entryInLog = timeEntryBody();
api.fetchTimeEntries.mockResolvedValue([
currentEntry,
entryInLog,
]);
api.fetchProjects.mockResolvedValue([]);
api.fetchCurrentEntry.mockResolvedValue(currentEntry);
await tracking.initialize();
jest.spyOn(tracking, 'refreshCurrentEntry');
await flushPromises();
});
test('api is not called initially', () => {
expect(api.updateTimeEntry).not.toHaveBeenCalled();
expect(api.createTimeEntry).not.toHaveBeenCalled();
expect(api.deleteTimeEntry).not.toHaveBeenCalled();
expect(tracking.refreshCurrentEntry).not.toHaveBeenCalled();
});
describe('request time entry details', () => {
beforeEach(() => {
Transmitter.emitMessageReceived(MESSAGE_TYPE.REQUEST_ENTRY_DETAILS, {
entryId: entryInLog.id,
});
});
it('should send time entry info from the log', () => {
expect(Transmitter.instanceSendMessage).toHaveBeenLastCalledWith({
type: MESSAGE_TYPE.TIME_ENTRY_DETAILS,
data: {
...timeEntryDetails(entryInLog),
cur: false,
},
});
});
});
describe('stop current entry', () => {
let stop;
beforeEach(() => {
stop = Date.now();
Transmitter.emitMessageReceived(MESSAGE_TYPE.STOP_TIME_ENTRY, {
id: currentEntry.id,
stop,
});
});
it('should call api.updateTimeEntry with stop property from message', () => {
expect(api.updateTimeEntry).toHaveBeenCalledTimes(1);
expect(api.updateTimeEntry).toHaveBeenLastCalledWith(expect.objectContaining({
id: currentEntry.id,
stop: new Date(stop).toISOString(),
}));
});
describe('when id from message does not match current', () => {
beforeEach(async () => {
api.updateTimeEntry.mockClear();
Transmitter.emitMessageReceived(MESSAGE_TYPE.STOP_TIME_ENTRY, {
id: faker.random.number(),
stop,
});
await flushPromises();
});
it('should not call api.updateTimeEntry', () => {
expect(api.updateTimeEntry).not.toHaveBeenCalled();
});
});
});
describe('resume last entry', () => {
let start;
let wid;
beforeEach(() => {
wid = faker.random.number();
start = Date.now();
api.fetchUserInfo.mockResolvedValue({default_workspace_id: wid});
Transmitter.emitMessageReceived(MESSAGE_TYPE.START_TIME_ENTRY, {
id: currentEntry.id,
start,
});
});
it('should call api.createTimeEntry with entry data and start from message', () => {
expect(api.createTimeEntry).toHaveBeenCalledTimes(1);
expect(api.createTimeEntry).toHaveBeenLastCalledWith(expect.objectContaining({
id: currentEntry.id,
start: new Date(start).toISOString(),
stop: null,
}));
});
describe('when there is entry matched by id', () => {
beforeEach(async () => {
api.createTimeEntry.mockClear();
api.fetchCurrentEntry.mockResolvedValue(null);
await tracking.initialize();
tracking.currentEntry = null;
await flushPromises();
Transmitter.emitMessageReceived(MESSAGE_TYPE.START_TIME_ENTRY, {
start,
});
await flushPromises();
});
it('should create new with "wid"(required property) taken from user', () => {
expect(api.createTimeEntry).toHaveBeenLastCalledWith(expect.objectContaining({
start: new Date(start).toISOString(),
stop: null,
wid,
}));
});
});
describe('when id from message does not match current', () => {
beforeEach(async () => {
api.createTimeEntry.mockClear();
Transmitter.emitMessageReceived(MESSAGE_TYPE.START_TIME_ENTRY, {
id: entryInLog.id,
start,
});
await flushPromises();
});
it('should resume entry from the log', () => {
expect(api.createTimeEntry).toHaveBeenLastCalledWith(expect.objectContaining({
...entryInLog,
start: new Date(start).toISOString(),
stop: null,
}));
});
});
});
describe('delete current entry', () => {
beforeEach(() => {
Transmitter.emitMessageReceived(MESSAGE_TYPE.DELETE_TIME_ENTRY, {
id: currentEntry.id,
});
});
it('should call api.deleteTimeEntry with entry id', () => {
expect(api.deleteTimeEntry).toHaveBeenCalledTimes(1);
expect(api.deleteTimeEntry).toHaveBeenLastCalledWith(expect.objectContaining({
id: currentEntry.id,
}));
});
assertRefreshesCurrentEntry();
describe('when id from message does not match current', () => {
beforeEach(async () => {
api.deleteTimeEntry.mockClear();
Transmitter.emitMessageReceived(MESSAGE_TYPE.DELETE_TIME_ENTRY, {
id: faker.random.number(),
});
await flushPromises();
});
it('should not call api.deleteTimeEntry', () => {
expect(api.deleteTimeEntry).not.toHaveBeenCalled();
});
});
});
});
describe('.initialize', () => {
it('should fetch current user', async () => {
expect(api.fetchUserInfo).not.toHaveBeenCalled();
await tracking.initialize();
expect(api.fetchUserInfo).toHaveBeenCalledTimes(1);
});
describe('when all api requests pass', () => {
let currentEntry;
let currentEntryProject;
let projects;
let lastTimeEntry;
beforeEach(async () => {
projects = _.times(10, projectBody);
currentEntryProject = _.sample(projects);
currentEntry = timeEntryBody({
description: 'Short description',
pid: currentEntryProject.id,
});
lastTimeEntry = timeEntryBody({
description: _.times(OPTIMAL_TEXTS_LENGTH, () => 'BumBada').join(''),
isPlaying: false,
id: currentEntry.id - 1,
pid: currentEntryProject.id,
});
api.fetchTimeEntries.mockResolvedValue([
currentEntry,
lastTimeEntry,
]);
api.fetchUserInfo.mockResolvedValue({id: 20});
api.fetchCurrentEntry.mockResolvedValue(currentEntry);
api.fetchProjects.mockResolvedValue(projects);
Transmitter.instanceSendMessage.mockClear();
await tracking.initialize();
});
it('should fetch current time entry', async () => {
expect(api.fetchCurrentEntry).toHaveBeenCalledTimes(1);
});
it('should transmit current entry basic info', async () => {
const expectedData = expect.objectContaining({
id: currentEntry.id,
desc: currentEntry.description,
start: Date.parse(currentEntry.start),
isPlaying: true,
bil: currentEntry.billable,
});
expect(Transmitter.instanceSendMessage).toHaveBeenCalledWith({
type: MESSAGE_TYPE.TIME_ENTRY_DETAILS,
data: expectedData,
});
});
it('should transmit entries log with ids', () => {
expect(Transmitter.instanceSendMessage).toHaveBeenCalledWith({
type: MESSAGE_TYPE.ENTRIES_LOG_UPDATE,
data: [lastTimeEntry.id],
});
});
it('should transmit project name and color', async () => {
expect(Transmitter.instanceSendMessage).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
color: currentEntryProject.color,
projectName: currentEntryProject.name,
}),
}));
});
it('should send entries updates in intervals', async () => {
jest.advanceTimersByTime(ENTRIES_REFRESH_INTERVAL*2);
await flushPromises();
currentEntry = timeEntryBody({description: faker.lorem.word()});
api.fetchCurrentEntry.mockResolvedValueOnce(currentEntry);
jest.advanceTimersByTime(ENTRIES_REFRESH_INTERVAL);
await flushPromises();
const expectedData = expect.objectContaining({
id: currentEntry.id,
cur: true,
desc: currentEntry.description,
start: Date.parse(currentEntry.start),
bil: currentEntry.billable,
});
expect(Transmitter.instanceSendMessage).toHaveBeenCalledWith({
type: MESSAGE_TYPE.TIME_ENTRY_DETAILS,
data: expectedData,
});
});
describe('when project is not present', () => {
beforeEach(async () => {
currentEntry = _.without(timeEntryBody(), 'pid', 'description');
api.fetchCurrentEntry.mockResolvedValue(currentEntry);
Transmitter.instanceSendMessage.mockClear();
await tracking.initialize();
});
it('should set project name to "no project" and color to gray', async () => {
expect(Transmitter.instanceSendMessage).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({
desc: gettext('no_description'),
color: NO_PROJECT_COLOR,
projectName: gettext('no_project'),
}),
}));
});
});
describe('when entry is null', () => {
beforeEach(async () => {
api.fetchTimeEntries.mockResolvedValue([lastTimeEntry]);
api.fetchCurrentEntry.mockResolvedValue(null);
Transmitter.instanceSendMessage.mockClear();
await tracking.initialize();
});
describe('when entries present', () => {
it('should send the first of them', async () => {
expect(Transmitter.instanceSendMessage).toHaveBeenLastCalledWith(expect.objectContaining({
data: expect.objectContaining({isPlaying: false, start: Date.parse(lastTimeEntry.start)}),
}));
expect(Transmitter.instanceSendMessage).toHaveBeenLastCalledWith({
type: MESSAGE_TYPE.TIME_ENTRY_DETAILS,
data: expect.objectContaining({
id: lastTimeEntry.id,
cur: true,
desc: expect.stringContaining(lastTimeEntry.description.slice(0, 50)),
bil: lastTimeEntry.billable,
}),
});
});
});
describe('and there is no last entry', () => {
beforeEach(async () => {
api.fetchTimeEntries.mockResolvedValue([]);
Transmitter.instanceSendMessage.mockClear();
await tracking.initialize();
});
it('should transmit empty time entries log', () => {
expect(Transmitter.instanceSendMessage).toHaveBeenCalledWith({
type: MESSAGE_TYPE.ENTRIES_LOG_UPDATE,
data: [],
});
});
it('should send update with default current entry', async () => {
expect(Transmitter.instanceSendMessage).toHaveBeenCalledWith({
type: MESSAGE_TYPE.TIME_ENTRY_DETAILS,
data: {
desc: gettext('no_description'),
cur: true,
bil: false,
...NO_PROJECT_INFO,
},
});
});
});
});
});
});
});
| 31.179361 | 104 | 0.589598 |
b9822db029a9ec5223d4800cb1114c0cdacf5e60 | 297 | js | JavaScript | doxygen_docs/html/yshell_8cpp.js | flyinskyin2013/yLib_Docs | 7d47f060b5531449e6455e188190ba4f2ee67153 | [
"BSD-3-Clause"
] | null | null | null | doxygen_docs/html/yshell_8cpp.js | flyinskyin2013/yLib_Docs | 7d47f060b5531449e6455e188190ba4f2ee67153 | [
"BSD-3-Clause"
] | null | null | null | doxygen_docs/html/yshell_8cpp.js | flyinskyin2013/yLib_Docs | 7d47f060b5531449e6455e188190ba4f2ee67153 | [
"BSD-3-Clause"
] | null | null | null | var yshell_8cpp =
[
[ "SHELL_CMDANDPARAM_MAX_NUM", "yshell_8cpp.html#a2caf8e0a2fc316a7703f72044c8c68ab", null ],
[ "Y_SHELL_ARGV_LEN", "yshell_8cpp.html#a8d03008c07653341eb6daa10557420d9", null ],
[ "Y_SHELL_LOC_CMD_LEN", "yshell_8cpp.html#adfa6869d5281c5d1597c9dec1f0bf9e6", null ]
]; | 49.5 | 96 | 0.774411 |
b98288d14bed20aa72ecf3f1955c091331bfc041 | 1,144 | js | JavaScript | src/components/Spinner/Spinner.test.js | psywalker/react-gh-pages | bd7413788d802977d024c82860e7c2574f7155d0 | [
"MIT"
] | 5 | 2019-02-25T08:30:05.000Z | 2021-01-26T09:18:39.000Z | src/components/Spinner/Spinner.test.js | psywalker/react-gh-pages | bd7413788d802977d024c82860e7c2574f7155d0 | [
"MIT"
] | 73 | 2018-11-10T12:47:18.000Z | 2019-11-28T13:39:00.000Z | src/components/Spinner/Spinner.test.js | psywalker/react-gh-pages | bd7413788d802977d024c82860e7c2574f7155d0 | [
"MIT"
] | 3 | 2019-06-05T16:26:35.000Z | 2019-07-01T10:53:06.000Z | import React from 'react';
import Spinner from '.';
describe('Test of component of Spinner', () => {
// Default Data
const initialProps = {
};
const pageSpinnerContainer = 'div[data-test="spinnerContainer"]';
const pageSpinnerInner = 'div[data-test="spinnerInner"]';
const pageSpinnerInnerItem = 'div[data-test="spinnerInnerItem"]';
const appSelector = wrapper => ({
getSpinnerContainer: () => wrapper.find(pageSpinnerContainer),
getPageSpinnerInner: () => wrapper.find(pageSpinnerInner),
getPageSpinnerInnerItem: () => wrapper.find(pageSpinnerInnerItem),
});
// const propses = {
// ...initialProps,
// };
// const spinner = global.mountWrap(<Spinner {...propses} />);
// console.log(spinner.debug());
describe('Spinner component initial', () => {
it('renders without initial props', () => {
const spinnerMount = global.mountWrap(<Spinner />);
const page = appSelector(spinnerMount);
const spinnerContainer = page.getSpinnerContainer();
const spinnerInner = page.getPageSpinnerInner();
const spinnerInnerItem = page.getPageSpinnerInnerItem();
});
});
}); | 31.777778 | 70 | 0.670455 |
b98474d68ffd7c2226ca357b1e03299dde884730 | 2,625 | js | JavaScript | src/extended-repeater.js | PavelBradnitski/basic-js | 8691875994ff2b87b54e318f0bee17df7d5df717 | [
"MIT"
] | null | null | null | src/extended-repeater.js | PavelBradnitski/basic-js | 8691875994ff2b87b54e318f0bee17df7d5df717 | [
"MIT"
] | null | null | null | src/extended-repeater.js | PavelBradnitski/basic-js | 8691875994ff2b87b54e318f0bee17df7d5df717 | [
"MIT"
] | null | null | null | const CustomError = require("../extensions/custom-error");
module.exports = function repeater(str, options) {
let init = String(str);
if(options.repeatTimes === undefined) {
if(options.additionRepeatTimes === undefined){
if (options.addition !== undefined) str = str + String(options.addition);
} else {
for(let j=0;j<options.additionRepeatTimes;j++){
if (j != options.additionRepeatTimes-1){
if (options.additionSeparator === undefined){
str = String(str) + String(options.addition) + '|';
}else{
str = String(str) + String(options.addition) + String.additionSeparator;
};
} else {
str = String(str) + String(options.addition);
};
if(options.separator === undefined){
str = String(str) + '+';
}else {
str = String(str) + options.separator;
};
}
str = str + init;
}
} else {
for(let i = 0; i<options.repeatTimes-1;i++){
if(options.additionRepeatTimes === undefined){
if (options.addition !== undefined) str = String(str) + String(options.addition);
if (options.separator === undefined){
str = String(str) + '+' + init;
}else{
str = String(str) + String(options.separator) + init;
};
}else {
for(let j=0;j<options.additionRepeatTimes;j++){
if (j != options.additionRepeatTimes-1){
if (options.additionSeparator === undefined){
str = String(str) + String(options.addition) + '|';
}else{
str = String(str) + String(options.addition) + String(options.additionSeparator);
};
}else {
str = String(str) + String(options.addition);
};
}
if(options.separator === undefined){
str = String(str) + '+';
}else {
str = String(str) + options.separator;
};
str = str + init;
}
}
if (options.additionRepeatTimes === undefined) {
if (options.addition !== undefined) str = String(str) + String(options.addition);
} else {
for(let j=0;j<options.additionRepeatTimes;j++){
if (j != options.additionRepeatTimes-1){
if (options.additionSeparator === undefined){
str = String(str) + String(options.addition) + '|';
}else{
str = String(str) + String(options.addition) + String(options.additionSeparator);
};
}else {
str = String(str) + String(options.addition);
};
}
}
}
return str;
};
| 35 | 95 | 0.54019 |
b984edd98f4902c7e6c19f63d0d0da67f0c32a24 | 262 | js | JavaScript | obj/src/version1/PlatformDataV1.js | pip-services-ecommerce/pip-clients-payments-node | 432564a93c2c4336f98a3d4751bd49a23040ca1c | [
"MIT"
] | null | null | null | obj/src/version1/PlatformDataV1.js | pip-services-ecommerce/pip-clients-payments-node | 432564a93c2c4336f98a3d4751bd49a23040ca1c | [
"MIT"
] | null | null | null | obj/src/version1/PlatformDataV1.js | pip-services-ecommerce/pip-clients-payments-node | 432564a93c2c4336f98a3d4751bd49a23040ca1c | [
"MIT"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class PlatformDataV1 {
constructor(platform_id) {
this.platform_id = platform_id;
}
}
exports.PlatformDataV1 = PlatformDataV1;
//# sourceMappingURL=PlatformDataV1.js.map | 29.111111 | 62 | 0.732824 |
b985a94b2d8b1c113d0c8a90fc2e666ddc546a3d | 231 | js | JavaScript | test/kitchensink/src/components/features/less-camelcase-inclusion.js | shilomagen/yoshi | 26e12693257abb65a85868821d43fbab43d9afaa | [
"RSA-MD"
] | 1 | 2018-03-27T11:27:24.000Z | 2018-03-27T11:27:24.000Z | test/kitchensink/src/components/features/less-camelcase-inclusion.js | shilomagen/yoshi | 26e12693257abb65a85868821d43fbab43d9afaa | [
"RSA-MD"
] | 3 | 2018-03-21T10:26:02.000Z | 2021-03-03T06:53:37.000Z | test/kitchensink/src/components/features/less-camelcase-inclusion.js | shilomagen/yoshi | 26e12693257abb65a85868821d43fbab43d9afaa | [
"RSA-MD"
] | null | null | null | import React from 'react';
import styles from './assets/style.less';
export default () => (
<div>
<p id="less-camelcase-inclusion" className={styles.lessModulesInclusion}>
CSS Modules are working!
</p>
</div>
);
| 21 | 77 | 0.65368 |
b9870eaaf244ac00d554a88132830e06f1da0f15 | 9,668 | js | JavaScript | src/Containers/Checkout/Checkout.js | MarcinSufa/Shoemaster | b006cb1d046ba7d42ffeb63050657da339006604 | [
"MIT"
] | 1 | 2019-07-18T05:48:34.000Z | 2019-07-18T05:48:34.000Z | src/Containers/Checkout/Checkout.js | MarcinSufa/Shoemaster | b006cb1d046ba7d42ffeb63050657da339006604 | [
"MIT"
] | null | null | null | src/Containers/Checkout/Checkout.js | MarcinSufa/Shoemaster | b006cb1d046ba7d42ffeb63050657da339006604 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import './Checkout.css';
import axios from '../../axios-products';
import Spinner from "../../Components/UI/Spinner/Spinner";
import Input from '../../Components/UI/Input/Input';
import Button from '../../Components/UI/Button/Button';
import { connect } from 'react-redux';
import * as checkoutListActions from '../../store/actions/index';
class Checkout extends Component {
state= {
Order: null,
CustomerData:{
name: {
elementType:'input',
elementConfig: {
type: 'text',
placeholder: 'Your Name'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
street: {
elementType:'input',
elementConfig: {
type: 'text',
placeholder: 'Street'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
zipCode: {
elementType:'input',
elementConfig: {
type: 'text',
placeholder: 'ZIP Code'
},
value: '',
validation: {
required: true,
minLength: 5,
maxLength: 6
},
valid: false,
touched: false
},
country: {
elementType:'input',
elementConfig: {
type: 'text',
placeholder: 'Country'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
email: {
elementType:'input',
elementConfig: {
type: 'email',
placeholder: 'Your E-Mail'
},
value: '',
validation: {
required: true
},
valid: false,
touched: false
},
deliveryMethod: {
elementType:'select',
elementConfig: {
options: [
{value: 'fastest', displayValue: 'Delivery - Fastest'},
{value: 'cheapest', displayValue: 'Delivery - Cheapest'},
]
},
value: 'fastest',
validation: {},
valid: true
}
},
loading: false,
error: false,
checkoutPrice: null,
formIsValid: false
}
orderHandler = (event) => {
event.preventDefault();
this.setState ({loading: true});
const customerData = {};
let userToken = this.props.token;
for (let formElementIdentifier in this.state.CustomerData) {
customerData[formElementIdentifier] = this.state.CustomerData[formElementIdentifier]
}
let OrderDate = new Date().toLocaleString();
const order = {
OrderDetails: this.props.Cart,
CustomerData: customerData,
OrderDate: OrderDate ,
Price: this.props.fullPrice,
userId: this.props.userId
}
axios.post ('/orders.json?auth=' + userToken, order)
.then ( response => {
this.setState({loading: false});
this.props.cartDeleteHandler();
this.props.onUpdateCart();
//to do - render success component
})
.then ( () => this.props.history.replace('/'))
.catch (error => {
this.setState({loading: false});
});
}
componentDidMount (props) {
if(!this.props.token) {
this.props.history.replace('/');
}
this.props.onInitCheckout();
console.log(this.props.Cart)
console.log(this.state.Order)
}
fullPriceCheckout = () => {
let allCartPrices = Object.values(this.props.Cart);
let fullPrice= 0;
for (let i = 0; i < allCartPrices.length; i++) {
fullPrice += allCartPrices[i].price;
}
this.setState({checkoutPrice: fullPrice});
}
checkValidity (value, rules) {
let isValid = true;
if (rules.required) {
isValid = value.trim() !== '' && isValid;
}
if(rules.minLength) {
isValid = value.length >= rules.minLength && isValid;
}
if(rules.maxLength) {
isValid = value.length <= rules.maxLength && isValid;
}
return isValid;
}
// User input will update state and present input to form
inputChangeHandler= (event, inputIdentifier) => {
const updatedCustomerData = {
...this.state.CustomerData
};
const updatedFormElement = {
...updatedCustomerData[inputIdentifier]
};
updatedFormElement.value = event.target.value;
updatedFormElement.valid = this.checkValidity(updatedFormElement.value, updatedFormElement.validation)
updatedFormElement.touched= true;
updatedCustomerData[inputIdentifier] = updatedFormElement;
let formIsValid = true;
for ( let inputIdentifier in updatedCustomerData) {
formIsValid = updatedCustomerData[inputIdentifier].valid && formIsValid
}
this.setState({CustomerData: updatedCustomerData, formIsValid:formIsValid})
}
// redirect to /Cart if user want to edit cart //
handleCartEdit = () => {
this.props.history.replace('/Cart');
}
render () {
let orderPrice = this.props.fullPrice;
let form = null;
let formElementArray = [];
let printCheckoutProducts = null;
for (let key in this.state.CustomerData){
formElementArray.push({
id: key,
config: this.state.CustomerData[key]
});
}
if(this.props.loading) {
return <Spinner/>
}
else if(this.props.fullPrice && this.props.Cart) {
orderPrice = <h4>{this.props.fullPrice} $</h4>
form = (
<form onSubmit={this.orderHandler}>
<h3>Contact Data</h3>
{formElementArray.map(formElement => (
<Input
key={formElement.id}
elementType={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
changed={(event) => this.inputChangeHandler(event, formElement.id)}
invalid={!formElement.config.valid}
shouldValidate={formElement.config.validation}
touched={formElement.config.touched}
/>
))}
<Button disabled={!this.state.formIsValid}>ORDER</Button>
</form>
)
printCheckoutProducts = (Object.entries(this.props.Cart).map((product) => {
return (
<div className='ProductInCheckout' key={product[0]}>
<div className='CheckoutProductInfo' ><img className='CheckoutProductImage' src={product[1].image} alt='nike shoes'></img></div>
<div className='ProductWrapper'>
<div className='CheckoutProductInfo'><p>{product[1].brand}</p><p>{product[1].model}</p><p>{product[1].size}</p></div>
<div className='CheckoutProductInfo'><p>{product[1].price}$</p> </div>
</div>
</div>
);
}));
}
return (
<div className='Checkoutwrapper'>
<h1>Checkout</h1>
<hr></hr>
<div className='CheckoutTemplate'>
<div className ='CheckoutForm'>
{form}
</div>
<div className='CheckoutSummary'>
<h3>Order Summary</h3>
<hr></hr>
<div className='OrderFullPrice'>
<h4>Order Price: </h4>{orderPrice}
</div>
<p>Product list</p>
{ printCheckoutProducts}
<div className='editCartBtn'><Button btnType='editCartBtn' clicked={this.handleCartEdit}>Edit</Button></div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
Cart: state.cart.cart,
loading: state.cart.loading,
fullPrice: state.cart.fullCartPrice,
token: state.auth.token,
userId: state.auth.userId
};
}
const mapDispatchToProps = dispatch => {
return {
onInitCheckout: () => dispatch(checkoutListActions.fetchLocalStoreCart()),
cartDeleteHandler: () => dispatch(checkoutListActions.clearLocalStore()),
onUpdateCart: () => dispatch(checkoutListActions.fetchLocalStoreCart()),
};
}
export default connect(mapStateToProps, mapDispatchToProps) (Checkout); | 34.65233 | 144 | 0.481175 |
b987165ae163abfa3425eff17ab25009055c6421 | 2,618 | js | JavaScript | website/src/pages/index.js | Kevin-Lee/maven2sbt | 78477c52d558f4030d9a264eafc7587181ad791c | [
"MIT"
] | 14 | 2017-04-04T12:26:22.000Z | 2021-07-24T04:12:07.000Z | website/src/pages/index.js | Kevin-Lee/maven2sbt | 78477c52d558f4030d9a264eafc7587181ad791c | [
"MIT"
] | 63 | 2017-04-03T13:27:50.000Z | 2022-01-10T11:56:27.000Z | website/src/pages/index.js | Kevin-Lee/maven2sbt | 78477c52d558f4030d9a264eafc7587181ad791c | [
"MIT"
] | 3 | 2020-09-25T02:40:24.000Z | 2022-02-18T10:33:19.000Z | import React from 'react';
import clsx from 'clsx';
import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import styles from './styles.module.css';
const features = [
{
title: <>Maven to sbt</>,
imageUrl: 'img/m2s.svg',
description: (
<>
Convert Maven's <code>pom.xml</code> into sbt's <code>build.sbt</code>.
</>
),
},
{
title: <>Library</>,
imageUrl: 'img/files-and-folders.svg',
description: (
<>
It can be used as a normal Scala library.
</>
),
},
{
title: <>CLI</>,
imageUrl: 'img/terminal.svg',
description: (
<>
It can be used as a CLI tool with an easy installation if you already have Java.
</>
),
},
];
function Feature({imageUrl, title, description}) {
const imgUrl = useBaseUrl(imageUrl);
return (
<div className={clsx('col col--4', styles.feature)}>
{imgUrl && (
<div className="text--center">
<img className={styles.featureImage} src={imgUrl} alt={title} />
</div>
)}
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}
function Home() {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
return (
<Layout
title={`${siteConfig.title}`}
description="Convert Maven's pom.xml into build.sbt">
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<img src={`${useBaseUrl('img/')}/poster.png`} alt="Project Logo" />
<h1 className="hero__title">{siteConfig.title}</h1>
<p className="hero__subtitle"><div dangerouslySetInnerHTML={{__html: siteConfig.tagline}} /></p>
<div className={styles.buttons}>
<Link
className={clsx(
'button button--outline button--secondary button--lg',
styles.getStarted,
)}
to={useBaseUrl('docs/')}>
Get Started
</Link>
</div>
</div>
</header>
<main>
{features && features.length > 0 && (
<section className={styles.features}>
<div className="container">
<div className="row">
{features.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
</div>
</section>
)}
</main>
</Layout>
);
}
export default Home;
| 27.270833 | 106 | 0.541635 |
b98727427ca993ec6bf85c3786706bfe4372f896 | 234 | js | JavaScript | Dashboard/WebContent/resources/js/common/command.js | t-hiramatsu/ENdoSnipe | ee6af4a70946d42e4a7b0134f17f6851d2921db4 | [
"MIT"
] | null | null | null | Dashboard/WebContent/resources/js/common/command.js | t-hiramatsu/ENdoSnipe | ee6af4a70946d42e4a7b0134f17f6851d2921db4 | [
"MIT"
] | null | null | null | Dashboard/WebContent/resources/js/common/command.js | t-hiramatsu/ENdoSnipe | ee6af4a70946d42e4a7b0134f17f6851d2921db4 | [
"MIT"
] | null | null | null | function command(target, argument) {
this.target = target;
this.argument = argument;
};
command.prototype.execute = function() {
};
command.prototype.redo = function() {
};
command.prototype.undo = function() {
}; | 15.6 | 41 | 0.649573 |
b9876ffc6b197a4ae489231101d83ed5d4d877e5 | 156 | js | JavaScript | pathfinder-character-sheet/src/Components/Feats/obsFeats.js | YellowSmiley/PathfinderCharSheet | f5fa103eccaf56f038b17033b1cc779301e2d4c4 | [
"MIT"
] | null | null | null | pathfinder-character-sheet/src/Components/Feats/obsFeats.js | YellowSmiley/PathfinderCharSheet | f5fa103eccaf56f038b17033b1cc779301e2d4c4 | [
"MIT"
] | null | null | null | pathfinder-character-sheet/src/Components/Feats/obsFeats.js | YellowSmiley/PathfinderCharSheet | f5fa103eccaf56f038b17033b1cc779301e2d4c4 | [
"MIT"
] | null | null | null | import { observable } from "mobx";
const obsFeats = observable({
feats: { mastered: [], specialAbilities: [], traits: [] }
});
export default obsFeats;
| 19.5 | 59 | 0.660256 |
b987b55494f499fb03cbd65105e12d2e8cdbf508 | 37 | js | JavaScript | icon[ds-4].js | nitrogen17/skin | b490cd988f9204d6a01be1a6e87ea15f86486ac7 | [
"MIT"
] | null | null | null | icon[ds-4].js | nitrogen17/skin | b490cd988f9204d6a01be1a6e87ea15f86486ac7 | [
"MIT"
] | 1 | 2021-02-24T03:08:52.000Z | 2021-02-24T03:08:52.000Z | icon[ds-4].js | nitrogen17/skin | b490cd988f9204d6a01be1a6e87ea15f86486ac7 | [
"MIT"
] | null | null | null | require('./dist/icon/ds4/icon.css');
| 18.5 | 36 | 0.675676 |
b9887abafdd011cb58e458f974a5b2368d5c8b20 | 1,274 | js | JavaScript | lib/crud-ops/update.js | thanpolas/crude | a45418747df2913db5b2c011f09c546e23cc719c | [
"MIT"
] | 15 | 2015-01-22T01:46:40.000Z | 2021-01-18T15:10:44.000Z | lib/crud-ops/update.js | thanpolas/crude | a45418747df2913db5b2c011f09c546e23cc719c | [
"MIT"
] | 1 | 2017-04-28T04:14:38.000Z | 2017-06-29T08:18:20.000Z | lib/crud-ops/update.js | thanpolas/crude | a45418747df2913db5b2c011f09c546e23cc719c | [
"MIT"
] | 7 | 2015-08-03T14:46:12.000Z | 2017-01-20T21:21:48.000Z | /**
* @fileOverview The Update of the CRUD ops, a mixin.
*/
var cip = require('cip');
var Promise = require('bluebird');
var appErr = require('nodeon-error');
var enums = require('../enums');
/**
* The Update of the CRUD ops.
*
* @param {app.ctrl.ControllerCrudBase} base DI The callee instance.
* @constructor
*/
var Update = module.exports = cip.extend();
/**
* Handle item update.
*
* @param {Object} req The request Object.
* @param {Object} res The response Object.
* @return {Promise} A promise.
* @protected
*/
Update.prototype._update = Promise.method(function(req, res) {
var itemId = req.body.id || req.params.id;
if (!itemId) {
var err = new appErr.Validation('No "id" field passed');
this.opts.onError(req, res, enums.CrudOps.UPDATE,
enums.HttpCode.UNAUTHORIZED, err);
return;
}
var query = Object.create(null);
query[this.opts.idField] = itemId;
return this.updateQuery(query, req, res)
.bind(this)
.then(function (queryFinal) {
var self = this;
return Promise.try(function() {
return self.controller.update(queryFinal, req.body);
});
})
.then(this.mkSuccessHandler(req, res, enums.CrudOps.UPDATE))
.catch(this.mkErrorHandler(req, res, enums.CrudOps.UPDATE));
});
| 24.980392 | 68 | 0.654631 |
b98a2ed3631a0a0cc81c68016cc328954a495789 | 168 | js | JavaScript | src/redux/types.js | irfiacre/NbaStats | 57e6a474995e02431590018dd6a58c381a7a2c3a | [
"MIT"
] | null | null | null | src/redux/types.js | irfiacre/NbaStats | 57e6a474995e02431590018dd6a58c381a7a2c3a | [
"MIT"
] | null | null | null | src/redux/types.js | irfiacre/NbaStats | 57e6a474995e02431590018dd6a58c381a7a2c3a | [
"MIT"
] | null | null | null | export const FETCH_TASKS = 'FETCH_TASKS';
export const ADD_TASKS = 'ADD_TASKS';
export const UPDATE_TASKS = 'UPDATE_TASKS';
export const DELETE_TASKS = 'DELETE_TASKS';
| 33.6 | 43 | 0.785714 |
b98ae2caa99b359d2807a8276aa57fbebe429f1a | 505 | js | JavaScript | day1/event-emitter/03_http_server.js | xiaolozhang/node_training | bf6d148e5d98a316ef71b918c09ca1a21e4b77f0 | [
"MIT"
] | 4 | 2017-08-17T11:31:54.000Z | 2020-03-28T06:54:54.000Z | day1/event-emitter/03_http_server.js | xiaolozhang/node_training | bf6d148e5d98a316ef71b918c09ca1a21e4b77f0 | [
"MIT"
] | null | null | null | day1/event-emitter/03_http_server.js | xiaolozhang/node_training | bf6d148e5d98a316ef71b918c09ca1a21e4b77f0 | [
"MIT"
] | null | null | null | var server = require('http').createServer();
var closing = false;
var port = process.argv[2] || 9000;
server.on('request', function(req, res) {
res.setHeader('Connection', 'close'); // turn off keep-alive
res.end('Hello World!');
if (! closing) {
closing = true;
server.close();
}
});
server.once('listening', function() {
console.log('Server listening on port %d', port);
});
server.once('close', function() {
console.log('Server is closing. Bye bye!');
});
server.listen(port);
| 21.041667 | 62 | 0.637624 |
b98b2fec49c9a69fee78ee695d314dc3afb42990 | 87 | js | JavaScript | frontend/src/config.js | blockchainreg/faucet-testnet | 3796cf0fff10a28945ed3a38aadbad8d3e0bb818 | [
"Apache-2.0"
] | null | null | null | frontend/src/config.js | blockchainreg/faucet-testnet | 3796cf0fff10a28945ed3a38aadbad8d3e0bb818 | [
"Apache-2.0"
] | 1 | 2021-09-25T09:31:31.000Z | 2021-09-25T09:31:31.000Z | frontend/src/config.js | blockchainreg/faucet-testnet | 3796cf0fff10a28945ed3a38aadbad8d3e0bb818 | [
"Apache-2.0"
] | 1 | 2021-12-27T04:36:27.000Z | 2021-12-27T04:36:27.000Z | export const networks = [
{
key: 'groot-',
lcd: 'https://localhost',
},
];
| 12.428571 | 29 | 0.505747 |
b98ec5ecdcf93c23f723f01ec96a4ff940905be3 | 1,715 | js | JavaScript | Atividades/atividade-pratica-01/escala.js | UFOP-CSI477/2020-03-ple-atividades-alorenalopes | 641e93df5592d81dc8fe8ec6aa9e85e3c5345986 | [
"MIT"
] | 2 | 2020-08-27T22:58:52.000Z | 2020-09-01T21:26:04.000Z | Atividades/atividade-pratica-01/escala.js | UFOP-CSI477/2020-03-ple-atividades-alorenalopes | 641e93df5592d81dc8fe8ec6aa9e85e3c5345986 | [
"MIT"
] | 8 | 2021-02-02T18:01:32.000Z | 2021-04-30T01:07:23.000Z | Atividades/atividade-pratica-01/escala.js | UFOP-CSI477/2020-03-ple-atividades-alorenalopes | 641e93df5592d81dc8fe8ec6aa9e85e3c5345986 | [
"MIT"
] | null | null | null | function calcular_escala() {
const a = document.getElementById("input_amplitude").value;
const t = document.getElementById("input_tempo").value;
const m = (Math.log10(a) + (3 * (Math.log10(8 * t))) - 2.92).toFixed(2);
if (m < 3.5) {
gera_resultado("Geralmente não sentido, mas gravado.", 0, m);
}
if (m >= 3.5 && m <= 5.4) {
gera_resultado("Às vezes sentido, mas raramente causa danos.", 0, m);
}
if (m >= 5.5 && m <= 6) {
gera_resultado("No máximo causa pequenos danos a prédios bem construídos, mas pode danificar casas mal construídas na região. ", 1, m);
}
if (m >= 6.1 && m <= 6.9) {
gera_resultado("Pode ser destrutivo em áreas em torno de até 100km do epicentro.", 1, m);
}
if (m >= 7 && m <= 7.9) {
gera_resultado("Grande terremoto. Pode causar sérios danos em uma grande faixa.", 1, m);
}
if (m >= 8) {
gera_resultado("Enorme terremoto. Pode causar graves danos em muitas áreas mesmo que estejam a centenas de quilômetros.", 1, m);
}
}
function gera_resultado(mensagem, status, m) {
const div_alerta = document.getElementById("alertas");
if (status == 0) {
div_alerta.innerHTML = `
<div class="alert alert-warning" role="alert">
Magnitude:
<a class="alert-link">${m}</a>
</div>
<div class="alert alert-success" role="alert">${mensagem} </div>`;
} else {
div_alerta.innerHTML =
`<div class="alert alert-warning" role="alert">
Magnitude:
<a class="alert-link">${m}</a>
</div>
<div class="alert alert-danger" role="alert">
${mensagem}
</div>`;
}
} | 35 | 143 | 0.573178 |
b98f599c5ff3496347314da2b0dd8128050281e2 | 4,681 | js | JavaScript | lib/ContractError.js | Toryt/contracts | 03b83affe1d37ea2829c29666e2547327de3bf12 | [
"Apache-2.0"
] | null | null | null | lib/ContractError.js | Toryt/contracts | 03b83affe1d37ea2829c29666e2547327de3bf12 | [
"Apache-2.0"
] | 78 | 2018-09-16T20:38:51.000Z | 2021-07-19T10:08:51.000Z | lib/ContractError.js | Toryt/contracts | 03b83affe1d37ea2829c29666e2547327de3bf12 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2016 - 2020 by Jan Dockx
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict'
const is = require('./_private/is')
const stack = require('./_private/stack')
const property = require('./_private/property')
const assert = require('assert')
const stackEOL = require('./_private/eol').stack
/* Custom Error types are notoriously difficult in JavaScript.
See, e.g.,
- http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript
- http://pastebin.com/aRpPr5Sd
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/toString
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack
- https://nodejs.org/api/errors.html
- https://msdn.microsoft.com/en-us/library/hh699850%28v=vs.94%29.aspx?f=255&MSPPError=-2147217396
The main problems are:
- Calling Error() without new doesn't initialize this. It creates a new object, and does nothing with this.
Error.call(this) does nothing with this.
- The stack trace is filled out differently per platform, or not at all (older IE). Safari produces a stack
that skips (optimize?) stack frames.
Some platforms fill out the stack trace on throw (which seems to be correct). Other on creation of an
Error. But, when following the regular inheritance pattern, this is at type definition time, where
we want to create an Error-instance as prototype for a custom error type. That is obviously never
the stack trace we want.
Some platforms offer a method to fill out the stack trace.
this.stack = "A String" does nothing on node.
Errors support the following properties common over all platforms:
- message
- name
- toString === name + ": " + message
A file name, lineNumber and columnNumber is standard and supported on most platforms, and evolving.
There is little or no documentation about how they are filled out.
Most platforms do support a stack property, which is a multi-line string. The first line is the message.
There are libraries to deal with these complexities, but different for node and browsers.
Furthermore, the landscape is evolving.
That we cannot call Error() to initialise a new custom error, is not a big problem. The standard syntax is
new Error([message[, fileName[, lineNumber]]]). We can set these properties directly in our constructor.
For fileName and lineNumber, we have the same problem as with the stack: we need a reference to somewhere else
than where we create the custom error.
*/
const message = 'abstract type'
/**
* ContractError is the general supertype of all errors thrown by Toryt Contracts.
* ContractError itself is to be considered abstract.
*
* The main feature of a ContractError is that it provides a safe, cross-platform stack trace.
* Instances should be frozen before they are thrown.
*
* <h3>Invariants</h3>
* <ul>
* <li>`name` is a mandatory property, and refers to a string</li>
* <li>`message` refers to a string</li>
* <li>`stack` is a read-only property, that returns a string, that starts with the instances `name`, the
* string ": ", and `message`, and is followed by stack code references, that do no contain references
* to the inner workings of the Toryt Contracts library.</li>
* </ul>
*
* @constructor
*/
function ContractError (rawStack) {
assert(is.stack(rawStack), 'rawStack is a stack')
property.setAndFreeze(this, '_rawStack', rawStack)
}
ContractError.prototype = new Error()
ContractError.prototype.constructor = ContractError
property.setAndFreeze(ContractError.prototype, 'name', ContractError.name)
property.setAndFreeze(ContractError.prototype, 'message', message)
property.setAndFreeze(ContractError.prototype, '_rawStack', stack.raw())
property.configurableDerived(ContractError.prototype, 'stack', function () {
// noinspection JSUnresolvedVariable
return `${this.name}: ${this.message}` + stackEOL + this._rawStack
})
ContractError.message = message
module.exports = ContractError
| 44.580952 | 113 | 0.745354 |
b98f9b6c04d6c5563380846ff040de4b987e0496 | 1,174 | js | JavaScript | src/components/Main/About.js | adriancleung/app | 1194c47d4f81c204011ea491d1d40cf24528f44d | [
"MIT"
] | null | null | null | src/components/Main/About.js | adriancleung/app | 1194c47d4f81c204011ea491d1d40cf24528f44d | [
"MIT"
] | null | null | null | src/components/Main/About.js | adriancleung/app | 1194c47d4f81c204011ea491d1d40cf24528f44d | [
"MIT"
] | null | null | null | import React, { useEffect, useState } from 'react';
import { Box, Text } from 'grommet';
import { ScaleLoader } from 'react-spinners';
import { getAboutContent } from '../../services/api';
import { SUCCESS_CODE } from '../../constants';
import parse from 'html-react-parser';
const About = _props => {
const [about, setAbout] = useState('');
const [aboutLoading, setAboutLoading] = useState(true);
const loadAbout = () => {
getAboutContent()
.then(res => (res.status === SUCCESS_CODE ? setAbout(res.data) : null))
.catch(err => console.error(err))
.finally(() => setAboutLoading(false));
};
useEffect(() => {
loadAbout();
}, []);
return (
<>
<Box width={'100%'} height={'100%'} justify={'center'} align={'center'}>
<ScaleLoader
loading={aboutLoading}
height={60}
width={10}
radius={20}
color={'white'}
/>
</Box>
{!aboutLoading && (
<Box overflow={'scroll'}>
<Text style={{ textAlign: 'justify' }} margin={'medium'}>
{parse(about)}
</Text>
</Box>
)}
</>
);
};
export default About;
| 25.521739 | 78 | 0.544293 |
b98fbb04abc5fef109ed1f29bdb86b452c8e9b06 | 463 | js | JavaScript | src/js/cartToolbar/index.js | andry-93/webixTmpMarketplace1 | 590e28c807929b000e9153ced6d3391eb472f9c7 | [
"MIT"
] | null | null | null | src/js/cartToolbar/index.js | andry-93/webixTmpMarketplace1 | 590e28c807929b000e9153ced6d3391eb472f9c7 | [
"MIT"
] | 4 | 2021-03-10T08:05:22.000Z | 2022-02-26T23:50:44.000Z | src/js/cartToolbar/index.js | andry-93/webixTmpMarketplace1 | 590e28c807929b000e9153ced6d3391eb472f9c7 | [
"MIT"
] | null | null | null | export const cartToolbar = {
view: "toolbar",
borderless: true,
margin: 10,
paddingX: 10,
paddingY: 14,
css: "cart_toolbar",
cols: [
{
view: "label",
label: "My products",
height: 44
},
{},
{
view: "button",
autowidth: true,
label: "Add new product",
css: "webix_primary"
},
{
view: "combo",
label: "Sort by",
labelWidth: 55,
value: "All",
options: ["All", "20", "40"]
}
]
};
| 15.433333 | 32 | 0.511879 |
b98fc7c90a735cb01335a73a5310e3f60f40a5e6 | 3,307 | js | JavaScript | Marketplace/libs/Network/src/cwLayoutNetwork.download.js | nevakee716/CasewiseLab | 75c90a6ef000efaf21e9b498098dac2dac44b2cb | [
"MIT"
] | null | null | null | Marketplace/libs/Network/src/cwLayoutNetwork.download.js | nevakee716/CasewiseLab | 75c90a6ef000efaf21e9b498098dac2dac44b2cb | [
"MIT"
] | null | null | null | Marketplace/libs/Network/src/cwLayoutNetwork.download.js | nevakee716/CasewiseLab | 75c90a6ef000efaf21e9b498098dac2dac44b2cb | [
"MIT"
] | null | null | null | /* Copyright (c) 2012-2013 Casewise Systems Ltd (UK) - All rights reserved */
/*global cwAPI, jQuery */
(function(cwApi, $) {
"use strict";
if (cwApi && cwApi.cwLayouts && cwApi.cwLayouts.cwLayoutNetwork) {
var cwLayoutNetwork = cwApi.cwLayouts.cwLayoutNetwork;
} else {
// constructor
var cwLayoutNetwork = function(options, viewSchema) {
cwApi.extend(this, cwApi.cwLayouts.CwLayout, options, viewSchema); // heritage
cwApi.registerLayoutForJSActions(this); // execute le applyJavaScript après drawAssociations
this.construct(options);
};
}
cwLayoutNetwork.prototype.downloadImage = function(event) {
var self = this;
function downloadURI(canvas, name) {
var link = document.createElement("a");
var actionContainer = document.getElementById("cwLayoutNetworkAction" + self.nodeID);
actionContainer.appendChild(link);
link.style = "display: none";
//link.download = name;
//link.href = uri;
//link.click();
//var blob = new Blob([uri], { type: "image/png" });
//window.navigator.msSaveOrOpenBlob(uri, name);
if (canvas.msToBlob) { //for IE
var blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, name);
} else {
canvas.toBlob(function(blob) {
link.href = URL.createObjectURL(blob);
link.download = name;
link.style = "display: block";
link.click();
link.remove();
// create a mouse event
//var event = new MouseEvent('click');
// dispatching it will open a save as dialog in FF
//link.dispatchEvent(event);
}, 'image/png');
////other browsers
//link.href = canvas.toDataURL('image/png');
//link.download = name;
//// create a mouse event
//var event = new MouseEvent('click');
//// dispatching it will open a save as dialog in FF
//link.dispatchEvent(event);
}
}
try {
this.networkUI.fit();
var container = document.getElementById("cwLayoutNetworkCanva" + this.nodeID);
var oldheight = container.offsetHeight;
var scale = this.networkUI.getScale(); // change size of the canva to have element in good resolution
container.style.width = (container.offsetWidth * 2 / scale).toString() + "px";
container.style.height = (container.offsetHeight * 2 / scale).toString() + "px";
this.networkUI.redraw();
downloadURI(container.firstElementChild.firstElementChild, cwAPI.getPageTitle() + ".png");
// this.networkUI.on("afterDrawing", function(ctx) {});
container.style.height = oldheight + "px";
container.style.width = "";
this.networkUI.redraw();
this.networkUI.fit();
} catch (e) {
console.log(e);
}
};
cwApi.cwLayouts.cwLayoutNetwork = cwLayoutNetwork;
}(cwAPI, jQuery)); | 35.55914 | 113 | 0.547626 |
b9900438190882324e91560341108962dfb11a2b | 19,040 | js | JavaScript | src/models/overview.js | MonitorOnlineTeam/PollutantSource | 8fa529248471d094f97db61fa4d0e13aba10acdf | [
"MIT"
] | null | null | null | src/models/overview.js | MonitorOnlineTeam/PollutantSource | 8fa529248471d094f97db61fa4d0e13aba10acdf | [
"MIT"
] | null | null | null | src/models/overview.js | MonitorOnlineTeam/PollutantSource | 8fa529248471d094f97db61fa4d0e13aba10acdf | [
"MIT"
] | null | null | null | import React from 'react';
import moment from 'moment';
// import { message } from 'antd';
import {
Popover,
Badge,
Icon,
Divider,
message
} from 'antd';
import { mainpollutantInfo, mainpoll, enterpriceid,onlyOneEnt } from "../config";
import {
querypolluntantentinfolist
} from '../services/entApi';
import {
querypollutanttypecode, getPollutantTypeList,
querydatalist, querylastestdatalist, queryhistorydatalist,
querypollutantlist,
querygetentdatalist
} from '../services/overviewApi';
import { Model } from '../dvapack';
import { isNullOrUndefined } from 'util';
import {formatPollutantPopover} from '../utils/utils';
export default Model.extend({
namespace: 'overview',
state: {
dataTemp: [],
lastestdata: [],
mainpcol: [],
detailpcol: [],
detaildata: [],
chartdata: [],
existdata: false,
gwidth: 0,
gheight: 0,
pollutantName: [],
detailtime: null,
addtaskstatus: false,
pollutantTypelist: null,
entbaseinfo: null,
selectent:null,
selectpoint: null,
onlypollutantList: [],
selectpollutantTypeCode: '',
//数据一览表头
columns: [],
data: [],
dataOne: null,//如果有点信息去第一个数据的MN号码
entlist:[],
//数据一览的参数
dataOverview: {
selectStatus: null,
time: moment(new Date()).add(-1, 'hour'),
terate: null,
pointName: null,
entName:null
},
mapdetailParams: {
dataType: 'HourData',
datatype: 'hour',
isAsc: true,
endTime: moment(new Date()).format('YYYY-MM-DD HH:00:00'),
beginTime: moment(new Date()).add('hour', -23).format('YYYY-MM-DD HH:00:00'),
pollutantCode: null,
pollutantName: null
},
upLoadParameters: {
manualUploaddataOne: null,
pointName: null,
pollutantTypes: '2',
RunState: '2',
}
},
effects: {
* querypollutanttypecode({
payload,
}, { call, update, put, take, select }) {
let gwidth = 300 + 140 + 70;
if(!onlyOneEnt)
{
gwidth=gwidth+300;
}
const { dataOverview, selectpollutantTypeCode } = yield select(a => a.overview);
const body = {
pollutantTypes: selectpollutantTypeCode,
};
const data = yield call(querypollutanttypecode, body);
yield put({
type: 'getPollutantTypeList',
payload: {
},
});
yield take('getPollutantTypeList/@@end');
if (data) {
gwidth += 200 * data.length;
}
yield update({ columns: data, gwidth });
},
* querydatalist({
payload,
}, { call, update, put, select }) {
const { dataOverview, selectpollutantTypeCode ,RunState,selectent,entbaseinfo} = yield select(a => a.overview);
let entCode=selectent?selectent.entCode:(entbaseinfo?entbaseinfo.entCode:null);
if(payload.entCode)
{
entCode=payload.entCode;
}
let body = {
time: dataOverview.time,
pollutantTypes: selectpollutantTypeCode,
pointName: dataOverview.pointName,
status: dataOverview.selectStatus,
terate: dataOverview.terate,
entName:dataOverview.entName,
entCode:entCode,
...payload
}
if(body.time)
{
body.time=body.time.format('YYYY-MM-DD HH:00:00');
}
if(payload.isAll)
{
body={};
}
const data = yield call(querydatalist, body);
if (data) {
data.map((item) => {
item.position = {
'longitude': item.longitude,
'latitude': item.latitude
};
item.key = item.DGIMN;
});
}
let { selectpoint } = yield select(_ => _.overview);
if (selectpoint) {
const newpoint = data.find(value => value.DGIMN == selectpoint.DGIMN);
yield update({
selectpoint: newpoint
});
}
yield update({ data });
yield update({ dataTemp: data });
yield update({ dataOne: data == null ? '0' : data[0].DGIMN });
if (payload.callback === undefined) {
} else {
payload.callback(data);
}
},
//手工数据上传数据列表(单独独立)
* manualUploadQuerydatalist({
payload,
}, { call, update, put, take, select }) {
const { upLoadParameters } = yield select(a => a.overview);
debugger;
const body = {
pollutantTypes: upLoadParameters.pollutantTypes,
pointName: upLoadParameters.pointName,
RunState: upLoadParameters.RunState,
}
const data = yield call(querydatalist, body);
if (data) {
yield update({ data });
yield update({ dataTemp: data });
}
else {
yield update({ data: null });
}
yield update({
upLoadParameters: {
...upLoadParameters,
manualUploaddataOne: data == null ? '0' : data[0].DGIMN
}
});
},
* querylastestdatalist({
payload,
}, { call, update }) {
const res = yield call(querylastestdatalist, payload);
if (res.data) {
yield update({ lastestdata: res.data });
} else {
yield update({ lastestdata: [] });
}
},
// 主要污染物
* querymainpollutantlist({
payload,
}, { call, update }) {
let col = [{
title: '监测点',
dataIndex: 'pointName',
key: 'pointName',
width: 110,
align: 'center'
}];
mainpollutantInfo.map((item, key) => {
col = col.concat({
title: `${item.pollutantName
}(${item.unit})`,
dataIndex: item.pollutantCode,
key: item.pollutantCode,
align: 'center',
render: (value, record, index) => {
return formatPollutantPopover(value,record[`${item.pollutantCode}_params`]);
}
});
});
yield update({ mainpcol: col });
},
* querydetailpollutant({
payload,
}, { call, update, put, take, select }) {
const { selectpoint, mapdetailParams } = yield select(a => a.overview);
let pollutantInfoList= yield call(querypollutanttypecode,{pollutantTypes:selectpoint.pollutantTypeCode});
//没绑定污染物则不渲染
if(!pollutantInfoList || !pollutantInfoList[0])
{
yield update({
detailtime:null,
detaildata:null,
detailpcol:null,
pollutantName:null,
existdata:false,
mapdetailParams:{
... mapdetailParams,
pollutantCode:null,
pollutantName:null
}
});
return;
}
pollutantInfoList=pollutantInfoList.filter(value=>value.isMainPollutant==true);
yield update({
mapdetailParams:{
... mapdetailParams,
pollutantCode:pollutantInfoList[0].field,
pollutantName:pollutantInfoList[0].name
}})
// 地图详细表格列头
let detailpcol = [{
title: '因子',
dataIndex: 'pollutantName',
key: 'pollutantName',
align: 'center',
}, {
title: `浓度`,
dataIndex: 'pollutantCode',
key: 'pollutantCode',
align: 'center',
render: (value, record, index) => {
if (selectpoint.stop) {
return "停产";
}
return formatPollutantPopover(value,record.pollutantCodeParam);
}
}
];
//只有废气有折算浓度
if (selectpoint.pollutantTypeCode==2) {
detailpcol = detailpcol.concat({
title: `折算`,
dataIndex: 'zspollutantCode',
key: 'zspollutantCode',
align: 'center',
render: (value, record, index) => {
if (selectpoint.stop) {
return "停产"
}
return formatPollutantPopover(value,record.zspollutantCodeParam);
}
});
}
let detaildata = [];
let detailtime = null;
const body = {
dataType: mapdetailParams.dataType,
DGIMNs: selectpoint.DGIMN,
isLastest: true
};
const res = yield call(querylastestdatalist, body);
if (res.data && res.data[0]) {
detailtime = res.data[0].MonitorTime;
pollutantInfoList.map(item => {
let zspollutantCode;
let zspollutantCodeParam;
let pollutantCode;
if(res.data[0][item.field] || res.data[0][item.field] ===0 )
{
pollutantCode=res.data[0][item.field]
}
else
{
pollutantCode='-';
}
if(selectpoint.pollutantTypeCode==2)
{
if(res.data[0][`zs${item.field}`] === 0 || res.data[0][`zs${item.field}`])
{
zspollutantCode=res.data[0][`zs${item.field}`];
}
else
{
zspollutantCode='-';
}
zspollutantCodeParam=res.data[0][`zs${item.field}_params`]
}
detaildata.push(
{
pollutantName: item.name,
pollutantCode: pollutantCode,
pollutantCodeParam: res.data[0][`${item.field}_params`],
zspollutantCode: zspollutantCode,
zspollutantCodeParam: zspollutantCodeParam,
dgimn: payload.dgimn,
pcode: item.field,
},
);
});
}
yield update({
detailtime,
detaildata,
detailpcol,
});
yield put({
type: 'queryoptionDataOnClick',
payload: {
...payload,
isAsc: true
}
});
yield take('queryoptionDataOnClick/@@end');
},
* queryoptionDataOnClick({ payload }, {
call, update, select, take
}) {
const { mapdetailParams, selectpoint, selectpollutantTypeCode } = yield select(a => a.overview);
const body = {
DGIMNs: selectpoint.DGIMN,
datatype: mapdetailParams.datatype,
beginTime: mapdetailParams.beginTime,
endTime: mapdetailParams.endTime,
isAsc: mapdetailParams.isAsc
};
const pollutantparams = {
DGIMNs: selectpoint.DGIMN
};
const resultlist = yield call(queryhistorydatalist, body);
const pollutantlist = yield call(querypollutantlist, pollutantparams);
let seriesdata = [];
let zsseriesdata = [];
let xData = [];
if (resultlist && resultlist.data) {
resultlist.data.map(item => {
const time = moment(item.MonitorTime).hour();
xData = xData.concat(time);
seriesdata = seriesdata.concat(item[mapdetailParams.pollutantCode]);
zsseriesdata = zsseriesdata.concat(item[`zs${mapdetailParams.pollutantCode}`]);
});
}
//污染物标准线的组织;
let polluntinfo;
let zspolluntinfo;
let markLine = {};
let zsmarkLine = {};
if (pollutantlist) {
polluntinfo = pollutantlist.find((value, index, arr) => value.pollutantCode === mapdetailParams.pollutantCode);
zspolluntinfo = pollutantlist.find((value, index, arr) => value.pollutantCode === `zs${mapdetailParams.pollutantCode}`);
}
if (polluntinfo && polluntinfo.standardValue) {
markLine = {
symbol: 'none', // 去掉警戒线最后面的箭头
data: [{
lineStyle: {
type: 'dash',
color: '#54A8FF',
},
yAxis: polluntinfo.standardValue
}]
};
}
if (zspolluntinfo && zspolluntinfo.standardValue) {
zsmarkLine = {
symbol: 'none', // 去掉警戒线最后面的箭头
data: [{
lineStyle: {
type: 'dash',
color: '#FF00FF',
},
yAxis: zspolluntinfo.standardValue
}]
};
}
let existdata = true;
if ((!seriesdata[0] && seriesdata[0] != 0) && (!zsseriesdata[0] && zsseriesdata[0] != 0)) {
existdata = false;
}
const pollutantInfoList = mainpoll.find(value => value.pollutantCode == selectpollutantTypeCode);
let legend = [mapdetailParams.pollutantName];
if (pollutantInfoList.zspollutant) {
legend.push(`折算${mapdetailParams.pollutantName}`);
}
const option = {
legend: {
data: legend
},
tooltip: {
trigger: 'axis',
formatter: function (params, ticket, callback) {
let res = `${params[0].axisValue}时<br/>`;
params.map(item => {
res += `${item.seriesName}:${item.value}<br />`;
});
return res;
}
},
toolbox: {
show: true,
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
name: '时间',
boundaryGap: false,
data: xData
},
yAxis: {
type: 'value',
name: '浓度(' + 'mg/m³' + ')',
axisLabel: {
formatter: '{value}'
},
},
series: [{
type: 'line',
name: mapdetailParams.pollutantName,
data: seriesdata,
markLine: markLine,
itemStyle: {
normal: {
color: '#54A8FF',
lineStyle: {
color: '#54A8FF'
}
}
},
},
{
type: 'line',
name: `折算${mapdetailParams.pollutantName}`,
data: zsseriesdata,
markLine: zsmarkLine,
itemStyle: {
normal: {
color: '#FF00FF',
lineStyle: {
color: '#FF00FF'
}
}
},
}
]
};
yield update({
chartdata: option,
existdata,
pollutantName: mapdetailParams.pollutantName,
});
},
//获取系统污染物类型
* getPollutantTypeList({
payload
}, { call, update, put, take }) {
const res = yield call(getPollutantTypeList, payload);
if (res ) {
yield update({
pollutantTypelist: res
});
if(!payload.treeCard)
{
yield put({
type: 'querydatalist',
payload: {
...payload,
},
});
yield take('querydatalist/@@end');
}
} else {
yield update({
pollutantTypelist: null
});
}
},
//获取企业信息
* queryentdetail({
payload,
}, { call, update, put, take }) {
const body= {parentIDs:enterpriceid};
const entbaseinfo = yield call(querypolluntantentinfolist,body);
if(entbaseinfo)
{
yield update({ entbaseinfo: entbaseinfo[0] });
}
else
{
yield update({ entbaseinfo: null });
}
yield put({
type: 'getPollutantTypeList',
payload: {
...payload,
},
});
yield take('getPollutantTypeList/@@end');
},
* querygetentdatalist({
payload,
}, { call, update, put, take }) {
const body = {entName:payload.entName};
const entlist = yield call(querygetentdatalist,body);
yield update({ entlist });
},
}
});
| 35 | 136 | 0.418067 |
b990d43a92cded423db19517f8e2593788a7fd37 | 2,793 | js | JavaScript | src/debug/logbuffer.js | Saber-Team/SogouJS | 95f0e0b131d29d4a829a20d8d63a664b088cb089 | [
"MIT"
] | 2 | 2015-01-09T01:28:02.000Z | 2015-01-09T03:39:24.000Z | src/debug/logbuffer.js | Saber-Team/SogouJS | 95f0e0b131d29d4a829a20d8d63a664b088cb089 | [
"MIT"
] | null | null | null | src/debug/logbuffer.js | Saber-Team/SogouJS | 95f0e0b131d29d4a829a20d8d63a664b088cb089 | [
"MIT"
] | null | null | null | /**
* @fileoverview 模块提供log记录的缓冲buffer, 目的是提升log日志的性能并且在buffer满溢的时候
* 能尽量使用以前创建的对象. 同时客户端程序中不再需要自己实现log buffer. The
* disadvantage to doing this is that log handlers cannot maintain references to
* log records and expect that they are not overwriten at a later point.
* @author Leo.Zhang
* @email zmike86@gmail.com
*/
define(['../debug/logrecord'], function(LogRecord) {
'use strict';
/**
* 单例
* @type {LogBuffer}
* @private
*/
var instance_ = null;
/**
* 创建log buffer.
* @constructor
*/
var LogBuffer = function() {
this.clear();
};
/**
* 单例模式返回LogBuffer.
* @return {!LogBuffer} The LogBuffer singleton instance.
*/
LogBuffer.getInstance = function() {
if (!instance_) {
instance_ = new LogBuffer();
}
return instance_;
};
/**
* @define {number} 要缓冲的log records数目. 0表示禁止缓冲.
*/
LogBuffer.CAPACITY = 0;
/**
* 一个数组缓存所有的Record对象.
* @type {!Array.<!LogRecord|undefined>}
* @private
*/
LogBuffer.prototype.buffer_ = null;
/**
* 最新加入的record的索引或者-1(代表没有缓存的LogRecord).
* @type {number}
* @private
*/
LogBuffer.prototype.curIndex_ = -1;
/**
* 缓冲区是否已满.
* @type {boolean}
* @private
*/
LogBuffer.prototype.isFull_ = false;
/**
* 增加一条日志记录, 可能会覆盖缓存中老的记录.
* @param {LogLevel} level One of the level identifiers.
* @param {string} msg 日志消息.
* @param {string} loggerName source logger的名称.
* @return {!LogRecord} The log record.
*/
LogBuffer.prototype.addRecord = function(level, msg, loggerName) {
var curIndex = (this.curIndex_ + 1) % LogBuffer.CAPACITY;
this.curIndex_ = curIndex;
if (this.isFull_) {
var ret = this.buffer_[curIndex];
ret.reset(level, msg, loggerName);
return ret;
}
this.isFull_ = (curIndex === LogBuffer.CAPACITY - 1);
return this.buffer_[curIndex] = new LogRecord(level, msg, loggerName);
};
/**
* @return {boolean} 是否开启了log buffer.
*/
LogBuffer.isBufferingEnabled = function() {
return LogBuffer.CAPACITY > 0;
};
/**
* 移除所有缓存的log records.
*/
LogBuffer.prototype.clear = function() {
this.buffer_ = new Array(LogBuffer.CAPACITY);
this.curIndex_ = -1;
this.isFull_ = false;
};
/**
* 在缓存的每个record上执行func. 从最久的record开始.
* @param {function(!LogRecord)} func The function to call.
*/
LogBuffer.prototype.forEachRecord = function(func) {
var buffer = this.buffer_;
// Corner case: no records.
if (!buffer[0]) {
return;
}
var curIndex = this.curIndex_;
// 要从最老的开始就要判断isFull_和curIndex
var i = this.isFull_ ? curIndex : -1;
do {
i = (i + 1) % LogBuffer.CAPACITY;
func(/** @type {!LogRecord} */ (buffer[i]));
} while (i !== curIndex);
};
return LogBuffer;
}); | 21 | 80 | 0.62048 |
b990e34c7c24c47e326f25cb3bd6b94c47cc9d89 | 949 | js | JavaScript | themes/letsecureme/assets/js/base.js | llambiel/letsecureme | 0a43c5746e9daec0f0117bb93b70859fb95a826c | [
"MIT"
] | 49 | 2016-03-15T15:53:26.000Z | 2019-02-24T08:12:51.000Z | themes/letsecureme/assets/js/base.js | llambiel/letsecureme | 0a43c5746e9daec0f0117bb93b70859fb95a826c | [
"MIT"
] | 12 | 2016-03-30T07:02:08.000Z | 2017-06-07T09:54:56.000Z | themes/letsecureme/assets/js/base.js | llambiel/letsecureme | 0a43c5746e9daec0f0117bb93b70859fb95a826c | [
"MIT"
] | 12 | 2016-03-30T04:41:19.000Z | 2018-08-29T14:11:30.000Z | "use strict";
jQuery(document).ready(function($) {
var lightbox_class = 'image-popup-fit-width';
(function() {
var images = $('.post img');
$.each(images, function(index, i) {
var image = $(i);
var anchor = image.attr('src');
image.wrap('<a class="' + lightbox_class + '" href="' + anchor + '""></a>');
});
}());
(function() {
$('.' + lightbox_class).magnificPopup({
type: 'image',
closeOnContentClick: true,
closeBtnInside: false,
fixedContentPos: true,
mainClass: 'mfp-no-margins mfp-with-zoom', // class to remove default margin from left and right side
image: {
verticalFit: true,
},
zoom: {
enabled: true,
duration: 300, // don't foget to change the duration also in CSS
},
});
}());
});
| 28.757576 | 113 | 0.479452 |
b992b6cc7092efddc9fe5dc886802be465d1bd94 | 4,298 | js | JavaScript | lambda/worker/sources/slack/parsers/messages.js | bitscooplabs/bitscoop-social-app-demo | fbd8975dd54efb51b45aab2d134458277c020601 | [
"MIT"
] | 1 | 2020-07-27T21:45:08.000Z | 2020-07-27T21:45:08.000Z | lambda/worker/sources/slack/parsers/messages.js | bitscooplabs/lifescope | fbd8975dd54efb51b45aab2d134458277c020601 | [
"MIT"
] | 15 | 2020-07-16T00:15:33.000Z | 2022-03-01T23:56:16.000Z | lambda/worker/sources/slack/parsers/messages.js | bitscooplabs/bitscoop-social-app-demo | fbd8975dd54efb51b45aab2d134458277c020601 | [
"MIT"
] | 2 | 2017-07-06T23:18:13.000Z | 2017-07-22T03:53:13.000Z | 'use strict';
const _ = require('lodash');
const moment = require('moment');
const mongoTools = require('../../../util/mongo-tools');
let tagRegex = /#[^#\s]+/g;
module.exports = function(data, db) {
var contacts, content, events, objectCache, tags, self = this;
objectCache = {
contacts: {},
content: {},
tags: {}
};
contacts = [];
content = [];
tags = [];
events = [];
if (data && data.length > 0) {
for (let i = 0; i < data.length; i++) {
let item = data[i];
let newContact = {};
let localContacts = [];
let localContactsIds = {};
let localContent = [];
let localContentIds = {};
let datetime = moment(parseInt(item.ts.split('.')[0]) * 1000).utc().toDate();
let newTags = [];
let bodyTags = item.text.match(tagRegex);
if (bodyTags != null) {
for (let j = 0; j < bodyTags.length; j++) {
let tag = bodyTags[j].slice(1);
let newTag = {
tag: tag,
user_id: this.connection.user_id
};
if (!_.has(objectCache.tags, newTag.tag)) {
objectCache.tags[newTag.tag] = newTag;
tags.push(objectCache.tags[newTag.tag]);
}
if (newTags.indexOf(newTag.tag) === -1) {
newTags.push(newTag.tag);
}
}
}
let message = {
identifier: this.connection._id.toString('hex') + ':::slack:::message:::' + item.channel + ':::' + item.ts,
connection_id: this.connection._id,
provider_id: this.connection.provider_id,
provider_name: 'slack',
user_id: this.connection.user_id,
text: item.text,
type: 'text'
};
if (newTags.length > 0) {
message['tagMasks.source'] = newTags;
}
if (!_.has(objectCache.content, message.identifier)) {
objectCache.content[message.identifier] = message;
localContent.push(objectCache.content[message.identifier]);
localContentIds[message.identifier] = true;
content.push(objectCache.content[message.identifier]);
}
else {
if (!_.has(localContentIds, message.identifier)) {
localContent.push(objectCache.content[message.identifier]);
localContentIds[message.identifier] = true;
}
}
let newEvent = {
type: 'messaged',
provider_name: 'slack',
identifier: this.connection._id.toString('hex') + ':::messaged:::slack:::conversation:::' + item.channel + ':::' + item.ts,
datetime: datetime,
content: [message],
connection_id: this.connection._id,
provider_id: this.connection.provider_id,
user_id: this.connection.user_id
};
if (item.user_hydrated && item.user_hydrated.email !== self.connection.metadata.email) {
let user = item.user_hydrated;
newContact = {
identifier: this.connection._id.toString('hex') + ':::' + user.email,
connection_id: this.connection._id,
provider_id: this.connection.provider_id,
provider_name: 'slack',
user_id: this.connection.user_id,
handle: user.email,
name: user.real_name,
updated: moment().utc().toDate()
};
if (user.image_512 || user.image_192 || user.image_72 || user.image_48 || user.image_32 || user.image_24) {
newContact.avatar_url = user.image_512 ? user.image_512 : user.image_192 ? user.image_192 : user.image_72 ? user.image_72 : user.image_48 ? user.image_48 : user.image_32 ? user.image_32 : user.image_24;
}
if (!_.has(objectCache.contacts, newContact.identifier)) {
objectCache.contacts[newContact.identifier] = newContact;
localContacts.push(objectCache.contacts[newContact.identifier]);
localContactsIds[newContact.identifier] = true;
contacts.push(objectCache.contacts[newContact.identifier]);
}
else {
if (!_.has(localContactsIds, newContact.identifier)) {
localContacts.push(objectCache.contacts[newContact.identifier]);
localContactsIds[newContact.identifier] = true;
}
}
}
if (localContacts.length > 0) {
newEvent.contacts = localContacts;
newEvent.contact_interaction_type = 'from';
}
else {
newEvent.contact_interaction_type = 'to';
}
events.push(newEvent);
}
if (events.length > 0) {
return mongoTools.mongoInsert({
contacts: contacts,
content: content,
events: events,
tags: tags
}, db);
}
else {
return Promise.resolve(null);
}
}
else {
return Promise.resolve(null);
}
};
| 26.368098 | 207 | 0.641694 |
b9946b49af3cc3a559c5dc4bd203b3eb0ea893d3 | 325 | js | JavaScript | docs/html/hierarchy.js | frc5024/BaseBot | 7f7fb56a617daaf55301c5e3500ccfd9d1cacc75 | [
"MIT"
] | null | null | null | docs/html/hierarchy.js | frc5024/BaseBot | 7f7fb56a617daaf55301c5e3500ccfd9d1cacc75 | [
"MIT"
] | 4 | 2018-11-28T21:46:29.000Z | 2018-12-07T02:57:23.000Z | docs/html/hierarchy.js | frc5024/BaseBot | 7f7fb56a617daaf55301c5e3500ccfd9d1cacc75 | [
"MIT"
] | 1 | 2018-12-10T20:57:00.000Z | 2018-12-10T20:57:00.000Z | var hierarchy =
[
[ "Command", null, [
[ "DriveWithJoystick", "classDriveWithJoystick.html", null ]
] ],
[ "OI", "classOI.html", null ],
[ "Subsystem", null, [
[ "DriveTrain", "classDriveTrain.html", null ]
] ],
[ "TimedRobot", null, [
[ "Robot", "classRobot.html", null ]
] ]
]; | 25 | 66 | 0.523077 |
b99847c6dca15076652cd060d1f78dd36eceb594 | 72 | js | JavaScript | src/popup/application/index.js | tangzitong/wohApp | 957bda1042bc926eafc65b12e27b640dbf07a427 | [
"MIT"
] | null | null | null | src/popup/application/index.js | tangzitong/wohApp | 957bda1042bc926eafc65b12e27b640dbf07a427 | [
"MIT"
] | null | null | null | src/popup/application/index.js | tangzitong/wohApp | 957bda1042bc926eafc65b12e27b640dbf07a427 | [
"MIT"
] | null | null | null | import application from './application.vue'
export default application
| 18 | 43 | 0.819444 |
b999f53f69f8fb2483cb3929a03af87857ceaeb3 | 459 | js | JavaScript | test/benchmark.js | nornagon/windows-active-process | d3b3d3fce39e7b7f6b76ab20d01793a6487cd99e | [
"MIT"
] | 15 | 2017-04-27T05:22:08.000Z | 2021-04-26T17:30:01.000Z | test/benchmark.js | nornagon/windows-active-process | d3b3d3fce39e7b7f6b76ab20d01793a6487cd99e | [
"MIT"
] | null | null | null | test/benchmark.js | nornagon/windows-active-process | d3b3d3fce39e7b7f6b76ab20d01793a6487cd99e | [
"MIT"
] | 3 | 2018-08-24T06:03:22.000Z | 2019-05-16T20:28:46.000Z | const perfy = require('perfy')
const getActiveProcessName = require('../lib/index').getActiveProcessName
const iterations = process.argv[2] || 100000
function measureThisTime () {
perfy.start('this')
for (let i = 0; i < iterations; i++) {
getActiveProcessName()
}
return perfy.end('this').time
}
// Fight!
console.log(`Reading the active process ${iterations} times:`)
const thisTime = measureThisTime()
console.log(`It took: ${thisTime}`)
| 20.863636 | 73 | 0.694989 |
b99a41b9f4d3322a8ef006d4938257f01b5128f1 | 1,406 | js | JavaScript | public/assets/js/transaksi/cash-card.js | nspbdz/wasaki-shop | 2c2bdf0b7de1c7f3e4f0ef6fb9dc01b500026620 | [
"MIT"
] | null | null | null | public/assets/js/transaksi/cash-card.js | nspbdz/wasaki-shop | 2c2bdf0b7de1c7f3e4f0ef6fb9dc01b500026620 | [
"MIT"
] | null | null | null | public/assets/js/transaksi/cash-card.js | nspbdz/wasaki-shop | 2c2bdf0b7de1c7f3e4f0ef6fb9dc01b500026620 | [
"MIT"
] | null | null | null | $(function () {
// Action Looping Form Kode Perkiraan
// Picker Translations
$(".pickadate-translations-cash").pickadate({
formatSubmit: "dd/mm/yyyy",
monthsFull: [
"Januari",
"Februari",
"Maret",
"April",
"Mei",
"Juni",
"Juli",
"Agustus",
"September",
"Oktober",
"November",
"Desember",
],
monthsShort: [
"Jan",
"Feb",
"Mar",
"Apr",
"Mei",
"Jun",
"Jul",
"Ags",
"Sep",
"Okt",
"Nov",
"Des",
],
weekdaysShort: ["Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"],
today: "Hari Ini",
clear: "Reset",
close: "Tutup",
});
var html = $(".clones").html();
$("#btn-add").click(function () {
var jum = $("#count").val();
if (jum < 50) {
var html2 = html;
$(".increments").after(html2);
$("#count").val(parseInt(jum) + 1);
} else {
Swal.fire({
icon: "error",
title: "Data Maksimal 50 pernyataan!",
text: "Hanya diperbolehkan menambahkan premis perjanjian sebanyak 50 pernyataan",
confirmButtonText: "Tutup",
});
}
});
// Delete Looping Form Kode Perkiraan
$("body").on("click", ".btn-danger", function () {
$(this).parents(".control-groups").remove();
var jum = $("#count").val();
$("#count").val(parseInt(jum) - 1);
});
});
| 21.30303 | 89 | 0.483642 |
b99acb590e48db96c8848415c8bd7087e4560e77 | 4,339 | js | JavaScript | linda/query_designer/static/query_designer/subqueries.js | LinDA-tools/LindaWorkbench | 3e313b77de1f47bd149cfcedc9c43840efce8845 | [
"MIT"
] | 18 | 2015-01-28T14:18:07.000Z | 2019-01-24T15:21:51.000Z | linda/query_designer/static/query_designer/subqueries.js | alanponce/LindaWorkbench | 6a67c23237be2f78a991b96bfb62e8e214b47b32 | [
"MIT"
] | 194 | 2015-01-04T15:09:40.000Z | 2016-10-04T09:31:59.000Z | linda/query_designer/static/query_designer/subqueries.js | alanponce/LindaWorkbench | 6a67c23237be2f78a991b96bfb62e8e214b47b32 | [
"MIT"
] | 4 | 2015-11-27T10:43:52.000Z | 2021-01-28T12:07:54.000Z | var sub_Q = {
colors: ['#FC5006', '#99b433', '#b91d47', '#1e7145', '#CF000F', '#ff0097', '#00a300', '#9f00a7', '#603cba', '#da532c', '#00aba9', '#F27935'],
inactive_autoscroll_left: [], //disable left scroll if inactive_autoscroll_left[n] is true
inactive_autoscroll_right: [], //disable right scroll if inactive_autoscroll_right[n] is true
//get the color corresponding to letter
get_color: function(letter) {
var letter_pos = letter.charCodeAt(0) - 'A'.charCodeAt(0);
return this.colors[letter_pos % this.colors.length];
},
//is the subquery selector shown?
subquery_selector_shown: function(n) {
return $("#subquery-selector-" + n).length > 0;
},
//show the subquery selector
subquery_selector: function(n) {
$("#class_instance_" + n).append('<div id="subquery-selector-' + n + '" data-about="' + n + '" class="subquery-selector"><span></span></div>');
$("#subquery-selector-" + n).append('<span class="subquery-value" data-value="none" style="color: #1d1d1d">none</span>');
for(var i='A'.charCodeAt(0); i<='Z'.charCodeAt(0); i++) {
var c = String.fromCharCode(i);
$("#builder_workspace #subquery-selector-" + n).append('<span class="subquery-value" data-value="' + c + '" style="background-color: ' + this.get_color(c) + '">' + c + '</span>');
}
},
//close the selector
subquery_selector_close: function(n) {
return $("#subquery-selector-" + n).remove();
},
//util for instance rename
rename_instance: function(n, m) {
$("#subquery-selector-" + n).attr("id", '#subquery-selector-' + m);
$("#subquery-selector-" + m).attr("data-about", m);
$("#subquery-selector-" + m).data("about", m);
},
set_subquery: function(n, c) {
if ((c != undefined) && (c != "none")) {
builder_workbench.instances[n].subquery = c;
$("#class_instance_" + n + " .subquery-select").removeClass("empty");
$("#class_instance_" + n + " .subquery-select").html(c);
$("#class_instance_" + n + " .subquery-select").css('background-color', this.get_color(c));
} else {
builder_workbench.instances[n].subquery = undefined;
$("#class_instance_" + n + " .subquery-select").addClass("empty");
$("#class_instance_" + n + " .subquery-select").html('');
$("#class_instance_" + n + " .subquery-select").css('background-color', '');
}
},
};
//on change subquery
$("#builder_workspace").on('click', '.class-instance > .title > .subquery-select', function(e) {
var n = $(this).parent().parent().data('n');
if (sub_Q.subquery_selector_shown(n)) {
sub_Q.subquery_selector_close(n);
} else {
sub_Q.subquery_selector(n);
}
e.preventDefault();
e.stopPropagation();
});
//hide all subquery selectors
$("#builder_workspace").on('click', function(e) {
$(".subquery-selector").remove();
});
//on subquery selector value select
$("#builder_workspace").on('click', '.subquery-selector .subquery-value', function(e) {
var val = $(this).data('value');
var n = $(this).parent().data('about');
sub_Q.set_subquery(n, val);
sub_Q.subquery_selector_close(n);
builder.reset();
});
//auto-scroll
//when mouse move towards the edges of the selector, scroll to next/prev options
$("#builder_workspace").on('mousemove', '.subquery-selector', function(e) {
var n = $(this).data('about');
var x = e.pageX - $(this).offset().left;
var y = e.pageY - $(this).offset().top;
if ((x >= $(this).width() - 50) && (sub_Q.inactive_autoscroll_right[n] === undefined)) { //right scroll
sub_Q.inactive_autoscroll_right[n] = true;
$(this).animate( { scrollLeft: '+=100' }, 100);
setTimeout(function(){ sub_Q.inactive_autoscroll_right[n] = undefined }, 1000);
}
else
if ((x <= 50) && (sub_Q.inactive_autoscroll_left[n] === undefined)) { //left scroll
sub_Q.inactive_autoscroll_left[n] = true;
$(this).animate( { scrollLeft: '-=100' }, 100);
setTimeout(function(){ sub_Q.inactive_autoscroll_left[n] = undefined }, 1000);
}
});
//on pattern change recalculate query
$("#builder_pattern > input").on('change', function(e) {
builder.reset();
}); | 39.09009 | 191 | 0.598755 |
b99b4f40316bb15d46a601a0fc05f8f5f9202735 | 782 | js | JavaScript | src/main/clay/download.js | coke12103/Twimg-Save-Next | c26b1c8ba6f8b4205139c3a33fda5f052601b015 | [
"Apache-2.0"
] | 1 | 2021-05-04T06:14:34.000Z | 2021-05-04T06:14:34.000Z | src/main/clay/download.js | coke12103/Twimg-Save-Next | c26b1c8ba6f8b4205139c3a33fda5f052601b015 | [
"Apache-2.0"
] | 3 | 2021-05-10T02:16:04.000Z | 2021-06-13T13:33:50.000Z | src/main/clay/download.js | coke12103/Twimg-Save-Next | c26b1c8ba6f8b4205139c3a33fda5f052601b015 | [
"Apache-2.0"
] | null | null | null | const got = require('got');
const fs = require('fs');
module.exports = async function download(url, filename, save_dir, ref){
const opt = {
url: url,
method: 'GET',
responseType: 'buffer',
headers: {
'User-Agent': ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.97 Safari/537.36'
}
}
if(ref) opt.headers['Referer'] = ref;
let body;
try{
body = await got(opt);
body = body.body;
}catch(err){
this.Clay.log(`Download: ${err}`);
console.log(err);
throw err;
}
this.Clay.set_status_text('Download: OK');
try{
fs.writeFileSync(`${save_dir}/${filename}`, body, { encoding: 'binary' });
}catch(err){
console.log(err);
throw err;
}
return true;
}
| 20.578947 | 137 | 0.599744 |
b99f6fba78f19ee4910ea6a3d51fe85f0c659b6c | 1,354 | js | JavaScript | server/hacky-database-routes/index.js | ubc-farm/api | b87d12437ea09df7fb3f0ea7ae9f0d84e3d9dba5 | [
"MIT"
] | null | null | null | server/hacky-database-routes/index.js | ubc-farm/api | b87d12437ea09df7fb3f0ea7ae9f0d84e3d9dba5 | [
"MIT"
] | 1 | 2016-09-19T20:44:59.000Z | 2019-01-28T04:02:43.000Z | server/hacky-database-routes/index.js | ubc-farm/server-api | b87d12437ea09df7fb3f0ea7ae9f0d84e3d9dba5 | [
"MIT"
] | null | null | null | // Quick and dirty route generators for the API
import * as models from '../../database/index.js';
import { validate } from '../database-routes/transformer-validation.js';
import modelHandler from './model-handler/index.js';
const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];
function* methodRoutes(model) {
for (const method of methods) {
const handler = modelHandler({ method }, { model });
const config = { validate };
if (method === 'POST') {
yield {
method,
handler,
path: `/api/${model.label}`,
config: {
validate,
payload: {
parse: true,
},
},
};
} else {
yield {
method,
handler,
config,
path: `/api/${model.label}/{id?}`,
};
yield {
method,
handler,
config,
path: `/api/${model.label}/{id}/{property}`,
};
}
}
}
function* modelRoutes() {
const completed = [];
for (const modelName in models) {
if (modelName === 'joins') continue;
const model = models[modelName];
if (!model.label) {
const tableName = model.tableName.toLowerCase();
model.label = `${tableName}s`;
}
if (completed.indexOf(model.label) > -1) {
console.warn(model.label, 'from', modelName, 'already processed');
continue;
}
yield* methodRoutes(model, model.label);
completed.push(model.label);
}
}
export default [...modelRoutes()];
| 21.83871 | 72 | 0.605613 |
b9a0a23752f388092cb7ebe18012160797cb882a | 127 | js | JavaScript | LUFA/Documentation/html/struct_m_a_c___address__t.js | cosailer/mass_storage_device | 9d86abf9c9184b1f73d4363e8a14252b1cc6fc6e | [
"MIT"
] | null | null | null | LUFA/Documentation/html/struct_m_a_c___address__t.js | cosailer/mass_storage_device | 9d86abf9c9184b1f73d4363e8a14252b1cc6fc6e | [
"MIT"
] | null | null | null | LUFA/Documentation/html/struct_m_a_c___address__t.js | cosailer/mass_storage_device | 9d86abf9c9184b1f73d4363e8a14252b1cc6fc6e | [
"MIT"
] | null | null | null | var struct_m_a_c___address__t =
[
[ "Octets", "struct_m_a_c___address__t.html#a0b939cc1dd7a66c9be426af2f18ce63f", null ]
]; | 31.75 | 90 | 0.787402 |
b9a214e632065ad1a15e3fcb6e6304d279be5ce5 | 863 | js | JavaScript | src/index.js | Waleed-Nasir/Car-Parking- | 3e87877996ad1c79cd20888bce5ff8cb2160e1fb | [
"MIT"
] | null | null | null | src/index.js | Waleed-Nasir/Car-Parking- | 3e87877996ad1c79cd20888bce5ff8cb2160e1fb | [
"MIT"
] | null | null | null | src/index.js | Waleed-Nasir/Car-Parking- | 3e87877996ad1c79cd20888bce5ff8cb2160e1fb | [
"MIT"
] | null | null | null | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {grey900,lightGreenA200, pink800, green500, green700} from 'material-ui/styles/colors';
import {cyan500, darkBlack, white} from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
// #ff7804
const muiTheme = getMuiTheme({
palette: {
textColor: white,
// primary1Color: '#89e81a',
primary1Color: '#ff7804',
// primary1Color:'#8eff0a'
},
appBar: {
height: 50,
},
});
ReactDOM.render(
<MuiThemeProvider muiTheme={muiTheme}>
<App />
</MuiThemeProvider>
, document.getElementById('root'));
registerServiceWorker();
| 21.575 | 94 | 0.691773 |
b9a26c2fccec480e761e0dd765351dec0d48f10d | 185 | js | JavaScript | index.js | himajagattu/imagereader | 350c57c52110a6dc15d13be22d0efea421143dbb | [
"MIT"
] | null | null | null | index.js | himajagattu/imagereader | 350c57c52110a6dc15d13be22d0efea421143dbb | [
"MIT"
] | null | null | null | index.js | himajagattu/imagereader | 350c57c52110a6dc15d13be22d0efea421143dbb | [
"MIT"
] | null | null | null | $(document).ready(function(){
alert("hello")
$('#submit').on('click',function(){
$('#images').empty();
$.get('/image',function(data){
console.log("data=====",data)
})
})
}) | 18.5 | 36 | 0.545946 |
b9a3a3eddaef09010c37c8c97b9162b868221680 | 545 | js | JavaScript | 7-assets/past-student-repos/Sprint-Challenge-Node-Express-master/index.js | eengineergz/Lambda | 1fe511f7ef550aed998b75c18a432abf6ab41c5f | [
"MIT"
] | null | null | null | 7-assets/past-student-repos/Sprint-Challenge-Node-Express-master/index.js | eengineergz/Lambda | 1fe511f7ef550aed998b75c18a432abf6ab41c5f | [
"MIT"
] | null | null | null | 7-assets/past-student-repos/Sprint-Challenge-Node-Express-master/index.js | eengineergz/Lambda | 1fe511f7ef550aed998b75c18a432abf6ab41c5f | [
"MIT"
] | null | null | null | const express = require('express');
const helmet = require('helmet');
const logger = require('morgan');
const cors = require('cors');
const actionRouter = require('./routes/action_routes');
const projectRouter = require('./routes/project_routes');
const server = express();
server.use(
express.json(),
helmet(),
logger('dev'),
cors()
);
const PORT = process.env.PORT || 4310;
server.use('/projects', projectRouter);
server.use('/actions', actionRouter);
server.listen(PORT, ()=>{
console.log("It's aliiiiive!");
}) | 18.166667 | 57 | 0.66422 |
b9a3d9abdf3001f67be19f7cb96c09f862f76ee9 | 4,653 | js | JavaScript | prop/ve-widget/select-widget/select.js | tickbh/VisualUIEditor | 13e38a95be4d37aaa6f7faac3c57ff0e5190a0f9 | [
"MIT"
] | 84 | 2016-07-15T03:47:02.000Z | 2022-03-11T10:58:08.000Z | prop/ve-widget/select-widget/select.js | tickbh/VisualUIEditor | 13e38a95be4d37aaa6f7faac3c57ff0e5190a0f9 | [
"MIT"
] | 3 | 2016-09-02T10:17:32.000Z | 2017-01-05T03:53:31.000Z | prop/ve-widget/select-widget/select.js | tickbh/VisualUIEditor | 13e38a95be4d37aaa6f7faac3c57ff0e5190a0f9 | [
"MIT"
] | 53 | 2016-08-26T16:33:17.000Z | 2022-03-14T02:18:19.000Z | 'use strict'
Polymer({
behaviors: [],
listeners: {
'focus': '_onFocus',
'blur': '_onBlur',
'focusin': '_onFocusIn',
'focusout': '_onFocusOut',
'keydown': '_onKeyDown',
'mousedown': '_onMouseDown'
},
properties: {
placeholder: {
type: String,
value: ''
},
value: {
type: String,
value: '',
notify: true
},
text: {
type: String,
value: ''
},
readonly: {
type: Boolean,
value: false,
reflectToAttribute: true
}
},
created() {
this._inited = false
},
ready() {
this._inited = true
},
add(value, text) {
var el = document.createElement('ve-option')
Polymer.dom(el).textContent = text
el.value = value.toString()
Polymer.dom(this).appendChild(el)
},
addHtml(value, html) {
var el = document.createElement('ve-option')
Polymer.dom(el).innerHTML = html
el.value = value.toString()
Polymer.dom(this).appendChild(el)
},
showMenu() {
if (this.$.menu.hidden) {
this.$.menu.hidden = false
this.$.menu.focus()
this._updateMenu()
}
},
attached() {
if (this.$.menu.selectedItem) {
if (this.$.menu.selectedItem.text) {
this.text = this.$.menu.selectedItem.text
} else {
this.text = this.$.menu.selectedItem.innerText
}
}
},
toggleMenu() {
this.$.menu.hidden = !this.$.menu.hidden
if (!this.$.menu.hidden) {
this.$.menu.focus()
this._updateMenu()
} else {
this.focus()
}
},
_onFocusIn() {},
_onFocusOut() {
this.async(() => {
if (!this.focused) {
this.$.menu.hidden = true
}
}, 1)
},
_onSelectedItemChanged() {
if (this.$.menu.selectedItem) {
if (this.$.menu.selectedItem.text) {
this.text = this.$.menu.selectedItem.text
} else {
this.text = this.$.menu.selectedItem.innerText
}
} else {
this.text = ''
}
if (this._inited) {
this.async(() => {
this.fire('end-editing', {})
}, 1)
}
},
_onKeyDown(event) {
if (this.readonly) {
return
}
// up-arrow
if (event.keyCode === 38) {
event.preventDefault()
event.stopPropagation()
this.showMenu()
}
// down-arrow
else if (event.keyCode === 40) {
event.preventDefault()
event.stopPropagation()
this.showMenu()
}
// space, enter
else if (event.keyCode === 13 || event.keyCode === 32) {
event.preventDefault()
event.stopPropagation()
this.showMenu()
}
},
_onMouseDown(event) {
if (this.readonly) {
return
}
event.preventDefault()
event.stopPropagation()
this.toggleMenu()
},
_updateMenu() {
window.requestAnimationFrame(() => {
if (this.$.menu.hidden) {
return
}
var bodyBcr = document.body.getBoundingClientRect()
var menuBcr = this.$.menu.getBoundingClientRect()
var bcr = this.getBoundingClientRect()
if (bcr.bottom + menuBcr.height > bodyBcr.bottom) {
this.$.menu.style.top = 'auto'
this.$.menu.style.borderTop = '1px solid #0c70a6'
this.$.menu.style.bottom = (bodyBcr.height - bcr.bottom + bcr.height + 5) + 'px'
this.$.menu.style.borderBottom = '0px'
} else {
this.$.menu.style.top = (bcr.top + bcr.height - 1) + 'px'
this.$.menu.style.borderTop = '0px'
this.$.menu.style.bottom = 'auto'
this.$.menu.style.borderBottom = '1px solid #0c70a6'
}
this.$.menu.style.width = bcr.width + 'px'
this.$.menu.style.left = bcr.left + 'px'
this._updateMenu()
})
},
_text(text) {
if (text === '') {
return this.placeholder
}
return text
},
_textClass(text) {
if (text === '') {
return 'placeholder'
}
return ''
}
}) | 23.265 | 96 | 0.453471 |
b9a492a5224f3a92bfe2bb0815137b7fd70d488c | 1,905 | js | JavaScript | dev/runTests.js | daviemakz/micro-service-framework | fb5ea860105bb63739e2ace578f477acc143391f | [
"MIT"
] | 1 | 2019-11-12T05:40:22.000Z | 2019-11-12T05:40:22.000Z | dev/runTests.js | daviemakz/micro-service-framework | fb5ea860105bb63739e2ace578f477acc143391f | [
"MIT"
] | 177 | 2020-11-18T18:38:26.000Z | 2022-03-28T17:06:25.000Z | dev/runTests.js | daviemakz/micro-service-framework | fb5ea860105bb63739e2ace578f477acc143391f | [
"MIT"
] | 1 | 2019-01-08T21:31:04.000Z | 2019-01-08T21:31:04.000Z | 'use strict';
/* eslint-disable no-console */
/* eslint-disable import/no-extraneous-dependencies */
// Import NPM modules
import { run } from 'jest';
import { Risen } from '..';
// Import system components
/* eslint-disable-next-line */
import jestConfigBase from '../../jest.config.js';
const endTests = () => {
return new Risen({
mode: 'client',
verbose: false
}).request(
{
body: null,
destination: 'serviceCore',
functionName: 'end'
},
() => void 0
);
};
// Wrapper to run the function programatically
const executeTests = (jestConfig, args) => {
// Run the tests for the Risen.JS
console.log(`Starting full test suite for Risen.JS....`);
// For CLI arguments
const processArgs =
Object.entries(require('minimist')(process.argv.slice(2)))
.map(([cliParam, cliValue]) => {
if (cliParam !== '_') {
return cliValue ? `--${cliParam}=${cliValue}` : `--${cliParam}`;
}
return void 0;
})
.filter((arg) => arg) || [];
const argv = [];
// Add CLI arguments
processArgs.forEach((arg) => {
argv.push(arg);
});
// Add config argument
argv.push('--no-coverage');
argv.push('--config', JSON.stringify(jestConfig));
argv.push(
...Object.entries(args).map(([cliParam, cliValue]) =>
cliValue ? `--${cliParam}=${cliValue}` : `--${cliParam}`
)
);
// Show parameters
if (Object.prototype.hasOwnProperty.call(args, 'verbose')) {
console.log(argv);
}
// Run JEST
return run(argv).then(
() => {
console.log(
`Completed test suite for Risen.JS, check JEST for test results!`
);
return endTests();
},
(err) => {
console.error(
`Failed test suite for Risen.JS. An unexpected error has occurred!`
);
console.error(err);
return endTests();
}
);
};
executeTests(jestConfigBase, []);
| 22.678571 | 75 | 0.581627 |
b9a5f05da726debd4a8912455aa3858e07cf7117 | 203 | js | JavaScript | scripts/testExtendedCoverage.js | mattaereal/tpl-contracts | 0498dd75d77ec13620e1734ea6b99fef945b2e8a | [
"MIT"
] | 60 | 2018-04-11T21:42:29.000Z | 2022-03-23T23:33:44.000Z | scripts/testExtendedCoverage.js | mattaereal/tpl-contracts | 0498dd75d77ec13620e1734ea6b99fef945b2e8a | [
"MIT"
] | 5 | 2018-04-07T20:24:52.000Z | 2019-07-03T14:01:07.000Z | scripts/testExtendedCoverage.js | mattaereal/tpl-contracts | 0498dd75d77ec13620e1734ea6b99fef945b2e8a | [
"MIT"
] | 23 | 2018-04-07T20:13:08.000Z | 2020-05-26T08:57:10.000Z | // insert default coverage provider
var Web3 = require('web3')
web3Provider = new Web3('ws://localhost:8555')
var testExtended = require('./testExtended.js')
testExtended.test(web3Provider, 'coverage') | 29 | 47 | 0.753695 |
b9a67241112e2cc2ebeb825f03373c7780ef8040 | 1,454 | js | JavaScript | src/components/homepage/menu.js | luciebaker/zupa-soup | dbc34839ab3ef2f90cad2bac930b8c5c1f8e0554 | [
"MIT"
] | null | null | null | src/components/homepage/menu.js | luciebaker/zupa-soup | dbc34839ab3ef2f90cad2bac930b8c5c1f8e0554 | [
"MIT"
] | null | null | null | src/components/homepage/menu.js | luciebaker/zupa-soup | dbc34839ab3ef2f90cad2bac930b8c5c1f8e0554 | [
"MIT"
] | null | null | null | import React from 'react'
const menu = () => {
return (
<div id="menu" className="container-fluid menu-container pt-4 pb-4">
<div className="container text-center">
<h1>Today's Soup Menu</h1>
</div>
<div className="container">
<div className="row">
<div className="col-6">
<h2>Beef Goolash</h2>
<p>Prime beef cut stewed in the paprika, loaded with vegetables</p>
<h2>Boston Clam Chowder</h2>
<p>Juicy sweet razor clams are cooked to a rich creamy finish, thickened with butter roux, potatoes and celery for that added flourish.</p>
<h2>Meatless Minestrone</h2>
<p>A wonderful burst of colors and flavors in every spoonful, with zucchinis, kidney beans and plump tomatoes</p>
</div>
<div className="col-6">
<h2>Roasted PumpKin Soup</h2>
<p>Pumpkins roasted to perfection with a blend of spices.</p>
<h2>Tangy Tomato with Basil</h2>
<p>This soup is creamy with the smell of freshly roasted tomatoes blended to perfection.</p>
<h2>Chicken & Mushroom Soup</h2>
<p>Rich, creamy soup filled with chunks of marinated chicken, herbs and mushrooms</p>
</div>
</div>
</div>
</div>
)
}
export default menu | 41.542857 | 155 | 0.552957 |
b9a693a6df18d8732f1ede28f1e547d26a69ed4d | 907 | js | JavaScript | src/families/tezos/libcore-hw-signTransaction.js | kiroboio/ledger-live-common | 6be2972e6cf0088f6985abc9195c4a4581785f47 | [
"Apache-2.0"
] | 1 | 2021-03-19T11:59:05.000Z | 2021-03-19T11:59:05.000Z | src/families/tezos/libcore-hw-signTransaction.js | kiroboio/ledger-live-common | 6be2972e6cf0088f6985abc9195c4a4581785f47 | [
"Apache-2.0"
] | null | null | null | src/families/tezos/libcore-hw-signTransaction.js | kiroboio/ledger-live-common | 6be2972e6cf0088f6985abc9195c4a4581785f47 | [
"Apache-2.0"
] | 1 | 2020-11-30T20:00:20.000Z | 2020-11-30T20:00:20.000Z | // @flow
import Xtz from "./hw-app-xtz";
import Transport from "@ledgerhq/hw-transport";
import type { CryptoCurrency, DerivationMode, Account } from "../../types";
import type { CoreCurrency } from "../../libcore/types";
import type { CoreTezosLikeTransaction } from "./types";
export async function tezosSignTransaction({
account,
transport,
coreTransaction
}: {
isCancelled: () => boolean,
account: Account,
transport: Transport<*>,
currency: CryptoCurrency,
coreCurrency: CoreCurrency,
coreTransaction: CoreTezosLikeTransaction,
derivationMode: DerivationMode
}) {
const hwApp = new Xtz(transport);
const { signature } = await hwApp.signOperation(
account.freshAddressPath,
await coreTransaction.serialize()
);
await coreTransaction.setSignature(signature);
const raw = await coreTransaction.serialize();
return raw;
}
export default tezosSignTransaction;
| 24.513514 | 75 | 0.733186 |
b9a7250dc4f28dc16348a0c3358467b052a883ad | 5,029 | js | JavaScript | wijmo.chart.hierarchical.js | jas-trainning/wijmo-system-min | babf3c752450710368adcdea21cb6c9b28b721fa | [
"Apache-2.0"
] | null | null | null | wijmo.chart.hierarchical.js | jas-trainning/wijmo-system-min | babf3c752450710368adcdea21cb6c9b28b721fa | [
"Apache-2.0"
] | null | null | null | wijmo.chart.hierarchical.js | jas-trainning/wijmo-system-min | babf3c752450710368adcdea21cb6c9b28b721fa | [
"Apache-2.0"
] | null | null | null | /*
*
* Wijmo Library 5.20163.234
* http://wijmo.com/
*
* Copyright(c) GrapeCity, Inc. All rights reserved.
*
* Licensed under the Wijmo Commercial License.
* sales@wijmo.com
* http://wijmo.com/products/wijmo-5/license/
*
*/
System.register(['wijmo/wijmo.chart','wijmo/wijmo','wijmo/wijmo.chart.hierarchical'],function(n,t){"use strict";var s=t&&t.id,o=this&&this.__extends||function(n,t){function r(){this.constructor=n}for(var i in t)t.hasOwnProperty(i)&&(n[i]=t[i]);n.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)},r,i,f,e,u;return{setters:[function(n){r=n},function(n){i=n},function(n){f=n}],execute:function(){window.wijmo=window.wijmo||{};window.wijmo.chart=window.wijmo.chart||{};window.wijmo.chart.hierarchical=f;e=function(n){function t(t,i){n.call(this,t,i);this._processedData=[];this._legendLabels=[];this._level=1;this._sliceIndex=0;this._selectionIndex=0;this.applyTemplate('wj-sunburst',null,null)}return o(t,n),Object.defineProperty(t.prototype,"bindingName",{get:function(){return this._bindName},set:function(n){n!=this._bindName&&(i.assert(n==null||i.isArray(n)||i.isString(n),'bindingName should be an array or a string.'),this._bindName=n,this._bindChart())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"childItemsPath",{get:function(){return this._childItemsPath},set:function(n){n!=this._childItemsPath&&(i.assert(n==null||i.isArray(n)||i.isString(n),'childItemsPath should be an array or a string.'),this._childItemsPath=n,this._bindChart())},enumerable:!0,configurable:!0}),t.prototype._initData=function(){n.prototype._initData.call(this);this._processedData=[];this._level=1;this._legendLabels=[]},t.prototype._performBind=function(){var t=this,n;this._initData();this._cv&&(n=this._cv.items,n&&(this._processedData=u.parseDataToHierarchical(n,this.binding,this.bindingName,this.childItemsPath),this._sum=this._calculateValueAndLevel(this._processedData,1),this._processedData.forEach(function(n){t._legendLabels.push(n.name)})))},t.prototype._calculateValueAndLevel=function(n,t){var i=this,r=0,u=this._values,f=this._labels;return this._level<t&&(this._level=t),n.forEach(function(n){var e;n.items?(e=i._calculateValueAndLevel(n.items,t+1),n.value=e,u.push(e),f.push(n.name)):(e=i._getBindData(n,u,f,'value','name'),n.value=e);r+=e}),r},t.prototype._renderPie=function(n,t,i,r,u){var f=this._getCenter();this._sliceIndex=0;this._renderHierarchicalSlices(n,f.x,f.y,this._processedData,this._sum,t,i,r,2*Math.PI,u,1)},t.prototype._renderHierarchicalSlices=function(n,t,i,r,u,f,e,o,s,h,c){var rt=r.length,a=o,g=this.reversed==!0,nt,tt,d,l,y,p,it,w,b,k,v;for(d=(f-e)/this._level,nt=f-(this._level-c)*d,tt=e+(c-1)*d,v=0;v<rt;v++)w=t,b=i,it=n.startGroup('slice-level'+c),c===1&&(n.fill=this._getColorLight(v),n.stroke=this._getColor(v)),y=r[v],p=Math.abs(y.value),l=Math.abs(p-u)<1e-10?s:s*p/u,k=g?a-.5*l:a+.5*l,h>0&&l<s&&(w+=h*Math.cos(k),b+=h*Math.sin(k)),y.items&&this._renderHierarchicalSlices(n,w,b,y.items,p,f,e,a,l,0,c+1),this._renderSlice(n,w,b,k,this._sliceIndex,nt,tt,a,l,s),this._sliceIndex++,g?a-=l:a+=l,n.endGroup(),this._pels.push(it)},t.prototype._getLabelsForLegend=function(){return this._legendLabels||[]},t.prototype._highlightCurrent=function(){this.selectionMode!=r.SelectionMode.None&&this._highlight(!0,this._selectionIndex)},t}(r.FlexPie);n("Sunburst",e);u=function(){function n(){}return n.parseDataToHierarchical=function(t,r,u,f){var e=[],o;return t.length>0&&(i.isString(u)&&u.indexOf(',')>-1&&(u=u.split(',')),f?e=n.parseItems(t,r,u,f):(o=n.ConvertFlatData(t,r,u),e=n.parseItems(o,'value',u,'items'))),e},n.parseItems=function(t,i,r,u){for(var e=[],o=t.length,f=0;f<o;f++)e.push(n.parseItem(t[f],i,r,u));return e},n.isFlatItem=function(n,t){return i.isArray(n[t])?!1:!0},n.ConvertFlatData=function(t,i,r){for(var f=[],e={},o,s=t.length,u=0;u<s;u++)o=t[u],n.ConvertFlatItem(e,o,i,r);return n.ConvertFlatToHierarchical(f,e),f},n.ConvertFlatToHierarchical=function(t,i){var r=i.flatDataOrder;r&&r.forEach(function(r){var u={},f=i[r],e;u[i.field]=r;f.flatDataOrder?(e=[],n.ConvertFlatToHierarchical(e,f),u.items=e):u.value=f;t.push(u)})},n.ConvertFlatItem=function(t,i,r,u){var e,o,f,s,h;return(e=u.slice(),o=e.shift().trim(),f=i[o],f==null)?!1:(e.length===0?(t[f]=i[r],t.flatDataOrder?t.flatDataOrder.push(f):t.flatDataOrder=[f],t.field=o):(t[f]==null&&(t[f]={},t.flatDataOrder?t.flatDataOrder.push(f):t.flatDataOrder=[f],t.field=o),s=t[f],h=n.ConvertFlatItem(s,i,r,e),h||(t[f]=i[r])),!0)},n.parseItem=function(t,r,u,f){var e={},h,l,o,c,s;return i.isArray(f)?(s=f.slice(),c=s.length?s.shift().trim():''):(s=f,c=f),i.isArray(u)?(h=u.slice(),l=h.shift().trim(),e.nameField=l,e.name=t[l],o=t[c],h.length===0?e.value=t[r]:o&&i.isArray(o)&&o.length>0?e.items=n.parseItems(o,r,h,s):e.value=t[r]||0):(e.nameField=u,e.name=t[u],o=t[c],o!=null&&i.isArray(o)&&o.length>0?e.items=n.parseItems(o,r,u,s):e.value=t[r]),e},n.parseFlatItem=function(n){n.items||(n.items=[])},n}();n("HierarchicalUtil",u)}}}) | 386.846154 | 4,759 | 0.707497 |
b9a7c5bbaf0cf62a1eb9aaa5fc1c5dc68f2b60f3 | 5,202 | js | JavaScript | docs/.vuepress/config.js | XxLittleCxX/51book | 71353372841b6f6d8c8f2a6bcd45aa3a072129ca | [
"MIT"
] | null | null | null | docs/.vuepress/config.js | XxLittleCxX/51book | 71353372841b6f6d8c8f2a6bcd45aa3a072129ca | [
"MIT"
] | null | null | null | docs/.vuepress/config.js | XxLittleCxX/51book | 71353372841b6f6d8c8f2a6bcd45aa3a072129ca | [
"MIT"
] | null | null | null | module.exports = {
title: '温州市第五十一中学新生导引',
description: '温州市第五十一中学新生导引,提供五十一中生存学习攻略,帮助新同学快速了解校园,融入校园,更快地进入学习环境。',
base: '/',
serviceWorker: true,
markdown: {
lineNumbers: true,
externalLinks: { target: '_blank' }
},
locales: {
'/': {
lang: 'zh-CN'
}
},
plugin:
['@vuepress/back-to-top'],
head: [
['link', { "rel": 'icon', href: 'https://i.loli.net/2021/07/18/X9h3ZYpyNK7jwCS.png' }],
['meta', { "itemprop": 'image', content: 'https://i.loli.net/2021/07/18/X9h3ZYpyNK7jwCS.png' }],
['meta', { "http-equiv": 'Content-Type', content: 'text/html; charset=UTF-8' }],
['meta', { name: 'keywords', content: '温州市第五十一中学新生导引,温州市第五十一中学,温州市五十一中学,温州市第51中学,温州市51中学,五十一中学,五十一中,51中,51中学,温五十一中,温51中,浙江省温州中学,温州中学,温一中,新生,五十一中新生,温州市第五十一中学贴吧,新生导引,新生攻略' }],
['script', { 'async': true, 'remark': '谷歌统计', 'src': 'https://www.googletagmanager.com/gtag/js?id=G-DYCSYN7GFC' }],
['script', { 'remark': '统计' }, `
if(window.location.host === "www.wz51z.wiki"){
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-DYCSYN7GFC');
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?5c7b60df1e46195f2dda5d21854f3a3a";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
}
`]
],
themeConfig: {
docsRepo: 'ENDsoft233/51book',
docsDir: 'docs',
docsBranch: 'main',
editLinks: true,
editLinkText: '帮我们一起完善',
logo: 'https://i.loli.net/2021/07/18/C8VybnX4NUEIDJT.png',
lastUpdated: '上次修改 ',
nav: [
{ text: '加入读者交流群', link: 'https://qm.qq.com/cgi-bin/qm/qr?k=z-_ivibiwB4JEXrBdCB2oK9SzhJp8gq_&jump_from=webapi' },
{ text: '返回 五十一中官网', link: 'http://www.wz51z.com/' }
],
sidebar: [
['/', '开始之前'],
{
title: '新生准备',
path: '/新生准备/',
sidebarDepth: 1,
children: [
"/新生准备/",
'/新生准备/寝室生活',
'/新生准备/学习生活',
'/新生准备/文化生活'
]
},
{
title: '学校文化',
path: '/学校文化/',
sidebarDepth: 1,
children: [
"/学校文化/",
"/学校文化/校志",
"/学校文化/校训",
"/学校文化/办学历程"
]
},
['/学校布局/', '学校布局'],
{
title: '规章制度',
path: '/规章制度/',
sidebarDepth: 1,
children: [
"/规章制度/",
"/规章制度/学习",
"/规章制度/生活",
"/规章制度/机构",
"/规章制度/违纪之后",
{
title: '章程文件',
path: '/规章制度/文件/',
sidebarDepth: 1,
children: [
"/规章制度/文件/一、学校章程制度/",
"/规章制度/文件/一、学校章程制度/(一)中小学生守则",
"/规章制度/文件/一、学校章程制度/(二)中学生日常行为规范(修订)",
"/规章制度/文件/一、学校章程制度/(三)温州市第五十一中学生学籍管理条例(修订)",
"/规章制度/文件/一、学校章程制度/(四)五十一中学业余党校章程",
"/规章制度/文件/一、学校章程制度/(五)考试制度",
"/规章制度/文件/一、学校章程制度/(六)团委学生会干事招新及干部换雇细则",
"/规章制度/文件/一、学校章程制度/(七)权益维护制度",
"/规章制度/文件/一、学校章程制度/(八)处分制度",
"/规章制度/文件/一、学校章程制度/(九)校级优秀学生、优秀学生干部、先进班集体评选制度",
"/规章制度/文件/一、学校章程制度/(十)传达室管理制度",
"/规章制度/文件/二、常规管理相关条例/",
"/规章制度/文件/二、常规管理相关条例/(一)温州市第五十一中学班级常规考核实施办法",
"/规章制度/文件/二、常规管理相关条例/(二)温州市第五十一中学学生发展指数操作细则(修订)",
"/规章制度/文件/二、常规管理相关条例/(三)五十一中学生自主学习十个细节",
"/规章制度/文件/二、常规管理相关条例/(四)考勤制度",
"/规章制度/文件/二、常规管理相关条例/(五)请假制度",
"/规章制度/文件/二、常规管理相关条例/(六)晚自修管理制度",
"/规章制度/文件/二、常规管理相关条例/(七)温州市第五十一中学值周班管理规定",
"/规章制度/文件/二、常规管理相关条例/(八)校园环境卫生管理办法",
"/规章制度/文件/二、常规管理相关条例/(九)文明用膳制度",
"/规章制度/文件/三、宿舍管理规定/",
"/规章制度/文件/三、宿舍管理规定/(一)寝室管理细则",
"/规章制度/文件/三、宿舍管理规定/(二)周末住校管理规定",
"/规章制度/文件/三、宿舍管理规定/(三)寝室评优办法",
"/规章制度/文件/三、宿舍管理规定/(四)走读生管理办法",
"/规章制度/文件/三、宿舍管理规定/(五)学生宿管人员职责",
"/规章制度/文件/三、宿舍管理规定/(六)学生宿舍内务、纪律评分细则",
"/规章制度/文件/四、场馆管理规定/",
"/规章制度/文件/四、场馆管理规定/(一)实验室守则",
"/规章制度/文件/四、场馆管理规定/(二)计算机室守则",
"/规章制度/文件/五、安全注意事项/",
"/规章制度/文件/五、安全注意事项/(一)温州市第五十一中学安全工作章程",
"/规章制度/文件/五、安全注意事项/(二)校园涉外安全管理细则",
"/规章制度/文件/五、安全注意事项/(三)体育运动中的安全问题",
"/规章制度/文件/五、安全注意事项/(四)户外安全",
"/规章制度/文件/五、安全注意事项/(五)心理健康与人身安全",
"/规章制度/文件/五、安全注意事项/(六)火场逃生十要素",
"/规章制度/文件/五、安全注意事项/(附一)五十一中学应急、疏散逃生预案",
"/规章制度/文件/五、安全注意事项/(附二)教室用电安全注意事项"
]
},
]
},
{
title: '学校生活',
path: '/学校生活/',
sidebarDepth: 1,
children: [
"/学校生活/",
"/学校生活/吃",
"/学校生活/穿",
"/学校生活/住",
"/学校生活/行",
"/学校生活/玩",
"/学校生活/通信",
"/学校生活/受伤了"
]
},
['/学业规划/', '学业规划'],
['/知识百科/', '知识百科'],
['/联系我们', '联系我们']
],
smoothScroll: true
},
evergreen: true
} | 32.924051 | 177 | 0.474241 |
b9a7cd96bb30216dbeab2da8468a676a3ad4fa7b | 524 | js | JavaScript | pages/api/posts/update/[id].js | agustacandi/arrcube | 838883639edb45d7ab11cd438ff449cf51b968be | [
"MIT"
] | null | null | null | pages/api/posts/update/[id].js | agustacandi/arrcube | 838883639edb45d7ab11cd438ff449cf51b968be | [
"MIT"
] | null | null | null | pages/api/posts/update/[id].js | agustacandi/arrcube | 838883639edb45d7ab11cd438ff449cf51b968be | [
"MIT"
] | null | null | null | import db from '../../../../libs/db';
import authorization from '../../../../middlewares/authorization';
export default async function handler(req, res) {
if (req.method !== 'PUT') return res.status(405).end();
await authorization(req, res);
const { id } = req.query;
const { title, content } = req.body;
await db('posts').where({ id }).update({
title,
content,
});
const post = await db('posts').where({ id }).first();
res.status(200);
res.json({
message: 'Post updated successfully!',
post,
});
}
| 20.153846 | 66 | 0.620229 |
b9a807fac16f6f0051fed49ba28fb07ad3b36d34 | 926 | js | JavaScript | www/src/Console.js | dancegit/grafka | 7f82297ff7e3d7704d4dcae3dc87e50977821c00 | [
"MIT"
] | 12 | 2019-11-26T16:47:39.000Z | 2021-05-06T23:30:40.000Z | www/src/Console.js | dancegit/grafka | 7f82297ff7e3d7704d4dcae3dc87e50977821c00 | [
"MIT"
] | 28 | 2019-11-10T20:45:17.000Z | 2020-08-28T23:35:21.000Z | www/src/Console.js | dancegit/grafka | 7f82297ff7e3d7704d4dcae3dc87e50977821c00 | [
"MIT"
] | 5 | 2019-11-27T08:02:25.000Z | 2021-05-06T20:54:15.000Z | import React, { useState } from "react";
import Settings from "./settings/Settings";
import { Public } from "@material-ui/icons/";
import Button from "@material-ui/core/Button";
export default function() {
const [hideFrame, setHideFrame] = useState(true);
const console = hideFrame ? (
<React.Fragment />
) : (
<iframe
src={Settings.queryUiUrl}
width={"100%"}
height={800}
name="inline-graphiql"
/>
);
const buttonContent = hideFrame ? (
<React.Fragment>
<Public /> Open Query UI
</React.Fragment>
) : (
<React.Fragment>
<Settings.icons.Close /> Close Query UI
</React.Fragment>
);
return (
<React.Fragment>
<Button
key="queryui"
aria-label="queryui"
color="inherit"
onClick={() => setHideFrame(!hideFrame)}
>
{buttonContent}
</Button>
{console}
</React.Fragment>
);
} | 21.534884 | 51 | 0.583153 |
b9a8590cc6a310b5d7af4b1641c161dd5ccbfd29 | 605 | js | JavaScript | src/common/app/mapDispatchToProps.js | Chart3JS/music4ever | e64cb711c1c03e3c8f21312612129195ef8fd197 | [
"MIT"
] | null | null | null | src/common/app/mapDispatchToProps.js | Chart3JS/music4ever | e64cb711c1c03e3c8f21312612129195ef8fd197 | [
"MIT"
] | null | null | null | src/common/app/mapDispatchToProps.js | Chart3JS/music4ever | e64cb711c1c03e3c8f21312612129195ef8fd197 | [
"MIT"
] | null | null | null | import * as authActions from '../auth/actions';
import * as postsActions from '../posts/actions';
import * as eventsActions from '../events/actions';
import * as uiActions from '../ui/actions';
import {Map} from 'immutable';
import {bindActionCreators} from 'redux';
const actions = [
authActions,
postsActions,
eventsActions,
uiActions
];
export default function mapDispatchToProps(dispatch) {
const creators = Map()
.merge(...actions)
.filter(value => typeof value === 'function')
.toObject();
return {
actions: bindActionCreators(creators, dispatch),
dispatch
};
}
| 23.269231 | 54 | 0.690909 |
b9a996261c70bdef51301724803a5cadda1e262f | 3,005 | js | JavaScript | components/Footer.js | janlauber/autokueng-frontend | 05b66330511176a7327b6b587d7f2a77b67b64d8 | [
"Apache-2.0"
] | null | null | null | components/Footer.js | janlauber/autokueng-frontend | 05b66330511176a7327b6b587d7f2a77b67b64d8 | [
"Apache-2.0"
] | 16 | 2021-11-24T00:14:49.000Z | 2022-03-30T18:18:04.000Z | components/Footer.js | janlauber/autokueng-frontend | 05b66330511176a7327b6b587d7f2a77b67b64d8 | [
"Apache-2.0"
] | null | null | null | /* This example requires Tailwind CSS v2.0+ */
const navigation = [
{
name: 'Telefon',
href: 'tel:+41319585757',
icon: (props) => (
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 3h5m0 0v5m0-5l-6 6M5 3a2 2 0 00-2 2v1c0 8.284 6.716 15 15 15h1a2 2 0 002-2v-3.28a1 1 0 00-.684-.948l-4.493-1.498a1 1 0 00-1.21.502l-1.13 2.257a11.042 11.042 0 01-5.516-5.517l2.257-1.128a1 1 0 00.502-1.21L9.228 3.683A1 1 0 008.279 3H5z" />
</svg>
),
},
{
name: 'E-Mail',
href: 'mailto:info@autokueng.ch',
icon: (props) => (
<svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 19v-8.93a2 2 0 01.89-1.664l7-4.666a2 2 0 012.22 0l7 4.666A2 2 0 0121 10.07V19M3 19a2 2 0 002 2h14a2 2 0 002-2M3 19l6.75-4.5M21 19l-6.75-4.5M3 10l6.75 4.5M21 10l-6.75 4.5m0 0l-1.14.76a2 2 0 01-2.22 0l-1.14-.76" />
</svg>
),
},
{
name: 'GitHub',
href: 'https://github.com/janlauber',
icon: (props) => (
<svg fill="currentColor" viewBox="0 0 24 24" {...props}>
<path
fillRule="evenodd"
d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"
clipRule="evenodd"
/>
</svg>
),
},
]
export default function Example() {
return (
<footer className="bg-white">
<div className="max-w-7xl mx-auto py-12 px-4 sm:px-6 md:items-center lg:px-8">
<div className="flex justify-center space-x-6 md:order-2">
{navigation.map((item) => (
<a key={item.name} href={item.href} className="text-gray-400 hover:text-gray-500" target="_blank">
<span className="sr-only">{item.name}</span>
<item.icon className="h-6 w-6" aria-hidden="true" />
</a>
))}
</div>
<div className="mt-8 md:mt-0 md:order-1">
<p className="text-center text-base text-gray-400">© 2022 AutoKüng AG. All rights reserved.</p>
</div>
</div>
</footer>
)
}
| 54.636364 | 736 | 0.580699 |
b9a9dc8d644d4f1f90b673908e18e8cf097f2b15 | 77 | js | JavaScript | tests/unit/lib/util/sharelibtestdata/martini_lib/lib/common/common/innermartini2.common.js | pranavparikh/arrow | c74116a7d2d5dcb1826ad5f203cfac31ac6590c7 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/lib/util/sharelibtestdata/martini_lib/lib/common/common/innermartini2.common.js | pranavparikh/arrow | c74116a7d2d5dcb1826ad5f203cfac31ac6590c7 | [
"BSD-3-Clause"
] | null | null | null | tests/unit/lib/util/sharelibtestdata/martini_lib/lib/common/common/innermartini2.common.js | pranavparikh/arrow | c74116a7d2d5dcb1826ad5f203cfac31ac6590c7 | [
"BSD-3-Clause"
] | null | null | null | YUI.add("inner-martini-lib-common2", function (Y) {
}, "0.1",{requires:[]});
| 25.666667 | 51 | 0.61039 |
b9acf59d3d1efff1f661aeda7071582f63dbd26a | 2,737 | js | JavaScript | src/components/three_components/scenes/Scene5.js | EvanDaley/r3f-overlay | 6095fa0abad313ec3db0d4abe02442f825129ee0 | [
"MIT"
] | null | null | null | src/components/three_components/scenes/Scene5.js | EvanDaley/r3f-overlay | 6095fa0abad313ec3db0d4abe02442f825129ee0 | [
"MIT"
] | null | null | null | src/components/three_components/scenes/Scene5.js | EvanDaley/r3f-overlay | 6095fa0abad313ec3db0d4abe02442f825129ee0 | [
"MIT"
] | null | null | null |
import OxygenContainer2 from '../objects/OxygenContainer2'
import Box from '../objects/Box'
import AbstractSphere from '../objects/AbstractSphere'
import { OrbitControls, Stats, Stage, Loader, PerspectiveCamera, Environment, useTexture, Reflector } from '@react-three/drei';
import { Canvas, useThree } from '@react-three/fiber';
import React, { useState, useEffect, Suspense, useRef, useMemo } from 'react';
import * as THREE from 'three'
import { MeshPhysicalMaterial } from 'three';
function MidsectionPlane() {
const plane = useRef()
const { viewport, aspect } = useThree()
const texture = useTexture(window.location.href + '/images/majestic_deer_Benoît_FLEURY.png')
const alpha = useTexture(window.location.href + '/images/AlphamapTest.gif')
useMemo(() => (texture.minFilter = THREE.LinearFilter), [])
const adaptedHeight = 3800 * (aspect > 5000 / 3800 ? viewport.width / 5000 : viewport.height / 3800)
const adaptedWidth = 5000 * (aspect > 5000 / 3800 ? viewport.width / 5000 : viewport.height / 3800)
return (
<>
<mesh ref={plane} position={[0, 4, -8]} scale={[adaptedWidth + 1, adaptedHeight + 0.5, 1]}>
<planeBufferGeometry attach="geometry" args={[1, 1]} />
<meshBasicMaterial
attach="material"
map={texture}
transparent={true}
/>
{/* <meshBasicMaterial
attach="material"
map={texture}
alphaMap={alpha}
transparent={true}
/> */}
</mesh>
{/* <mesh ref={plane} position={[0, 4, -4]} scale={[adaptedWidth + 2, adaptedHeight + 1.5, 2]}>
<planeBufferGeometry attach="geometry" args={[1, 1]} />
<meshBasicMaterial attach="material" map={texture} alphaMap={alpha} transparent={true} />
</mesh> */}
</>
)
}
function ReflectorPlane() {
return (
<Reflector
position={[0, 0, -2]}
rotation={[-Math.PI / 2, 0, 0]}
args={[15, 15]}
resolution={1024}
mirror={0.001}
mixBlur={1.0}
mixBlur={0}
mixStrength={1}
depthScale={1}
minDepthThreshold={0.9}
maxDepthThreshold={1}
depthToBlurRatioBias={0.25}
distortion={0}
opacity={.5}
transparent={true}
// distortionMap={distortionTexture}
debug={0}
>
{(Material, props) => <Material color="#808F8D" metalness={1} normalScale={[1, 1]} {...props} />}
</Reflector>
)
}
export default function Scene() {
return (
<>
<Stage adjustCamera={false} contactShadow={true} shadows={true} >
<MidsectionPlane />
<ReflectorPlane />
<Suspense fallback={null}>
<Environment preset={'forest'} background={false} />
</Suspense>
</Stage>
</>
);
}
| 31.102273 | 127 | 0.610522 |
b9ad76e0d86377c4ac6976bdbeab013bafb1e389 | 112 | js | JavaScript | app/lib/server-port.js | Finnberry/accessibility-manual | e9deb970cae98552ec4f785ae23bfecc70af6dda | [
"MIT"
] | 34 | 2020-12-01T11:44:37.000Z | 2022-02-01T13:12:50.000Z | app/lib/server-port.js | Finnberry/accessibility-manual | e9deb970cae98552ec4f785ae23bfecc70af6dda | [
"MIT"
] | 38 | 2020-12-01T10:36:33.000Z | 2022-01-19T21:04:50.000Z | app/lib/server-port.js | Finnberry/accessibility-manual | e9deb970cae98552ec4f785ae23bfecc70af6dda | [
"MIT"
] | 21 | 2020-10-22T07:52:00.000Z | 2022-02-01T13:12:17.000Z | module.exports = function (port) {
if (typeof port === 'undefined') return '3000'
return process.env.PORT
}
| 22.4 | 48 | 0.678571 |
b9ad82900331625b75ddc2fb738f6fb75f77587c | 41,149 | js | JavaScript | scripts/compiled/bundle.js | crsmnd/HNselect | c898e7021d46ac2a88c87d9b6b6cd3f822453bab | [
"MIT"
] | 1 | 2017-06-10T10:48:42.000Z | 2017-06-10T10:48:42.000Z | scripts/compiled/bundle.js | vdaranyi/HNselect | c898e7021d46ac2a88c87d9b6b6cd3f822453bab | [
"MIT"
] | 5 | 2015-03-17T21:51:37.000Z | 2015-03-17T22:10:25.000Z | scripts/compiled/bundle.js | crsmnd/hn-select | c898e7021d46ac2a88c87d9b6b6cd3f822453bab | [
"MIT"
] | 3 | 2015-04-21T16:30:36.000Z | 2015-04-21T16:45:47.000Z | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
require('./sidebar.jsx');
require('./pageHighlighting.js');
// FILE TO BE CLEANED UP
// Google Analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-61604728-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
console.log('GAQ:',_gaq);
})();
// Constants
var hnOrange = '#ff6600',
commentsBgColor = hnOrange,
commentsTitleColor = hnOrange,
authorColor = hnOrange,
commentersTextColor = "#ffffff",
commentersBgColor = hnOrange,
bgGrey = "#f7f7f1",
following = [],
// getCommentersRoute = 'http://www.hnselect.com/getCommenters';
getCommentersRoute = 'https://hn-select.herokuapp.com/getCommenters';
// Selecting highlighting method depending on view
// var tabUrl = window.location.href;
// var tabQuery = window.location.search;
// if (tabQuery.indexOf('?id=') > -1 || tabUrl.indexOf('newcomments') > -1) {
// console.log(' > Highlighting comments');
// // highlightComments();
// } else {
// console.log(' > Highlighting stories');
// // highlightNews();
// }
var user, following;
//remove duplication of getting user
chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
if (request.action == "getUser") {
var user = $('a[href^="user?id="]').attr('href').replace('user?id=', '');
sendResponse({user: user});
console.log('sending', user);
} else
sendResponse({}); // Send nothing..
});
/* Inform the backgrund page that
* this tab should have a page-action */
chrome.runtime.sendMessage({
from: 'content',
subject: 'showPageAction'
});
/* Listen for message from the popup */
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.request) {
following = request.request
}
else {
console.log('error')
}
});
},{"./pageHighlighting.js":2,"./sidebar.jsx":3}],2:[function(require,module,exports){
//console.log('pageHighlighting');
// var server = 'http://www.hnselect.com';
var server = 'http://hn-select.herokuapp.com';
// var server = 'http://localhost:3000';
var hnOrange = '#ff6600',
hnGrey = '#828282',
commentsBgColor = hnOrange,
commentsTitleColor = hnOrange,
authorColor = hnOrange,
commentersTextColor = 'black',
commentersBgColor = hnGrey,
bgGrey = "#f7f7f1";
parseHnPage();
function parseHnPage() {
var storiesOnPage = {},
storyIdsOnPage = [],
highlightData;
var user = $('span.pagetop').last().children('a[href]').attr('href');
if (user.indexOf('login') === 0) {
// Replace alert with request in sidebar to login!
alert('To use HNselect, please log into HN first');
// Stop code execution of extension. Return not sufficient!
return;
} else {
user = user.replace('user?id=', '');
}
$('.subtext').each(function (index) {
var story = {};
var $author = $(this).children('a[href^="user?id"]');
var author = $author.text();
var $storyTitle = $(this).parents('tr:first').prev('tr').find('a[href^="http"]');
// Check if it is a story, otherwise skip (i.e. Jobs, e.g. https://news.ycombinator.com/item?id=11639942)
try {
var storyId = $author.parent().children('span').find('a[href^="item?id"]').attr('href').replace('item?id=', '');
}
catch(err) {
return true; // go to next .each iteration
}
// console.log(user, index, $author, $storyTitle, storyId);
// Put all stories on page into array for subsequent comment following analysis
storiesOnPage[storyId] = {
storyId: storyId,
$storyTitle: $storyTitle,
$author: $author,
author: author
};
storyIdsOnPage.push(Number(storyId));
addBookmarkButton($storyTitle, storyId, user);
addPlusButton($author, author, user);
});
// var storyIdsReqObject = {storyIds: storyIdsOnPage};
fetchHighlight(user, storiesOnPage, storyIdsOnPage);
}
function fetchHighlight(username, storiesOnPage, storyIdsOnPage) {
// Get highlight data from server
// console.log(storyIdsOnPage);
chrome.runtime.sendMessage({
method: 'POST',
action: 'ajax',
url: server + '/user/' + username + '/highlight',
data: storyIdsOnPage
}, function (response) {
//console.log(typeof response, response);
if (response && response !== 'Not Found') {
highlightData = JSON.parse(response);
//console.log(highlightData);
highlightStories(storiesOnPage, highlightData);
} else {
console.log('Did not retrieve highlight data');
}
})
}
function highlightStories(stories, highlightData) {
//console.log(highlightData);
// s stands for storyId
for (var s in highlightData) {
if (highlightData.hasOwnProperty(s)) {
//console.log(s);
stories[s].$storyTitle.css({color: commentsTitleColor});
if (highlightData[s].author.length) {
commenterStyling(stories[s].$author, 'story');
}
if (highlightData[s].commenters.length) {
var commenters = highlightData[s].commenters;
for (var c = 0; c < commenters.length; c++) {
var commentersElement = "<a href='https://news.ycombinator.com/user?id=" + commenters[c] + "'> " + commenters[c] + " </a>";
//console.log(commentersElement, 'comment');
var $commentersElement = commenterStyling($(commentersElement));
stories[s].$author.nextAll().eq(2).after($commentersElement);
}
}
}
}
function commenterStyling($authorDomElem, type) {
$authorDomElem.css({
color: commentersTextColor,
'font-weight': 'bold',
});
if (type === 'story') {
$authorDomElem.prepend("<span> </span>").append("<span> </span>");
} else {
var $toInsert = $("<span> </span>").css("background-color", bgGrey).append($authorDomElem);
return $toInsert;
}
}
}
function addPlusButton($author, author, user) {
// Replace + with Glyphicon
$plusButtonHtml = $("<span class='add-plus-button'> +</span>")
$plusButtonHtml.insertAfter($author).click(function(){
chrome.runtime.sendMessage({
method: 'POST',
action: 'ajax',
url: server + '/user/' + user + '/followuser/' + author,
}, function (response) {
console.log('DONE',response);
}
);
});
}
function addBookmarkButton($storyTitle, storyId, user) {
// Replace + with Glyphicon
$plusButtonHtml = $("<span class='add-plus-button'> +</span>")
$plusButtonHtml.insertAfter($storyTitle).click(function(){
chrome.runtime.sendMessage({
method: 'POST',
action: 'ajax',
url: server + '/user/' + user + '/bookmark/' + storyId,
}, function (response) {
console.log('DONE',response);
}
);
});
}
// NOT YET FUNCTIONAL
/*
function highlightComments() {
$('a[href^="user?id"]').each(function (index) {
var author = $(this).text();
if (following.indexOf(author) > -1) {
$(this).parents('td:first').css({'background-color': commentsBgColor});
$(this).css({'color': commentersTextColor, 'font-weight': 'bold'});
$(this).nextAll().css({'color': commentersTextColor});
}
});
}
*/
},{}],3:[function(require,module,exports){
// Constants
//var server = 'http://localhost:3000';
// var server = 'http://www.hnselect.com';
var server = 'http://hn-select.herokuapp.com';
var hnUrl = "https://news.ycombinator.com";
//require("./react-materialize/src/input.js");
var addFonts = document.createElement('style');
addFonts.type = 'text/css';
addFonts.textContent = '@font-face { font-family: FontAwesome; src: url("'
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/material-design-icons/Material-Design-Icons.eot')
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/material-design-icons/Material-Design-Icons.svg')
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/material-design-icons/Material-Design-Icons.ttf')
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/roboto/Roboto-Bold.ttf')
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/roboto/Roboto-Light.ttf')
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/roboto/Roboto-Medium.ttf')
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/roboto/Roboto-Regular.ttf')
+ chrome.extension.getURL('https://cdnjs.cloudflare.com/ajax/libs/materialize/0.95.3/font/roboto/Roboto-Thin.ttf')
+ '"); }';
document.head.appendChild(addFonts);
// TO DO
// Change server, change following indexOf check
// Global variables
var newsfeed, lastItemFromDB, lastItemFetched, following, user
initialLoadHasTakenPlace = false,
maxItemFb = new Firebase('https://hacker-news.firebaseio.com/v0/maxitem');
//==========================================================
// Sidebar container and slider functionality
// Attaches an empty div to the DOM and renders component
$(document).ready(function () {
username = $('a[href^="user?id="]').attr('href').replace('user?id=', '');
$("body").append("<div id='sidebar-anchor'></div>");
React.render(React.createElement(SidebarBox, null), $("#sidebar-anchor").get(0));
});
// Sidebar component
var SidebarBox = React.createClass({
displayName: 'SidebarBox',
closeDrawer: function(){
this.setState({drawerIsClosed: !this.state.drawerIsClosed});
},
isDrawerClosed: function(){
var self=this;
chrome.storage.local.get("sidebarClosed", function (result) {
console.log('sidebar:',result);
var answer = result.sidebarClosed
console.log("isdrawerclosed, ", answer)
if (!answer) chrome.storage.local.set({sidebarClosed: false})
else self.setState({drawerIsClosed: answer})
})
},
// Attaches sidebar to the DOM and causes it to slide in
componentDidMount: function () {
this.isDrawerClosed();
if (!this.state.drawerIsClosed) {
setTimeout(function () {
$(".sidebarbox").css({
right: 0
});
$("#sidebarcontentarea")
}, 500)
}
},
getInitialState: function () {
return {
target: "Newsfeed",
userData: null,
drawerIsClosed: false
}
},
changeState: function (targetName) {
this.setState({target: targetName})
},
passBookmarkProps: function (data) {
this.setState({userData: data})
},
render: function () {
var self = this;
return (
React.createElement("div", {className: "sidebarbox"},
React.createElement("div", {className: "sidebarbutton"},
React.createElement(CloseButton, {closed: this.state.drawerIsClosed, toggleSidebar: this.closeDrawer})
),
React.createElement("div", {className: "sidebarcontentarea container container-fluid"},
React.createElement("nav", {id: "navheight-top"},
React.createElement("div", {className: "row top-nav nav-wrapper", id: "topnav"},
React.createElement(OwnerInfo, null)
)
),
React.createElement("nav", {id: "navheight-bottom"},
React.createElement(NavBar, {changeState: this.changeState, initialState: this.getInitialState})
),
React.createElement("div", {id: "feed-holder", className: this.state.target},
React.createElement(ContentHolder, {passBookmarkProps: this.passBookmarkProps, userData: this.state.data})
)
)
)
);
}
});
// Close button component
// --> ISSUE: All these jQuery queries should be stored as variables, so we only need to access them once.
// also: we should use React, not jQuery, for this
var CloseButton = React.createClass({displayName: "CloseButton",
// Functionality: Button causes sidebar to slide closed if it is open, open if it is closed.
closeBox: function () {
var self=this;
console.log("closed?", self.props.closed)
if (!self.props.closed) {
self.props.toggleSidebar();
chrome.storage.local.set({sidebarClosed: false})
setTimeout(function () {
$(".sidebarbox").css({
"right": "-470"
});
// Icon changes depending if sidebar is open or closed; shadow goes away if closed
$("#sidebutton").attr("src", "https://s3.amazonaws.com/gdcreative-general/HNselectlogotab_orange.png")
$("#sidebutton").css("-webkit-filter", "none");
$("#sidebarcontentarea").css("box-shadow", "none");
}, 0);
}
else {
setTimeout(function () {
self.props.toggleSidebar();
chrome.storage.local.set({sidebarClosed: true})
$(".sidebarbox").css({
right: 0
});
// Icon changes depending if sidebar is open or closed; shadow goes away if closed
$("#sidebutton").attr("src", "https://s3.amazonaws.com/gdcreative-general/HNselectXtab_orange.png");
$("#sidebutton").css("-webkit-filter", "drop-shadow(-2px 0px 2px rgba(70,40,10,0.6))");
$("#sidebarcontentarea").css("box-shadow", "-2px 0px 3px #C0C0C0");
}, 0);
}
},
// Renders the actual button
render: function () {
return React.createElement("img", {src: "https://s3.amazonaws.com/gdcreative-general/HNselectXtab_orange.png", id: "sidebutton", width: "30px", onClick: this.closeBox});
}
});
//End basic Sidebar functionality
//==========================================================
//Header
var OwnerInfo = React.createClass({displayName: "OwnerInfo",
render: function () {
return (
React.createElement("div", null,
React.createElement("div", {id: "owner-box", className: "col s6"},
React.createElement("div", {id: "owner-name"},
React.createElement("h2", {id: "nav-title"},
React.createElement("img", {src: "https://s3.amazonaws.com/gdcreative-general/HNselectlogo_white.png", height: "12px", id: "rvs_logo"}), username)
)
),
React.createElement("div", {id: "owner-stats", className: "col s6"},
React.createElement("div", {className: "col s4 owner-stat"},
React.createElement("div", {className: "owner-stattitle"}, "karma"),
React.createElement("div", {className: "owner-statscore"}, "1")
),
React.createElement("div", {className: "col s4 owner-stat"},
React.createElement("div", {className: "owner-stattitle"}, "following"),
React.createElement("div", {className: "owner-statscore"}, "15")
),
React.createElement("div", {className: "col s4 owner-stat"},
React.createElement("div", {className: "owner-stattitle"}, "followers"),
React.createElement("div", {className: "owner-statscore"}, "1")
)
)
)
)
}
});
var NavBar = React.createClass({displayName: "NavBar",
getInitialState: function () {
return {active: "NewsfeedActive"}
},
componentDidMount: function () {
var self = this;
//var newsfeed = "This right cheer is some newsfeed thingy";
self.props.initialState(newsfeed)
},
setTarget: function (target) {
this.props.changeState(target);
//console.log("Target received by navbar: ", target);
},
render: function () {
var self = this;
var changeParentState = function (target) {
self.props.changeState(target)
self.setState({active: target + "Active"})
};
return (
React.createElement("div", {id: "navbar-bar"},
React.createElement("div", {id: "navbar-buttons", className: "row"},
React.createElement("ul", {id: this.state.active},
React.createElement("li", {className: "col s2 navbar-button waves-effect waves-light", id: "nf"},
React.createElement(NavButton, {changeParentState: changeParentState, buttonName: "newsfeed", buttonTarget: "Newsfeed"})
),
React.createElement("li", {className: "col s2 navbar-button waves-effect waves-light", id: "co"},
React.createElement(NavButton, {changeParentState: changeParentState, buttonName: "connections", buttonTarget: "Connections"})
),
React.createElement("li", {className: "col s2 navbar-button waves-effect waves-light", id: "bm"},
React.createElement(NavButton, {changeParentState: changeParentState, buttonName: "bookmarks", buttonTarget: "Bookmarks"})
),
React.createElement("li", {className: "col s2", id: "disablehover"},
React.createElement("div", null, " ")
),
React.createElement("li", {className: "col s2", id: "disablehover"},
React.createElement("div", null, " ")
),
React.createElement("li", {className: "col s2 navbar-button waves-effect waves-light"},
React.createElement("div", {id: "twitter"},
React.createElement("a", {href: "http://www.hn-select.herokuapp.com/user/" + username + "/twitter/connect"},
React.createElement("img", {src: "https://s3.amazonaws.com/gdcreative-general/twitter_white_circle_48.png", height: "14px"})
)
)
)
)
)
)
);
}
});
var NavButton = React.createClass({displayName: "NavButton",
handleClick: function () {
var self = this;
self.props.changeParentState(self.props.buttonTarget);
},
render: function () {
return (
React.createElement("div", {id: this.props.buttonName, onClick: this.handleClick}, this.props.buttonName)
)
}
})
// End header
//=====================================================================
// Main content area
var ContentHolder = React.createClass({displayName: "ContentHolder",
passBookmarkProps: function () {
return null;
},
render: function () {
return (
React.createElement("div", {id: "visible"},
React.createElement("div", {className: "absposition", id: "news"},
React.createElement(Newsfeed, null)
),
React.createElement("div", {className: "absposition", id: "conn"},
React.createElement(Connections, {passBookmarkProps: this.passBookmarkProps})
),
React.createElement("div", {className: "absposition", id: "noti"},
React.createElement(Bookmarks, {data: this.props.userData})
)
)
)
}
})
var timeToNow = function (timestamp) {
var now = Date()
//console.log(now)
var since = now - timestamp
if (since < 3600000) return Math.floor(since / 60000) + " minutes ago";
else return Math.floor(since / 360000) + "hours ago";
}
var Newsfeed = React.createClass({displayName: "Newsfeed",
getInitialState: function () {
return {
data: null,
tempNewsfeed: [],
hideOrShow: "hide"
}
},
initialArticleLoad: function () {
var self = this;
if (!initialLoadHasTakenPlace) {
chrome.runtime.sendMessage({
method: 'GET',
action: 'ajax',
url: server + '/user/' + username + '/newsfeed',
data: ''
}, function (response) {
if (response && response !== 'Not Found') {
newsfeed = response.newsfeed;
lastItemFromDB = response.lastItem;
following = response.following;
//console.log(lastItemFromDB);
self.setState({data: newsfeed});
} else {
self.setState({data: null});
}
})
initialLoadHasTakenPlace = true;
}
},
articleUpdate: function () {
var self = this;
maxItemFb.on('value', function (snapshot) {
setTimeout(function () {
var maxItem = snapshot.val();
if (!lastItemFetched)
lastItemFetched = lastItemFromDB;
console.log(lastItemFetched, maxItem);
var nextItem = lastItemFetched + 1;
if (maxItem > nextItem) {
self.newItemsToFetch(nextItem, maxItem);
}
}, 10000);
})
},
newItemsToFetch: function (start, end) {
var self = this,
newNewsfeedItems = [],
promiseArray = []
for (var i = start; i <= end; i++) { // 9311348
var itemUrl = 'https://hacker-news.firebaseio.com/v0/item/' + i + '.json';
promiseArray.push(
$.get(itemUrl)
.then(function (newNewsfeedItem) {
if (newNewsfeedItem) { // following.indexOf(newNewsfeedItem.by) > -1
if (newNewsfeedItem.type === "comment") {
return fetchParent(newNewsfeedItem.parent);
function fetchParent(parentId) {
var itemUrl = 'https://hacker-news.firebaseio.com/v0/item/' + parentId + '.json';
return $.get(itemUrl)
.then(function (response) {
if (response.type === "story") {
newNewsfeedItem.storytitle = response.title;
newNewsfeedItem.storyurl = response.url;
newNewsfeedItem.storyby = response.by;
newNewsfeedItem.storyid = response.id;
newsfeed = [newNewsfeedItem].concat(newsfeed);
self.setState({tempNewsfeed: newsfeed});
} else {
return fetchParent(response.parent);
}
}, function (err) {
console.log("here is the error: ", err);
return;
});
}
} else if (newNewsfeedItem.type === "story") {
newsfeed = [newNewsfeedItem].concat(newsfeed)
self.setState({tempNewsfeed: newsfeed});
}
}
}, function (err) {
console.log("here is another error: ", err);
return;
})
);
}
$.when.apply($, promiseArray)
.done(function () {
console.log(i, ' all updated > refresh');
self.setState({hideOrShow: "show"});
});
},
updateNewsfeed: function () {
var self = this
self.setState({
data: this.state.tempNewsfeed,
hideOrShow: "hide"
});
},
componentDidMount: function () {
this.initialArticleLoad();
this.articleUpdate();
},
render: function () {
if (this.state.data) {
return (
React.createElement("div", null,
React.createElement("div", {id: "feedbuttondiv", className: this.state.hideOrShow, onClick: this.updateNewsfeed},
React.createElement("a", {className: "waves-effect waves-ripple btn", id: "feedbutton", href: "#"},
React.createElement("p", {id: "feedbuttontext"}, "↑New Items")
)
),
React.createElement("div", null,
this.state.data.map(function (item) {
if (item.type === "story") {
return React.createElement(StoryItem, {data: item})
} else if (item.type === "comment") {
//console.log(item.text)
return React.createElement(CommentItem, {data: item})
}
})
)
)
)
} else {
return React.createElement("h6", {className: "feed-title"}, "Could not retrieve data from server. Chrome extension might not have fully loaded yet. Please try reloading the page");
}
}
});
var StoryItem = React.createClass({displayName: "StoryItem",
render: function () {
return (
React.createElement("div", {className: "feed-box"},
React.createElement("div", {className: "feed-titlebox"},
React.createElement("div", {className: "feed-title truncate"},
React.createElement("a", {href: this.props.data.storyurl, target: "_blank"},
this.props.data.storytitle
)
),
React.createElement("div", {className: "feed-context"},
"by ",
React.createElement("a", {className: "feed-author", href: hnUrl + '/user?id=' + this.props.data.by}, this.props.data.by, " | "), " ", this.props.data.time, " |",
React.createElement("a", {href: hnUrl + '/item?id=' + this.props.data.storyid}, " all comments")
)
),
React.createElement("div", {className: "feed-content"},
React.createElement("p", {className: "feed-text"}, this.props.data.text)
)
)
)
}
});
var CommentItem = React.createClass({displayName: "CommentItem",
render: function () {
return (
React.createElement("div", {className: "feed-box"},
React.createElement("div", {className: "feed-titlebox"},
React.createElement("div", {className: "feed-title"},
React.createElement("a", {href: this.props.data.storyurl, target: "_blank"},
this.props.data.storytitle
)
),
React.createElement("div", {className: "feed-context"},
"by ",
React.createElement("a", {href: hnUrl + '/user?id=' + this.props.data.storyby, id: "feedlink"}, this.props.data.storyby, " | "), " ", this.props.data.time, " |",
React.createElement("a", {href: hnUrl + '/item?id=' + this.props.data.storyid}, " all comments")
)
),
React.createElement("div", {className: "feed-content"},
React.createElement("a", {className: "feed-author", href: hnUrl + '/item?id=' + this.props.data.id}, this.props.data.by + '\'s comment: '),
React.createElement("span", {className: "feed-text", dangerouslySetInnerHTML: {__html: this.props.data.text}})
)
)
)
}
});
var userData,
followingArr = [];
var Connections = React.createClass({displayName: "Connections",
getInitialState: function () {
return {
data: null,
value: "",
errorMessage: "",
remove: null,
editEnabled: false,
connHead: "Users you follow:",
editOrDelete: "Edit",
selectedToRemove: "unselected",
usersToDelete: []
}
},
passUserData: function (data) {
this.props.passBookmarkProps(data)
},
getUserData: function (server, username) {
var self = this;
//console.log("Getting called")
chrome.runtime.sendMessage({
method: 'GET',
action: 'ajax',
url: server + '/user/' + username + '/userdata',
data: ''
}, function (response) {
//console.log(response)
if (response && response !== 'Not Found') {
userData = response;
self.setState({data: userData});
self.passUserData(self.state.data);
//console.log(userData);
} else {
self.setState({data: null});
}
})
},
componentDidMount: function () {
this.getUserData(server, username);
},
searchFocus: function () {
$("#searchFollow").focus();
},
showUsers: function () {
var self = this;
//console.log("Show users, ", this.state)
// Are we allowed to build an if/else statement in here, i.e. returning different html components?
if (self.state.data === null) {
return (
React.createElement("span", null, "It looks like you're not following anyone. Would you care to",
React.createElement("a", {href: "#", onClick: self.searchFocus()}, " add a user to follow now?")
)
)
} else {
//console.log("There is indeed data: ", this.state.data.following)
return (
React.createElement("ul", null,
this.state.data.following.map(function (user) {
return React.createElement("li", {ref: user, id: user, onClick: self.userRemover(user)}, user);
})
)
)
}
},
showFollowers: function () {
var self = this;
if (self.state.data !== null && self.state.data.followers.length) {
//console.log("There is indeed data: ", this.state.data.following)
return (
React.createElement("ul", null,
this.state.data.followers.map(function (user) {
return React.createElement("li", {ref: user, id: user, onClick: self.userRemover(user)}, user);
})
)
)
}
},
showSuggestedFollowers: function () {
var self = this;
if (self.state.data !== null && self.state.data.suggestedFollowing.length) {
//console.log("There is indeed data: ", this.state.data.following)
return (
React.createElement("ul", null,
this.state.data.suggestedFollowing.map(function (user) {
return React.createElement("li", {ref: user, id: user, onClick: self.userRemover(user)}, user);
})
)
)
}
},
enableEdit: function () {
var self = this;
if (!self.state.editEnabled) {
self = this;
self.setState({
editOrDelete: "Unfollow",
connHead: "Select which users you want to stop following.",
editEnabled: true
});
} else {
self.deleteUsers(this.state.usersToDelete);
self.setState({
editEnabled: false,
editOrDelete: "Edit"
});
}
},
userRemover: function (user) {
var self = this;
return function clickHandler() {
//console.log('!! Clicked the button');
if (self.state.editEnabled) {
var me = self.refs[user].props.children;
console.log(me);
$("#" + me).attr('class', 'toBeDeleted');
self.state.usersToDelete.push(me);
console.log(self.state.usersToDelete);
self.setState.usersToDelete = self.state.usersToDelete;
}
}
},
deleteUsers: function (arr) {
var self = this;
$('.toBeDeleted').remove();
chrome.runtime.sendMessage({
method: 'DELETE',
action: 'ajax',
url: server + '/user/' + username + '/unfollowuser',
data: arr
}, function (response) {
console.log("Response: ", response)
});
},
handleChange: function (event) {
this.setState({value: event.target.value});
},
followInputUser: function () {
var self = this,
followUser = self.state.value;
if (self.state.data.following.indexOf(followUser) !== -1) {
// Find out if the user already exists in their following; if so, give them a message
self.setState({errorMessage: "It appears you are already following this user. Would you like to try again?"})
} else {
chrome.runtime.sendMessage({
method: 'GET',
action: 'ajax',
url: 'https://hacker-news.firebaseio.com/v0' + '/user/' + followUser + '.json?print=pretty',
data: ''
}, function (response) {
if (response !== null) {
chrome.runtime.sendMessage({
method: 'POST',
action: 'ajax',
url: server + '/user/' + username + '/followuser/' + followUser,
}, function (response) {
console.log("Response: ", response);
if (response == "User added") {
self.state.data.following.push(followUser)
self.setState({data: self.state.data});
} else {
self.setState({errorMessage: "There appears to be a server error. Would you like to try again?"});
}
});
} else {
self.setState({errorMessage: "It appears this user either doesn't exist or has never posted on Hacker News. Would you like to try again?"});
}
})
}
this.setState({value: ''});
},
render: function () {
var value = this.state.value;
//console.log('VALUE', value);
return (
React.createElement("div", null,
React.createElement("div", {className: "row"},
React.createElement("form", {className: "col s12", id: "inputForm"},
React.createElement("div", {className: "row"},
React.createElement("div", {className: "input-field col s12"},
React.createElement("label", {htmlFor: "searchFollow"}, "Follow a Hacker News user"),
React.createElement("input", {id: "searchFollow", value: value, onChange: this.handleChange, type: "text", className: "validate"}),
React.createElement("button", {id: "ourbutton", className: "btn btn-default", type: "button", onClick: this.followInputUser}, "Follow")
)
)
)
),
React.createElement("div", null,
React.createElement("h3", {id: "following-title"}, this.state.connHead,
React.createElement("a", {href: "#", id: "connedit", onClick: this.enableEdit}, this.state.editOrDelete)
),
React.createElement("div", {className: "suggest-tags"},
this.showUsers()
)
),
React.createElement("div", null,
React.createElement("h3", {id: "suggested-following-title"}, "Suggested Followers including your Twitter connections",
React.createElement("a", {href: "#", id: "connedit", onClick: this.enableEdit}, this.state.editOrDelete)
),
React.createElement("div", {className: "suggest-tags"},
this.showSuggestedFollowers()
)
),
React.createElement("div", null,
React.createElement("h3", {id: "followers-title"}, "Users that follow you",
React.createElement("a", {href: "#", id: "connedit", onClick: this.enableEdit}, this.state.editOrDelete)
),
React.createElement("div", {className: "suggest-tags"},
this.showFollowers()
)
)
/*<div>
<h4 className="connectionhead">Users who follow you:</h4>
<div className="suggest-tags">
<ul>
<li>userName</li>
</ul>
</div>
</div>*/
)
)
}
});
// Get userdata.bookmarks
var bookmarkData;
var Bookmarks = React.createClass({displayName: "Bookmarks",
getInitialState: function () {
return {
data: null
}
},
getBookmarks: function (server, username) {
var self = this;
//console.log("Getting called")
chrome.runtime.sendMessage({
method: 'GET',
action: 'ajax',
url: server + '/user/' + username + '/bookmarks',
data: ''
}, function (response) {
//console.log(response)
if (response && response !== 'Not Found') {
console.log("Bookmarks response, ", response)
bookmarkData = response;
self.setState({data: bookmarkData});
} else {
self.setState({data: null});
}
})
},
componentDidMount: function(){
this.getBookmarks(server, username)
},
render: function () {
var self=this;
//console.log("Bookmarks: ", this.state.data)
if (self.state.data) {
return (
React.createElement("div", null,
self.state.data.map(function (item) {
if (item.type === "story") {
return React.createElement(StoryItem, {data: item})
} else if (item.type === "comment") {
//console.log(item.text)
return React.createElement(CommentItem, {data: item})
}
})
)
)
}
else return React.createElement("div", null, "You don't have any bookmarks!")
}
})
},{}]},{},[1]);
| 39.528338 | 480 | 0.516392 |
b9ad8e9c6c57d733d01ff8c0b69cfc7121f7c134 | 8,546 | js | JavaScript | src/router/index.js | lai123456789/TiaoLing_Yuncang_admin | dc067201e8c3c987550a02bb40dccc7d8b61d6ed | [
"MIT"
] | null | null | null | src/router/index.js | lai123456789/TiaoLing_Yuncang_admin | dc067201e8c3c987550a02bb40dccc7d8b61d6ed | [
"MIT"
] | null | null | null | src/router/index.js | lai123456789/TiaoLing_Yuncang_admin | dc067201e8c3c987550a02bb40dccc7d8b61d6ed | [
"MIT"
] | null | null | null | import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
/* Layout */
import Layout from '@/layout'
/**
* Note: sub-menu only appear when route children.length >= 1
* Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
*
* hidden: true if set true, item will not show in the sidebar(default is false)
* alwaysShow: true if set true, will always show the root menu
* if not set alwaysShow, when item has more than one children route,
* it will becomes nested mode, otherwise not show the root menu
* redirect: noRedirect if set noRedirect will no redirect in the breadcrumb
* name:'router-name' the name is used by <keep-alive> (must set!!!)
* meta : {
roles: ['admin','editor'] control the page roles (you can set multiple roles)
title: 'title' the name show in sidebar and breadcrumb (recommend set)
icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
breadcrumb: false if set false, the item will hidden in breadcrumb(default is true)
activeMenu: '/example/list' if set path, the sidebar will highlight the path you set
}
*/
/**
* constantRoutes
* a base page that does not have permission requirements
* all roles can be accessed
*/
export const constantRoutes = [
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: '系统首页', icon: 'dashboard' }
}]
},
{
path: '/fictitious',
component: Layout,
redirect: '/fictitious/table',
name: 'fictitious',
meta: { title: '虚拟仓', icon: 'el-icon-s-help' },
children: [
{
path: 'Pending',
name: 'Pending',
component: () => import('../views/fictitious/Pending/pengding.vue'),
meta: { title: '待处理订单', icon: 'el-icon-document' }
},
{
path: 'complete',
name: 'complete',
component: () => import('../views/fictitious/complete/complete.vue'),
meta: { title: '已完成订单', icon: 'el-icon-tickets' }
},
]
},
{
path: '/returning',
component: Layout,
redirect: '/returning/table',
name: 'returning',
meta: { title: '退件仓', icon: 'el-icon-edit-outline' },
children: [
{
path: 'ReturnStock',
name: 'ReturnStock',
component: () => import('../views/return/ReturnStock.vue'),
meta: { title: '退件库存管理', icon: 'el-icon-shopping-bag-1' }
},
{
path: 'ShelfHistory',
name: 'ShelfHistory',
component: () => import('../views/return/ShelfHistory.vue'),
meta: { title: '上架历史', icon: 'el-icon-shopping-bag-2' }
},
{
path: 'Tobeshipped',
name: 'Tobeshipped',
component: () => import('../views/return/Tobeshipped.vue'),
meta: { title: '待二次出货', icon: 'el-icon-document' }
},
{
path: 'Shipped',
name: 'Shipped',
component: () => import('../views/return/Shipped.vue'),
meta: { title: '已二次出货', icon: 'el-icon-tickets' }
},
{
path: 'Tobedestroyed',
name: 'Tobedestroyed',
component: () => import('../views/return/Tobedestroyed.vue'),
meta: { title: '待销毁', icon: 'el-icon-delete' }
},
{
path: 'destroyed',
name: 'destroyed',
component: () => import('../views/return/destroyed.vue'),
meta: { title: '已销毁', icon: 'el-icon-delete-solid' }
},
]
},
{
path: '/HistoricalOrders',
component: Layout,
children: [
{
path: 'HistoricalOrders',
name: 'HistoricalOrders',
component: () => import('../views/HistoricalOrders/index.vue'),
meta: { title: '历史订单', icon: 'form' }
}
]
},
{
path: '/ResetRecord',
component: Layout,
children: [
{
path: 'ResetRecord',
name: 'ResetRecord',
component: () => import('../views/ResetRecord/index.vue'),
meta: { title: '充值记录', icon: 'el-icon-notebook-2' }
}
]
},
// 404 page must be placed at the end !!!
{ path: '*', redirect: '/404', hidden: true },
{
path: '/invite',
component: Layout,
redirect: '/invite/table',
name: 'invite',
meta: { title: '邀请返现', icon: 'el-icon-office-building' },
children: [
{
path: 'ReturnStock',
name: 'ReturnStock',
component: () => import('../views/invite/index.vue'),
meta: { title: '开通返现功能', icon: 'el-icon-document' }
},
{
path: 'Tobereviewed',
name: 'Tobereviewed',
component: () => import('../views/invite/Tobereviewed.vue'),
meta: { title: '待审核返现', icon: 'el-icon-tickets' }
},
{
path: 'returned',
name: 'returned',
component: () => import('../views/invite/returned.vue'),
meta: { title: '已返现订单', icon: 'el-icon-document-remove' }
},
{
path: 'RechargeCommission',
name: 'RechargeCommission',
component: () => import('../views/invite/RechargeCommission.vue'),
meta: { title: '充值分佣', icon: 'el-icon-collection' }
},
{
path: 'proportion',
name: 'proportion',
component: () => import('../views/invite/proportion.vue'),
meta: { title: '分佣比例', icon: 'el-icon-document-copy' }
},
]
},
{
path: '/personCenter',
component: Layout,
children: [
{
path: 'index',
name: 'personCenter',
component: () => import('@/views/personCenter/index'),
// meta: { title: '个人中心', icon: 'form' }
}
]
},
{
path: '/announcements',
component: Layout,
children: [
{
path: 'index',
name: 'announcements',
component: () => import('../views/announcements.vue'),
meta: { title: '公告管理', icon: 'el-icon-document' }
}
]
},
{
path: '/attachment',
component: Layout,
redirect: '/attachment/table',
name: 'attachment',
meta: { title: '附件管理', icon: 'el-icon-document-checked' },
children: [
{
path: 'useJiaocheng',
name: 'useJiaocheng',
component: () => import('../views/attachment/useJiaocheng.vue'),
meta: { title: '使用教程', icon: 'el-icon-s-flag' }
},
{
path: 'changjianProblem',
name: 'changjianProblem',
component: () => import('../views/attachment/changjianProblem.vue'),
meta: { title: '常见问题', icon: 'el-icon-question' }
},
{
path: 'fujianDowload',
name: 'fujianDowload',
component: () => import('../views/attachment/fujianDowload.vue'),
meta: { title: '附件下载', icon: 'el-icon-download' }
},
{
path: 'feiyongPrice',
name: 'feiyongPrice',
component: () => import('../views/attachment/feiyongPrice.vue'),
meta: { title: '物流费用报价', icon: 'el-icon-price-tag' }
},
]
},
{
path: '/usermanage',
component: Layout,
redirect: '/usermanage/table',
name: 'usermanage',
meta: { title: '用户管理', icon: 'el-icon-user' },
children: [
{
path: 'userInfo',
name: 'userInfo',
component: () => import('../views/usermanage/userInfo.vue'),
meta: { title: '用户信息', icon: 'el-icon-view' }
},
{
path: 'payTicket',
name: 'payTicket',
component: () => import('../views/usermanage/payTicket.vue'),
meta: { title: '支付流水', icon: 'el-icon-tickets' }
},
{
path: 'shouquanShop',
name: 'shouquanShop',
component: () => import('../views/usermanage/shouquanShop.vue'),
meta: { title: '授权店铺', icon: 'el-icon-office-building' }
},
]
},
]
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRoutes
})
const router = createRouter()
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router
| 29.267123 | 103 | 0.542476 |
b9ae168ab4b19ca775f01d3a614741016fb84e35 | 6,111 | js | JavaScript | packages/db/lib/resources/TheLogResource.js | takuto-y/the | b4116241727634fff60b9e93519d12f64d62c80d | [
"MIT"
] | 8 | 2019-03-17T12:52:00.000Z | 2022-01-14T17:29:44.000Z | packages/db/lib/resources/TheLogResource.js | takuto-y/the | b4116241727634fff60b9e93519d12f64d62c80d | [
"MIT"
] | 46 | 2019-05-15T08:51:35.000Z | 2022-03-08T22:40:28.000Z | packages/db/lib/resources/TheLogResource.js | takuto-y/the | b4116241727634fff60b9e93519d12f64d62c80d | [
"MIT"
] | 4 | 2019-05-20T09:00:31.000Z | 2021-01-18T05:42:57.000Z | 'use strict'
const {
ResourceEvents: {
ENTITY_CREATE,
ENTITY_CREATE_BULK,
ENTITY_DESTROY,
ENTITY_DESTROY_BULK,
ENTITY_UPDATE,
ENTITY_UPDATE_BULK,
},
} = require('clay-constants')
const cluster = require('cluster')
const mkdirp = require('mkdirp')
const { EOL } = require('os')
const path = require('path')
const rfs = require('rotating-file-stream')
const logStreamFor = (filename) => {
const basename = path.basename(filename)
return rfs.createStream(
(time, index) => {
if (!time) {
return basename
}
const pad = (v) => String(v).padStart(2, '0')
const yearAndMonth = `${time.getFullYear()}${pad(time.getMonth() + 1)}`
const day = pad(time.getDate())
const hour = pad(time.getHours())
const minute = pad(time.getMinutes())
return `${yearAndMonth}/${yearAndMonth}${day}-${hour}${minute}-${basename}-${index}.gzip`
},
{
compress: 'gzip',
interval: '1d',
path: path.dirname(filename),
size: '10MB',
},
)
}
/**
* Resource of data history
* @memberof module:@the-/db
* @class TheLogResource
*/
const TheLogResource = ({ define }) => {
const Log = define({})
Log.data = {}
Log.logListeners = {}
Log.flushLoop = true
const flushTick = () =>
setTimeout(async () => {
try {
await Log.flushData()
} catch (e) {
console.warn('[the-db]Failed to flush log data', e)
}
if (Log.flushLoop) {
Log.flushTimer = flushTick()
}
}, 500).unref()
if (cluster.isMaster) {
Log.flushTimer = flushTick()
}
const { addRef, close, removeRef } = Log
Object.assign(Log, {
addRef(resourceName, resource) {
addRef.call(Log, resourceName, resource)
const isMetaSchema = /^TheDB/.test(resourceName)
if (!isMetaSchema) {
Log.startListeningFor(resourceName)
}
},
prepare({ filename }) {
Log.filename = filename
const stream = logStreamFor(filename)
stream.on('error', (err) => {
console.warn(`[@the-/db]Failed to flush log for "${filename}"`, err)
})
Log.stream = stream
process.setMaxListeners(process.getMaxListeners() + 1)
process.on('beforeExit', () => {
stream.end()
})
},
pushLog(resourceName, entityId, attributes) {
Log.data[resourceName] = Log.data[resourceName] || {}
Log.data[resourceName][String(entityId)] = Object.assign(
Log.data[resourceName][String(entityId)] || {},
attributes,
)
// Flush Logs if needed
{
const WATERMARK = 100
const { length: counts } = Object.keys(Log.data[resourceName])
const needsFlush = WATERMARK <= counts && counts % WATERMARK === 0
if (needsFlush) {
void Log.flushData()
}
}
},
removeRef(resourceName) {
removeRef.call(Log, resourceName)
Log.stopListeningFor(resourceName)
},
startListeningFor(resourceName) {
const resource = Log.getRef(resourceName)
const logListeners = {
[ENTITY_CREATE]: ({ created }) =>
Log.pushLog(resourceName, created.id, {
createdAt: new Date(),
}),
[ENTITY_CREATE_BULK]: ({ created }) =>
created.map((created) =>
Log.pushLog(resourceName, created.id, {
createdAt: new Date(),
}),
),
[ENTITY_DESTROY]: ({ id }) =>
Log.pushLog(resourceName, id, { destroyedAt: new Date() }),
[ENTITY_DESTROY_BULK]: ({ ids }) =>
ids.map((id) =>
Log.pushLog(resourceName, id, { destroyedAt: new Date() }),
),
[ENTITY_UPDATE]: ({ id }) =>
Log.pushLog(resourceName, id, { updatedAt: new Date() }),
[ENTITY_UPDATE_BULK]: ({ ids }) =>
ids.map((id) =>
Log.pushLog(resourceName, id, { updatedAt: new Date() }),
),
}
Log.logListeners[resourceName] = logListeners
for (const [event, listener] of Object.entries(logListeners)) {
resource.addListener(event, listener)
resource.setMaxListeners(resource.getMaxListeners() + 1)
}
},
stopListeningFor(resourceName) {
const resource = Log.getRef(resourceName)
const logListeners = Log.logListeners[resourceName]
for (const [event, listener] of Object.entries(logListeners)) {
resource.removeListener(event, listener)
resource.setMaxListeners(resource.getMaxListeners() - 1)
}
delete Log.logListeners[resourceName]
},
async close() {
Log.flushLoop = false
clearTimeout(Log.flushTimer)
if (cluster.isMaster) {
await Log.flushData().catch(() => null)
}
for (const resourceName of Object.keys(Log.logListeners)) {
Log.stopListeningFor(resourceName)
}
close.call(Log, ...arguments)
},
async flushData() {
const { stream } = Log
const { theDBResourceLogEnabled } = Log.db || {}
if (!theDBResourceLogEnabled) {
return
}
const { dialect } = (Log.db && Log.db.env) || {}
if (String(dialect).trim() === 'memory') {
return
}
if (Log._flushTask) {
await Log._flushTask
}
Log._flushTask = (async () => {
await mkdirp(path.dirname(Log.filename))
for (const resourceName of Object.keys(Log.data)) {
const entries = Object.entries(Log.data[resourceName])
Log.data[resourceName] = {}
if (entries.length === 0) {
continue
}
const lines = entries
.map(([entityId, attributes]) =>
[
`${resourceName}#${entityId}`,
Object.entries(attributes)
.map(([k, v]) => [k, JSON.stringify(v)].join('='))
.join(','),
].join(' '),
)
.join(EOL)
stream.write(lines + EOL)
}
Log._flushTask = null
})()
await Log._flushTask
},
})
return Log
}
module.exports = TheLogResource
| 28.291667 | 95 | 0.560956 |
b9ae432c23fa7ff2e54c1ab2a2608ce7a77871a4 | 318 | js | JavaScript | src/buyBeer/index.js | aar9nk/genxi-jwd-testing | aeb4d1b90e3af660e42b93cd5f0a9d523e89bbde | [
"MIT"
] | null | null | null | src/buyBeer/index.js | aar9nk/genxi-jwd-testing | aeb4d1b90e3af660e42b93cd5f0a9d523e89bbde | [
"MIT"
] | 1 | 2021-02-17T02:19:39.000Z | 2021-02-17T02:19:39.000Z | src/buyBeer/index.js | aar9nk/genxi-jwd-testing | aeb4d1b90e3af660e42b93cd5f0a9d523e89bbde | [
"MIT"
] | 28 | 2021-02-15T22:27:57.000Z | 2021-02-17T05:34:18.000Z | const canBuyBeer = (age) => {
if (age > 17) {
return true;
} else {
return false;
}
};
const greg = new Person();
const canGregBuyBeer = () => {
if (canBuyBeer(greg.age)) {
return `Greg is ${greg.age}, he can buy beer!`;
} else {
return `Greg is ${greg.age}, he can not buy beer :(`;
}
}; | 18.705882 | 57 | 0.550314 |
b9af63daa6d6da0cb006b563b452a53d3d25982a | 169 | js | JavaScript | src/scripts/sams/js/student-profile.js | IronCountySchoolDistrict/sams | d23f963137dab4e1d865eefd8a8e5ae5c1ee83ef | [
"Apache-2.0"
] | null | null | null | src/scripts/sams/js/student-profile.js | IronCountySchoolDistrict/sams | d23f963137dab4e1d865eefd8a8e5ae5c1ee83ef | [
"Apache-2.0"
] | 5 | 2015-06-09T23:41:41.000Z | 2015-06-10T14:57:19.000Z | src/scripts/sams/js/student-profile.js | IronCountySchoolDistrict/sams | d23f963137dab4e1d865eefd8a8e5ae5c1ee83ef | [
"Apache-2.0"
] | null | null | null | /*global $j*/
(function() {
'use strict';
var template = $j($j('#template').html());
var select = $j('#std_information');
select.prepend(template);
}()); | 24.142857 | 46 | 0.56213 |
b9b0839458ab03e1951b7dc528d6bad56ed514a9 | 595 | js | JavaScript | frontend/src/style-guide/StyleGuidePage.js | spruce-bruce/daves.pics | 6a3769d92a26a7de781a9f784598ba16ef21e6e3 | [
"MIT"
] | null | null | null | frontend/src/style-guide/StyleGuidePage.js | spruce-bruce/daves.pics | 6a3769d92a26a7de781a9f784598ba16ef21e6e3 | [
"MIT"
] | null | null | null | frontend/src/style-guide/StyleGuidePage.js | spruce-bruce/daves.pics | 6a3769d92a26a7de781a9f784598ba16ef21e6e3 | [
"MIT"
] | null | null | null | import React from 'react';
import Typography from './sections/Typography';
import TextInputs from './sections/TextInputs';
import SelectInputs from './sections/SelectInputs';
import Checkboxes from './sections/Checkboxes';
import Radios from './sections/Radios';
import Buttons from './sections/Buttons';
import Modal from './sections/Modal';
function StyleGuide() {
return (
<div className="container">
<Typography />
<TextInputs />
<SelectInputs />
<Checkboxes />
<Radios />
<Buttons />
<Modal />
</div>
);
}
export default StyleGuide;
| 22.884615 | 51 | 0.667227 |
b9b1c51db96d51557bdd6af5f8218798ac59ec36 | 1,337 | js | JavaScript | test/adocker_nginx_test.js | a-labo/adocker-nginx | eaf7ade3d69d63b7b4752a0a1270d7f5a512122c | [
"MIT"
] | null | null | null | test/adocker_nginx_test.js | a-labo/adocker-nginx | eaf7ade3d69d63b7b4752a0a1270d7f5a512122c | [
"MIT"
] | null | null | null | test/adocker_nginx_test.js | a-labo/adocker-nginx | eaf7ade3d69d63b7b4752a0a1270d7f5a512122c | [
"MIT"
] | 1 | 2018-12-21T14:34:13.000Z | 2018-12-21T14:34:13.000Z | /**
* Test case for adockerNginx.
* Runs with mocha.
*/
'use strict'
const adockerNginx = require('../lib/adocker_nginx.js')
const {equal, ok} = require('assert')
const aport = require('aport')
const asleep = require('asleep')
const arequest = require('arequest')
describe('adocker-nginx', function () {
this.timeout(300000)
before(async () => {
})
after(async () => {
})
it('Adocker nginx', async () => {
let port = await aport()
let nginx = adockerNginx('adocker-nginx-test-01', {
template: `${__dirname}/../misc/mocks/nginx.conf.template`,
staticDir: `${__dirname}/../misc/mocks/mock-public`,
httpPublishPort: port,
localhostAs: '10.0.2.2'
})
let {run, remove, logs, stop, isRunning, hasContainer} = nginx.cli()
if (await isRunning()) {
await remove({force: true})
}
equal(await isRunning(), false)
equal(await hasContainer(), false)
await run()
equal(await isRunning(), true)
equal(await hasContainer(), true)
let {statusCode, body} = await arequest(`http://localhost:${port}/index.html`)
equal(statusCode, 200)
ok(body)
await asleep(100)
await stop()
equal(await isRunning(), false)
equal(await hasContainer(), true)
await remove({force: true})
})
})
/* global describe, before, after, it */
| 21.564516 | 82 | 0.623785 |
b9b36fd3dcab6e2a2feb75893e13f85edeb78eed | 702 | js | JavaScript | target/collapp/app/directives/lvg-match.js | devendarsai/CollApp | 74f22288043be85066d4d653267d987daa37b554 | [
"MIT"
] | null | null | null | target/collapp/app/directives/lvg-match.js | devendarsai/CollApp | 74f22288043be85066d4d653267d987daa37b554 | [
"MIT"
] | null | null | null | target/collapp/app/directives/lvg-match.js | devendarsai/CollApp | 74f22288043be85066d4d653267d987daa37b554 | [
"MIT"
] | null | null | null | (function () {
'use strict';
var directives = angular.module('collapp.directives');
directives.directive('lvgMatch', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
modelValueToMatch: '=lvgMatch'
},
link: function ($scope, $element, $attrs, ngModel) {
ngModel.$validators.lvgMatch = function (ngModelValue) {
return ngModelValue === $scope.modelValueToMatch;
};
$scope.$watch($scope.modelValueToMatch, function () {
ngModel.$validate();
});
}
};
});
}());
| 28.08 | 72 | 0.470085 |
b9b476911393844e9c63c1d14a8f4cd0780e124e | 880 | js | JavaScript | functionx.js | IoTOpen/node-lynx | ea68677991aeb0e85770e75cb165b9a3f0084aba | [
"Apache-2.0"
] | null | null | null | functionx.js | IoTOpen/node-lynx | ea68677991aeb0e85770e75cb165b9a3f0084aba | [
"Apache-2.0"
] | null | null | null | functionx.js | IoTOpen/node-lynx | ea68677991aeb0e85770e75cb165b9a3f0084aba | [
"Apache-2.0"
] | null | null | null | import querystring from "querystring";
import {Endpoints, request} from "./util";
export const GetFunctions = (installationId, filter) => {
let qs = filter ? '?' + querystring.stringify(filter) : '';
let url = Endpoints.FunctionX + '/' + installationId + qs;
return request(url, {});
};
export const GetFunction = (installationId, id) => request(Endpoints.FunctionX + '/' + installationId + '/' + id, {});
export const CreateFunction = (func) => request(Endpoints.FunctionX + '/' + func.installation_id, {
method: 'POST', body: JSON.stringify(func)
});
export const UpdateFunction = (func) => request(Endpoints.FunctionX + '/' + func.installation_id + '/' + func.id, {
method: 'PUT', body: JSON.stringify(func)
});
export const DeleteFunction = (func) => request(Endpoints.FunctionX + '/' + func.installation_id + '/' + func.id, {
method: 'DELETE'
}); | 40 | 118 | 0.660227 |
b9b4d527e1caa890f14111336b394347649d6cdc | 8,744 | js | JavaScript | public/app/controllers/purchase_orders_controller.js | elemento15/pharmax | d4701b3c6b47502d9b24f9264d477bff3b5128f1 | [
"MIT"
] | null | null | null | public/app/controllers/purchase_orders_controller.js | elemento15/pharmax | d4701b3c6b47502d9b24f9264d477bff3b5128f1 | [
"MIT"
] | null | null | null | public/app/controllers/purchase_orders_controller.js | elemento15/pharmax | d4701b3c6b47502d9b24f9264d477bff3b5128f1 | [
"MIT"
] | null | null | null | app.controller('PurchaseOrdersController', function ($scope, $http, $route, $location, $timeout, $ngConfirm, $uibModal, PurchaseOrderService, ProductService, VendorService, toastr) {
this.index = '/purchase-orders';
this.title = {
new: 'Nueva Orden de Compra',
edit: 'Orden de Compra: '
}
this.validation = function () {
var data = $scope.data;
var invalid = false;
if (! data.vendor) {
invalid = toastr.warning('Proveedor requerido', 'Validaciones');
} else {
data.vendor_id = data.vendor.id; // select2
}
return (invalid) ? false : data;
}
// model data
$scope.data = {
id: 0,
vendor_id: '',
status: 'N',
order_date: '',
subtotal: 0,
iva_amount: 0,
total: 0,
active: 1,
comments: '',
purchase_order_details: [],
vendor: null
};
$scope.filters = {
status: ''
}
$scope.product = {
id: 0,
code: '',
description: '',
quantity: '',
price: '',
subtotal: 0,
iva: 0
};
$scope.input_quantity = 0;
$scope.input_price = 0;
$scope.vendorsList = [];
$scope.getVendors = function () {
VendorService.read({
filters: [{ field: 'active', value: 1 }]
}).success(function (response) {
$scope.vendorsList = response;
}).error(function (response) {
toastr.error(response.msg || 'Error en el servidor');
});
}
$scope.searchCode = function (evt) {
var code;
if (evt.keyCode == 13) {
evt.preventDefault();
code = $scope.product.code;
if (code == '') {
$scope.focusDescription();
return false;
}
ProductService.search_code({
code: code
}).success(function (response) {
if (response.success) {
$scope.setProduct(response.product);
$scope.getProductPrice(response.product);
$scope.focusQuantity();
} else {
toastr.warning(response.msg);
$scope.clearProduct();
$('input[ng-model="product.code"]').focus().select();
}
}).error(function (response) {
toastr.error(response.msg || 'Error en el servidor');
});
}
}
$scope.searchDescription = function (evt) {
var description;
if (evt.keyCode == 13) {
evt.preventDefault();
description = $scope.product.description;
ProductService.search_description({
description: description
}).success(function (response) {
if (response.success) {
if (response.product) {
$scope.setProduct(response.product);
$scope.getProductPrice(response.product);
$scope.focusQuantity();
} else {
$scope.openSearch(description);
}
} else {
toastr.warning(response.msg);
$scope.clearProduct();
$('input[ng-model="product.code"]').focus().select();
}
}).error(function (response) {
toastr.error(response.msg || 'Error en el servidor');
});
}
}
$scope.setProduct = function (product) {
$scope.product = {
id: product.id,
code: product.code,
description: product.description,
quantity: 1,
price: 0,
subtotal: 0,
iva: product.iva
};
}
$scope.setFocus = function (evt, opt) {
if (evt.keyCode == 13) {
evt.preventDefault();
switch (opt) {
case 'price' : $('input[ng-model="product.price"]').focus().select();
break;
case 'add' : $('#btnAddProduct').focus();
break;
}
}
}
$scope.addProduct = function () {
var product = $scope.product;
var iva_amount = 0;
var total = 0;
if (! product.id) {
toastr.warning('Seleccione un producto válido');
$('input[ng-model="product.code"]').focus().select();
return false;
}
iva_amount = (product.iva / 100) * product.subtotal;
total = product.subtotal + iva_amount;
$scope.data.purchase_order_details.push({
product_id: product.id,
quantity: product.quantity,
price: product.price,
subtotal: product.subtotal,
iva: product.iva,
iva_amount: iva_amount,
total: total,
product: {
id: product.id,
code: product.code,
description: product.description
}
});
$scope.clearProduct();
$('input[ng-model="product.code"]').focus().select();
$scope.calculateTotal();
}
$scope.openSearch = function (search) {
var modal = $uibModal.open({
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: '/partials/templates/modalProducts.html',
controller: 'ModalProductsSearch',
controllerAs: '$ctrl',
resolve: {
items: function () {
return {
search: search || ''
};
}
}
});
modal.result.then(function (product) {
if (product) {
$scope.setProduct(product);
$scope.getProductPrice(product);
$scope.focusQuantity();
}
});
}
$scope.clearProduct = function () {
$scope.product = {
id: 0,
code: '',
description: '',
quantity: '',
price: '',
subtotal: 0,
iva: 0
};
}
$scope.deleteProduct = function (product, key) {
$scope.data.purchase_order_details[key]._deleted = true;
$scope.calculateTotal();
$scope.focusCode();
}
$scope.calculateDetailTotals = function () {
var product = $scope.product;
var subtotal = product.quantity * product.price;
var iva_amount = subtotal * product.iva;
$scope.product.subtotal = subtotal;
}
$scope.calculateTotal = function () {
var subtotal = 0;
var iva_amount = 0;
var total = 0;
$scope.data.purchase_order_details.forEach(function (item) {
if (! item._deleted) {
subtotal += item.subtotal;
iva_amount += item.iva_amount;
total += item.total;
}
});
$scope.data.subtotal = subtotal;
$scope.data.iva_amount = iva_amount;
$scope.data.total = total;
}
$scope.focusQuantity = function () {
$timeout(function () {
$('input[ng-model="product.quantity"]').focus().select();
}, 100);
}
$scope.focusCode = function () {
$timeout(function () {
$('input[ng-model="product.code"]').focus().select();
}, 100);
}
$scope.focusDescription = function () {
$timeout(function () {
$('input[ng-model="product.description"]').focus().select();
}, 100);
}
$scope.getProductPrice = function (product) {
// if no vendor selected, set price = 0
if (! $scope.data.vendor) {
$scope.product.price = 0;
return false;
}
ProductService.get_price({
id: product.id,
vendor: $scope.data.vendor.id
}).success(function (response) {
$scope.product.price = response.price;
$scope.calculateDetailTotals();
}).error(function (response) {
toastr.error(response.msg || 'Error en el servidor');
});
}
$scope.editDetail = function (detail, type) {
if (type == 'quantity') {
$scope.input_quantity = parseFloat(detail.quantity);
detail.editing_quantity = true;
$timeout(function () {
$('input[ng-model="input_quantity"]').focus().select();
}, 50);
}
if (type == 'price') {
$scope.input_price = parseFloat(detail.price);
detail.editing_price = true;
$timeout(function () {
$('input[ng-model="input_price"]').focus().select();
}, 50);
}
}
$scope.endEditDetail = function (detail, type, evt) {
var value = parseFloat(evt.target.value);
if (! value) {
toastr.warning('Capture un número válido', 'Validaciones');
$scope.clearEditingDetails('all');
return false;
}
if (type == 'quantity') {
detail.quantity = value;
}
if (type == 'price') {
detail.price = value;
}
$scope.clearEditingDetails(type);
detail.subtotal = detail.quantity * detail.price;
detail.iva_amount = (detail.iva / 100) * detail.subtotal;
detail.total = detail.subtotal + detail.iva_amount;
$scope.calculateTotal();
}
$scope.keyPressDetail = function (evt, type) {
var key = evt.keyCode;
if (key == 27) {
$scope.clearEditingDetails(type);
}
if (key == 13) {
evt.target.blur();
}
}
$scope.clearEditingDetails = function (type) {
$scope.data.purchase_order_details.forEach(function (item) {
if (type == 'quantity' || type == 'all') {
item.editing_quantity = false;
}
if (type == 'price' || type == 'all') {
item.editing_price = false;
}
});
}
$scope.cancel = function () {
var id = $scope.data.id;
$ngConfirm({
title: 'Cancelar',
content: '¿Desea cancelar el registro actual?',
type: 'red',
buttons: {
ok: {
text: 'Aceptar',
btnClass: 'btn-red',
action: function () {
PurchaseOrderService.cancel({
id: id
}).success(function (response) {
toastr.success('Registro Cancelado');
$location.path('/purchase-orders');
}).error(function (response) {
toastr.error(response.msg || 'Error en el servidor');
});
}
},
close: {
text: 'Omitir',
btnClass: 'btn-default'
}
}
});
}
$scope.getVendors();
BaseController.call(this, $scope, $route, $location, $ngConfirm, PurchaseOrderService, toastr);
}); | 22.478149 | 182 | 0.615851 |
b9b64c434a7fb34915018b14e7e7d0167fc186f6 | 8,617 | js | JavaScript | public/component---src-pages-index-js-46f5d2e8dba48d136b1b.js | calvin-zheng/personal-website-v2 | be82b8bb8e5bc446c19904a96fe561b60883e8ac | [
"RSA-MD"
] | null | null | null | public/component---src-pages-index-js-46f5d2e8dba48d136b1b.js | calvin-zheng/personal-website-v2 | be82b8bb8e5bc446c19904a96fe561b60883e8ac | [
"RSA-MD"
] | null | null | null | public/component---src-pages-index-js-46f5d2e8dba48d136b1b.js | calvin-zheng/personal-website-v2 | be82b8bb8e5bc446c19904a96fe561b60883e8ac | [
"RSA-MD"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[2],{RXBc:function(e,t,r){"use strict";r.r(t);var n=r("dI71"),a=r("q1tI"),l=r.n(a),o=r("Wbzz");var i=function(){var e=Object(a.useState)(!1),t=e[0],r=e[1];return l.a.createElement("header",{className:"fixed min-w-full flex items-center justify-between flex-wrap bg-white-custom p-6 shadow-sm",style:{zIndex:"2"}},l.a.createElement("div",{className:"flex items-center flex-shrink-0 text-white mr-6"}),l.a.createElement("div",{className:"block md:hidden"},l.a.createElement("button",{onClick:function(){return r(!t)},className:"flex items-center px-3 py-2 border rounded text-gray-400 border-gray-400 hover:text-cyan-500 hover:border-cyan-500 focus:outline-none focus:text-cyan-500 focus:border-cyan-500"},l.a.createElement("svg",{className:"fill-current h-3 w-3 outline-none",viewBox:"0 0 20 20",xmlns:"http://www.w3.org/2000/svg"},l.a.createElement("title",null,"Menu"),l.a.createElement("path",{d:"M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z"})))),l.a.createElement("div",{className:(t?"block":"hidden")+" w-full block flex-grow md:flex md:items-center md:w-auto"},l.a.createElement("div",{className:"ml-auto text-center"},l.a.createElement(o.a,{to:"",href:"#responsive-header",className:"block mt-4 md:inline-block md:mt-0 text-gray-500 hover:text-cyan-500 md:mr-4"},"About"),l.a.createElement(o.a,{to:"",className:"block mt-4 md:inline-block md:mt-0 text-gray-500 hover:text-cyan-500 md:mr-4"},"Experience"),l.a.createElement(o.a,{to:"",className:"block mt-4 md:inline-block md:mt-0 text-gray-500 hover:text-cyan-500 md:mr-4"},"Projects"),l.a.createElement(o.a,{to:"",className:"block mt-4 md:inline-block md:mt-0 text-gray-500 hover:text-cyan-500 md:mr-4"},"Contact"),l.a.createElement("a",{href:"#download",className:"inline-block px-4 py-2 leading-none border rounded text-gray-500 border-gray-500 hover:border-cyan-500 hover:text-cyan-500 mt-4 md:mt-0"},"Resume"))))};function c(){return(c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function s(e,t){if(null==e)return{};var r,n,a=function(e,t){if(null==e)return{};var r,n,a={},l=Object.keys(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}var m=Object(a.forwardRef)((function(e,t){var r=e.color,n=void 0===r?"currentColor":r,a=e.size,o=void 0===a?24:a,i=s(e,["color","size"]);return l.a.createElement("svg",c({ref:t,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},i),l.a.createElement("path",{d:"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"}),l.a.createElement("rect",{x:"2",y:"9",width:"4",height:"12"}),l.a.createElement("circle",{cx:"4",cy:"4",r:"2"}))}));m.displayName="Linkedin";var u=m;function d(){return(d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function f(e,t){if(null==e)return{};var r,n,a=function(e,t){if(null==e)return{};var r,n,a={},l=Object.keys(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}var p=Object(a.forwardRef)((function(e,t){var r=e.color,n=void 0===r?"currentColor":r,a=e.size,o=void 0===a?24:a,i=f(e,["color","size"]);return l.a.createElement("svg",d({ref:t,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},i),l.a.createElement("path",{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"}))}));p.displayName="GitHub";var v=p;function h(){return(h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function y(e,t){if(null==e)return{};var r,n,a=function(e,t){if(null==e)return{};var r,n,a={},l=Object.keys(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(n=0;n<l.length;n++)r=l[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}var x=Object(a.forwardRef)((function(e,t){var r=e.color,n=void 0===r?"currentColor":r,a=e.size,o=void 0===a?24:a,i=y(e,["color","size"]);return l.a.createElement("svg",h({ref:t,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},i),l.a.createElement("path",{d:"M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"}),l.a.createElement("polyline",{points:"22,6 12,13 2,6"}))}));x.displayName="Mail";var g=x;var w=function(){return l.a.createElement("div",{className:"min-h-screen px-10 flex flex-col sm:py-12 w-3/4 max-w-5xl mx-auto justify-center"},l.a.createElement("div",{className:"pattern-dots-md rounded-3xl text-cyan-500"},l.a.createElement("div",{className:"transform translate-x-5 -translate-y-5 relative px-4 py-10 bg-white rounded-3xl sm:p-20 ring-2 ring-opacity-30 ring-cyan-500"},l.a.createElement("div",{className:"min-w-full mx-auto space-y-6"},l.a.createElement("div",null,l.a.createElement("h1",{className:"text-cyan-600 text-5xl"},"Hello, I'm Calvin."),l.a.createElement("div",{className:"pattern-dots-sm text-gray-300 h-3"}),l.a.createElement("p",{className:"text-gray-500 text-lg w-full"},"I’m a computer science junior at the University of Michigan in Ann Arbor, MI, interested in software engineering, web development, machine learning, and natural language processing.")),l.a.createElement("div",{className:"min-w-full flex flex-row justify-center fill-current text-gray-400"},l.a.createElement("a",{href:"https://www.linkedin.com/in/calvin-zheng/"},l.a.createElement(u,{className:"mr-8 hover:text-cyan-500 transition duration-500 ease-in-out",size:30})),l.a.createElement("a",{href:"https://github.com/calvin-zheng"},l.a.createElement(v,{className:"mr-8 hover:text-cyan-500 transition duration-500 ease-in-out",size:30})),l.a.createElement("a",{href:"mailto:calzheng@umich.edu"},l.a.createElement(g,{className:"hover:text-cyan-500 transition duration-500 ease-in-out",size:30})))))))};var b=function(){return l.a.createElement("div",{className:"min-h-screen px-10 flex flex-col sm:py-12 w-3/4 max-w-5xl mx-auto justify-center"},l.a.createElement("div",{className:"min-w-full flex flex-row"},l.a.createElement("div",{className:"px-4 py-10 bg-white rounded-3xl sm:p-20 ring-2 ring-opacity-30 ring-cyan-500",style:{transform:"translate(20px, -20px)"}},l.a.createElement("div",{className:"min-w-full mx-auto space-y-6"},l.a.createElement("div",null,l.a.createElement("h1",{className:"text-cyan-600 text-5xl"},"About Me"),l.a.createElement("div",{className:"pattern-dots-sm text-gray-300 h-3"}),l.a.createElement("p",{className:"text-gray-500 text-lg w-full"},"Hello! I’m Calvin, a computer science junior at the University of Michigan. On campus, I am involved with Michigan Hackers and MPowered Entrepreneurship. Last summer, I am participating in an engineering co-op with Toyota North America, focusing on developing new solutions for internal tools for virtual meetings and also working to digitally optimize different parts of their supply chain process. For Summer 2021, I will interning with Capital One as a software engineer in New York City."))))))},E=function(e){function t(){return e.apply(this,arguments)||this}return Object(n.a)(t,e),t.prototype.render=function(){return l.a.createElement("div",{className:"content"},l.a.createElement(i,null),l.a.createElement("div",{className:"greeting"},l.a.createElement(w,null)),l.a.createElement("div",{className:"about"},l.a.createElement(b,null)))},t}(l.a.Component);t.default=E}}]);
//# sourceMappingURL=component---src-pages-index-js-46f5d2e8dba48d136b1b.js.map | 4,308.5 | 8,537 | 0.715446 |
b9b7b6ae6f3b6ab908dc0f231fc215e45f7cc11d | 77 | js | JavaScript | app/js/app.js | portojs/angular-project-5 | 23336fc4f91208c5ba591b09b0db384e9ab97c54 | [
"MIT"
] | null | null | null | app/js/app.js | portojs/angular-project-5 | 23336fc4f91208c5ba591b09b0db384e9ab97c54 | [
"MIT"
] | null | null | null | app/js/app.js | portojs/angular-project-5 | 23336fc4f91208c5ba591b09b0db384e9ab97c54 | [
"MIT"
] | null | null | null | 'use strict';
angular.module('bobbleApp', [
'ngRoute',
'ngResource'
]);
| 11 | 29 | 0.623377 |
b9b7c3185d824955cbe467a91d84d1066ef060d2 | 1,770 | js | JavaScript | js/script.js | TUMxInteractionProgramming/challenges-week-3-TatyanaGoltvyanitsa | 7b43d0f05c00b0c24f954bcc9c76ff292a32ed80 | [
"MIT"
] | null | null | null | js/script.js | TUMxInteractionProgramming/challenges-week-3-TatyanaGoltvyanitsa | 7b43d0f05c00b0c24f954bcc9c76ff292a32ed80 | [
"MIT"
] | null | null | null | js/script.js | TUMxInteractionProgramming/challenges-week-3-TatyanaGoltvyanitsa | 7b43d0f05c00b0c24f954bcc9c76ff292a32ed80 | [
"MIT"
] | null | null | null | "use strict";
// console.log('working'); ##STEP 1 TEST TO SEE IF JS IS WORKING
//Function changes star in chat app bar to empty; called by switchChannel() function
function emptyStar() {
console.log('Changing star');
$('#titleStar').attr('src', 'http://ip.lfe.mw.tum.de/sections/star-o.png');
}
//Function changes channel name in chat app bar when channel is clicked in channel list
//Also: Adds and removes class .selected to indicate whether or not that channel is active
function switchChannel(channelName) {
console.log('Tuning into channel ' + channelName); //console test for validation of changing channels
emptyStar(); //calling this function to change star icon in chat app bar
document.getElementById('channelTitle').innerHTML = channelName;
document.getElementById('titleAuthor').innerHTML = '<a href="http://w3w.co/upgrading.never.helps" target="_blank">upgrading.never.helps</a>';
$("#channelList>li").removeClass("selected");
$("li:contains(" + channelName + ")").addClass("selected");
}
//Function fills the star in the chat app bar when clicked
function filledStar() {
console.log('Filling the star');
$('#titleStar').attr('src', 'http://ip.lfe.mw.tum.de/sections/star.png');
}
//Function adds and removes .selected class of tabs on click
function selectTab(tabId) {
console.log('Toggling tab selections');
console.log(tabId); //checking to see if correct tab button is being selected
$("#tab-bar>button").removeClass("selected"); //removes selected class only from buttons with #tab-bar as parent
$("#"+tabId).addClass("selected"); //adds selected class to clicked tab
}
//Function toggles visibility of emojis when icon is clicked
function toggleEmojis() {
$("#emojis").toggle();
} | 45.384615 | 145 | 0.712429 |
b9b7d45b42d6be7c1f135baa16299b82f4de6e0e | 1,924 | js | JavaScript | test/token/FixedPriceTokenAgent.js | wealdtech/wealdtech-solidity | 5058039356d62d6b1bc7c7a20703fbeb4aa0ed47 | [
"Apache-2.0"
] | 32 | 2017-09-07T10:42:22.000Z | 2022-03-16T20:06:11.000Z | test/token/FixedPriceTokenAgent.js | wealdtech/wealdtech-solidity | 5058039356d62d6b1bc7c7a20703fbeb4aa0ed47 | [
"Apache-2.0"
] | 3 | 2019-05-28T13:54:35.000Z | 2021-05-06T19:28:51.000Z | test/token/FixedPriceTokenAgent.js | wealdtech/wealdtech-solidity | 5058039356d62d6b1bc7c7a20703fbeb4aa0ed47 | [
"Apache-2.0"
] | 12 | 2017-09-25T11:04:48.000Z | 2022-02-04T05:39:01.000Z | 'use strict';
const assertRevert = require('../helpers/assertRevert');
const FixedPriceTokenAgent = artifacts.require('./token/FixedPriceTokenAgent.sol');
const TestERC20Token = artifacts.require('./samplecontracts/TestERC20Token.sol');
contract('FixedPriceTokenAgent', accounts => {
const tokenOwner = accounts[0];
const faucetOwner = accounts[1];
const requestor = accounts[2];
var token;
var faucet;
it('can set up the contracts', async() => {
token = await TestERC20Token.new({gas: 10000000});
await token.activate();
faucet = await FixedPriceTokenAgent.new(token.address, tokenOwner, 10, {
from: faucetOwner
});
});
it('can approve token transfers by the faucet agent', async() => {
var active = await faucet.active();
assert.equal(active, false);
await token.approve(faucet.address, 1000, {
from: tokenOwner
});
const tokens = await token.allowance(tokenOwner, faucet.address);
assert.equal(tokens, 1000);
active = await faucet.active();
assert.equal(active, true);
});
it('rejects requests for too many tokens', async() => {
try {
await faucet.sendTransaction({
from: requestor,
value: 101
});
assert.fail();
} catch (error) {
assertRevert(error);
}
});
it('can exchange Ether for tokens', async() => {
await faucet.sendTransaction({
from: requestor,
value: 10
});
const tokens = await token.balanceOf(requestor);
assert.equal(tokens, 100);
});
it('can be drained', async() => {
await faucet.sendTransaction({
from: requestor,
value: 90
});
var active = await faucet.active();
assert.equal(active, false);
});
});
| 30.0625 | 83 | 0.574324 |
b9b99156ac2b24ab18932a3b43f516643bf70d00 | 1,147 | js | JavaScript | public/js/custom.js | pratik617/portmapp | 71eed7c57fcfed319b0f2a26d4cca4bc48238a49 | [
"MIT"
] | null | null | null | public/js/custom.js | pratik617/portmapp | 71eed7c57fcfed319b0f2a26d4cca4bc48238a49 | [
"MIT"
] | null | null | null | public/js/custom.js | pratik617/portmapp | 71eed7c57fcfed319b0f2a26d4cca4bc48238a49 | [
"MIT"
] | null | null | null | //Initialize form validator
$.validate({});
//Initialize Select2 Elements
$('.select2').select2()
//iCheck for checkbox and radio inputs
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass : 'iradio_minimal-blue'
})
//Date picker
$('.datepicker').datepicker({
autoclose: true,
format: 'dd/mm/yyyy'
})
$(document).ready(function() {
$('#change_password').click(function() {
$('#password_field').toggle();
});
$('#users-table, #programs-table, #projects-table').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
var table_id = $(this).data('table');
// confirm then
if (confirm('Are you sure you want to delete this?')) {
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
}).always(function (data) {
$('#'+table_id).DataTable().draw(false);
});
}else
alert("You have cancelled!");
});
}); | 23.408163 | 108 | 0.61116 |
b9b9a2f6590da63de585ca20fdbd30c4edb38a5e | 1,087 | js | JavaScript | src/Components/ModalComplete.js | theteladras/TCGame | 1cdbba7db0fc7f69a0798e97738f4168b0262835 | [
"MIT"
] | null | null | null | src/Components/ModalComplete.js | theteladras/TCGame | 1cdbba7db0fc7f69a0798e97738f4168b0262835 | [
"MIT"
] | null | null | null | src/Components/ModalComplete.js | theteladras/TCGame | 1cdbba7db0fc7f69a0798e97738f4168b0262835 | [
"MIT"
] | null | null | null | import React from 'react'
import { View, Text, Button, Dimensions } from 'react-native'
import Canvas from './CanvasComponent'
import styles from '../Styles/ModalCompleteStyle'
const ModalComplete = ({ thisLevel, modalBtnNo, modalBtnYes }) => {
return(
<View style={styles.container}>
<Text style={styles.modalHeader}>You have completed level: {thisLevel}</Text>
<Text style={styles.cps}>Clicks per second for the first 10 clicks</Text>
<Canvas />
<View>
<Text style={styles.modalParagraph}>Do you want to play the next level?</Text>
<View style={styles.btnContainer}>
<View style={styles.btnView}>
<Button title="No" onPress={modalBtnNo} color="#dbd00d" />
</View>
<View style={styles.btnView}>
<Button title="Yes" onPress={modalBtnYes} color="#01a80a" />
</View>
</View>
</View>
</View>
);
};
export default ModalComplete; | 38.821429 | 94 | 0.552898 |
b9badc915f56b7820f2b7e4252c98c378c398175 | 287 | js | JavaScript | src/index.js | lucasconstantino/redux-transient | d4fec091b4a8150f5ac9dc3bab1c4008fbc20977 | [
"MIT"
] | 30 | 2017-05-28T09:52:33.000Z | 2020-06-03T12:16:49.000Z | src/index.js | lucasconstantino/redux-transient | d4fec091b4a8150f5ac9dc3bab1c4008fbc20977 | [
"MIT"
] | 4 | 2017-05-31T20:24:39.000Z | 2019-04-23T17:45:35.000Z | src/index.js | lucasconstantino/redux-transient | d4fec091b4a8150f5ac9dc3bab1c4008fbc20977 | [
"MIT"
] | 5 | 2017-05-29T01:07:06.000Z | 2017-08-02T13:19:39.000Z | import {
ADD_REDUCER,
REMOVE_REDUCER,
addReducer,
removeReducer,
transientEnhancer,
} from './transient-enhancer'
export { addReducer, removeReducer, transientEnhancer }
export const actions = { ADD_REDUCER, REMOVE_REDUCER }
export const enhancer = transientEnhancer // alias
| 23.916667 | 55 | 0.773519 |
b9bc5ffe932623f96b473b8128c029e66af074e8 | 273 | js | JavaScript | Node_Services/models/lookups.model.js | ParnabBasak/Group3_Hackathon | fa5d56c82eeb3d3aae228eb647d14507ac064ec5 | [
"MIT"
] | null | null | null | Node_Services/models/lookups.model.js | ParnabBasak/Group3_Hackathon | fa5d56c82eeb3d3aae228eb647d14507ac064ec5 | [
"MIT"
] | 11 | 2020-09-07T16:32:22.000Z | 2022-02-13T00:19:18.000Z | Node_Services/models/lookups.model.js | ParnabBasak/Group3_Hackathon | fa5d56c82eeb3d3aae228eb647d14507ac064ec5 | [
"MIT"
] | 4 | 2019-11-06T05:50:10.000Z | 2019-11-17T16:15:54.000Z | var mongoose = require('mongoose');
var lookupsSchema = new mongoose.Schema({
key: { type: String , required:true},
values :{
key: String,
value: String
}
},
{
timestamps:true
})
module.exports = mongoose.model('lookups', lookupsSchema);
| 17.0625 | 58 | 0.622711 |
b9bd9b4553c9bd0efaee8c84bbdaf30e76116c59 | 10,467 | js | JavaScript | client/src/store/DeviceStore.js | InteroperGit/online-store | 7b3ada3cc8632ed46afc4a1df44a13bd071dbb29 | [
"MIT"
] | null | null | null | client/src/store/DeviceStore.js | InteroperGit/online-store | 7b3ada3cc8632ed46afc4a1df44a13bd071dbb29 | [
"MIT"
] | null | null | null | client/src/store/DeviceStore.js | InteroperGit/online-store | 7b3ada3cc8632ed46afc4a1df44a13bd071dbb29 | [
"MIT"
] | null | null | null | import { set, keys, computed, makeAutoObservable, remove } from 'mobx';
const ELEMENTS_ON_PAGE = process.env.REACT_APP_ELEMENT_ON_PAGE_COUNT;
const orderFunctions = {
orderByAsc: (orderProp) => {
return (a, b) => {
if (a[orderProp] > b[orderProp]) {
return 1;
}
if (a[orderProp] < b[orderProp]) {
return -1;
}
return 0;
}
},
orderByDesc: (orderProp) => {
return (a, b) => {
if (a[orderProp] < b[orderProp]) {
return 1;
}
if (a[orderProp] > b[orderProp]) {
return -1;
}
return 0;
}
}
}
export default class DeviceStore {
constructor() {
this._types = [];
this._brands = [];
this._devices = [
/*
{ id: 1, name: "IPhone 11 Pro", price: 90000, rating: 5, img: '', imageUrl: 'https://via.placeholder.com/150' },
{ id: 2, name: "IPhone 12 Pro", price: 100000, rating: 5, img: '', imageUrl: 'https://via.placeholder.com/150' },
{ id: 3, name: "IPhone 7", price: 10000, rating: 5, img: '', imageUrl: 'https://via.placeholder.com/150' },
{ id: 4, name: "IPhone 5", price: 50000, rating: 5, img: '', imageUrl: 'https://rklm-online-store.s3.eu-central-1.amazonaws.com/Apple/%D0%A1%D0%BC%D0%B0%D1%80%D1%82%D1%84%D0%BE%D0%BD%D1%8B/b185614e-4ee4-40ca-b95c-5a77c9e2685f.jpg' },
{ id: 5, name: "IPhone 6", price: 50000, rating: 5, img: '', imageUrl: 'https://via.placeholder.com/150' },
{ id: 6, name: "IPhone 8", price: 50000, rating: 5, img: '', imageUrl: 'https://via.placeholder.com/150' },
*/
];
/**
* TYPES
*/
this._selectedType = this._types[0];
this._totalTypesCount = 0;
this._typeOrderKey = 'name';
this._typeOrderDirection = 'ASC';
this._typeActivePage = 1;
/**
* BRANDS
*/
this._selectedBrand = this._brands[0];
this._totalBrandsCount = 0;
this._brandOrderKey = 'name';
this._brandOrderDirection = 'ASC';
this._brandActivePage = 1;
/**
* DEVICES
*/
this._totalDevicesCount = 0;
this._deviceOrderKey = 'name';
this._deviceOrderDirection = 'ASC';
this._deviceActivePage = 1;
this._filteredDevices = [];
/**
* BASKET
*/
this._totalBasketDevicesCount = 0;
this._basketDevices = [];
makeAutoObservable(this, {
orderedTypes: computed
});
}
/**
* TYPES
*/
/**
*
* @param {*} types
*/
setTypes(types) {
this._types = types;
}
addType(type) {
const nextKey = keys(this._types).slice(-1)[0] + 1;
set(this._types, nextKey, type);
this.setTotalTypesCount(this.totalTypesCount + 1);
}
updateType(updatingType) {
const type = this.getType(updatingType.id);
type.name = updatingType.name;
}
setType(key, type) {
set(this._types, key, type);
}
removeType(id) {
const removingType = this.getType(id);
const key = this._types.indexOf(removingType);
remove(this._types, key);
this.setTotalTypesCount(this.totalTypesCount - 1);
}
setTypeActivePage(page) {
this._typeActivePage = page;
}
setSelectedType(type) {
this._selectedType = type;
}
setTotalTypesCount(count) {
this._totalTypesCount = count;
}
setTypeOrderKey(orderKey) {
this._typeOrderKey = orderKey || 'name';
}
setTypeOrderDirection(orderDirection) {
this._typeOrderDirection = orderDirection || 'ASC';
}
get types() {
return this._types;
}
getType(id) {
return this._types.filter(type => type.id === id)[0];
}
get typeActivePage() {
return this._typeActivePage;
}
get selectedType() {
return this._selectedType;
}
get totalTypesCount() {
return this._totalTypesCount;
}
get typeOrderKey() {
return this._typeOrderKey;
}
get typeOrderDirection() {
return this._typeOrderDirection;
}
get orderedTypes() {
const orderProp = 'name';
const orderByAsc = orderFunctions.orderByAsc(orderProp);
const orderByDesc = orderFunctions.orderByDesc(orderProp);
const orderedArray = this._types instanceof Array
? this._types.slice().sort(this._typeOrderDirection === 'ASC' ? orderByAsc : orderByDesc)
: [];
return orderedArray.map((item, index) => {
item['serialNumber'] = index + 1 + (this._typeActivePage - 1) * ELEMENTS_ON_PAGE;
return item;
});
}
/**
* BRANDS
*/
setBrands(brands) {
this._brands = brands;
}
addBrand(brand) {
const nextKey = keys(this._brands).slice(-1)[0] + 1;
set(this._brands, nextKey, brand);
this.setTotalBrandsCount(this.totalBrandsCount + 1);
}
updateBrand(updatingBrand) {
const brand = this.getBrand(updatingBrand.id);
brand.name = updatingBrand.name;
}
setBrand(key, brand) {
set(this._brands, key, brand);
}
removeBrand(id) {
const removingBrand = this.getBrand(id);
const key = this._brands.indexOf(removingBrand);
remove(this._brands, key);
this.setTotalBrandsCount(this.totalBrandsCount - 1);
}
setBrandActivePage(page) {
this._brandActivePage = page;
}
setSelectedBrand(brand) {
this._selectedBrand = brand;
}
setTotalBrandsCount(count) {
this._totalBrandsCount = count;
}
setBrandOrderKey(orderKey) {
this._brandOrderKey = orderKey || 'name';
}
setBrandOrderDirection(orderDirection) {
this._brandOrderDirection = orderDirection || 'ASC';
}
get brands() {
return this._brands;
}
getBrand(id) {
return this._brands.find(brand => brand.id === id);
}
get brandActivePage() {
return this._brandActivePage;
}
get selectedBrand() {
return this._selectedBrand;
}
get totalBrandsCount() {
return this._totalBrandsCount;
}
get brandOrderKey() {
return this._brandOrderKey;
}
get brandOrderDirection() {
return this._brandOrderDirection;
}
get orderedBrands() {
const orderProp = 'name';
const orderByAsc = orderFunctions.orderByAsc(orderProp);
const orderByDesc = orderFunctions.orderByDesc(orderProp);
const orderedArray = this._brands instanceof Array
? this._brands.slice().sort(this._brandOrderDirection === 'ASC' ? orderByAsc : orderByDesc)
: [];
return orderedArray.map((item, index) => {
item['serialNumber'] = index + 1 + (this._brandActivePage - 1) * ELEMENTS_ON_PAGE;
return item;
});
}
/**
* DEVICES
*/
setDevices(devices) {
this._devices = devices;
}
addDevice(device) {
set(this._devices, device);
}
updateDevice(updatingDevice) {
const device = this.getDevice(updatingDevice.id);
device.name = updatingDevice.name;
}
setDevice(key, device) {
set(this._devices, key, device);
}
removeDevice(id) {
const removingDevice = this.getDevice(id);
const key = this._devices.indexOf(removingDevice);
remove(this._devices, key);
this.setTotalDevicesCount(this.totalDevicesCount - 1);
}
setDeviceActivePage(page) {
this._deviceActivePage = page;
}
setSelectedDevice(device) {
this._selecteDevice = device;
}
setTotalDevicesCount(count) {
this._totalDevicesCount = count;
}
setDeviceOrderKey(orderKey) {
this._deviceOrderKey = orderKey || 'name';
}
setDeviceOrderDirection(orderDirection) {
this._deviceOrderDirection = orderDirection || 'ASC';
}
setFilteredDevices(filteredDevices) {
this._filteredDevices = filteredDevices || [];
}
get devices() {
return this._devices;
}
getDevice(id) {
return this._devices.find(device => device.id === id);
}
get deviceActivePage() {
return this._deviceActivePage;
}
get selectedDevice() {
return this._selectedDevice;
}
get totalDevicesCount() {
return this._totalDevicesCount;
}
get deviceOrderKey() {
return this._deviceOrderKey;
}
get deviceOrderDirection() {
return this._deviceOrderDirection;
}
get filteredDevices() {
return this._filteredDevices;
}
get orderedDevices() {
const orderProp = 'name';
const orderByAsc = orderFunctions.orderByAsc(orderProp);
const orderByDesc = orderFunctions.orderByDesc(orderProp);
const orderedArray = this._devices instanceof Array
? this._devices.slice().sort(this._deviceOrderDirection === 'ASC' ? orderByAsc : orderByDesc)
: [];
return orderedArray.map((item, index) => {
item['serialNumber'] = index + 1 + (this._deviceActivePage - 1) * ELEMENTS_ON_PAGE;
return item;
});
}
/**
* BASKET
*/
setBasketDevices(basketDevices) {
this._basketDevices = basketDevices || [];
}
get basketDevices() {
return this._basketDevices;
}
get totalBasketDevicesCount() {
return this._totalBasketDevicesCount;
}
setTotalBasketDevicesCount(count) {
this._totalBasketDevicesCount = count;
}
getBasketDevice(id) {
return this._basketDevices.find(device => device.id === id);
}
addBasketDevice(basketDevice) {
set(this._basketDevices, basketDevice);
this.setTotalBasketDevicesCount(this.totalBasketDevicesCount + 1);
}
removeBasketDevice(deviceId) {
const removingDevice = this.getBasketDevice(deviceId);
const key = this._basketDevices.indexOf(removingDevice);
remove(this._basketDevices, key);
this.setTotalBasketDevicesCount(this.totalBasketDevicesCount - 1);
}
} | 24.570423 | 245 | 0.57495 |
b9be982a349ac1f53cf0363c44c86b724db957fc | 316 | js | JavaScript | vkit/ref.js | VincentyTM/vk | 0643c6012a94fd834e63124a82aaa04c9c599d17 | [
"MIT"
] | 2 | 2021-03-18T13:17:43.000Z | 2021-07-10T21:02:29.000Z | vkit/ref.js | VincentyTM/vk | 0643c6012a94fd834e63124a82aaa04c9c599d17 | [
"MIT"
] | 1 | 2021-03-18T13:19:27.000Z | 2021-03-18T13:19:27.000Z | vkit/ref.js | VincentyTM/vkit | 4b1023d1c78beef8e1a44ac1c61a865e1403d470 | [
"MIT"
] | null | null | null | (function($){
var unmount = $.unmount;
function createRef(){
function reset(){
ref.current = null;
}
function ref(el){
if( ref.current ){
throw new Error("This reference has already been set.");
}
ref.current = el;
unmount(reset);
}
ref.current = null;
return ref;
}
$.ref = createRef;
})($);
| 13.73913 | 59 | 0.620253 |
b9bf535c0bfdcc05848a192f92c1a0e497a6ce78 | 7,688 | js | JavaScript | src/js/page/index.js | sanguiyou/baobei | d41da7a89bf1140d1c1fad6074a72a08cd00d7ee | [
"MIT"
] | null | null | null | src/js/page/index.js | sanguiyou/baobei | d41da7a89bf1140d1c1fad6074a72a08cd00d7ee | [
"MIT"
] | null | null | null | src/js/page/index.js | sanguiyou/baobei | d41da7a89bf1140d1c1fad6074a72a08cd00d7ee | [
"MIT"
] | null | null | null | var chart1;
var chart2;
var chart3;
function setChart1() {
var dom = document.getElementById("chart_01");
chart1 = echarts.init(dom);
option = null;
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
name: "成交",
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: 0.3,
lineStyle: {
width: 1,
color: '#d6ebfe',
opacity: 1
},
areaStyle: {
color: '#d6ebfe',
opacity: 0.5
}
}, {
name: "通过",
data: [720, 1232, 701, 1234, 1090, 1030, 320],
type: 'line',
smooth: 0.3,
lineStyle: {
width: 1,
color: '#b4e2ec',
opacity: 1
},
areaStyle: {
color: '#b4e2ec',
opacity: 0.5
}
}],
grid: {
show: true,
height: 400,
x: 50,
x2: 20,
y: 12
}
};
chart1.setOption(option, true);
}
function setChart2() {
var dom = document.getElementById("chart_02");
chart2 = echarts.init(dom);
var option = {
tooltip: {
trigger: 'item'
},
visualMap: {
min: 0,
max: 100,
left: 'left',
top: 'bottom',
text: ['高', '低'], // 文本,默认为数值文本
calculable: true
},
series: [
{
tooltip: {
formatter: function (params) {
var html = "<div >";
var data = params.data;
html += "<span style='color:#efecec;'>项目</span>:<span style='font-size:20px;color:#f57a5b;'>" + data.value + "</span><br/>";
html += "<span style='color:#efecec;'>金额</span>:<span style='font-size:20px;color:#f57a5b;'>" + data.money + "</span>";
html += "</div>";
return html;
}
},
name: '项目',
type: 'map',
mapType: 'china',
roam: false,
top: '0%',
bottom: '0%',
label: {
normal: {
show: true
},
emphasis: {
show: true
}
},
data: [
{name: '北京', value: 1, money: 2},
{name: '天津', value: 2, money: 2},
{name: '上海', value: 3, money: 2},
{name: '重庆', value: 4, money: 2},
{name: '河北', value: 5, money: 2},
{name: '河南', value: 6, money: 2},
{name: '云南', value: 7, money: 2},
{name: '辽宁', value: 8, money: 2},
{name: '黑龙江', value: 9, money: 2},
{name: '湖南', value: 10, money: 2},
{name: '安徽', value: 11, money: 2},
{name: '山东', value: 12, money: 2},
{name: '新疆', value: 13, money: 2},
{name: '江苏', value: 14, money: 2},
{name: '浙江', value: 15, money: 2},
{name: '江西', value: 16, money: 2},
{name: '湖北', value: 17, money: 2},
{name: '广西', value: 18, money: 2},
{name: '甘肃', value: 19, money: 2},
{name: '山西', value: 20, money: 2},
{name: '内蒙古', value: 21, money: 2},
{name: '陕西', value: 22, money: 2},
{name: '吉林', value: 23, money: 2},
{name: '福建', value: 24, money: 2},
{name: '贵州', value: 25, money: 2},
{name: '广东', value: 26, money: 2},
{name: '青海', value: 27, money: 2},
{name: '西藏', value: 28, money: 2},
{name: '四川', value: 29, money: 2},
{name: '宁夏', value: 30, money: 2},
{name: '海南', value: 31, money: 2},
{name: '台湾', value: 32, money: 2},
{name: '香港', value: 33, money: 2},
{name: '澳门', value: 34, money: 2}
]
}
]
};
;
chart2.setOption(option, true);
}
function setChart3() {
var dom = document.getElementById("chart_03");
chart3 = echarts.init(dom);
option = null;
var colors = ['#9393FE', '#EA51EE', '#FDEECF'];
option = {
color: colors,
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
grid: {
right: '1%',
left: '3%'
},
xAxis: [
{
type: 'category',
axisTick: {
alignWithLabel: true
},
data: ['陈天宝部门', '安冰部门', '全塞部门', '如为部门', '能华部门', '周堵红部门', '李东部门']
}
],
yAxis: [
{
type: 'value',
name: 'kvar',
min: 0,
max: 100,
position: 'left',
axisLine: {
lineStyle: {
color: colors[0]
}
}
},
{
type: 'value',
name: 'kvar',
min: 0,
max: 100,
position: 'left',
axisLine: {
lineStyle: {
color: colors[1]
}
}
},
{
type: 'value',
name: 'kvar',
min: 0,
max: 100,
position: 'left',
axisLine: {
lineStyle: {
color: colors[2]
}
}
}
],
series: [
{
name: '年度任务(kvar)',
type: 'bar',
data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
},
{
name: '已完成任务(kvar)',
type: 'bar',
yAxisIndex: 1,
data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6]
},
{
name: '回款率',
type: 'line',
yAxisIndex: 2,
data: [5.0, 2.2, 3.3, 10.5, 6.3, 15.2, 50.3],
smooth: 0.3,
lineStyle: {
width: 1,
color: colors[2],
opacity: 1
},
areaStyle: {
color: colors[2],
opacity: 0.5
}
}
]
};
chart3.setOption(option, true);
}
window.onresize = function () {
chart1 && chart1.resize();
chart2 && chart2.resize();
chart3 && chart3.resize();
}
setChart1();
setChart2();
setChart3(); | 29.914397 | 148 | 0.327263 |
b9bf8363522dfa0527b0576fd1298b83f42d21dc | 1,988 | js | JavaScript | src/styles/layout.js | seanyboy49/quaranzine | 6bba63b572a94d45e7b7f864f6ec59204f96e44f | [
"MIT"
] | null | null | null | src/styles/layout.js | seanyboy49/quaranzine | 6bba63b572a94d45e7b7f864f6ec59204f96e44f | [
"MIT"
] | null | null | null | src/styles/layout.js | seanyboy49/quaranzine | 6bba63b572a94d45e7b7f864f6ec59204f96e44f | [
"MIT"
] | null | null | null | import styled, { css } from "styled-components"
export const breakpoints = {
phoneWide: `(max-width: 600px)`,
tabletWide: `(max-width: 880px)`,
laptop: `(max-width: 1024px)`,
desktop: `(max-width: 1440px)`,
iphone5: `(max-height: 658px) and (max-width: 320px)`,
iphonePlus: `(max-height: 736px) and (max-width: 414px)`,
iphone678: `(max-height: 667px) and (max-width: 375px)`,
iphoneX: `(max-height: 812px) and (max-width: 375px)`,
}
export const mediaQueries = Object.entries(breakpoints)
.map(([media, query]) => {
return {
[media]: `@media only screen and ${query}`,
}
})
.reduce((mediaQueries, query) => {
return {
...mediaQueries,
...query,
}
}, {})
export const PaddedWidthContainer = styled.section`
padding: 73.5px 145px;
${mediaQueries.tabletWide} {
padding: 28px;
}
`
export const FullWidthContainer = styled.section`
padding: 145px 0;
${mediaQueries.tabletWide} {
padding: 56px 0;
}
`
export const Row = styled.div`
display: flex;
justify-content: space-between;
flex-wrap: wrap;
margin: 20px 0;
${mediaQueries.tabletWide} {
flex-direction: column;
align-items: center;
${p =>
p.reverseColumn &&
css`
flex-direction: column-reverse;
`}
}
${p =>
p.center &&
css`
justify-content: center;
`};
${p =>
p.start &&
css`
justify-content: flex-start;
`};
${p =>
p.end &&
css`
justify-content: flex-end;
`};
`
export const Column = styled.div`
display: flex;
width: ${props => props.width || 50}%;
flex-direction: column;
align-items: ${props => props.align || "center"};
${p =>
p.center &&
css`
justify-content: center;
`};
${mediaQueries.tabletWide} {
width: 100%;
}
`
export const FluidImageContainer = styled.div`
width: ${props => props.desktop || 70}%;
${mediaQueries.phoneWide} {
width: ${props => props.mobile || 90}%;
}
`
| 19.300971 | 59 | 0.59004 |
b9c001debd9670e1ac7753a5c415441854e580f9 | 2,307 | js | JavaScript | src/pages/curriculo.js | eudiegoborgs/eudiegoborgs.github.io | 3d945cf1870c71dc3f58f565b576da315f6b20ca | [
"MIT"
] | null | null | null | src/pages/curriculo.js | eudiegoborgs/eudiegoborgs.github.io | 3d945cf1870c71dc3f58f565b576da315f6b20ca | [
"MIT"
] | 1 | 2022-02-27T18:59:16.000Z | 2022-02-27T18:59:16.000Z | src/pages/curriculo.js | eudiegoborgs/eudiegoborgs.github.io | 3d945cf1870c71dc3f58f565b576da315f6b20ca | [
"MIT"
] | 1 | 2019-10-17T12:18:08.000Z | 2019-10-17T12:18:08.000Z | import React from "react"
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import {dracula} from 'react-syntax-highlighter/dist/cjs/styles/prism'
import Layout from "../components/themes/layout"
import SEO from "../components/organisms/seo"
import Content from "../components/organisms/content"
import BlogResume from "../components/organisms/blog-resume"
const data = `{
"name": "Diego Borges Ferreira",
"birthday": "1994-12-27",
"from": {
"city": "Vespasiano",
"state": "Minas Gerais",
"country": "Brasil",
"complete": "Vespasiano/MG - Brasil"
},
"skills": {
"hard": [
"HTML",
"CSS",
"JavaScript",
"React",
"React Native",
"TypeScript",
"Node.js",
"PHP",
"Python",
"SQL DB (MySQL, Postgre & Maria DB)",
"NoSQL DB (Mongo, Firebase & Redis)",
"AWS Services (EC2, ECS, ELB, S3, Lambda Functions)",
"Docker & Docker Compose",
"Git",
],
"concepts": [
"OOP",
"TDD",
"Clean Architecture",
"Clean Code",
"Micro Services",
"Events",
],
"soft": [
"Criatividade",
"Comunicação",
"Trabalho em equipe",
"Autodidata",
],
},
"academics": [
{
"name": "Sistemas de Informação",
"school": "PUC MG",
"type": "Graduação",
}
],
"experiences": [
{
"name": "Picpay",
"from": "05/2021",
"to": undefined,
},
{
"name": "Sympla",
"from": "10/2020",
"to": "04/2021",
},
{
"name": "Gamefik",
"from": "01/2020",
"to": "10/2020",
},
{
"name": "MaxMilhas",
"from": "10/2018",
"to": "01/2020",
},
{
"name": "4yousee",
"from": "10/2017",
"to": "10/2018",
},
{
"name": "Quartel Design",
"from": "02/2017",
"to": "10/2017",
},
]
}`;
const CurriculoPage = () => (
<Layout>
<SEO title="Curriculo" />
<Content>
<main style={{textAlign: 'center'}}>
<SyntaxHighlighter
language={'javascript'}
style={dracula}
showLineNumbers={true}
>
{data}
</SyntaxHighlighter>
</main>
<BlogResume />
</Content>
</Layout>
)
export default CurriculoPage
| 20.972727 | 70 | 0.507152 |
b9c1ec25722f5119afcf3821e80b09cea6d470d1 | 1,414 | js | JavaScript | server/models/Poll/methods.js | rimij405/igme430-pollr | 46c28dc9dfbf0cfee41941a600f555f64225b9e3 | [
"MIT"
] | 1 | 2021-03-13T00:15:04.000Z | 2021-03-13T00:15:04.000Z | server/models/Poll/methods.js | rimij405/igme430-pollr | 46c28dc9dfbf0cfee41941a600f555f64225b9e3 | [
"MIT"
] | 3 | 2022-02-14T01:15:44.000Z | 2022-02-27T11:21:53.000Z | server/models/Poll/methods.js | rimij405/igme430-pollr | 46c28dc9dfbf0cfee41941a600f555f64225b9e3 | [
"MIT"
] | null | null | null | // ////////////////////////
// INSTANCE FUNCTIONS
// ////////////////////////
// Query options subdocument assigned to this Poll.
const findOptions = function (callback) {
return this.populate('options').select('options').lean().exec((err, options) => {
if (err) {
// Error in query. No options returned.
return callback(err, null);
}
if (!options) {
// Options may be empty.
return callback(null, null);
}
// If populate is successful, returns the options.
return callback(null, options);
});
};
// Query votes subdocument assigned to this Poll.
const findVotes = function (callback) {
return this.populate('votes').select('votes').lean().exec((err, votes) => {
if (err) {
// Error in query. No votes returned.
return callback(err, null);
}
if (!votes) {
// Votes may be empty.
return callback(null, null);
}
// If populate is successful, returns the votes.
return votes(null, votes);
});
};
// ////////////////////////
// MODULE EXPORTS
// ////////////////////////
// Assign methods to schema.
module.exports.assign = (schema) => {
// Object containing static functions to assign to the schema.
const fns = {
findOptions,
findVotes,
};
// Assign all fns (functions) listed above to the schema.
Object.keys(fns).forEach((fnKey) => {
schema.methods[fnKey] = fns[fnKey];
});
};
| 24.37931 | 83 | 0.577793 |
b9c35a54c30a66e0522d568dbd700f7da66e602d | 564 | js | JavaScript | src/pages/404.js | Zarkoix/JailBirdGame | e27aa2540da8e898f39ef702edde3fe1731cbe74 | [
"MIT"
] | null | null | null | src/pages/404.js | Zarkoix/JailBirdGame | e27aa2540da8e898f39ef702edde3fe1731cbe74 | [
"MIT"
] | 5 | 2021-03-10T05:08:31.000Z | 2022-02-26T22:45:55.000Z | src/pages/404.js | JailBirdGame/JailBirdGame | e27aa2540da8e898f39ef702edde3fe1731cbe74 | [
"MIT"
] | null | null | null | import React from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
import Video from "../components/video"
import "../components/video.css"
const NotFoundPage = () => (
<Layout>
<SEO title="404: Not found" />
<h1>404: NOT FOUND</h1>
<h3 className="videoText">How 'bout a video instead?</h3>
<div className="videoContainer">
<Video
videoSrcURL="https://www.youtube.com/embed/2aafcTYbS2Y"
videoTitle="The JailBird is Back"
/>
</div>
</Layout>
)
export default NotFoundPage
| 23.5 | 63 | 0.652482 |
b9c4648fd5523169cdc4748e3100ebe7da20d3ea | 1,975 | js | JavaScript | wordpress/wp-content/plugins/gt3-themes-core/dist/js/widgets/gt3-core-testimonialsverticalcarousel.js | marcos081295/Wordpressexample | c72e6d9ea62b771cb96d759b93b4fca6e3de827d | [
"Apache-1.1"
] | null | null | null | wordpress/wp-content/plugins/gt3-themes-core/dist/js/widgets/gt3-core-testimonialsverticalcarousel.js | marcos081295/Wordpressexample | c72e6d9ea62b771cb96d759b93b4fca6e3de827d | [
"Apache-1.1"
] | null | null | null | wordpress/wp-content/plugins/gt3-themes-core/dist/js/widgets/gt3-core-testimonialsverticalcarousel.js | marcos081295/Wordpressexample | c72e6d9ea62b771cb96d759b93b4fca6e3de827d | [
"Apache-1.1"
] | null | null | null | !function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r(r.s=657)}({657:function(e,t,r){"use strict";r.r(t);var n,o,i;r(658);function a(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var l=GT3,u=(l.Hooks,l.autobind),s=l.ThemesCore,c=s.Widgets.BasicWidget,d=s.isRTL,f=s.jQuery,p=u((i=o=function(e){var t,r;function n(){var t;t=e.apply(this,arguments)||this;var r=f(t.el);if(!(r=f(".gt3_testimonial",r)).length)return a(t);var n=r.data("settings");return f(".testimonials_rotator",r).slick({autoplay:n.autoplay,autoplaySpeed:n.autoplaySpeed,fade:n.fade,dots:n.dots,arrows:n.arrows,slidesToScroll:1,slidesToShow:3,centerMode:!0,focusOnSelect:!0,speed:500,vertical:!0,verticalSwiping:!0,infinite:!0,prevArrow:'<div class="slick-prev">'+n.l10n.prev+"</div>",nextArrow:'<div class="slick-next">'+n.l10n.next+"</div>",rtl:d}),t}return r=e,(t=n).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,n}(c),o.widgetName="gt3-core-testimonialsverticalcarousel",n=i))||n;GT3.ThemesCore.onWidgetRegisterHandler(p.widgetName,p)},658:function(e,t,r){}}); | 1,975 | 1,975 | 0.713924 |
b9c5596ed620b3c631f973900d8bab525aefc63d | 2,626 | js | JavaScript | src/Proxy/index.js | RReverser/proxyfill | d200d8a596438d1039ab2f750f3fdab237851909 | [
"MIT"
] | 4 | 2015-06-11T15:27:28.000Z | 2017-07-18T13:23:47.000Z | src/Proxy/index.js | RReverser/proxyfill | d200d8a596438d1039ab2f750f3fdab237851909 | [
"MIT"
] | null | null | null | src/Proxy/index.js | RReverser/proxyfill | d200d8a596438d1039ab2f750f3fdab237851909 | [
"MIT"
] | null | null | null | import { PROXY_HANDLER, PROXY_TARGET, CALL, CONSTRUCT } from '../symbols';
import { setInternalMethods } from '../internalMethods';
import * as internalMethods from './_internalMethods';
import * as internalFnMethods from './_internalFnMethods';
import { assertObject } from '../helpers';
import { create, assign, hasOwnProperty } from '../Object/_original';
function getProxyHandler() {
var handler = this[PROXY_HANDLER];
if (handler === null) {
throw new TypeError('Proxy was revoked.');
}
return handler;
}
function assertValidProxyArgument(obj) {
assertObject(obj);
obj::getProxyHandler();
}
export function isProxy(obj) {
return obj::hasOwnProperty(PROXY_HANDLER);
}
export default class Proxy {
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-proxycreate
constructor(target, handler) {
assertValidProxyArgument(target);
assertValidProxyArgument(handler);
var proxy;
if (typeof target === 'function') {
proxy = Object.setPrototypeOf(function proxied(...args) {
if (this instanceof proxied) {
return proxy[CONSTRUCT](args, this.constructor);
}
return proxy[CALL](this, args);
}, FunctionProxyProto);
} else {
proxy = this;
}
proxy[PROXY_TARGET] = target;
proxy[PROXY_HANDLER] = handler;
return proxy;
}
static revocable(target, handler) {
// [[RevocableProxy]]
var revocableProxy = new Proxy(target, handler);
return {
proxy: revocableProxy,
revoke() {
if (revocableProxy !== null) {
let proxy = revocableProxy;
revocableProxy = null;
proxy[PROXY_TARGET] = proxy[PROXY_HANDLER] = null;
}
}
};
}
}
const ProxyProto = Proxy.prototype = create(null);
function wrapTrap(method, name) {
return function trapWrapper(...args) {
var handler = this::getProxyHandler();
var target = this[PROXY_TARGET];
args.unshift(target);
var trap = handler[name];
if (trap == null) {
return Reflect[name](...args);
}
return method(handler::trap(...args), ...args);
};
}
setInternalMethods(ProxyProto, internalMethods, wrapTrap);
const FunctionProxyProto = create(Function.prototype, {
toString: {
writable: true,
configurable: true,
value: function toString() {
return this[PROXY_TARGET].toString();
}
}
});
assign(FunctionProxyProto, ProxyProto);
setInternalMethods(FunctionProxyProto, internalFnMethods, wrapTrap);
// using `.bind()` to remove `prototype` on function
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-proxy-constructor
Proxy = Proxy.bind();
| 26.26 | 96 | 0.676695 |
b9c563f4252e62c16d2fd3baf9d08a1e9407f9fa | 461 | js | JavaScript | src/archrn.js | 4Stripe/archrn-cli | b03eb8a527c055b5fab4fc7934ab9ee84c0fa287 | [
"MIT"
] | null | null | null | src/archrn.js | 4Stripe/archrn-cli | b03eb8a527c055b5fab4fc7934ab9ee84c0fa287 | [
"MIT"
] | null | null | null | src/archrn.js | 4Stripe/archrn-cli | b03eb8a527c055b5fab4fc7934ab9ee84c0fa287 | [
"MIT"
] | null | null | null | #!/usr/bin/env node
import program from 'commander';
import colors from 'colors';
program
.version('2.2.0')
.description('Archtools, a set tools that will bring your react-native productivity to the next level')
.command('generate [name]', 'Create a new react-native component').alias('g')
.command('update', 'Update react-native dependecy').alias('u')
.parse(process.argv);
console.log();
console.log(' Arch ☕ '.rainbow); // ARCH rainbow
console.log();
| 24.263158 | 103 | 0.713666 |
b9c5f2c1f465873101e52f350a4df9984c911fb1 | 857 | js | JavaScript | src/views/NotFound.js | pikokr/UniqueBots-Frontend | 3f6610919e49958be1a25c2e19862d5fdde05416 | [
"MIT"
] | 3 | 2020-12-08T05:21:23.000Z | 2020-12-10T05:31:05.000Z | src/views/NotFound.js | pikokr/UniqueBots-Frontend | 3f6610919e49958be1a25c2e19862d5fdde05416 | [
"MIT"
] | null | null | null | src/views/NotFound.js | pikokr/UniqueBots-Frontend | 3f6610919e49958be1a25c2e19862d5fdde05416 | [
"MIT"
] | 2 | 2020-12-09T08:29:20.000Z | 2020-12-17T08:58:30.000Z | import React from 'react';
import {Button, Typography} from "@material-ui/core";
import {Link} from "react-router-dom";
import GREY from '@material-ui/core/colors/grey'
const NotFound = () => {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
width: '100vw',
height: '100vh',
overflow: 'hidden',
flexDirection: 'column',
position: 'absolute',
left: 0,
top: 0,
zIndex: 999,
background: GREY["900"]
}}>
<Typography variant="h4">404 Not Found</Typography>
<Typography>페이지를 찾을 수 없습니다.</Typography>
<Button component={Link} to="/">홈으로</Button>
</div>
);
};
export default NotFound; | 29.551724 | 64 | 0.50175 |
b9c608fb59d943a3c15971477c70f99454d092c8 | 287 | js | JavaScript | src/utilities/collections.js | omarkdev/levxyca-pandadomalbot | a19e8975edfdb03acd258526082923c07eafb12d | [
"MIT"
] | null | null | null | src/utilities/collections.js | omarkdev/levxyca-pandadomalbot | a19e8975edfdb03acd258526082923c07eafb12d | [
"MIT"
] | null | null | null | src/utilities/collections.js | omarkdev/levxyca-pandadomalbot | a19e8975edfdb03acd258526082923c07eafb12d | [
"MIT"
] | null | null | null | /**
* Obtém um valor aleatório do Array.
*
* @param collection
* @returns {*}
*/
function sample(collection) {
const length = collection == null ? 0 : collection.length;
return length ? collection[Math.floor(Math.random() * length)] : undefined;
}
module.exports = { sample };
| 22.076923 | 77 | 0.665505 |
b9c66a9229a099ebf5651c156f58682b05586967 | 5,890 | js | JavaScript | tests/lib/rules/prefer-promises/fs.js | giltayar/eslint-plugin-node | ffed3edbc94dfac87ee817fafc3f6e1d4125477f | [
"MIT"
] | 900 | 2016-01-15T21:20:56.000Z | 2022-03-17T06:55:43.000Z | tests/lib/rules/prefer-promises/fs.js | giltayar/eslint-plugin-node | ffed3edbc94dfac87ee817fafc3f6e1d4125477f | [
"MIT"
] | 282 | 2015-12-11T15:07:40.000Z | 2022-03-26T15:09:44.000Z | tests/lib/rules/prefer-promises/fs.js | giltayar/eslint-plugin-node | ffed3edbc94dfac87ee817fafc3f6e1d4125477f | [
"MIT"
] | 176 | 2016-01-09T06:09:33.000Z | 2022-03-23T01:25:15.000Z | /**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const RuleTester = require("eslint").RuleTester
const rule = require("../../../../lib/rules/prefer-promises/fs")
new RuleTester({
parserOptions: {
ecmaVersion: 2015,
sourceType: "module",
},
globals: {
require: false,
},
}).run("prefer-promises/fs", rule, {
valid: [
"const fs = require('fs'); fs.createReadStream()",
"const fs = require('fs'); fs.accessSync()",
"const fs = require('fs'); fs.promises.access()",
"const {promises} = require('fs'); promises.access()",
"const {promises: fs} = require('fs'); fs.access()",
"const {promises: {access}} = require('fs'); access()",
"import fs from 'fs'; fs.promises.access()",
"import * as fs from 'fs'; fs.promises.access()",
"import {promises} from 'fs'; promises.access()",
"import {promises as fs} from 'fs'; fs.access()",
],
invalid: [
{
code: "const fs = require('fs'); fs.access()",
errors: [{ messageId: "preferPromises", data: { name: "access" } }],
},
{
code: "const {access} = require('fs'); access()",
errors: [{ messageId: "preferPromises", data: { name: "access" } }],
},
{
code: "import fs from 'fs'; fs.access()",
errors: [{ messageId: "preferPromises", data: { name: "access" } }],
},
{
code: "import * as fs from 'fs'; fs.access()",
errors: [{ messageId: "preferPromises", data: { name: "access" } }],
},
{
code: "import {access} from 'fs'; access()",
errors: [{ messageId: "preferPromises", data: { name: "access" } }],
},
// Other members
{
code: "const fs = require('fs'); fs.copyFile()",
errors: [
{ messageId: "preferPromises", data: { name: "copyFile" } },
],
},
{
code: "const fs = require('fs'); fs.open()",
errors: [{ messageId: "preferPromises", data: { name: "open" } }],
},
{
code: "const fs = require('fs'); fs.rename()",
errors: [{ messageId: "preferPromises", data: { name: "rename" } }],
},
{
code: "const fs = require('fs'); fs.truncate()",
errors: [
{ messageId: "preferPromises", data: { name: "truncate" } },
],
},
{
code: "const fs = require('fs'); fs.rmdir()",
errors: [{ messageId: "preferPromises", data: { name: "rmdir" } }],
},
{
code: "const fs = require('fs'); fs.mkdir()",
errors: [{ messageId: "preferPromises", data: { name: "mkdir" } }],
},
{
code: "const fs = require('fs'); fs.readdir()",
errors: [
{ messageId: "preferPromises", data: { name: "readdir" } },
],
},
{
code: "const fs = require('fs');fs.readlink()",
errors: [
{ messageId: "preferPromises", data: { name: "readlink" } },
],
},
{
code: "const fs = require('fs'); fs.symlink()",
errors: [
{ messageId: "preferPromises", data: { name: "symlink" } },
],
},
{
code: "const fs = require('fs'); fs.lstat()",
errors: [{ messageId: "preferPromises", data: { name: "lstat" } }],
},
{
code: "const fs = require('fs'); fs.stat()",
errors: [{ messageId: "preferPromises", data: { name: "stat" } }],
},
{
code: "const fs = require('fs'); fs.link()",
errors: [{ messageId: "preferPromises", data: { name: "link" } }],
},
{
code: "const fs = require('fs'); fs.unlink()",
errors: [{ messageId: "preferPromises", data: { name: "unlink" } }],
},
{
code: "const fs = require('fs'); fs.chmod()",
errors: [{ messageId: "preferPromises", data: { name: "chmod" } }],
},
{
code: "const fs = require('fs'); fs.lchmod()",
errors: [{ messageId: "preferPromises", data: { name: "lchmod" } }],
},
{
code: "const fs = require('fs'); fs.lchown()",
errors: [{ messageId: "preferPromises", data: { name: "lchown" } }],
},
{
code: "const fs = require('fs'); fs.chown()",
errors: [{ messageId: "preferPromises", data: { name: "chown" } }],
},
{
code: "const fs = require('fs'); fs.utimes()",
errors: [{ messageId: "preferPromises", data: { name: "utimes" } }],
},
{
code: "const fs = require('fs'); fs.realpath()",
errors: [
{ messageId: "preferPromises", data: { name: "realpath" } },
],
},
{
code: "const fs = require('fs'); fs.mkdtemp()",
errors: [
{ messageId: "preferPromises", data: { name: "mkdtemp" } },
],
},
{
code: "const fs = require('fs'); fs.writeFile()",
errors: [
{ messageId: "preferPromises", data: { name: "writeFile" } },
],
},
{
code: "const fs = require('fs'); fs.appendFile()",
errors: [
{ messageId: "preferPromises", data: { name: "appendFile" } },
],
},
{
code: "const fs = require('fs'); fs.readFile()",
errors: [
{ messageId: "preferPromises", data: { name: "readFile" } },
],
},
],
})
| 35.059524 | 80 | 0.441766 |
b9c6730409ccb9395dd0b92dd24964c4865e8836 | 641 | js | JavaScript | src/services/service.js | emre-bayrak/vue-movie-spa | a9b22b37c62b70ef229ac1182ce8fde8d2ce0a88 | [
"Apache-2.0"
] | null | null | null | src/services/service.js | emre-bayrak/vue-movie-spa | a9b22b37c62b70ef229ac1182ce8fde8d2ce0a88 | [
"Apache-2.0"
] | 1 | 2022-03-02T08:19:24.000Z | 2022-03-02T08:19:24.000Z | src/services/service.js | emre-bayrak/vue-movie-spa | a9b22b37c62b70ef229ac1182ce8fde8d2ce0a88 | [
"Apache-2.0"
] | null | null | null | export default {
fetchMovies() {
return firebase.database().ref('/movies').once('value');
},
fetchMovieDetails(id) {
return firebase.database().ref(`/movieDetails/${id}`).once('value');
},
fetchTicketPrices() {
return firebase.database().ref('ticketPrices').once('value');
},
fetchMovieTimes(id) {
return firebase.database().ref(`/movieTimes/${id}`).once('value');
},
fetchSeating(hallId) {
return firebase.database().ref(`/halls/${hallId}`).once('value');
},
fetchSoldTickets({ movieId, time }) {
return firebase.database().ref(`/soldTickets/${movieId}/${time}`).once('value');
},
};
| 23.740741 | 84 | 0.628705 |
b9c678da76fb5d5930880b4aebb062c4bf12f9cc | 1,030 | js | JavaScript | dist/src/cnpj/constants/index.js | AlbertDev33/documents-validation | dda701d79d3cc85e565b3ed9849db5cffb91f69a | [
"MIT"
] | null | null | null | dist/src/cnpj/constants/index.js | AlbertDev33/documents-validation | dda701d79d3cc85e565b3ed9849db5cffb91f69a | [
"MIT"
] | null | null | null | dist/src/cnpj/constants/index.js | AlbertDev33/documents-validation | dda701d79d3cc85e565b3ed9849db5cffb91f69a | [
"MIT"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.weigthChoice = exports.verificationLength = exports.splitRest = exports.EXPECTED_LENGTH = exports.IS_SEQUENTIAL = exports.REPLACE_INVALID_CHARACTER = void 0;
const CLEAN_INVALID_CHARACTER = /[^0-9]/;
const FLAG = 'g';
exports.REPLACE_INVALID_CHARACTER = new RegExp(CLEAN_INVALID_CHARACTER, FLAG);
const SEQUENTIAL_PATTERN = /^(\d)\1{3,14}$/;
exports.IS_SEQUENTIAL = new RegExp(SEQUENTIAL_PATTERN);
exports.EXPECTED_LENGTH = 14;
const splitRest = (split) => {
const keys = {
1: '0',
0: '0',
};
const value = keys[split];
return value || split;
};
exports.splitRest = splitRest;
exports.verificationLength = {
first: 12,
second: 13,
};
const weigthChoice = (digit) => {
const choice = {
first: [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2],
second: [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2],
};
return choice[digit];
};
exports.weigthChoice = weigthChoice;
//# sourceMappingURL=index.js.map | 33.225806 | 165 | 0.656311 |
b9c7058cffafdf14ee8f0a2ea9a8265649a561b6 | 3,674 | js | JavaScript | Official Windows Platform Sample/Windows 8.1 Store app samples/[JavaScript]-Windows 8.1 Store app samples/Portable device services sample/JavaScript/js/s2_listRingtones.js | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[JavaScript]-Windows 8.1 Store app samples/Portable device services sample/JavaScript/js/s2_listRingtones.js | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[JavaScript]-Windows 8.1 Store app samples/Portable device services sample/JavaScript/js/s2_listRingtones.js | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | null | null | null | //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/s2_listRingtones.html", {
ready: function (element, options) {
document.getElementById("button1").addEventListener("click", scenario2_showRingtones, false);
}
});
function scenario2_showRingtones() {
// Find all devices that support the ringtones service
document.getElementById("scenarioOutput").innerHTML = "";
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(
Windows.Devices.Portable.ServiceDevice.getDeviceSelector(Windows.Devices.Portable.ServiceDeviceType.ringtonesService),
null)
.done(
function (ringtonesServices) {
// Display ringtones for the selected device
if (ringtonesServices.length) {
SdkSample.showItemSelector(ringtonesServices, showRingtones);
} else {
WinJS.log && WinJS.log("No ringtone services found. Please connect a device that supports the Ringtones Service to the system", "sample", "status");
}
},
function (e) {
WinJS.log && WinJS.log("Failed to find all ringtones services, error: " + e.message, "sample", "error");
});
}
function showRingtones(deviceInfoElement) {
var deviceName = deviceInfoElement.name;
var deviceFactory = new ActiveXObject("PortableDeviceAutomation.Factory");
deviceFactory.getDeviceFromIdAsync(deviceInfoElement.id,
function (device) {
// Get the first ringtone service on that device
var ringtoneService = device.services[0];
// Find all mp3 ringtones on the service
ringtoneService.onGetChildrenByFormatComplete = function (errorCode, ringtones) {
if (errorCode === 0) {
var scenarioOutput = document.getElementById("scenarioOutput");
var numRingtones = ringtones.count;
scenarioOutput.innerHTML = "<h3>" + deviceName + " ringtones (" + numRingtones + " found)<h3/>";
for (var j = 0; j < numRingtones; j++) {
var ringtone = ringtones[j];
scenarioOutput.innerHTML += ringtone.objectName + " (" + ringtone.objectSize + " bytes)<br />";
}
} else {
WinJS.log && WinJS.log("Failed to list ringtones on " + deviceName + ", error: " + errorCode.toString(16), "sample", "error");
}
};
ringtoneService.getChildrenByFormat("mp3");
},
function (errorCode) {
var E_ACCESSDENIED = 2147942405; // 0x80070005
if (errorCode === E_ACCESSDENIED) {
WinJS.log && WinJS.log("Access to " + deviceInfoElement.name + " is denied. Only a Privileged Application may access this device.", "sample", "error");
} else {
WinJS.log && WinJS.log("Failed to get the selected device, error: " + errorCode.toString(16), "sample", "error");
}
});
}
})();
| 51.027778 | 176 | 0.560425 |
b9c7fe2e75fcdb6356ce3374a6c0216047451cb0 | 3,741 | js | JavaScript | js/repos/imageBuilder.js | jaybenaim/new-portfolio | 661a18b29c0adff9d266d409b25b315cbbe51a3c | [
"MIT"
] | 1 | 2020-05-31T05:15:40.000Z | 2020-05-31T05:15:40.000Z | js/repos/imageBuilder.js | jaybenaim/new-portfolio | 661a18b29c0adff9d266d409b25b315cbbe51a3c | [
"MIT"
] | 2 | 2021-03-10T21:08:41.000Z | 2021-05-10T18:48:00.000Z | js/repos/imageBuilder.js | jaybenaim/new-portfolio | 661a18b29c0adff9d266d409b25b315cbbe51a3c | [
"MIT"
] | null | null | null | const imageBuilder = (filter, name, lang) => {
let images = {
all: {
link: "../img/gradHat.png",
ref: "https://seeklogo.com/vector-logo/248724/graduation",
},
bitmaker: {
link: "../img/gradHat.png",
ref: "https://seeklogo.com/vector-logo/248724/graduation",
},
bit: {
link: "../img/gradHat.png",
ref: "https://seeklogo.com/vector-logo/248724/graduation",
},
wdi: {
link: "../img/gradHat.png",
ref: "https://seeklogo.com/vector-logo/248724/graduation",
},
angular: {
link: "../img/angular.png",
ref: "https://icons8.com/icons/set/angularjs",
},
tour: {
link: "../img/angular.png",
ref: "https://icons8.com/icons/set/angularjs",
},
react: {
link: "../img/react-logo.svg",
ref: "https://seeklogo.com/vector-logo/273845/react",
},
yelp: {
link: "../img/js-logo.svg",
ref: "https://seeklogo.com/vector-logo/273557/javascript-js",
},
game: {
link: "../img/games.jpg",
ref: "http://clipart-library.com/clipart/6376.htm",
},
tic: {
link: "../img/games.jpg",
ref: "http://clipart-library.com/clipart/6376.htm",
},
python: {
link: "../img/python.svg",
ref: "https://seeklogo.com/vector-logo/273830/python",
},
django: {
link: "../img/python.svg",
ref: "https://seeklogo.com/vector-logo/273830/python",
},
free: {
link: "../img/fcc.png",
ref: "https://icons8.com/icons/set/free-code-camp",
},
boot: {
link: "../img/bootstrap.png",
rel: "https://icons8.com/icons/set/bootstrap",
},
shop: {
link: "../img/shopping-cart.png",
rel: "https://pixabay.com/vectors/shopping-cart-shopping-icon-1105049/",
},
sell: {
link: "../img/shopping-cart.png",
rel: "https://pixabay.com/vectors/shopping-cart-shopping-icon-1105049/",
},
dolce: {
link: "../img/shopping-cart.png",
rel: "https://pixabay.com/vectors/shopping-cart-shopping-icon-1105049/",
},
store: {
link: "../img/shopping-cart.png",
rel: "https://pixabay.com/vectors/shopping-cart-shopping-icon-1105049/",
},
job: {
link: "../img/api-img.png",
rel:
"https://pixabay.com/?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=2126876",
},
backend: {
link: "../img/api-img.png",
rel:
"https://pixabay.com/?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=2126876",
},
api: {
link: "../img/api-img.png",
rel:
"https://pixabay.com/?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=2126876",
},
ruby: {
link: "../img/ruby.png",
rel:
"https://pixabay.com/?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=160777",
},
rails: {
link: "../img/ruby.png",
rel:
"https://pixabay.com/?utm_source=link-attribution&utm_medium=referral&utm_campaign=image&utm_content=160777",
},
java: {
link: "../img/js-logo.svg",
ref: "https://seeklogo.com/vector-logo/273557/javascript-js",
},
javascript: {
link: "../img/js-logo.svg",
ref: "https://seeklogo.com/vector-logo/273557/javascript-js",
},
};
let imageKeys = Object.keys(images);
let image = imageKeys.filter((key) => {
lang = lang && lang.toLowerCase();
return name.includes(key) || (lang && lang.includes(key) && key);
});
let key = image[0];
let matchedImage = images[key];
return matchedImage ? matchedImage : images[filter];
};
| 30.917355 | 130 | 0.58487 |
b9caa3900fda557d2e2f5f26a0b674c07314a68a | 1,497 | js | JavaScript | packages/page-contracts/build/Contracts/Outcome.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | packages/page-contracts/build/Contracts/Outcome.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | packages/page-contracts/build/Contracts/Outcome.js | arjunchamyal/apps | f638587627afb07299a5c8738fdd29d1ca8bebf5 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017-2021 @axia-js/app-contracts authors & contributors
// SPDX-License-Identifier: Apache-2.0
import React from 'react';
import styled from 'styled-components';
import { Button, IdentityIcon, Output } from '@axia-js/react-components';
import valueToText from '@axia-js/react-params/valueToText';
import MessageSignature from "../shared/MessageSignature.js";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
function Outcome({
className = '',
onClear,
outcome: {
from,
message,
output,
params,
result,
when
}
}) {
return /*#__PURE__*/_jsxs("div", {
className: className,
children: [/*#__PURE__*/_jsx(IdentityIcon, {
value: from
}), /*#__PURE__*/_jsx(Output, {
className: "output",
isError: !result.isOk,
isFull: true,
label: /*#__PURE__*/_jsx(MessageSignature, {
message: message,
params: params
}),
labelExtra: /*#__PURE__*/_jsxs("span", {
className: "date-time",
children: [when.toLocaleDateString(), ' ', when.toLocaleTimeString()]
}),
value: valueToText('Text', result.isOk ? output : result)
}), /*#__PURE__*/_jsx(Button, {
icon: "times",
onClick: onClear
})]
});
}
export default /*#__PURE__*/React.memo(styled(Outcome).withConfig({
displayName: "Outcome",
componentId: "sc-1hnsqhp-0"
})(["align-items:center;display:flex;.output{flex:1 1;margin:0.25rem 0.5rem;}"])); | 29.94 | 82 | 0.639279 |
b9cad9c61a0c199561c0e5b7ca213fbc64bb2764 | 6,962 | js | JavaScript | src/main/webapp/javascript/basefunctions.js | dblabuofi/VisFlow | cf18d797911453208b5896e66b770179bbb70ace | [
"MIT"
] | null | null | null | src/main/webapp/javascript/basefunctions.js | dblabuofi/VisFlow | cf18d797911453208b5896e66b770179bbb70ace | [
"MIT"
] | null | null | null | src/main/webapp/javascript/basefunctions.js | dblabuofi/VisFlow | cf18d797911453208b5896e66b770179bbb70ace | [
"MIT"
] | null | null | null | //helper functions uuid
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
String.prototype.allTrim = String.prototype.allTrim ||
function () {
// return this.replace(/\s+/g, ' ')
// .replace(/^\s+|\s+$/, '');
return this.replace(/\s+/g, ' ')
.trim();
};
String.prototype.getFileType = function () {
var type = this.replace(/.*\./, '').toUpperCase()
.trim();
switch (type) {
case "XML":
case "CSV":
break;
case "":
type = "Other";
break;
default:
type = "SQL";
}
return type;
};
Array.prototype.clean = function (deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
function findNodes(nodes) {
var i = 0;
for (; i < nodes.length; ++i) {
if (nodes[i].id === curData.id) {
return i;
}
}
return -1;
}
function myInclude(attributes, attr) {
for (var i = 0; i < attributes.length; ++i) {
if (attributes[i] == attr) {
return true;
}
}
return false;
}
//use myIncludeFieldIndex
function isInclude(resources, id) {
for (var i = 0; i < resources.length; ++i) {
if (resources[i].id == id) {
return i;
}
}
return -1;
}
//use myIncludeFieldIndex
function myIncludeName(attributes, attr) {
for (var i = 0; i < attributes.length; ++i) {
if (attributes[i].name == attr) {
return true;
}
}
return false;
}
//use myIncludeFieldIndex
function myResourceName(attributes, attr) {
for (var i = 0; i < attributes.length; ++i) {
if (attributes[i].resourceName == attr) {
return i;
}
}
return -1;
}
//use myIncludeFieldIndex
function myIncludeNameIndex(attributes, attr) {
for (var i = 0; i < attributes.length; ++i) {
if (attributes[i].name == attr) {
return i;
}
}
return -1;
}
//use myIncludeFieldIndex
function myIncludelibraryNameIndex(attributes, attr) {
for (var i = 0; i < attributes.length; ++i) {
if (attributes[i].libraryName == attr) {
return i;
}
}
return -1;
}
//use myIncludeFieldIndex
function myIncludeActionIndex(actions, attr) {
for (var i = 0; i < actions.length; ++i) {
if (actions[i].resourceName == attr) {
return i;
}
}
return -1;
}
function myIncludeFieldIndex(array, value, attr) {
if (array === undefined) return -1;
for (var i = 0; i < array.length; ++i) {
if (array[i][attr] == value) {
return i;
}
}
return -1;
}
function myWebFieldIndex(webservices, value, attr) {
for (var i = 0; i < webservices.length; ++i) {
for (var j = 0; j < webservices[i].attributes.length; ++j) {
if (webservices[i].attributes[j][attr] == value) {
return j;
}
}
}
return -1;
}
function addresourcesIn(resourcesIn, resources) {
for (var i = 0; i < resources.length; ++i) {
var index = myIncludeFieldIndex(resourcesIn, resources[i].id, 'id');
if (index === -1) {
resourcesIn.push(resources[i]);
}
}
return resourcesIn;
}
function removeResources(resourcesIn, resources) {
for (var i = 0; i < resources.length; ++i) {
var index = myIncludeFieldIndex(resourcesIn, resources[i].id, 'id');
if (index !== -1) {
resourcesIn = resourcesIn.splice(i, 1);
}
}
return resourcesIn;
}
function random_rgba() {
var o, r, s, r1, g1, b1;
o = Math.round, r = Math.random, s = 255;
do {
r1 = o(r()*s), g1 = o(r()*s), b1 = o(r()*s);
} while (0.2126 * r1 + 0.7152 * g1 + 0.0722 * b1 < 80);
return { r: r1, g:g1, b:b1 };
}
function assignColor() {
var color = {
r: 205,
g: 145,
b: 0};
function generateColor() {
return random_rgba();
}
function reset() {
color = {
r: 205,
g: 145,
b: 0};
}
return {generateColor:generateColor, reset : reset};
}
var colorFun = assignColor();
//uploaded files generalIO
var mySubGraphInterval = null;
var numberofIOs = 0;
var uploadedIOids = [];
var uploadFileGeneralIOids = [];
var uploadFileGeneralResourceOuts = [];
function generateUploadGeneralIO() {
uploadFileGeneralIOids = [];
uploadFileGeneralResourceOuts = [];
data.nodes.forEach(function (node) {
console.log(node);
if (node.type == 'IO') {
uploadFileGeneralIOids.push(node.id);
uploadFileGeneralResourceOuts.push(node.resourcesOut);
} else if (node.type == 'nested') {
var localNodes = getScaleFreeNetwork();
if (node.action != undefined) {
localNodes.nodes.add(node.action[0].module.graph.nodes);
localNodes.nodes.forEach(function (node2) {//current one level
if (node2.type == 'IO') {
uploadFileGeneralIOids.push(node2.id);
uploadFileGeneralResourceOuts.push(node2.resourcesOut);
}
});
}
}
});
uploadedIOids = [];
numberofIOs = uploadFileGeneralIOids.length;
mySubGraphInterval = setInterval(function () {
getStatusforSubGraph();
}, 500);
}
function makeFileName(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
} | 30.269565 | 84 | 0.455042 |
b9cb994a3bafb6b952c08103b6d1a3a4bd6c4744 | 8,584 | js | JavaScript | js/boundgame.js | yoonjonglyu/boundBallGame | ffe28f27c1a57d5db4e743f5ca2a88d2e0ba0a72 | [
"MIT"
] | 1 | 2020-10-10T11:48:56.000Z | 2020-10-10T11:48:56.000Z | js/boundgame.js | yoonjonglyu/boundBallGame | ffe28f27c1a57d5db4e743f5ca2a88d2e0ba0a72 | [
"MIT"
] | null | null | null | js/boundgame.js | yoonjonglyu/boundBallGame | ffe28f27c1a57d5db4e743f5ca2a88d2e0ba0a72 | [
"MIT"
] | null | null | null | const ball = new BallInfo;
const paddle = new PaddleInfo;
const brick = new BrickInfo;
const userRank = new UserRanks;
const stage = new StageInfo;
const items = new ItemInfo;
/**
* @function liveBall
* @description 공 속도 나 튕김등을 제어하면서 지속적으로 움직이는 공을 그린다
*/
function liveBall () {
const ballSpeedLimit = (((ball.canvas.width + ball.canvas.height) / 250) + stage.ballSpeed);
const ballRandom = Math.random() * (Math.random() * ballSpeedLimit);
if(items.ballReactive){
if((ball.ballRadius + ballRandom) < items.maxRadius / 2){
items.minRadius = ballRandom;
} else if((ball.ballRadius - (ball.ballRadius / 2)) > 0) {
items.minRadius = - (ball.ballRadius / 2);
}
ball.ballRadius += items.minRadius;
} else {
ball.ballRadius = (ball.basicRadius - stage.ballRadius);
}
// ball 변화 주기
if(ball.moveX > 0 && ball.moveX < ballSpeedLimit){
ball.moveX = ball.moveX + ballRandom;
} else if(ball.moveX < 0 && ball.moveX > -ballSpeedLimit) {
ball.moveX = ball.moveX - ballRandom;
} else {
if(ball.moveX > 0){
ball.moveX = ballSpeedLimit - ballRandom;
} else {
ball.moveX = -ballSpeedLimit + ballRandom;
}
}
if(ball.moveY > 0 && ball.moveY < ballSpeedLimit){
ball.moveY = ball.moveY + ballRandom;
} else if(ball.moveY < 0 && ball.moveY > -ballSpeedLimit){
ball.moveY = ball.moveY - ballRandom;
} else {
if(ball.moveY > 0){
ball.moveY = ballSpeedLimit - ballRandom;
} else {
ball.moveY = -ballSpeedLimit + ballRandom;
}
}
// x 반전
if((ball.x + ball.moveX) > (ball.canvas.width - ball.ballRadius) || (ball.x + ball.moveX) < ball.ballRadius){
ball.moveX = -ball.moveX + ballRandom;
ball.colorIndex++;
}
// y 반전
if(ball.y + ball.moveY < ball.ballRadius){
ball.moveY = -ball.moveY + ballRandom;
ball.colorIndex++;
} else if (ball.y + ball.moveY > ball.canvas.height - (ball.ballRadius/ 2)){
checkGameOver(ballRandom);
}
if(items.ballControl === false){
ball.x += ball.moveX;
ball.y += ball.moveY;
} else {
ball.x = (paddle.x + (paddle.width / 2));
ball.y = (ball.canvas.height - 30);
}
}
/**
* @function drawPaddle
* @description 공을 받아 칠 채를 그리고 이벤트에 따라 이동시킨다
*/
function drawPaddle () {
const paddleSpeed = (paddle.canvas.width / 110);
if(items.paddleCount === 0){
paddle.width = items.paddleBasicWidth;
} else {
paddle.width = (paddle.canvas.width * 2);
}
if(paddle.rightMove && paddle.x < (ball.canvas.width - paddle.width)){
paddle.x += paddleSpeed;
}
else if (paddle.leftMove && paddle.x > 0){
paddle.x -= paddleSpeed;
}
paddle.drawPaddle();
}
/**
* @function checkGameOver
* @description 공이 아래 선 위치에 도착했을때 채(paddle)의 위치를 비교해서 공을 튀기거나 실패에 대한 처리를 한다
* @param {Float} ballRandom
*/
function checkGameOver (ballRandom) {
const init = () => {
items.initItem();
ball.initBall();
paddle.initPaddle();
};
if((ball.x + ball.ballRadius - 2) > paddle.x && (ball.x - ball.ballRadius + 2) < (paddle.x + paddle.width)){
ball.moveY = -ball.moveY + ballRandom;
if(items.paddleCount > 0){
items.paddleCount++;
}
} else {
init();
if((userRank.life - 1) < 0){
userRank.gameOver(userRank.score);
paddle.canvasRender = false;
stage.initStage();
userRank.initGame();
} else {
userRank.life--;
}
}
ball.colorIndex++;
}
/**
* @function getBrick
* @description 벽돌 규격에 맞게 벽돌 2차원 배열을 생성한다
*/
function getBrick () {
for(let c = 0; c < brick.column; c++){
brick.box[c] = [];
for(let r = 0; r < brick.row; r++){
const item = Math.floor(Math.random() * 18);
brick.box[c][r] = {x: 0, y: 0, status: 1, item : item};
}
}
}
/**
* @function drawBrick
* @description get 해온 벽돌 배열 상태에 맞게 벽돌을 그린다
*/
function drawBrick () {
for(let c = 0; c < brick.column; c++){
for(let r = 0; r < brick.row; r++){
if(brick.box[c][r].status === 1){
brick.x = (c * (brick.width + brick.padding)) + brick.offsetX;
brick.y = (r * (brick.height + brick.padding)) + brick.offsetY;
brick.box[c][r].x = brick.x;
brick.box[c][r].y = brick.y;
setItems(brick.box[c][r].item);
brick.drawBricks();
}
}
}
}
/**
* @function setItems
* @description get 해온 벽돌의 아이템 여부에 맞게 벽돌 색깔을 변경한다
* @param {int} item item index
*/
function setItems (item) {
if(items.items.length >= item){
brick.blockIndex = item;
} else {
brick.blockIndex = 0;
}
}
/**
* @function crashBrick
* @description 공과 벽돌사이의 충돌을 감지하고 충돌 이벤트를 발생 시킨다
*/
function crashBrick () {
for(let c = 0; c < brick.column; c++) {
for(let r = 0; r < brick.row; r++) {
const state = brick.box[c][r];
if(state.status === 1) {
if((ball.x + ball.ballRadius) > state.x && (ball.x - ball.ballRadius) < (state.x + brick.width) && (ball.y + ball.ballRadius) > state.y && (ball.y - ball.ballRadius) < (state.y + brick.height)) {
if(items.penetrateCount === 0){
ball.moveY = -ball.moveY;
} else {
items.penetrateCount++;
}
checkItem(state.item);
brick.colorIndex++;
state.status = 0;
userRank.score += (1 + stage.stageLevel);
}
}
}
}
}
/**
* @function checkBrick
* @description 남은 벽돌이 있는지 검사하고 없을 시 새로 벽돌을 생성해준다
*/
async function checkBrick () {
let check = brick.box;
check = await (check.map((array) => array.filter((obj) => obj.status === 1))).filter((array) => array.length > 0);
if(check.length === 0){
getBrick();
stage.stageLevel++;
}
}
/**
* @function checkItem
* @description 벽돌이 격파 될때 해당 벽돌이 보유한 아이템이 있는지 확인하고 있으면 효과를 적용시켜준다
* @param {Int} item item index
*/
function checkItem (item) {
switch (item){
case 1:
items.paddleBasicWidth += (paddle.canvas.width / 30);;
break;
case 2:
items.paddleCount = 1;
if(items.paddleCount === 0){
items.paddleBasicWidth = paddle.width;
}
break;
case 3:
items.penetrateCount = 1;
break;
case 4:
if(items.ballReactive === false){
items.minRadius = ball.ballRadius;
items.maxRadius = (ball.ballRadius * 5)
}
items.ballReactive = true;
break;
case 5:
items.ballControl = true;
break;
default:
break;
}
}
/**
* @function draw
* @description canvas내용물을 request 애니메이션을 통해서 지속적으로 그린다
*/
function draw () {
setStage();
liveBall();
drawPaddle();
checkBrick()
drawBrick();
crashBrick();
if(paddle.canvasRender === true){
requestAnimationFrame(draw);
} else {
readyGame();
}
}
/**
* @function readyGame
* @description 게임 시작 전 대기화면 및 게임 시작 이벤트를 관리한다
*/
function readyGame () {
stage.clearCanvas();
stage.drawReady();
getStage();
getScore();
getBrick();
const readyEvent = (e) => {
stage.canvas.removeEventListener("click", readyEvent);
paddle.canvasRender = true;
requestAnimationFrame(draw);
};
stage.canvas.addEventListener("click", readyEvent);
}
/**
* @function getScore
* @description 점수와 기회를 그린다
*/
function getScore () {
userRank.getScore();
userRank.getLife();
}
/**
* @function getStage
* @description 스테이지 정보 가져오기
*/
function getStage () {
stage.getStage();
}
/**
* @function setStage
* @description 게임에 스테이지 난이도 적용하기
*/
function setStage () {
const stageData = stage.stages[stage.stageLevel];
stage.ballSpeed = stageData.speed;
stage.ballRadius = stageData.radius;
}
/**
* @function init
* @description 즉시 실행함수 이벤트 리스닝 등 1회성 함수들과 draw 함수의 실행을 담당한다
*/
(function init (){
paddle.keyEvent();
paddle.mouseEvent();
userRank.ranksEvent();
stage.stageEvent();
items.itemEvent();
items.getControl();
readyGame();
})(); | 26.412308 | 211 | 0.545317 |
b9cc9552724f9eb44b273febc950e191314b37c0 | 189 | js | JavaScript | src/components/sign-up/styles.js | fhalbiero/crwn-clothing | a40e621b62e739d9d14218c1a8de9b41ba71b4a2 | [
"MIT"
] | 1 | 2020-09-14T11:59:43.000Z | 2020-09-14T11:59:43.000Z | src/components/sign-up/styles.js | fhalbiero/crwn-clothing | a40e621b62e739d9d14218c1a8de9b41ba71b4a2 | [
"MIT"
] | 7 | 2021-03-09T17:44:03.000Z | 2022-02-26T17:50:22.000Z | src/components/sign-up/styles.js | fhalbiero/crwn-clothing | a40e621b62e739d9d14218c1a8de9b41ba71b4a2 | [
"MIT"
] | null | null | null | import styled from 'styled-components';
export const Container = styled.div`
display: flex;
flex-direction: column;
width: 380px;
.title {
margin: 10px 0;
}
`; | 17.181818 | 39 | 0.619048 |
b9ce0c6f22c1257ca2cac0b8ab322d0525a84ba4 | 1,881 | js | JavaScript | node_modules/ganache-core/node_modules/level-sublevel/range.js | mennat1/simple-yield-farm-truffle-version | 343389152c97448a6f1d79f3737bfadb2f819614 | [
"MIT"
] | 97 | 2015-01-01T04:15:27.000Z | 2021-03-06T23:11:35.000Z | node_modules/ganache-core/node_modules/level-sublevel/range.js | mennat1/simple-yield-farm-truffle-version | 343389152c97448a6f1d79f3737bfadb2f819614 | [
"MIT"
] | 89 | 2020-03-13T10:08:30.000Z | 2020-12-10T19:56:00.000Z | node_modules/ganache-core/node_modules/level-sublevel/range.js | mennat1/simple-yield-farm-truffle-version | 343389152c97448a6f1d79f3737bfadb2f819614 | [
"MIT"
] | 31 | 2015-01-28T11:17:11.000Z | 2021-07-02T14:49:32.000Z | var ltgt = require('ltgt')
//compare two array items
function isArrayLike (a) {
return Array.isArray(a) || Buffer.isBuffer(a)
}
function isPrimitive (a) {
return 'string' === typeof a || 'number' === typeof a
}
function has(o, k) {
return Object.hasOwnProperty.call(o, k)
}
function compare (a, b) {
if(isArrayLike(a) && isArrayLike(b)) {
var l = Math.min(a.length, b.length)
for(var i = 0; i < l; i++) {
var c = compare(a[i], b[i])
if(c) return c
}
return a.length - b.length
}
if(isPrimitive(a) && isPrimitive(b))
return a < b ? -1 : a > b ? 1 : 0
throw new Error('items not comparable:'
+ JSON.stringify(a) + ' ' + JSON.stringify(b))
}
//this assumes that the prefix is of the form:
// [Array, string]
function prefix (a, b) {
if(a.length > b.length) return false
var l = a.length - 1
var lastA = a[l]
var lastB = b[l]
if(typeof lastA !== typeof lastB)
return false
if('string' == typeof lastA
&& 0 != lastB.indexOf(lastA))
return false
//handle cas where there is no key prefix
//(a hook on an entire sublevel)
if(a.length == 1 && isArrayLike(lastA)) l ++
while(l--) {
if(compare(a[l], b[l])) return false
}
return true
}
exports = module.exports = function (range, key, _compare) {
_compare = _compare || compare
//handle prefix specially,
//check that everything up to the last item is equal
//then check the last item starts with
if(isArrayLike(range)) return prefix(range, key)
return ltgt.contains(range, key, _compare)
}
function addPrefix(prefix, range) {
var o = ltgt.toLtgt(range, null, function (key) {
return [prefix, key]
})
//if there where no ranges, then then just use a prefix.
if(!has(o, 'gte') && !has(o, 'lte')) return [prefix]
return o
}
exports.compare = compare
exports.prefix = prefix
exports.addPrefix = addPrefix
| 22.939024 | 60 | 0.631047 |
b9cf7b5bec0b774bb9c371942f6af09e28e734e2 | 86 | js | JavaScript | public/javascripts/app.js | BrandonWeng/padevo | a75669231ec3c6b125a64fe0027e7a114f61ac30 | [
"MIT"
] | 1 | 2017-06-04T16:44:11.000Z | 2017-06-04T16:44:11.000Z | public/javascripts/app.js | BrandonWeng/padevo | a75669231ec3c6b125a64fe0027e7a114f61ac30 | [
"MIT"
] | 8 | 2017-07-11T03:04:29.000Z | 2021-04-06T00:50:52.000Z | public/javascripts/app.js | BrandonWeng/padevo | a75669231ec3c6b125a64fe0027e7a114f61ac30 | [
"MIT"
] | null | null | null | var mainModule = angular.module('main', []); // add services
mainModule.controller()
| 21.5 | 60 | 0.709302 |
b9d0d43227f59ad49134a6651cc9701578cc0fe2 | 81 | js | JavaScript | app/templates/src/scripts/app.js | lukeed/generator-fly-webapp | c28601e836fe0a15325b66a1f502b8c17dac3b3b | [
"MIT"
] | 6 | 2016-01-03T06:25:02.000Z | 2016-05-02T14:49:14.000Z | app/templates/src/scripts/app.js | lukeed/generator-fly-webapp | c28601e836fe0a15325b66a1f502b8c17dac3b3b | [
"MIT"
] | 5 | 2016-01-03T06:26:31.000Z | 2016-01-03T06:46:04.000Z | app/templates/src/scripts/app.js | lukeed/generator-fly-starter | c28601e836fe0a15325b66a1f502b8c17dac3b3b | [
"MIT"
] | null | null | null | /* globals console */
const name = 'Johnny boy';
console.log(`Hello ${name}!!`);
| 20.25 | 31 | 0.62963 |
b9d0e0a8eac2ac5dc778152360d9451fb46d8790 | 5,561 | js | JavaScript | lib/hyperapp.js | SiddharthaSarma/hyperapp-todo-app-example | 4b65e9d8ee4fce43cec6d6e98edc64c6a0bc926a | [
"MIT"
] | null | null | null | lib/hyperapp.js | SiddharthaSarma/hyperapp-todo-app-example | 4b65e9d8ee4fce43cec6d6e98edc64c6a0bc926a | [
"MIT"
] | null | null | null | lib/hyperapp.js | SiddharthaSarma/hyperapp-todo-app-example | 4b65e9d8ee4fce43cec6d6e98edc64c6a0bc926a | [
"MIT"
] | null | null | null | !(function(n, e) {
'object' == typeof exports && 'undefined' != typeof module
? e(exports)
: ('function' == typeof define && define.amd) || e((n.hyperapp = {}));
})(this, function(n) {
'use strict';
(n.h = function(n, e) {
for (var r, o = [], t = [], i = arguments.length; i-- > 2; )
o.push(arguments[i]);
for (; o.length; )
if (Array.isArray((r = o.pop()))) for (i = r.length; i--; ) o.push(r[i]);
else null != r && !0 !== r && !1 !== r && t.push(r);
return 'function' == typeof n
? n(e || {}, t)
: { name: n, props: e || {}, children: t };
}),
(n.app = function(n, e, r, o) {
function t(n, e) {
return {
name: n.nodeName.toLowerCase(),
props: {},
children: e.call(n.childNodes, function(n) {
return 3 === n.nodeType ? n.nodeValue : t(n, e);
})
};
}
function i() {
y = !y;
var n = r(b, k);
for (o && !y && (N = m(o, N, w, (w = n))); (n = g.pop()); ) n();
}
function l() {
y || ((y = !y), setTimeout(i));
}
function u(n, e) {
var r = {};
for (var o in n) r[o] = n[o];
for (var o in e) r[o] = e[o];
return r;
}
function f(n, e, r) {
var o = {};
return n.length
? ((o[n[0]] = n.length > 1 ? f(n.slice(1), e, r[n[0]]) : e), u(r, o))
: e;
}
function c(n, e) {
for (var r = 0; r < n.length; r++) e = e[n[r]];
return e;
}
function p(n, e, r) {
for (var o in r)
'function' == typeof r[o]
? (function(o, t) {
r[o] = function(o) {
return (
'function' == typeof (o = t(o)) && (o = o(c(n, b), r)),
o &&
o !== (e = c(n, b)) &&
!o.then &&
l((b = f(n, u(e, o), b))),
o
);
};
})(o, r[o])
: p(n.concat(o), (e[o] = e[o] || {}), (r[o] = u(r[o])));
}
function a(n) {
return n && n.props ? n.props.key : null;
}
function s(n, e, r, o, t) {
if ('key' === e);
else if ('style' === e)
for (var i in u(t, r))
n[e][i] = null == r || null == r[i] ? '' : r[i];
else
'function' == typeof r || (e in n && !o)
? (n[e] = null == r ? '' : r)
: null != r && !1 !== r && n.setAttribute(e, r),
(null != r && !1 !== r) || n.removeAttribute(e);
}
function d(n, e) {
var r =
'string' == typeof n || 'number' == typeof n
? document.createTextNode(n)
: (e = e || 'svg' === n.name)
? document.createElementNS('http://www.w3.org/2000/svg', n.name)
: document.createElement(n.name);
if (n.props) {
n.props.oncreate &&
g.push(function() {
n.props.oncreate(r);
});
for (var o = 0; o < n.children.length; o++)
r.appendChild(d(n.children[o], e));
for (var t in n.props) s(r, t, n.props[t], e);
}
return r;
}
function h(n, e, r) {
if ((r = e.props)) {
for (var o = 0; o < e.children.length; o++)
h(n.childNodes[o], e.children[o]);
r.ondestroy && r.ondestroy(n);
}
return n;
}
function v(n, e, r, o) {
function t() {
n.removeChild(h(e, r));
}
r.props && (o = r.props.onremove) ? o(e, t) : t();
}
function m(n, e, r, o, t, i) {
if (o === r);
else if (null == r) e = n.insertBefore(d(o, t), e);
else if (o.name && o.name === r.name) {
!(function(n, e, r, o) {
for (var t in u(e, r))
r[t] !== ('value' === t || 'checked' === t ? n[t] : e[t]) &&
s(n, t, r[t], o, e[t]);
r.onupdate &&
g.push(function() {
r.onupdate(n, e);
});
})(e, r.props, o.props, (t = t || 'svg' === o.name));
for (var l = [], f = {}, c = {}, p = 0; p < r.children.length; p++)
(l[p] = e.childNodes[p]),
null != (w = a((y = r.children[p]))) && (f[w] = [l[p], y]);
p = 0;
for (var h = 0; h < o.children.length; ) {
var y = r.children[p],
N = o.children[h],
w = a(y),
b = a(N);
if (c[w]) p++;
else if (null == b) null == w && (m(e, l[p], y, N, t), h++), p++;
else {
var k = f[b] || [];
w === b
? (m(e, k[0], k[1], N, t), p++)
: k[0]
? m(e, e.insertBefore(k[0], l[p]), k[1], N, t)
: m(e, l[p], null, N, t),
h++,
(c[b] = N);
}
}
for (; p < r.children.length; )
null == a((y = r.children[p])) && v(e, l[p], y), p++;
for (var p in f) c[f[p][1].props.key] || v(e, f[p][0], f[p][1]);
} else
o.name === r.name
? (e.nodeValue = o)
: ((e = n.insertBefore(d(o, t), (i = e))), v(n, i, r));
return e;
}
var y,
g = [],
N = (o && o.children[0]) || null,
w = N && t(N, [].map),
b = u(n),
k = u(e);
return l(p([], b, k)), k;
});
});
//# sourceMappingURL=hyperapp.js.map
| 33.10119 | 79 | 0.349218 |
b9d1c5d053180b6ea32feba31ba9ff89964f5f68 | 838 | js | JavaScript | node_modules/scaledrone-react-native/sock_events.js | khouloudS/RPA_Telecom_Drive_tests | d46e5d6418655516010ffdc00ba983ef0fd4c7f6 | [
"MIT"
] | null | null | null | node_modules/scaledrone-react-native/sock_events.js | khouloudS/RPA_Telecom_Drive_tests | d46e5d6418655516010ffdc00ba983ef0fd4c7f6 | [
"MIT"
] | 2 | 2021-10-06T16:49:09.000Z | 2022-02-27T04:31:33.000Z | node_modules/scaledrone-react-native/sock_events.js | khouloudS/RPA_Telecom_Drive_tests | d46e5d6418655516010ffdc00ba983ef0fd4c7f6 | [
"MIT"
] | null | null | null | module.exports = function(sock, emitter, {debug} = {}) {
sock.onopen = function(event) {
if (!sock.old) {
if (debug) {
console.log('[SCALEDRONE DEBUGGER]: open', event);
}
emitter.trigger('open', event);
}
};
sock.onmessage = function(event) {
if (!sock.old) {
if (debug) {
console.log('[SCALEDRONE DEBUGGER]: message', event);
}
emitter.trigger('message', event);
}
};
sock.onclose = function(event) {
if (!sock.old) {
if (debug) {
console.log('[SCALEDRONE DEBUGGER]: close', event);
}
emitter.trigger('close', event);
}
};
sock.onerror = function(error) {
if (!sock.old) {
if (debug) {
console.log('[SCALEDRONE DEBUGGER]: error', error);
}
emitter.trigger('error', error);
}
};
};
| 22.052632 | 61 | 0.534606 |
b9d1d0cc7626c85b3c7de060e2f2ce67120a42ae | 39 | js | JavaScript | packages/2014/01/21/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 7 | 2017-07-03T19:53:01.000Z | 2021-04-05T18:15:55.000Z | packages/2014/01/21/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 1 | 2018-09-05T11:53:41.000Z | 2018-12-16T12:36:21.000Z | packages/2014/01/21/index.js | antonmedv/year | ae5d8524f58eaad481c2ba599389c7a9a38c0819 | [
"MIT"
] | 2 | 2019-01-27T16:57:34.000Z | 2020-10-11T09:30:25.000Z | module.exports = new Date(2014, 0, 21)
| 19.5 | 38 | 0.692308 |
b9d28d59097eea5117e3c7fb52841f490e7fc609 | 12,108 | js | JavaScript | spec/strategies.js | Floofies/Differentia.js | a31b33c5b4619e548b0006c41d1a2b1dc4c2591a | [
"MIT"
] | 12 | 2017-08-24T18:09:21.000Z | 2019-07-27T21:08:40.000Z | spec/strategies.js | Floofies/Differentia.js | a31b33c5b4619e548b0006c41d1a2b1dc4c2591a | [
"MIT"
] | 24 | 2016-12-27T01:26:06.000Z | 2018-08-18T21:44:44.000Z | spec/strategies.js | Floofies/Differentia.js | a31b33c5b4619e548b0006c41d1a2b1dc4c2591a | [
"MIT"
] | 6 | 2018-01-01T17:31:49.000Z | 2021-09-07T10:55:51.000Z | var d = global.d;
describe("forEach", function () {
it("should iterate all nodes and properties", function () {
var keyCounts = global.createKeyCounter();
var testObject = global.testObjects["Multidimensional Cyclic"]();
d.forEach(testObject, function (value, accessor, object) {
keyCounts[accessor]++;
});
//console.info("forEach Traversal & Iteration Results:");
for (var accessor in keyCounts) {
//console.info("Accessor \"" + accessor + "\" was visited " + keyCounts[accessor] + " time(s).");
expect(keyCounts[accessor] > 0).toBe(true);
}
});
});
describe("diff", function () {
it("should return true when two objects differ", function () {
expect(d.diff(global.testObjects["Linear Acyclic"](), global.testObjects["Linear Cyclic"]())).toBe(true);
expect(d.diff(global.testObjects["Multidimensional Cyclic"](), global.testObjects["Multidimensional Acyclic"]())).toBe(true);
expect(d.diff(global.testObjects["Linear Cyclic"](), global.testObjects["Multidimensional Acyclic"]())).toBe(true);
});
it("should return false when two objects are the same", function () {
expect(d.diff(global.testObjects["Linear Acyclic"](), global.testObjects["Linear Acyclic"]())).toBe(false);
expect(d.diff(global.testObjects["Linear Cyclic"](), global.testObjects["Linear Cyclic"]())).toBe(false);
expect(d.diff(global.testObjects["Multidimensional Acyclic"](), global.testObjects["Multidimensional Acyclic"]())).toBe(false);
expect(d.diff(global.testObjects["Multidimensional Cyclic"](), global.testObjects["Multidimensional Cyclic"]())).toBe(false);
});
it("should return true when two objects differ using the search index", function () {
expect(d.diff(global.testObjects["Linear Acyclic"](), global.testObjects["Linear Cyclic"](), { 3: null })).toBe(true);
});
it("should return false when two objects are the same using the search index", function () {
expect(d.diff(global.testObjects["Linear Acyclic"](), global.testObjects["Linear Cyclic"](), { 1: null })).toBe(false);
});
});
describe("clone", function () {
it("should make an exact copy of the subject", function () {
var clone = d.clone(global.testObjects["Linear Acyclic"]());
expect(global.testDiff(clone, global.testObjects["Linear Acyclic"]())).toBe(false);
clone = d.clone(global.testObjects["Linear Cyclic"]());
expect(global.testDiff(clone, global.testObjects["Linear Cyclic"]())).toBe(false);
clone = d.clone(global.testObjects["Multidimensional Cyclic"]());
expect(global.testDiff(clone, global.testObjects["Multidimensional Cyclic"]())).toBe(false);
});
it("should clone properties using the search index", function () {
var clone = d.clone(global.testObjects["Linear Acyclic"](), { 2: null });
var search = { 2: Number };
expect(global.testDiff(clone, global.testObjects["Linear Acyclic"](), search)).toBe(false);
search = [{
address: {
geo: {
lat: null
}
}
}];
clone = d.clone(global.testObjects["Multidimensional Cyclic"](), search);
expect(global.testDiff(clone, global.testObjects["Multidimensional Cyclic"](), search)).toBe(false);
});
});
describe("diffClone", function () {
var subject = { "hello": "world", "how": "are you?", "have a": "good day" };
var compare = { "hello": "world", "whats": "up?", "have a": "good night" };
it("should clone properties that differ", function () {
var clone = d.diffClone(subject, compare);
expect(global.testDiff(clone, { "how": "are you?", "have a": "good day" })).toBe(false);
});
it("should clone properties that differ using the search index", function () {
var clone = d.diffClone(subject, compare, { "how": null });
expect(global.testDiff(clone, { "how": "are you?" })).toBe(false);
});
});
describe("find", function () {
it("should return a value if it passes the test", function () {
expect(d.find(global.testObjects["Multidimensional Cyclic"](), function (value, accessor, object) {
return value === -37.3159;
})).toBe(-37.3159);
});
it("should return undefined if no values pass the test", function () {
expect(d.find(global.testObjects["Multidimensional Cyclic"](), function (value, accessor, object) {
return value === "This string does not exist in the test object!";
})).toBeUndefined();
});
});
describe("every", function () {
var testObject = [10, 11, 12, 13, 14, 15];
it("should return true if all values pass the test", function () {
expect(d.every(testObject, function (value, accessor, object) {
return typeof value === "number" && value >= 10;
})).toBe(true);
});
it("should return false if one value fails the test", function () {
expect(d.every(testObject, function (value, accessor, object) {
return typeof value === "number" && value < 13;
})).toBe(false);
});
});
describe("some", function () {
var testObject = [10, 11, 12, 13, 14, 15];
it("should return true if one value passes the test", function () {
expect(d.some(testObject, function (value, accessor, object) {
return typeof value === "number" && value === 13;
})).toBe(true);
});
it("should return false if no values pass the test", function () {
expect(d.some(testObject, function (value, accessor, object) {
return typeof value === "number" && value < 10;
})).toBe(false);
});
});
describe("deepFreeze", function () {
it("should freeze all nodes and properties", function () {
var frozenObject = d.deepFreeze(d.clone(global.testObjects["Multidimensional Cyclic"]()));
expect(d.every(frozenObject, function (value, accessor, object) {
return Object.isFrozen(object) && d.utils.isContainer(value) ? Object.isFrozen(value) : true;
})).toBe(true);
});
});
describe("deepSeal", function () {
it("should seal all nodes and properties", function () {
var sealedObject = d.deepSeal(d.clone(global.testObjects["Multidimensional Cyclic"]()));
expect(d.every(sealedObject, function (value, accessor, object) {
return Object.isSealed(object) && d.utils.isContainer(value) ? Object.isSealed(value) : true;
})).toBe(true);
});
});
describe("map", function () {
it("should map all elements", function () {
var start = [2, 4, 6, 8, 10, 12];
var mapped = [3, 5, 7, 9, 11, 13];
expect(global.testDiff(d.map(start, value => value + 1), mapped)).toBe(false);
});
});
describe("nodePaths", function () {
it("should return an array of all node/object paths", function () {
var expectedPaths = [
["0"],
["1"],
["0", "address"],
["0", "company"],
["1", "address"],
["1", "company"],
["0", "address", "geo"],
["1", "address", "geo"]
];
expect(global.testDiff(d.nodePaths(global.testObjects["Multidimensional Acyclic"]()), expectedPaths)).toBe(false);
expectedPaths = [
["0"],
["1"],
["0", "address"],
["0", "company"],
["1", "address"],
["1", "company"],
["0", "address", "geo"],
["1", "address", "geo"],
["0", "otherUser"],
["1", "otherUser"]
];
expect(global.testDiff(d.nodePaths(global.testObjects["Multidimensional Cyclic"]()), expectedPaths)).toBe(false);
});
});
describe("paths", function () {
const expectedPaths = [
["0"],
["1"],
["0", "id"],
["0", "name"],
["0", "username"],
["0", "email"],
["0", "regex"],
["0", "address"],
["0", "website"],
["0", "company"],
["1", "id"],
["1", "name"],
["1", "username"],
["1", "email"],
["1", "regex"],
["1", "address"],
["1", "website"],
["1", "company"],
["0", "address", "street"],
["0", "address", "suite"],
["0", "address", "city"],
["0", "address", "zipcode"],
["0", "address", "geo"],
["0", "company", "active"],
["0", "company", "name"],
["0", "company", "catchPhrase"],
["0", "company", "bs"],
["1", "address", "street"],
["1", "address", "suite"],
["1", "address", "city"],
["1", "address", "zipcode"],
["1", "address", "geo"],
["1", "company", "active"],
["1", "company", "name"],
["1", "company", "catchPhrase"],
["1", "company", "bs"],
["0", "address", "geo", "lat"],
["0", "address", "geo", "lng"],
["1", "address", "geo", "lat"],
["1", "address", "geo", "lng"]
];
it("should return an array of all node/object/primitive paths", function () {
expect(global.testDiff(d.paths(global.testObjects["Multidimensional Acyclic"]()), expectedPaths)).toBe(false);
});
});
describe("findPath", function () {
it("should return the first found path to the input if one is found", function () {
var expectedPath = ["0", "address", "geo", "lng"];
expect(global.testDiff(d.findPath(global.testObjects["Multidimensional Acyclic"](), 81.1496), expectedPath)).toBe(false);
expectedPath = ["1", "company", "name"];
expect(global.testDiff(d.findPath(global.testObjects["Multidimensional Acyclic"](), "Deckow-Crist"), expectedPath)).toBe(false);
});
it("should return null if a path to the input is not found", function () {
expect(d.findPath(global.testObjects["Multidimensional Acyclic"](), "This value does not exist!")).toBe(null);
})
});
describe("findPaths", function () {
it("should return the all paths to the input if any are found", function () {
var expectedPaths = [
["path2", "path22"],
["path1", "path12", "path13", "5"]
];
expect(global.testDiff(d.findPaths(global.testObjects["Multireference"](), "Hello!"), expectedPaths)).toBe(false);
expectedPaths = [
["0", "website"],
["1", "website"]
];
expect(global.testDiff(d.findPaths(global.testObjects["Multidimensional Cyclic"](), null), expectedPaths)).toBe(false);
});
it("should return null if a path to the input is not found", function () {
expect(d.findPaths(global.testObjects["Multidimensional Acyclic"](), "This value does not exist!")).toBe(null);
})
});
describe("findShortestPath", function () {
it("should find the shortest path to the value", function () {
var expectedPath = ["path2", "path22", "2"];
expect(global.testDiff(d.findShortestPath(global.testObjects["Multipath"](), 2), expectedPath)).toBe(false)
});
});
describe("diffPaths", function () {
it("should return an array of paths that differ", function () {
var expectedPaths = [
["0"],
["1"],
["0", "id"],
["0", "name"],
["0", "username"],
["0", "email"],
["0", "regex"],
["0", "address"],
["0", "website"],
["0", "company"],
["0", "otherUser"],
["1", "id"],
["1", "name"],
["1", "username"],
["1", "email"],
["1", "regex"],
["1", "address"],
["1", "website"],
["1", "company"],
["1", "otherUser"],
["0", "address", "street"],
["0", "address", "suite"],
["0", "address", "city"],
["0", "address", "zipcode"],
["0", "address", "geo"],
["0", "company", "active"],
["0", "company", "name"],
["0", "company", "catchPhrase"],
["0", "company", "bs"],
["1", "address", "street"],
["1", "address", "suite"],
["1", "address", "city"],
["1", "address", "zipcode"],
["1", "address", "geo"],
["1", "company", "active"],
["1", "company", "name"],
["1", "company", "catchPhrase"],
["1", "company", "bs"],
["0", "address", "geo", "lat"],
["0", "address", "geo", "lng"],
["1", "address", "geo", "lat"],
["1", "address", "geo", "lng"]
];
expect(global.testDiff(d.diffPaths(global.testObjects["Multidimensional Cyclic"](), global.testObjects["Linear Acyclic"]()), expectedPaths)).toBe(false);
});
});
describe("filter", function () {
it("should clone values which pass the test", function () {
var expectedObject = [
{
"id": 1,
"address": {
"zipcode": 92998,
"geo": {
"lat": -37.3159,
"lng": 81.1496
}
}
},
{
"id": 2,
"address": {
"zipcode": 90566,
"geo":
{
"lat": -43.9509,
"lng": -34.4618
}
}
}
];
expect(global.testDiff(d.filter(global.testObjects["Multidimensional Acyclic"](), value => typeof value === "number"), expectedObject)).toBe(false);
});
it("should return an empty array if no values pass the test", function () {
var clone = d.filter(global.testObjects["Multidimensional Acyclic"](), value => value === "This value does not exist!");
expect(Array.isArray(clone) && clone.length === 0).toBe(true);
});
}); | 35.822485 | 155 | 0.614883 |
67569e633119a19f7db9cda7808c4f2b541aa492 | 54 | js | JavaScript | resources/PaxHeader/ProgressIndicator.js | Bvdldf/ABP | 245d36043db59568fc373951dc477ba4c8454c77 | [
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null | resources/PaxHeader/ProgressIndicator.js | Bvdldf/ABP | 245d36043db59568fc373951dc477ba4c8454c77 | [
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null | resources/PaxHeader/ProgressIndicator.js | Bvdldf/ABP | 245d36043db59568fc373951dc477ba4c8454c77 | [
"PHP-3.0",
"Apache-2.0",
"ECL-2.0"
] | null | null | null | 30 mtime=1556803213.713600825
24 SCHILY.fflags=extent
| 18 | 29 | 0.851852 |
6756d09d8b6e770c654b13f3ee7707a3836e49c5 | 1,096 | js | JavaScript | freeCodeCamp-full-course/3_SASS/08_use-partials-using-split.js | fernandoarmonellifiedler/front-end-libraries | 858cef85917829b49bd969cdf37bd900eb53fb7a | [
"MIT"
] | null | null | null | freeCodeCamp-full-course/3_SASS/08_use-partials-using-split.js | fernandoarmonellifiedler/front-end-libraries | 858cef85917829b49bd969cdf37bd900eb53fb7a | [
"MIT"
] | null | null | null | freeCodeCamp-full-course/3_SASS/08_use-partials-using-split.js | fernandoarmonellifiedler/front-end-libraries | 858cef85917829b49bd969cdf37bd900eb53fb7a | [
"MIT"
] | null | null | null | /* Split Your Styles into Smaller Chunks with Partials
Partials in Sass are separate files that hold segments of CSS code. These are imported and used in other Sass files. This is a great way to group similar code into a module to keep it organized.
Names for partials start with the underscore (_) character, which tells Sass it is a small segment of CSS and not to convert it into a CSS file. Also, Sass files end with the .scss file extension. To bring the code in the partial into another Sass file, use the @import directive.
For example, if all your mixins are saved in a partial named "_mixins.scss", and they are needed in the "main.scss" file, this is how to use them in the main file:
@import 'mixins'
Note that the underscore and file extension are not needed in the import statement - Sass understands it is a partial. Once a partial is imported into a file, all variables, mixins, and other code are available to use.
--------------
Write an @import statement to import a partial named _variables.scss into the main.scss file.
<!-- The main.scss file -->
@import 'variables'
*/ | 68.5 | 280 | 0.760036 |