max_stars_repo_path
stringlengths 3
961
| max_stars_repo_name
stringlengths 5
122
| max_stars_count
int64 0
224k
| id
stringlengths 1
8
| content
stringlengths 2
1.07M
| score
float64 -0.95
3.88
| int_score
int64 0
4
|
---|---|---|---|---|---|---|
_/Chapter07/subjects/behavior-subject.js | paullewallencom/angular-978-1-7871-2240-6 | 0 | 15990716 | let behaviorSubject = new Rx.BehaviorSubject("default value");
// will emit 'default value'
behaviorSubject.subscribe(data => console.log(data));
// long running AJAX scenario
setTimeout(() => {
return Rx.Observable.ajax("data.json")
.map(r => r.response)
.subscribe(data => behaviorSubject.next(data));
}, 12000);
| 1.273438 | 1 |
0x03/08-external-data-load.js | javierandresgp/formio | 2 | 15990724 | /* You can load in data from an external API as a result of values entered in a
form. */
Formio.icons = "fontawesome";
Formio.createForm(
document.getElementById("formio"),
"https://examples.form.io/customerload"
).then(function (form) {
// Triggered when they click the submit button.
form.on("change", function (event) {
if (
event.changed &&
event.changed.component.key === "customerNumber" &&
event.changed.value
) {
Formio.fetch(
"https://examples.form.io/customers/submission?data.number=" +
event.changed.value,
{
headers: {
"content-type": "application/json",
},
mode: "cors",
}
).then(function (response) {
response.json().then(function (result) {
if (Array.isArray(result) && result.length > 0) {
var submission = { data: event.data };
submission.data.name = result[0].data.name;
submission.data.phoneNumber = result[0].data.phonenumber;
form.submission = submission;
}
});
});
}
});
});
| 1.390625 | 1 |
src/Week/index.js | the1codemaster/TennisFolderInventory | 0 | 15990732 | import React, { Component } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { select, unselect, refresh } from './WeekActions';
import { doNTimes, getWeekdays } from '../utilities';
import Slot from './Slot';
import styles from './styles.scss';
export const Week = ({ slotsPerTime, timeDuration, times, startDate, league, affiliationId }) => {
const weekdays = getWeekdays(startDate);
// Generate the starting date, and the ending date.
const weekDatesFormat = 'MMMM D, YYYY';
const weekStartDay = moment(startDate).weekday(0).format(weekDatesFormat);
const weekEndDay = moment(startDate).weekday(6).format(weekDatesFormat);
// gets hours and seconds out of a time.
const destructTime = (time) => {
const matches = time.match(/(\d+):(\d+)\s*(am|pm)/i);
console.log(matches);
return {
m: parseInt(matches[2]),
h: (matches[3].toLowerCase() == 'pm' ? 12 + parseInt(matches[1]) : parseInt(matches[1]))
};
};
// Time slots, contains destructed infor about the times.
const destructedTimes = [
destructTime(times.morning), destructTime(times.midday), destructTime(times.evening)
];
// Renders the individual time slot.
const renderTimeSlot = (time) => (n) => {
const timeData = destructedTimes[time];
const date = moment(startDate).weekday(0).add(n, 'days').minutes(timeData.m).hours(timeData.h);
const slots = doNTimes(slotsPerTime)((i) => {
return <Slot key={i}
index={i}
date={date.clone()}
time={time}
league={league}
affiliationId={affiliationId} />
});
return (
<td key={n}>
<div className={styles.slotsContainer}>
{slots}
</div>
</td>
)
};
return (
<div>
<span className={styles.title}>{weekStartDay} - {weekEndDay}</span>
<table className={styles.container}>
<tbody>
<tr>
<th></th>
{weekdays.map((day, index) => {
return (
<th key={index}>
<div>
<span>{day.weekday}</span>
<span>{day.month} {day.date}</span>
</div>
</th>
)
})}
</tr>
<tr>
<th>{times.morning}</th>
{doNTimes(7)(renderTimeSlot(0))}
</tr>
<tr>
<th>{times.midday}</th>
{doNTimes(7)(renderTimeSlot(1))}
</tr>
<tr>
<th>{times.evening}</th>
{doNTimes(7)(renderTimeSlot(2))}
</tr>
</tbody>
</table>
</div>
)
}
let hasRefreshed = false;;
export const WeekContainer = ({ leagueTitle, slotsPerTime, timeDuration, times, league, affiliationId, startDate, refresh, numbWeeks = 15 }) => {
if (league && affiliationId && hasRefreshed !== league) {
refresh({ type: league, affiliationId});
hasRefreshed = league;
}
const weeks = doNTimes(numbWeeks)((n) => {
return (
<Week slotsPerTime={slotsPerTime}
timeDuration={timeDuration}
times={times}
league={league}
startDate={moment(startDate).add(n, 'weeks')}
affiliationId={affiliationId}
key={n} />
);
});
return (
<div className={styles.weekContainer}>
<span className={styles.leagueTitle}>{leagueTitle}</span>
{weeks}
</div>
);
};
const mapStateToProps = (state) => {
return {
slotsPerTime: state.setup.slotsPerTime,
timeDuration: state.setup.timeDuration,
times: state.setup.times,
league: state.league.current.id,
leagueTitle: state.league.current.title,
affiliationId: state.setup.affiliationId,
startDate: state.setup.startDate
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
refresh: ({type, affiliationId}) => dispatch(refresh({ type, affiliationId }))
}
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(WeekContainer);
| 2.046875 | 2 |
src/logger.js | ragerxlol/ragerx-foss-frontend-api | 2 | 15990740 | import { general } from './constants'
import dateFormat from 'dateformat'
import fs from 'fs'
import { format } from 'util'
class Logger {
constructor() {
this.path = null
this.stream = null
this.setLogFile(general.logfile)
this.openLogFile()
}
setLogFile(path) {
this.path = path
}
openLogFile() {
if(this.stream) {
this.stream.end()
}
this.stream = fs.createWriteStream(this.path, {flags:'a'})
}
log(level, type, message, params=[], ctx=null) {
const timestamp = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss.l')
message = format(message, ...params)
if(ctx) {
message = `${timestamp} [${type}] [${ctx.ip}] [${ctx.controller}/${ctx.action}] [${ctx.method}] ${message}`
} else {
message = `${timestamp} [${type}] ${message}`
}
if(this.stream) {
this.stream.write(message+'\n')
}
const color_reset = '\x1b[0m'
let color = color_reset
switch(level) {
case 'error':
color = '\x1b[31m'
break
case 'success':
color = '\x1b[32m'
break
case 'warn':
color = '\x1b[33m'
break
case 'info':
color = '\x1b[34m'
break
}
console.log(color+message+color_reset)
}
}
const instance = new Logger()
process.on('SIGHUP', () => {
instance.openLogFile()
})
export default instance
| 1.71875 | 2 |
Lab3/Documentation/doxygen/html/_u_a_r_t_8c.js | MenkaMehta/48434-embedded-software-Labs | 1 | 15990748 | var _u_a_r_t_8c =
[
[ "__attribute__", "group___u_a_r_t__module.html#ga445500277ba0e363873b34cffc015745", null ],
[ "UART_InChar", "group___u_a_r_t__module.html#ga03049bcc3bf9af2a75ee77016d3b0d60", null ],
[ "UART_Init", "group___u_a_r_t__module.html#gae5760d1a086ec79a33901db253000af9", null ],
[ "UART_OutChar", "group___u_a_r_t__module.html#gab20ebaeefd1f29d31e098ade31189dda", null ],
[ "RxFIFO", "group___u_a_r_t__module.html#ga57a6bee2e32f83a4a1b52c99299794b8", null ],
[ "TxFIFO", "group___u_a_r_t__module.html#gabfc40789d380623f1ba598e006927b5e", null ]
]; | 0.183594 | 0 |
src/modules/Context/index.js | kk-tec/react-demo | 0 | 15990756 | import React, { Component } from 'react'
import { ThemeContext, themes } from './ThemeContext'
import ThemedButton from './ThemedButton'
// 一个使用 ThemedButton 的中间组件
function Toolbar(props) {
return <ThemedButton onClick={props.changeTheme}>Change Theme</ThemedButton>
}
class Context extends Component {
constructor(props) {
super(props)
this.state = {
theme: themes.light
}
this.toggleTheme = () => {
this.setState(state => ({
theme: state.theme === themes.dark ? themes.light : themes.dark
}))
}
}
render() {
// 在 ThemeProvider 内部的 ThemedButton 按钮组件使用 state 中的 theme 值,
// 而外部的组件使用默认的 theme 值
return (
<div>
<ThemeContext.Provider value={this.state.theme}>
<Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
<ThemedButton />
</div>
)
}
}
export default Context
| 1.523438 | 2 |
__tests__/Combination.test.js | SenFullDev66/React-D3-Silky-Charts | 42 | 15990764 | import React from 'react';
import { Combination } from '../src';
import { render, cleanup } from 'react-testing-library';
import { data, dataWidthDates } from '../__mocks__/combination';
import 'jest-styled-components';
const props = {
data,
lineSeries: ['cherries', 'dates'],
stackedSeries: ['apples', 'bananas'],
visibleTicks: true,
};
afterEach(cleanup);
test('Combination', () => {
const { container } = render(<Combination {...props} />);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Combination with dates', () => {
const { container } = render(
<Combination {...props} data={dataWidthDates} />
);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Bar responsive', () => {
const { container } = render(<Combination {...props} responsive />);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Bar with width', () => {
const { container } = render(<Combination {...props} width={100} />);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Bar with height', () => {
const { container } = render(<Combination {...props} height={100} />);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Combination width grid', () => {
const { container } = render(<Combination {...props} grid />);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Combination with Title, X label, Y label', () => {
const { container } = render(
<Combination
{...props}
title={'Test title'}
xAxisChartLabel={'Test X label'}
yAxisChartLabel={'Test Y label'}
/>
);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Combination with source', () => {
const { container } = render(
<Combination {...props} dataSource="Test source" />
);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Combination with source link', () => {
const { container } = render(
<Combination
{...props}
dataSource={{ href: '#', target: 'foo', title: 'combination' }}
/>
);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
test('Combination with X label rotation', () => {
const { container } = render(<Combination {...props} xAxisLabelRotation />);
const combination = container.firstChild;
expect(combination).toMatchSnapshot();
});
| 1.5625 | 2 |
modules/programs/client/config/programs.client.routes.js | shteeven/scradio | 0 | 15990772 | 'use strict';
// Setting up route
angular.module('programs').config(['$stateProvider',
function ($stateProvider) {
// Programs state routing
$stateProvider
.state('programs', {
abstract: true,
url: '/programs',
template: '<ui-view/>',
controller: 'ProgramsController'
})
.state('programs.list', {
url: '',
templateUrl: 'modules/programs/client/views/list-programs.client.view.html'
})
.state('programs.create', {
url: '/create',
templateUrl: 'modules/programs/client/views/create-program.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('programs.view', {
url: '/:programId',
templateUrl: 'modules/programs/client/views/view-program.client.view.html'
})
.state('programs.edit', {
url: '/:programId/edit',
templateUrl: 'modules/programs/client/views/edit-program.client.view.html',
data: {
roles: ['user', 'admin']
}
});
}
]);
| 1.03125 | 1 |
app/components/endpoint/endpointController.js | d-apurva/click2cloud | 0 | 15990780 | angular.module('endpoint', [])
.controller('EndpointController', ['$scope', '$state', '$stateParams', '$filter', 'EndpointService', 'Notifications',
function ($scope, $state, $stateParams, $filter, EndpointService, Notifications) {
if (!$scope.applicationState.application.endpointManagement) {
$state.go('endpoints');
}
$scope.state = {
error: '',
uploadInProgress: false
};
$scope.formValues = {
TLSCACert: null,
TLSCert: null,
TLSKey: null
};
$scope.updateEndpoint = function() {
var ID = $scope.endpoint.Id;
var endpointParams = {
name: $scope.endpoint.Name,
URL: $scope.endpoint.URL,
PublicURL: $scope.endpoint.PublicURL,
TLS: $scope.endpoint.TLS,
TLSCACert: $scope.formValues.TLSCACert !== $scope.endpoint.TLSCACert ? $scope.formValues.TLSCACert : null,
TLSCert: $scope.formValues.TLSCert !== $scope.endpoint.TLSCert ? $scope.formValues.TLSCert : null,
TLSKey: $scope.formValues.TLSKey !== $scope.endpoint.TLSKey ? $scope.formValues.TLSKey : null,
type: $scope.endpointType
};
EndpointService.updateEndpoint(ID, endpointParams)
.then(function success(data) {
Notifications.success('Endpoint updated', $scope.endpoint.Name);
$state.go('endpoints');
}, function error(err) {
$scope.state.error = err.msg;
}, function update(evt) {
if (evt.upload) {
$scope.state.uploadInProgress = evt.upload;
}
});
};
function getEndpoint(endpointID) {
$('#loadingViewSpinner').show();
EndpointService.endpoint($stateParams.id).then(function success(data) {
$('#loadingViewSpinner').hide();
$scope.endpoint = data;
if (data.URL.indexOf('unix://') === 0) {
$scope.endpointType = 'local';
} else {
$scope.endpointType = 'remote';
}
$scope.endpoint.URL = $filter('stripprotocol')(data.URL);
$scope.formValues.TLSCACert = data.TLSCACert;
$scope.formValues.TLSCert = data.TLSCert;
$scope.formValues.TLSKey = data.TLSKey;
}, function error(err) {
$('#loadingViewSpinner').hide();
Notifications.error('Failure', err, 'Unable to retrieve endpoint details');
});
}
getEndpoint($stateParams.id);
}]);
| 1.054688 | 1 |
src/app/routes.js | vedovelli/vue-boilerplate | 30 | 15990788 | import Vue from 'vue'
import VueRouter from 'vue-router'
const Home = r => require.ensure([], () => r(require('./modules/Home/Home.vue')), 'home')
const ErrorPage = r => require.ensure([], () => r(require('./modules/Error/Error.vue')), 'error')
Vue.use(VueRouter)
export const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '*',
name: 'error',
component: ErrorPage
}
]
export default new VueRouter({
mode: 'history',
routes
})
| 1.054688 | 1 |
service/kirjaAPI.js | sovelto-tommi/shuhuibanushas | 0 | 15990796 | const express = require('express');
const router = express.Router();
const kirjat = require('./kirjat');
const Kirja = require('../service/kirja').Kirja;
/* GET books listing. */
router.route('')
.get((req, res) => {
res.send(kirjat.kaikki());
})
.post((req, res) => {
let kirja;
try {
kirja = new Kirja(req.body);
kirjat.lisää(kirja);
} catch (err) {
res.status(400).send({ error: err.message||'tuntematon virhe' });
}
res.status(201)
.location('http://localhost:3000/api/kirjat/' + kirja.isbn)
.send();
});
router.route('/:isbn')
.get((req, res) => {
// isbn olisi hyvä kaivaa esille
const kirja = kirjat.haeYksi(isbn);
if (!kirja) {
// Tähän olisi hyvä kirjoittaa koodia
} else {
// niin tähänkin
}
});
module.exports = router;
| 1.523438 | 2 |
server/services/index.js | ComfortablyCoding/strapi-plugin-transformer | 16 | 15990804 | 'use strict';
const settingsService = require('./settings-service');
const transformService = require('./transform-service');
module.exports = {
settingsService,
transformService,
};
| 0.423828 | 0 |
pages/shared/window-buttons/window-buttons.js | RAHUL9545416/ytmdesktop | 5 | 15990812 | const { remote, ipcRenderer: ipc } = require("electron");
const electronStore = require("electron-store");
const store = new electronStore();
const { isWindows, isMac, isLinux } = require("../../../utils/systemInfo");
const currentWindow = remote.getCurrentWindow();
const winElement = document.getElementById("win");
const macElement = document.getElementById("mac");
if (isMac()) {
winElement.remove();
macElement.classList.remove("hide");
} else if (isWindows()) {
macElement.remove();
winElement.classList.remove("hide");
} else if (isLinux()) {
winElement.remove();
macElement.remove();
}
if (store.get("titlebar-type", "nice") !== "nice") {
document.getElementById("nice-titlebar").style.display = "none";
document.getElementById("nice-titlebar").style.height = 0;
document.getElementById("webview").style.height = "100vh";
} else {
document.getElementById("webview").style.height = "95vh";
document.getElementById("content").style.marginTop = "29px";
}
ipc.on("window-is-maximized", function(_, value) {
if (value) {
document.getElementById("icon_maximize").classList.add("hide");
document.getElementById("icon_restore").classList.remove("hide");
} else {
document.getElementById("icon_restore").classList.add("hide");
document.getElementById("icon_maximize").classList.remove("hide");
}
});
document.addEventListener("DOMContentLoaded", function() {
checkUrlParams();
document.getElementById("btn-minimize").addEventListener("click", function() {
currentWindow.minimize();
});
document.getElementById("btn-maximize").addEventListener("click", function() {
if (!currentWindow.isMaximized()) {
currentWindow.maximize();
} else {
currentWindow.unmaximize();
}
});
document.getElementById("btn-close").addEventListener("click", function() {
currentWindow.close();
});
});
// var webview = document.getElementById("webview");
// webview.addEventListener("dom-ready", function(){ webview.openDevTools(); });
function checkUrlParams() {
const params = new URL(window.location).searchParams;
let page = params.get("page");
let icon = params.get("icon");
let title = params.get("title");
let hide = params.get("hide");
if (page) {
document.getElementById("webview").src = `../../${page}.html`;
}
if (icon) {
document.getElementById("icon").innerText = icon;
}
if (title) {
// document.getElementById("music-title").innerText = title;
}
if (hide) {
hide = hide.split(",");
hide.forEach(element => {
document.getElementById(element).classList.add("hide");
});
}
}
| 1.492188 | 1 |
docs/search/functions_3.js | dimi309/small3d | 143 | 15990820 | var searchData=
[
['deletelogger_184',['deleteLogger',['../namespacesmall3d.html#ab9c95af461170e41d031a112466c014c',1,'small3d']]],
['deletetexture_185',['deleteTexture',['../classsmall3d_1_1_renderer.html#aa3edaca7521e526b5cf311ed4c541452',1,'small3d::Renderer']]]
];
| -0.109375 | 0 |
index.js | donaldp/interactjs | 3 | 15990828 | let CHANNEL_API = {
"_invoker": null,
"_cached": null,
"_channel": null,
"_callback": null,
"_options": {
"url": "/interact/messages",
"key": null
},
/**
* Refresh channel data
*/
"_refresh": () => {
fetch(CHANNEL_API._options.url, {
headers: {
"Authorization": "Bearer " + CHANNEL_API._options.key,
"Content-Type": "application/json"
},
body: JSON.stringify({ "channel": CHANNEL_API._channel }),
method: "POST"
}).then((response) => { return response.json(); } )
.catch((error) => {
return;
})
.then(response => {
if (JSON.stringify(CHANNEL_API._cached) !== JSON.stringify(response)) {
if (response.message !== null) {
CHANNEL_API._cached = response;
CHANNEL_API._callback(response.message);
}
}
});
}
};
export const channel = {
/**
* Listen to messages
*
* @param {string} channel
* @param {callback} callback
*/
listen: (channel, callback) => {
CHANNEL_API._channel = channel;
CHANNEL_API._callback = callback;
CHANNEL_API._invoker = setInterval(CHANNEL_API._refresh, 2000);
},
/**
* Configure channel
*
* @param {object} options
*/
config: (options) => {
CHANNEL_API._options = {
"url": options.url,
"key": options.key
};
}
};
| 1.507813 | 2 |
dvd.js | Bleyner99/programacionbasica | 0 | 15990836 | var dvd;
dvd <- 1500;
// 1500 = cantidad;
var cantidad = parseInt(prompt("Ingrese la cantidad de peliculas a alquilar",""));
var dias = parseInt(prompt("Ingrese la cantidad de dias a alquilar",""));
// if(cantidad >= 1500 ){
// alert("Gratis por promoción");
// }
var pago = cantidad * dias * 1500 ;
if(cantidad = 7500){
alert("gratis")
}else{
alert("El monto a pagar es de: " + pago);
}
// var pago = cantidad * dias;
//
| 1.53125 | 2 |
test/shared/combinations.js | l0n3star/powerplant | 74 | 15990844 | const assert = require('assert');
const {
Combinations,
areEqualCombinations
} = require('../../shared/combinations.js');
/**
* @return {Combinations}
*/
function createCombinations() {
let elements = [0, 1, 2, 3];
elements = elements.map(number => {
const element = new Number(number);
element.isCompatible = function(anotherElement) {
return this != anotherElement;
};
return element;
});
return new Combinations(elements);
}
/**
* Assert that the given sets of combinations are equal.
*
* @param {Array} actual
* @param {Array} expected
*/
function assertCombinations(actual, expected) {
const equal = actual.every(actualCombination =>
expected.some(expectedCombination =>
areEqualCombinations(actualCombination, expectedCombination)
)
);
assert.equal(
equal,
true,
'Sets of combinations of size ' + actual[0].length + ' are not equal'
);
}
describe('Combinations', () => {
it('generates correct combinations', () => {
const combinations = createCombinations();
assertCombinations([[0], [1], [2], [3]], combinations.getCombinations(1));
assertCombinations(
[[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]],
combinations.getCombinations(2)
);
assertCombinations(
[[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]],
combinations.getCombinations(3)
);
});
it('removes all combinations that contain the removed element', () => {
const combinations = createCombinations();
combinations.removeElement(0);
assertCombinations([[1], [2], [3]], combinations.getCombinations(1));
assertCombinations(
[[1, 2], [1, 3], [2, 3]],
combinations.getCombinations(2)
);
assertCombinations([[1, 2, 3]], combinations.getCombinations(3));
});
});
| 2.421875 | 2 |
stories/molecules/codeExpression/codeExpression.stories.js | stencila/designa | 9 | 15990852 | import { html } from 'lit-html'
export default {
title: 'Schema Nodes/Code Expression',
component: 'stencila-code-expression',
}
const handler = (e) => {
console.log(e)
return {
type: 'CodeExpression',
output: `Results of ${e.text}`,
}
}
export const codeExpression = () => html`
<div>
<stencila-code-expression
programming-language="r"
.executeHandler=${handler}
>
<code class="r" slot="text"
>length(subset(data2, Lot==1 & Time==0)$value)</code
>
<output slot="output">3</output>
</stencila-code-expression>
</div>
`
export const codeExpressionInAParagraph = () => html`
<p>
This is a paragraph with a code expression inside it
<stencila-code-expression data-collapsed="false">
<code slot="text">x * y </code>
<output slot="output">42</output></stencila-code-expression
>
followed by some more text.
</p>
`
export const multipleCodeExpressionsInAParagraph = () => html`
<p>
This is a paragraph with a code expression inside it
<stencila-code-expression data-collapsed="false">
<code slot="text">x * y</code>
<output slot="output">42</output></stencila-code-expression
>
followed by some more text and another
<stencila-code-expression
data-collapsed="false"
itemtype="stencila:CodeChunk"
>
<code slot="text">x * y - 128 * (212 - 2)</code>
<output slot="output">
Reaaaaalllyyyyyyyy loooongggggggggggggggggggg output
</output> </stencila-code-expression
>.
</p>
`
export const codeExpressionWithAnImageOutput = () => html`
<p>
This is a paragraph with a code expression inside it
<stencila-code-expression data-collapsed="false"
><code slot="text">x * y</code
><output slot="output">42</output></stencila-code-expression
>
followed by some more text and another
<stencila-code-expression
data-collapsed="false"
itemtype="stencila:CodeChunk"
>
<code slot="text">x * y - 128 * (212 - 2)</code>
<output slot="output"
><img src="https://place-hold.it/150x200"
/></output> </stencila-code-expression
>.
</p>
`
export const codeExpressionWithNoOutput = () => html`
<p>
This is a paragraph with a code expression inside it
<stencila-code-expression data-collapsed="false"
><code slot="text">x * y</code><output slot="output"></output
></stencila-code-expression>
followed by some more text.
</p>
`
export const codeExpressionWithSymbolsInOutput = () => html`
<p>
This is a paragraph with a code expression inside it
<stencila-code-expression data-collapsed="false"
><code slot="text">x * y</code
><output slot="output"><0.001</output></stencila-code-expression
>
followed by some more text.
</p>
`
| 1.867188 | 2 |
capture_images.js | ScreamingHawk/photo-log | 0 | 15990860 | const NodeWebcam = require("node-webcam");
const fs = require('fs');
const path = require('path');
const INTERVAL_SECONDS = 1
const IMG_FOLDER = "imgs"
// Count the images in the folder
const countImages = () => {
const files = fs.readdirSync(IMG_FOLDER);
return files.length;
}
// Save an image to the folder
const captureImage = () => {
const imageCount = `000000${countImages() + 1}`.slice(-6);
const imageName = `image${imageCount}.jpg`
NodeWebcam.capture(path.join(IMG_FOLDER, imageName), {}, function( err, data ) {
if (err){
console.error(err)
}
if (data){
console.log(data)
}
console.log(`Saving ${imageName}`)
});
}
// Run immediately
captureImage()
// Then run on a schedule
setInterval(captureImage, INTERVAL_SECONDS * 1000)
| 2.109375 | 2 |
asset/js/spc.js | billxu0521/OmekaS-Theme-CCSTWlib-Malaysia | 1 | 15990868 | (function($) {
$(document).ready(function() {
$('#search-form').addClass('closed');
$('.search-toggle').click(function() {
$('#search-form').toggleClass('closed').toggleClass('open');
if ($('#search-form').hasClass('open')) {
$('#query').focus();
}
});
});
})(jQuery) | 0.644531 | 1 |
tests/test.js | marcuslilja/stylus-mq | 2 | 15990876 |
var fs = require('fs');
var assert = require('assert');
var stylus = require('stylus');
var input = fs.readFileSync(__dirname + '/test.styl', 'utf8');
var output = fs.readFileSync(__dirname + '/test.css', 'utf8');
describe('stylus-mq', function () {
it('should preprocess test.styl as expected', function (done) {
stylus(input)
.render(function (err, css) {
if (err) {
throw err;
}
assert.equal(output, css);
done();
});
});
});
| 1.007813 | 1 |
app/src/cuidador/script/cuidador.create.controller.js | pedrohn13/OrganizeBabyFront | 0 | 15990884 | (function () {
angular
.module('users')
.controller('CuidadorCreateController',
['$http', '$location', '$mdDialog', CuidadorCreateController]);
function CuidadorCreateController($http, $location, $mdDialog) {
var root = 'https://leonardoads.pythonanywhere.com/OrganizeBaby/default/api';
var self = this;
self.novoCuid = {idbercario: 1};
self.loading = false;
self.create = create;
self.disableCreateButton = disableCreateButton;
function disableCreateButton() {
return isEmptyValue(self.novoCuid.c_nome) ||
isEmptyValue(self.novoCuid.p_cpf);
}
function isEmptyValue(value) {
return (value === '') || (value === undefined);
}
function create(ev) {
var confirm = $mdDialog.confirm()
.title('Salvar dados do Cuidador?')
.textContent('Os dados cadastrados serão persistidos no sistema.')
.targetEvent(ev)
.ok('OK')
.cancel('CANCELAR');
$mdDialog.show(confirm).then(function () {
self.loading = true;
$http({
method: "POST",
url: root + '/cuidadora.json',
data: self.novoCuid
}).then(function mySucces(response) {
self.loading = false;
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title('Cuidador Criado com Sucesso!')
.ariaLabel('Erro ao carregar')
.ok('OK')
);
$location.path('cuidador.list');
}, function myError(response) {
self.loading = false;
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title('Erro ao realizar operação')
.textContent('Provavelmente erro de conexão, tente novamente mais tarde.')
.ariaLabel('Erro ao carregar')
.ok('OK')
);
});
}, function () {
});
}
}
})();
| 1.304688 | 1 |
public/modules/main/services/main.client.filters.js | pasirauhala/artadvisor | 0 | 15990892 | 'use strict';
// Plain to HTML filter
angular.module('main').filter('plainToHtml', ['$sce', function($sce) {
// Return function
return function(input) {
// If not set
if (!input) return '';
// Html
var arrHtml = [];
// Split by lines
var lines = input.split('\n');
// Loop through lines
for (var i in lines) {
// Trim first
var line = lines[i].trim();
// If there's any
if (line) {
// Replace
line = line.replace(/(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/g, function(e) {
// Find first ://
var find = e.indexOf('://');
return '<a href="'+e+'" target="_blank">'+e.substr(find+3)+'</a>';
});
// Push to arrHtml
arrHtml.push(line);
} else {
arrHtml.push('');
}
}
// Return
return $sce.trustAsHtml('<p>' + arrHtml.join('<br />') + '</p>');
};
}]); | 1.65625 | 2 |
build/bin/build-lib.js | zjw666web/vant- | 0 | 15990900 | /**
* Build npm lib
*/
require('shelljs/global');
const signale = require('signale');
const tasks = [
'lint',
'build:entry',
'build:components',
'build:vant-css',
'build:vant',
'build:style-entry'
];
tasks.forEach(task => {
signale.pending(task);
exec(`npm run ${task} --silent`);
signale.success(task);
});
| 0.828125 | 1 |
skottie/modules/skottie-drive-sk/index.js | bodymovin/skia-buildbot | 0 | 15990908 | import './skottie-drive-sk.js'
import './skottie-drive-sk.scss'
| -0.166992 | 0 |
rules/base.js | pluralcom/eslint-config-plural | 3 | 15990916 | module.exports = {
rules: {
camelcase: 0,
'no-underscore-dangle': 0,
'arrow-parens': 0,
'no-confusing-arrow': 0,
},
};
| 0.25 | 0 |
src/components/PrometheusChart/component/context.js | openstack/skyline-console | 1 | 15990924 | import { createContext } from 'react';
import { defaultOneHourAgo } from '../utils/utils';
const BaseContentContext = createContext({
interval: 10,
range: defaultOneHourAgo(),
node: {
metric: {
hostname: '',
},
},
});
export default BaseContentContext;
| 0.867188 | 1 |
application/views/ajax.js | KaustubhGiri123/Management-Information-System-College | 0 | 15990932 | $(document).ready(function()
{ //choosing scheme on basis of dept
$('#did').change(
function()
{
var d_id=$('#did').val();
alert(d_id);
if(d_id!="")
{
$.ajax({
url:"unit/fetch_sc_id",
method:"POST",
data:{d_id:d_id},
success:function(data)
{ alert("success");
$('#sc_id').html(data);
}
})//ajax end
}
});
//choosing sem on basis of scheme
$('#sc_id').change(
function()
{
var sc_id=$('#sc_id').val();
alert(sc_id);
if(sc_id!="")
{
$.ajax({
url:"unit/fetch_sem_id",
method:"POST",
success:function(data)
{ alert("success");
$('#semid').html(data);
}
})//ajax end
}
});
//choosing course on basis of semister and scheme
$('#semid').change(
function()
{
var sem_id=$('#semid').val();
var sc_id=$('#sc_id').val();
alert(sem_id);
alert(sc_id);
if(sem_id!="")
{
$.ajax({
url:"unit/fetch_c_id",
method:"POST",
data:{sem_id:sem_id,sc_id:sc_id},
success:function(data)
{ alert("success");
$('#cid').html(data);
}
})//ajax end
}
});
}); | 0.859375 | 1 |
config.js | ShowBaba/learnable-test | 0 | 15990940 | module.exports = {
mongoUrl: 'mongodb://localhost:27017/mamaSauceApi',
};
| 0.304688 | 0 |
src/config.js | nningego/cconccourse | 2 | 15990948 | const env = require('env-var');
const url = require('url');
const fetchConfig = () => {
const URL = env.get('URL').required().asString();
const TEAM = env.get('TEAM').default('main').asString();
const AUTH_USERNAME = env.get('AUTH_USERNAME').required().asString();
const AUTH_PASSWORD = env.get('AUTH_PASSWORD').required().asString();
return {
url: new url.URL(URL),
teamName: TEAM,
authentication: {
username: AUTH_USERNAME,
password: <PASSWORD>,
},
};
};
const config = (environment) => {
switch (environment) {
case 'production':
return fetchConfig();
case 'test':
return {
url: new url.URL('http://localhost:1337'),
teamName: 'main',
authentication: {
username: 'some-username',
password: '<PASSWORD>',
},
};
default:
throw new Error('Must set NODE_ENV to production/test');
}
};
module.exports = config(process.env.NODE_ENV);
| 1.3125 | 1 |
src/main/resources/static/reactjs/components/seller/rating.js | PapamichMarios/NotEbay | 5 | 15990956 | import React from 'react';
import StarRatings from 'react-star-ratings';
import getRequest from '../utils/requests/getRequest';
import postRequest from '../utils/requests/postRequest';
import Loading from '../utils/loading/loading';
import * as Constants from '../utils/constants';
import LoadingButton from '../utils/loading/loadingButton';
import { Container, Row, Col, Card, Button, Alert } from 'react-bootstrap';
import { withRouter } from 'react-router-dom';
class SellerRating extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
loadingButton: false,
communicationRating: 1,
serviceRating: 1,
hasRated: false,
hasError: false,
errorMsg: '',
success: false
}
this.changeCommunicationRating = this.changeCommunicationRating.bind(this);
this.changeServiceRating = this.changeServiceRating.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
changeCommunicationRating(newRating, name) {
this.setState({
communicationRating: newRating
});
}
changeServiceRating(newRating, name) {
this.setState({
serviceRating: newRating
});
}
onSubmit(e) {
e.preventDefault();
this.setState({loadingButton: true});
const finalRating = (this.state.communicationRating + this.state.serviceRating) / 2;
const url = '/app/users/' + this.props.match.params.userId + '/bidderRating';
const bodyObj = {
rating: Math.round(finalRating),
itemId: this.props.match.params.itemId
};
postRequest(url, bodyObj)
.then( response => {
if(response.error) {
this.setState({
hasError: true,
errorMsg: response.msg
});
if(response.status === 500) {
this.props.history.push('/internal-server-error');
}
if(response.status === 404) {
this.props.history.push('/buyer-not-found');
}
} else {
this.setState({
success: true
},
() => {
//set loading
setTimeout(() => {
this.setState({loadingButton: false})
}, Constants.TIMEOUT_DURATION);
});
}
})
.catch(error => console.error('Error:', error));
}
componentDidMount() {
const url = '/app/users/' + this.props.match.params.userId
+ '/bidderRating/ratedAlready'
+ '?itemId=' + this.props.match.params.itemId;
getRequest(url)
.then(response => {
if(response.error) {
this.setState({
hasError: true,
errorMsg: response.msg
});
if(response.status === 500) {
this.props.history.push('/internal-server-error');
}
if(response.status === 404) {
this.props.history.push('/buyer-not-found');
}
} else {
this.setState({
hasRated: response
},
() => {
setTimeout(() => {
this.setState({loading: false})
}, Constants.TIMEOUT_DURATION);
});
}
})
.catch(error => console.error('Error', error));
}
render() {
if(this.state.loading) {
return <Loading />
} else {
//if the seller has rated the buyer already
if(this.state.hasRated) {
return(
<Container className="navbar-margin">
<Row>
<Col>
<Alert variant='primary'>
<p> You have already submitted a rating for this auction! </p>
<p>
Thanks for your feedback. It is essential for the
improvement of the user experience and our application in general.
</p>
</Alert>
</Col>
</Row>
</Container>
);
} else {
if(this.state.success) {
return (
<Container className="navbar-margin">
<Row>
<Col>
<Alert variant='success'>
<p> Your rating has been submitted! </p>
<p>
Thanks for your feedback. It is essential for the
improvement of the user experience and our application in general.
</p>
</Alert>
</Col>
</Row>
</Container>
);
} else {
return (
<Container className="navbar-margin">
<Row>
<Col md={{offset:4, span:4}}>
<Card>
<Card.Header as="h5" className="text-center bg-dark" style={{color:'white'}}> <b> Leave feedback </b> </Card.Header>
<Card.Body>
<Row>
<Col>
<b> Communication </b>
<br />
<span style={{color: 'DimGray', fontSize: '14px'}}>Was the buyer responsive and well behaved?</span>
<br />
<StarRatings
name="communicationRating"
numberOfStars={Constants.RATING_STARS}
rating={this.state.communicationRating}
starRatedColor="SandyBrown"
starDimension="40px"
starSpacing="5px"
changeRating={this.changeCommunicationRating}
/>
</Col>
</Row>
<br/>
<Row>
<Col>
<b> Sell Again </b>
<br />
<span style={{color: 'DimGray', fontSize: '14px'}}>Would you sell again to this buyer?</span>
<br />
<StarRatings
name="shippingRating"
numberOfStars={Constants.RATING_STARS}
rating={this.state.serviceRating}
starRatedColor="SandyBrown"
starDimension="40px"
starSpacing="5px"
changeRating={this.changeServiceRating}
/>
</Col>
</Row>
<br />
<Row>
<Col>
{this.state.loadingButton ? (
<Button variant='dark' block disabled>
<b> Loading </b>
<LoadingButton />
</Button>
) : (
<Button variant='dark' block onClick={this.onSubmit}>
<b> Rate Buyer</b>
</Button>
)}
</Col>
</Row>
{this.state.hasError && (
<Row>
<Col>
<Alert variant='danger'>
<p> {this.state.errorMsg} </p>
</Alert>
</Col>
</Row>
)}
</Card.Body>
</Card>
</Col>
</Row>
</Container>
);
}
}
}
}
}
export default withRouter(SellerRating); | 1.632813 | 2 |
Intro to JS Unit testing/textUtilities Example/textUtilities.js | LightLordYT/Traversy-Courses | 1 | 15990964 | var expect = require('chai').expect;
function titleCase(title){
var word = title.split(' ');
var titleCasedWords = word.map((word)=>{
return word[0].toUpperCase() + word.substring(1);
})
return titleCasedWords.join(' ')
}
expect(titleCase('raiders of the Lost Ark')).to.be.a('string');
expect(titleCase('a')).to.equal('A')
expect(titleCase('blade runner')).to.equal('Blade Runner')
expect(titleCase('raiders of the lost ark')).to.equal('Raiders of the Lost Ark'); | 1.28125 | 1 |
config/game/draughts/default-bot-thinker-5.js | mkhorin/e-champ-app | 3 | 15990972 | 'use strict';
const defaults = require('e-champ-draughts-thinker/config/default');
module.exports = {
...defaults,
label: 'Thinker Level 5',
params: {
...defaults.params,
depth: [9, 10]
},
translations: {
'ru': {
label: 'Мыслитель Уровень 5'
}
}
}; | 0.585938 | 1 |
data/talents/ranger/k3-cloaked-in-moss.js | filaraujo/crowfall-data | 1 | 15990980 | export default {
class: 'ranger',
id: 'cloaked-in-moss',
name: '<NAME>',
stats: {
'critical-damage': 5,
'damage-crushing': 10,
'damage-crushing-cap': 10,
'damage-slashing': 10,
'damage-slashing-cap': 10,
'power-damage-behind': 15,
'power-damage-melee': 9
},
type: 'talent',
version: '6.540'
};
| 0.546875 | 1 |
src/actions/index.js | jsdelivrbot/newsposts | 0 | 15990988 | // crud actions for news posts
import axios from 'axios';
// define action types so they can be used in reducers
export const ADD_POST = 'add_post';
export const FETCH_POST = 'fetch_post';
export const FETCH_POSTS = 'fetch_posts';
export const DELETE_POST = 'delete_post';
// vars for building API calls
const ROOT_URL = 'http://reduxblog.herokuapp.com/api/';
const API_KEY = '?key=starrynight';
export function addPost(values, callback) {
// API endpoint provided in documentation
const request = axios
.post(`${ROOT_URL}posts${API_KEY}`, values)
.then(() => callback()); // execute callback when complete
return {
type: ADD_POST,
payload: request
};
}
export function fetchPost(id) {
// API endpoint provided in documentation
const request = axios.get(`${ROOT_URL}posts/${id}${API_KEY}`);
return {
type: FETCH_POST,
payload: request
};
}
export function fetchPosts() {
// API endpoint provided in documentation
const request = axios.get(`${ROOT_URL}posts${API_KEY}`);
return {
type: FETCH_POSTS,
payload: request
};
}
export function deletePost(id, callback) {
// API endpoint provided in documentation
const request = axios.delete(`${ROOT_URL}posts/${id}${API_KEY}`)
.then(() => callback()); // execute callback when complete
return {
type: DELETE_POST,
payload: id // return id so object can be deleted from local state
}
} | 1.6875 | 2 |
cli.js | markusdosch/pagespeed-now | 1 | 15990996 | #!/usr/bin/env node
"use strict";
const meow = require("meow");
const chalk = require("chalk");
const updateNotifier = require("update-notifier");
const pagespeedNow = require(".");
const cli = meow(`
Usage
$ pagespeed-now <port|folder>
Options
--strategy Strategy to use when analyzing the page: mobile|desktop (default: mobile)
Examples
$ pagespeed-now 3000 --strategy=mobile
$ pagespeed-now _site
$ pagespeed-now .
`);
updateNotifier({ pkg: cli.pkg }).notify();
if (!cli.input[0]) {
console.error("Specify a port or folder");
process.exit(1);
}
pagespeedNow(cli.input[0], cli.flags)
.then(() => {
process.exit();
})
.catch(error => {
if (error.noStack) {
console.error(chalk.red(error.message));
process.exit(1);
} else {
throw error;
}
});
| 1 | 1 |
src/RegisterPopup.js | pawanbhole/slack-mention-notifier | 0 | 15991004 | import React, { Component } from 'react';
import Modal from 'react-awesome-modal';
import "./RegisterPopup.css";
import "github-fork-ribbon-css/gh-fork-ribbon.css";
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const STEPS = {
AUTHENTICATE: 'AUTHENTICATE',
VALIDATE_PIN: 'VALIDATE_PIN',
ALLOW_CONFIRMATION: 'ALLOW_CONFIRMATION',
BLOCK_CONFIRMATION: 'BLOCK_CONFIRMATION',
COMPLETION: 'COMPLETION',
ALREADY_SUBSCRIBED: 'ALREADY_SUBSCRIBED'
}
/*
* Class to that shows the notification badge on top right, notifications and notification registration popup.
*/
export default class RegisterPopup extends Component {
constructor(props) {
super(props);
this.api = props.api;
this.notificationsHandler = props.notificationsHandler;
this.state = this.getEmptyState();
this.handleUserIdChange = this.handleUserIdChange.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handleAuthenticate = this.handleAuthenticate.bind(this);
this.handleSecretCodeChange = this.handleSecretCodeChange.bind(this);
this.handleCodeVerification = this.handleCodeVerification.bind(this);
this.handleTokenSentToServer = this.handleTokenSentToServer.bind(this);
this.handleIncomingNotification = this.handleIncomingNotification.bind(this);
this.notificationsHandler.addIncomingNotificationListener(this.handleIncomingNotification);
this.notificationsHandler.addTokenStatusListener(this.handleTokenSentToServer);
}
/*
* notificationsHandler is initialized after mount so that the registered listeners will be executed.
*/
componentDidMount() {
this.notificationsHandler.init();
}
/*
* Initial state.
*/
getEmptyState() {
return {
visible : false,
userId: '',
email: '',
secretCode: '',
currentStep: STEPS.AUTHENTICATE,
message: '',
limitExceed: false,
permissionGranted: false
};
}
/*
* to set popup visible.
*/
openModal() {
this.setState({
visible : true
});
}
/*
* to set popup hidden.
*/
hideModal() {
this.setState({
visible : false
});
}
/*
* to reset widget state. it also close the popup
*/
closeModal() {
this.setState(this.getEmptyState());
}
/*
* to close the popup and mark flow as complete.
*/
closeModalAndCompleteFlow() {
this.setState({visible : false, currentStep: STEPS.ALREADY_SUBSCRIBED});
}
/*
* listener for userId change
*/
handleUserIdChange(event) {
event.preventDefault();
this.setState({userId: event.target.value});
}
/*
* listener for email change
*/
handleEmailChange(event) {
event.preventDefault();
this.setState({email: event.target.value});
}
/*
* it calls the authenticate API. If successful then change state to show validate pin form
*/
handleAuthenticate(event) {
event.preventDefault();
this.api.authenticate(this.state.userId, this.state.email).then((response) => {
if(response.success) {
this.setState({currentStep: STEPS.VALIDATE_PIN, message: ''});
} else {
this.setState({message: response.message});
}
}).catch((error) => {
console.log("error", error);
this.setState({message: error.message});
});
}
/*
* listener for secretCode change
*/
handleSecretCodeChange(event) {
event.preventDefault();
this.setState({secretCode: event.target.value});
}
/*
* it calls the validate secret code API. If successful then change state to sallow confirmation form
*/
handleCodeVerification(event) {
event.preventDefault();
this.api.validateSecretCode(this.state.userId, this.state.email, this.state.secretCode).then((response) => {
if(response.success) {
this.setState({currentStep: STEPS.ALLOW_CONFIRMATION});
this.notificationsHandler.updateUserData(this.state.userId, this.state.email, this.state.secretCode);
this.notificationsHandler.requestPermission().then((response) => {
this.setState({permissionGranted: true, message: ''});
}).catch((error) => {
console.log("error", error);
this.setState({permissionGranted: false, currentStep: STEPS.BLOCK_CONFIRMATION, message: ''});
});
} else {
this.setState({message: response.message, secretCode: '', limitExceed: response.limitExceed});
}
}).catch((error) => {
console.log("error", error);
this.setState({message: error.message});
});
}
/*
* it handles the response from server for update token.
*/
handleTokenSentToServer(response, error) {
if(response && response.success && response.alreadySent) {
this.setState({currentStep: STEPS.ALREADY_SUBSCRIBED});
} else if(response && response.success && !response.alreadySent) {
this.setState({currentStep: STEPS.COMPLETION});
} else {
this.setState({currentStep: STEPS.BLOCK_CONFIRMATION});
}
}
/*
* First form to show user name and email inout fields
*/
authenticationForm() {
return (
<div>
<div class="container1">
<h3>Enter slack user or email id to continue</h3>
</div>
<form onSubmit={this.handleAuthenticate} class="container2" >
<label htmlFor="userId">Username:</label>
<input type="text" name="userId" id="userId" placeholder="User name" value={this.state.userId} onChange={this.handleUserIdChange}/>
<label htmlFor="email">Email:</label>
<input type="text" name="email" id="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange}/>
<button type="submit" class="submit-button" name="submit">Continue</button>
</form>
<h3 class="error-message">{this.state.message}</h3>
<div class="container3">
<button type="button" class="submit-button cancelbtn" onClick={() => this.closeModal()}>Cancel</button>
</div>
</div>
);
}
/*
* Second form to show secret code inout fields
*/
secretPinVerificationForm() {
return (
<div>
<div class="container1">
<h3>Plese enter 4 digit code sent to your slack user</h3>
</div>
<form id="codeVerification" onSubmit={this.handleCodeVerification} class="container2" >
<label htmlFor="code">Code:</label>
<input disabled={this.state.limitExceed} type="password" size="4" name="code" id="code" placeholder="Code" value={this.state.secretCode} onChange={this.handleSecretCodeChange}/>
<button disabled={this.state.limitExceed} type="submit" class="submit-button" name="submit">Continue</button>
</form>
<h3 class="error-message">{this.state.message}</h3>
<div class="container3">
<button type="button" class="submit-button cancelbtn" onClick={() => this.closeModal()}>{this.state.limitExceed ? "Close" : "Cancel"}</button>
</div>
</div>
);
}
/*
* Third form to ask user to allow notification permission
*/
allowConfirmationForm() {
return (
<div>
<div class="container1">
<h3>Please select allow for "Show notifications".</h3>
</div>
<form id="codeVerification" class="container2" >
<button type="button" class="submit-button" onClick={() => this.hideModal()}>Close</button>
</form>
</div>
);
}
/*
* Fourth form to ask notification permission denied message.
*/
blockConfirmationForm() {
return (
<div>
<div class="container1">
<h3>Access for notifications denied.</h3>
</div>
<form id="codeVerification" class="container2" >
<button type="button" class="submit-button" onClick={() => this.hideModal()}>Close</button>
</form>
</div>
);
}
/*
* Fifth form to show completion message.
*/
completionForm() {
return (
<div>
<div class="container1">
<h3>Registration successful.</h3>
</div>
<form id="codeVerification" class="container2" >
<button type="button" class="submit-button" onClick={() => this.closeModalAndCompleteFlow()}>Done</button>
</form>
</div>
);
}
/*
* Fifth form to show completion message.
*/
alreadySubscribedForm() {
return (
<div>
<div class="container1">
<h3>You are already subscribed to slack mention events.</h3>
</div>
<form id="codeVerification" class="container2" >
<button type="button" class="submit-button" onClick={() => this.hideModal()}>Done</button>
</form>
</div>
);
}
/*
* Handler for showing notification when current window is active
*/
handleIncomingNotification(message) {
return toast(message.notification.body);
}
/*
* Render the form based on value of currentStep.
*/
render() {
let currentForm;
switch(this.state.currentStep) {
case STEPS.VALIDATE_PIN:
currentForm = this.secretPinVerificationForm();
break;
case STEPS.ALLOW_CONFIRMATION:
currentForm = this.allowConfirmationForm();
break;
case STEPS.BLOCK_CONFIRMATION:
currentForm = this.blockConfirmationForm();
break;
case STEPS.COMPLETION:
currentForm = this.completionForm();
break;
case STEPS.ALREADY_SUBSCRIBED:
currentForm = this.alreadySubscribedForm();
break;
case STEPS.AUTHENTICATE:
default:
currentForm = this.authenticationForm();
}
return (
<section>
<a onClick={() => this.openModal()} class="github-fork-ribbon mainbtn" title="Register for Notifications">Register for Notifications</a>
<ToastContainer autoClose={8000}/>
<Modal visible={this.state.visible} width="400" height="350" effect="fadeInUp" onClickAway={() => this.hideModal()}>
<div>
{currentForm}
</div>
</Modal>
</section>
);
}
} | 1.515625 | 2 |
public/static/js/vue/shop.js | qingbo198/thinkphp5 | 1 | 15991012 | //购物车
new Vue({
el: '#shop',
data: {
tota: '',
sum: 1493,
shopdata: [
{'id': 1, 'name': '衬衫', 'num': 1, 'price': 99, 'sub': 99},
{'id': 2, 'name': '毛衣', 'num': 2, 'price': 299, 'sub': 598},
{'id': 3, 'name': '裤子', 'num': 4, 'price': 199, 'sub': 796},
]
},
methods: {
add: function (index) {
// console.log(JSON.stringify(this.shopdata));
//console.log(index);
this.shopdata[index].num++;
this.shopdata[index].sub = this.shopdata[index].num * this.shopdata[index].price;
this.total();
},
reduce: function (index) {
if (this.shopdata[index].num == 1) {
return false;
}
this.shopdata[index].num--;
this.shopdata[index].sub = this.shopdata[index].num * this.shopdata[index].price;
this.total();
},
total: function () {
for (var i = 0, tota = 0; i < this.shopdata.length; i++) {
tota += this.shopdata[i].sub
}
this.sum = tota;
}
}
})
//列表增删
new Vue({
el: '#edit',
data: {
person: '',
// inputPerson:{'name':this.person},
list: [
{'name': '小明'},
{'name': '小花'},
{'name': '小亮'},
]
},
computed: {
inputPerson(){
return {'name': this.person}
}
},
methods: {
add: function () {
let that = this;
if(that.person==''){
return false;
}
that.list.unshift(that.inputPerson);
},
dele:function(index){
let that = this;
that.list.splice(index,1);
}
}
})
| 2.234375 | 2 |
bin/index.js | mhkeller/joiner | 43 | 15991020 | #!/usr/bin/env node
var optimist = require('optimist')
var joiner = require('../dist/joiner.node.js')
var queue = require('d3-queue').queue
var io = require('./io/index.js')
var argv = optimist
.usage('Usage: joiner -a DATASET_A_PATH -k DATASET_A_KEY -b DATASET_B_PATH -j DATASET_B_KEY -o OUT_FILE_PATH [-r (summary|full) -n NEST_KEY --geojson]')
.options('h', {
alias: 'help',
describe: 'Display help',
default: false
})
.options('a', {
alias: 'apath',
describe: 'Dataset A path'
})
.options('k', {
alias: 'akey',
describe: 'Dataset A key'
})
.options('b', {
alias: 'bpath',
describe: 'Dataset B path'
})
.options('j', {
alias: 'bkey',
describe: 'Dataset B key'
})
.options('g', {
alias: 'geojson',
describe: 'Is dataset A geojson?',
default: false,
boolean: true
})
.options('n', {
alias: 'nestkey',
describe: 'Nested key name'
})
.options('o', {
alias: 'out',
describe: 'Out path',
default: null
})
.options('r', {
alias: 'report',
describe: 'Report format',
default: 'summary'
})
.check(function (argv) {
if ((!argv['a'] || !argv['adata']) && (!argv['a'] || !argv['adata']) && (!argv['b'] || !argv['bdata']) && (!argv['k'] || !argv['akey']) && (!argv['j'] || !argv['bkey'])) {
throw 'What do you want to do?' // eslint-disable-line no-throw-literal
}
})
.argv
if (argv.h || argv.help) {
optimist.showHelp()
}
var aPath = argv.a || argv['apath']
var aKey = argv.k || argv['akey']
var bPath = argv.b || argv['bpath']
var bKey = argv.j || argv['bkey']
var geojson = argv.g || argv['geojson']
var nestKey = argv.n || argv['nestkey']
var outPath = argv.o || argv['out']
var reportDesc = argv.r || argv['report']
var q = queue()
q.defer(io.readData, aPath)
q.defer(io.readData, bPath)
q.await(function (err, aData, bData) {
console.log('adata', aData)
console.log('bdata', bData)
if (err) {
throw new Error(err)
}
var config = {
leftData: aData,
leftDataKey: aKey,
rightData: bData,
rightDataKey: bKey,
nestKey: nestKey,
geoJson: geojson
}
// Join data
var jd = joiner(config)
if (outPath !== null) {
io.writeData(outPath, jd.data, {makeDirectories: true}, function (err) {
if (err) {
console.error('Error writing data file', outPath)
throw new Error(err)
}
})
io.writeDataSync(stripExtension(outPath) + 'report.json', jd.report, {makeDirectories: true})
} else {
if (reportDesc === 'summary') {
console.log(jd.report.prose.summary)
} else {
console.log(jd.report.prose.full)
}
}
})
function stripExtension (fullPath) {
var ext = io.helpers.discernFormat(fullPath)
return fullPath.replace(new RegExp(ext + '$', 'g'), '')
}
| 1.382813 | 1 |
obj/src/auth/CredentialResolver.js | pip-services3-node/pip-services3-components-node | 0 | 15991028 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CredentialResolver = void 0;
/** @module auth */
/** @hidden */
let async = require('async');
const pip_services3_commons_node_1 = require("pip-services3-commons-node");
const pip_services3_commons_node_2 = require("pip-services3-commons-node");
const CredentialParams_1 = require("./CredentialParams");
/**
* Helper class to retrieve component credentials.
*
* If credentials are configured to be retrieved from [[ICredentialStore]],
* it automatically locates [[ICredentialStore]] in component references
* and retrieve credentials from there using store_key parameter.
*
* ### Configuration parameters ###
*
* __credential:__
* - store_key: (optional) a key to retrieve the credentials from [[ICredentialStore]]
* - ... other credential parameters
*
* __credentials:__ alternative to credential
* - [credential params 1]: first credential parameters
* - ... credential parameters for key 1
* - ...
* - [credential params N]: Nth credential parameters
* - ... credential parameters for key N
*
* ### References ###
*
* - <code>\*:credential-store:\*:\*:1.0</code> (optional) Credential stores to resolve credentials
*
* @see [[CredentialParams]]
* @see [[ICredentialStore]]
*
* ### Example ###
*
* let config = ConfigParams.fromTuples(
* "credential.user", "jdoe",
* "credential.pass", "<PASSWORD>"
* );
*
* let credentialResolver = new CredentialResolver();
* credentialResolver.configure(config);
* credentialResolver.setReferences(references);
*
* credentialResolver.lookup("123", (err, credential) => {
* // Now use credential...
* });
*
*/
class CredentialResolver {
/**
* Creates a new instance of credentials resolver.
*
* @param config (optional) component configuration parameters
* @param references (optional) component references
*/
constructor(config = null, references = null) {
this._credentials = [];
this._references = null;
if (config != null)
this.configure(config);
if (references != null)
this.setReferences(references);
}
/**
* Configures component by passing configuration parameters.
*
* @param config configuration parameters to be set.
*/
configure(config) {
let credentials = CredentialParams_1.CredentialParams.manyFromConfig(config);
this._credentials.push(...credentials);
}
/**
* Sets references to dependent components.
*
* @param references references to locate the component dependencies.
*/
setReferences(references) {
this._references = references;
}
/**
* Gets all credentials configured in component configuration.
*
* Redirect to CredentialStores is not done at this point.
* If you need fully fleshed credential use [[lookup]] method instead.
*
* @returns a list with credential parameters
*/
getAll() {
return this._credentials;
}
/**
* Adds a new credential to component credentials
*
* @param credential new credential parameters to be added
*/
add(credential) {
this._credentials.push(credential);
}
lookupInStores(correlationId, credential, callback) {
if (!credential.useCredentialStore()) {
callback(null, null);
return;
}
let key = credential.getStoreKey();
if (this._references == null) {
callback(null, null);
return;
}
let storeDescriptor = new pip_services3_commons_node_2.Descriptor("*", "credential-store", "*", "*", "*");
let components = this._references.getOptional(storeDescriptor);
if (components.length == 0) {
let err = new pip_services3_commons_node_1.ReferenceException(correlationId, storeDescriptor);
callback(err, null);
return;
}
let firstResult = null;
async.any(components, (component, callback) => {
let store = component;
store.lookup(correlationId, key, (err, result) => {
if (err || result == null) {
callback(err, false);
}
else {
firstResult = result;
callback(err, true);
}
});
}, (err) => {
if (callback)
callback(err, firstResult);
});
}
/**
* Looks up component credential parameters. If credentials are configured to be retrieved
* from Credential store it finds a [[ICredentialStore]] and lookups credentials there.
*
* @param correlationId (optional) transaction id to trace execution through call chain.
* @param callback callback function that receives resolved credential or error.
*/
lookup(correlationId, callback) {
if (this._credentials.length == 0) {
if (callback)
callback(null, null);
return;
}
let lookupCredentials = [];
for (let index = 0; index < this._credentials.length; index++) {
if (!this._credentials[index].useCredentialStore()) {
if (callback)
callback(null, this._credentials[index]);
return;
}
else {
lookupCredentials.push(this._credentials[index]);
}
}
let firstResult = null;
async.any(lookupCredentials, (credential, callback) => {
this.lookupInStores(correlationId, credential, (err, result) => {
if (err || result == null) {
callback(err, false);
}
else {
firstResult = result;
callback(err, true);
}
});
}, (err) => {
if (callback)
callback(err, firstResult);
});
}
}
exports.CredentialResolver = CredentialResolver;
//# sourceMappingURL=CredentialResolver.js.map | 1.265625 | 1 |
udemy-assignment-projects/src/assignment3/components/RouterApp/RouterApp.js | Alexzg/ReactJS-Projects | 0 | 15991036 | import React, { Component } from 'react';
import './RouterApp.css';
import { NavLink, Route, Redirect, Switch} from 'react-router-dom';
import Menu from '../../containers/pages/Menu/Menu';
import Courses from '../../containers/pages/Courses/Courses';
import Users from '../../containers/pages/Users/Users';
import Error from '../../containers/pages/Error/Error';
import Course from '../../components/Course/Course';
class routerApp extends Component {
render() {
return (
<div>
<header><nav><ul>
<li><NavLink to='/'>Menu</NavLink></li>
<li><NavLink to={{pathname:'/courses'}}>Courses</NavLink></li>
<li><NavLink to={{pathname:'/users'}}>Users</NavLink></li>
</ul></nav></header>
<h1>ROUTER App</h1>
<Switch>
<Route path='/' exact component={Menu}/>
<Route path='/courses' exact component={Courses}/>
<Route path='/users' exact component={Users}/>
<Redirect from='/all-courses' to='/courses'/>
<Route path='/courses/:id/:title' exact component={Course}/>
<Route path='/error' exact component={Error}/>
<Redirect from='/' to='/error'/>
</Switch>
</div>
)
}
}
export default routerApp; | 1.359375 | 1 |
06-build-page/index.js | AndreyPesh/HTML-builder | 0 | 15991044 | const path = require('path');
const fs = require('fs/promises');
const { rm } = require('fs');
const { createWriteStream, createReadStream } = require('fs');
const pathToProjectFolder = path.join(__dirname, 'project-dist');
const pathToIndexFile = path.join(__dirname, 'project-dist/index.html');
const pathToTemplate = path.join(__dirname, 'template.html');
const pathToComponents = path.join(__dirname, 'components');
const pathToFiles = path.join(__dirname, 'styles');
const pathToBundle = path.join(__dirname, 'project-dist/style.css');
const writeStream = createWriteStream(pathToBundle, { flags: 'w' });
const initPathToFolder = path.join(__dirname, 'assets');
const initPathToCopyFolder = path.join(__dirname, 'project-dist/assets');
let template = '';
createFolder(pathToProjectFolder);
templateHandler(pathToTemplate);
readFilesStyle(pathToFiles);
remove(initPathToFolder, initPathToCopyFolder);
async function templateHandler(pathToTemplate) {
try{
template += await fs.readFile(pathToTemplate);
const listTags = searchTagInTemplate(template);
const listComponents = getNamesComponents(listTags);
await replaceComponentsInTemplate(listComponents, listTags);
writeTemplateInDist(template);
} catch(error) {
console.log(error.message);
}
}
function replaceComponentsInTemplate(listComponents, listTags) {
return new Promise((resolve, reject) => {
try{
listComponents.forEach(async (componentName, index) => {
const tagName = listTags[index];
const componentContent = await fs.readFile(pathToComponents + `/${componentName}.html`);
replaceComponent(componentContent, tagName);
if (index == listComponents.length - 1) {
setTimeout(() => resolve(), 800);
}
});
} catch(error) {
console.log(error);
reject();
}
});
}
function replaceComponent(componentContent, tagName) {
const content = componentContent.toString();
const tag = tagName;
template = template.replace(tag, content);
}
function searchTagInTemplate(template) {
if(!template) {
return;
}
const tags = template.match(/(\{\{[a-zA-Z]+\}\})/g);
return tags;
}
function getNamesComponents(tags) {
const components = tags.map(tag => {
return tag.slice(2, tag.length - 2);
});
return components;
}
async function writeTemplateInDist(template) {
const indexFile = await fs.open(pathToIndexFile, 'w');
indexFile.write(template);
}
async function createFolder(pathToFolder) {
await fs.mkdir(pathToFolder, {recursive: true});
}
async function readFilesStyle(folder) {
try {
const files = await fs.readdir(folder, { withFileTypes: true });
filesHandler(files);
} catch (error) {
console.log(error.message);
}
}
async function filesHandler(files) {
let isExistFiles = false;
files.forEach(file => {
const fileName = file.name;
const isCssType = fileName.match(/\.(css)$/);
if (file.isFile() && isCssType) {
isExistFiles = true;
const pathToFile = path.join(__dirname, `styles/${fileName}`);
const readStream = createReadStream(pathToFile);
readStream.pipe(writeStream);
}
});
if (!isExistFiles) {
await fs.rm(pathToBundle);
}
}
async function remove(pathToFolder, pathToCopyFolder) {
rm(pathToCopyFolder, { recursive: true }, () => createCopyFolder(pathToFolder, pathToCopyFolder));
}
async function createCopyFolder(pathToFolder, pathToCopyFolder) {
try {
const files = await fs.readdir(pathToFolder, { withFileTypes: true });
await fs.mkdir(pathToCopyFolder, { recursive: true });
files.forEach(async file => {
if (file.isDirectory()) {
createCopyFolder(`${pathToFolder}/${file.name}`, `${pathToCopyFolder}/${file.name}`);
return;
} else {
await copyFiles(`${pathToFolder}/${file.name}`, `${pathToCopyFolder}/${file.name}`);
return;
}
});
} catch (error) {
console.log('The folder could not be copied\n', error.message);
}
}
async function copyFiles(pathToFolder, pathToCopyFolder) {
try {
await fs.copyFile(pathToFolder, pathToCopyFolder);
} catch (error) {
console.log('Can\'t copy file! ', error.message);
}
} | 1.289063 | 1 |
src/storage-module.js | Tointer/To-Do-List | 0 | 15991052 |
let db;
const tasksDBName = "tasks_db";
let deffered;
export let moduleInited = new Promise(function (resolve, reject) {
deffered = {resolve: resolve, reject: reject};
});
function openDatabase() {
let request = window.indexedDB.open(tasksDBName, 1);
request.onerror = function() {
console.log("Database failed to open");
};
request.onsuccess = function() {
db = request.result;
deffered.resolve();
}
request.onupgradeneeded = function(e) {
let db = e.target.result;
let objectStore = db.createObjectStore(tasksDBName, { keyPath: 'text', autoIncrement:true });
objectStore.createIndex("text", "text", { unique: false });
objectStore.createIndex("isChecked", "isChecked", { unique: false });
deffered.resolve();
console.log('Database setup complete ' + db);
};
}
openDatabase();
export async function getAllTasks(){
let objectStore = db.transaction(tasksDBName).objectStore(tasksDBName);
console.log("getAllTasks");
let result = [];
await new Promise(function (resolve, reject){
let getAll = objectStore.getAll();
getAll.onsuccess = (e) => {
console.log("getAllTasks done");
result = e.target.result
resolve();
};
getAll.onerror = reject;
})
//yield {text: cursor.value.text, isChecked: cursor.value.isChecked};
console.log(result);
return result;
}
export async function addTask(text, isChecked){
let newItem = { text: text, isChecked: isChecked };
let transaction = db.transaction([tasksDBName], "readwrite")
let objectStore = transaction.objectStore(tasksDBName);
let request = objectStore.add(newItem);
request.onsuccess = function() {
console.log(`${text.substr(0, Math.max(15, text.length))} task add start`)
};
transaction.oncomplete = function() {
console.log(`${text.substr(0, Math.max(15, text.length))} task add finish`)
};
}
export async function removeTask(taskText){
let transaction = db.transaction([tasksDBName], "readwrite")
let objectStore = transaction.objectStore(tasksDBName);
let request = objectStore.delete(taskText);
}
export async function toggleTask(taskText){
let transaction = db.transaction([tasksDBName], "readwrite")
let objectStore = transaction.objectStore(tasksDBName);
let request = objectStore.get(taskText);
request.onsuccess = function(event){
console.log("toggle success");
let data = event.target.result;
data.isChecked = !data.isChecked;
objectStore.put(data);
}
}
export async function getTask(taskText){
let transaction = db.transaction([tasksDBName], "readwrite")
let objectStore = transaction.objectStore(tasksDBName);
let result;
await new Promise(function (resolve, reject){
let request = objectStore.get(taskText);
request.onsuccess = function(event){
console.log("toggle success");
result = event.target.result;
resolve();
}
})
return result;
} | 1.59375 | 2 |
server.js | AC-Computer-Engineering-Technology/acHacks | 2 | 15991060 | const express = require('express');
const logger = require('morgan');
const app = express();
const port = process.env.PORT || 3000;
const routes = ['/', '/home'];
app.use(logger('dev'));
app.use(express.static(__dirname + "/app/resources"));
app.get(routes, (req, res) => {
res.sendFile(__dirname + '/app/index.html');
})
app.listen(port, () => console.log(`server running on port *${port}`));
| 1.257813 | 1 |
commands/database.js | dscape/futoncli | 8 | 15991068 | var fs = require('fs');
var path = require('path');
var futoncli = require('../futoncli');
var helpers = require('../helpers');
var database = exports;
database.list = function (callback) {
var server = futoncli.server;
server.db.list(helpers.generic_cb(callback));
};
database.get = function (name, callback) {
var server = futoncli.server;
if(typeof name === "function") {
return name(new Error("You didn't provide a database name."));
}
server.db.get(name, helpers.generic_cb(callback));
};
database.destroy = function (name, callback) {
var server = futoncli.server;
if(typeof name === "function") {
return name(new Error("You didn't provide a database name."));
}
server.db.destroy(name, helpers.generic_cb(callback));
};
database.create = function (name, callback) {
var server = futoncli.server;
if(typeof name === "function") {
return name(new Error("You didn't provide a database name."));
}
server.db.create(name, helpers.generic_cb(callback));
};
database.usage = [
'',
'`futon config *` commands allow you to edit your',
'local futon configuration file. Valid commands are:',
'',
'futon database list',
'futon database get <dbname>',
'futon database destroy <dbname>',
'futon database create <dbname>'
]; | 1.148438 | 1 |
backend/themes/qltk2/assets/global/scripts/main.js | HTeamCoder/asv | 0 | 15991076 | /**
* Created by HungLuongHien on 6/23/2016.
*/
function getAjax(controllerAction, data, callbackBeforeSend, target){
return $.ajax({
url: 'index.php?r='+controllerAction,
data: data,
type: 'post',
dataType: 'json',
beforeSend: callbackBeforeSend,
error: function (r1, r2) {
var text = r1.responseText;
$(".thongbao").html(text.replace('',''));
},
complete: function () {
Metronic.unblockUI(target);
}
})
}
function createTypeHead(target, action, callbackAfterSelect){
$(target).typeahead({
source: function (query, process) {
var states = [];
return $.get('index.php?r=autocomplete/'+action, { query: query }, function (data) {
$.each(data, function (i, state) {
states.push(state.name);
});
return process(states);
}, 'json');
},
afterSelect: function (item) {
if(typeof callbackAfterSelect != 'undefined')
callbackAfterSelect(item);
/*$.ajax({
url: 'index.php?r=khachhang/getdiachi',
data: {name: item},
type: 'post',1
dataType: 'json',
success: function (data) {
$("#diachikhachhang").val(data);
}
})*/
}
});
}
function setDatePicker() {
$('.datepicker').datepicker({
autoclose: true,
format: 'dd/mm/yyyy',
language: 'vi',
todayBtn: true,
todayHighlight: true,
});
}
jQuery(document).ready(function() {
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
QuickSidebar.init(); // init quick sidebar
// $(".tien-te").maskMoney({thousands:",", allowZero:true, /*suffix: " VNĐ",*/precision:3});
});
$('#ajaxCrudModal').attr('tabindex',''); | 1.25 | 1 |
storage/flexi/rest-api-generator/redux/actionTypes.js | kimheang-born/real_estate | 0 | 15991084 | // ___REPLACE_ME___
export const CREATE_u___replace_me____SUCCESS = "CREATE_u___replace_me____SUCCESS";
export const DELETE_u___replace_me____SUCCESS = "DELETE_u___replace_me____SUCCESS";
export const GET_u___replace_me____SUCCESS = "GET_u___replace_me____SUCCESS";
export const LIST_u___replace_me____SUCCESS = "LIST_u___replace_me____SUCCESS";
export const UPDATE_u___replace_me____SUCCESS = "UPDATE_u___replace_me____SUCCESS";
// END CRUD CONSTANTS
| 0.429688 | 0 |
src/scene/Scene.js | JaegarSarauer/SeedGameEngine | 5 | 15991092 | import Updateable from '../base/Updateable';
import { SceneObject } from '../entry';
/**
* Baseclass for all scenes. When creating a new scene, it should inherit this
* class.
* Scenes keep track of their scene objects and viewports. The scene baseclass has
* functions for registering these with the scene.
*/
export default class Scene extends Updateable {
/**
* Builds the SceneObjects and Viewports list.
*/
constructor() {
super();
this.viewportIDCounter = 0;
this.sceneObjects = [];
this.viewports = [];
}
/**
* When a SceneObject is created, it is routed through the SceneManager to the current
* active scene to this function. The SceneObject will register with the scene to be referenced
* on update/pause/destruct calls on a scene specific basis.
*
* @param {SceneObject} sceneObject A SceneObject to register.
*/
registerSceneObject(sceneObject) {
this.sceneObjects.push(sceneObject);
let deregisterCallback = () => {
for (let i = 0; i < this.sceneObjects.length; i++) {
if (this.sceneObjects[i].id ==sceneObject.id)
this.sceneObjects.splice(i, 1);
return;
}
}
return deregisterCallback;
}
/**
* Registers a Renderable component with the viewport, by index.
*
* @param {Renderable} renderable A Renderable to register to the viewport.
* @param {number} viewportIndex The index of the viewport.
*/
registerRenderableComponent(renderable, viewportIndex) {
if (this.viewports.length > viewportIndex)
return this.viewports[viewportIndex].registerRenderableComponent(renderable);
else {
throw "This viewport doesn't exist on this scene!";
}
}
/**
* When a Viewport is created, it is routed through the SceneManager to the current
* active scene to this function. The Viewport will register with the scene to be referenced
* by the RenderManager and assigned to by Renderables.
*
* @param {Viewport} viewport A Viewport to register.
*/
registerViewport(viewport) {
viewport.viewportIndex = this.viewportIDCounter++;
this.viewports.push(viewport);
let deregisterCallback = () => {
for (let i = 0; i < this.viewports.length; i++) {
if (this.viewports[i].viewportIndex === viewport.viewportIndex) {
this.viewports.splice(i, 1);
return;
}
}
}
return deregisterCallback;
}
} | 1.8125 | 2 |
test/unit/utils/asyncify.test.js | lukix/genemo | 8 | 15991100 | const asyncify = require('../../../src/utils/asyncify');
describe('asyncify', () => {
test('Runs asynchronously and returns correct value with promise', (done) => {
const mockFn = jest.fn(x => x);
const mockFnAsync = asyncify(mockFn);
const arg = 5;
mockFnAsync(arg).then((result) => {
expect(result).toStrictEqual(arg);
done();
});
expect(mockFn).toHaveBeenCalledTimes(0);
});
test('Correctly handles exception', (done) => {
const mockFn = jest.fn((x) => { throw x; });
const mockFnAsync = asyncify(mockFn);
const arg = 5;
mockFnAsync(arg).catch((result) => {
expect(result).toStrictEqual(arg);
done();
});
expect(mockFn).toHaveBeenCalledTimes(0);
});
});
| 1.367188 | 1 |
resources/js/project/components/chat/MessageForm.js | tartakovskyi/chat.loc | 0 | 15991108 | import React, { useState } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import Axios from 'axios'
import { getMessagesAction } from '../../store/actions/chatAction'
import InfoBlock from '../common/InfoBlock'
import setFormObject from "../common/FormUtils"
const initialData = {
text: ''
}
const MessageForm = ({user_id, chat_id, getMessagesAction}) => {
const [data, setData] = useState(initialData)
const [errors, setErrors] = useState({})
const handleSubmit = e => {
e.preventDefault()
const errors = validate(data)
setErrors(errors)
if (Object.keys(errors).length === 0) {
axios.post('/api/chat/' + chat_id + '/message', {
user_id : user_id,
chat_id : chat_id,
text: data.text
})
.then(function (response) {
if (response.status == 200) {
setData(initialData)
}
})
.catch(function (error) {
console.log(error);
})
}
}
const validate = (data) => {
const errors = {}
if (!data.text) errors.text = 'Message cannot be blank'
return errors
}
return (
<form onSubmit={handleSubmit} className="messageForm" id="messageForm">
<h2 className="mb-4">Add a Message</h2>
{Object.keys(errors).length > 0 && <InfoBlock errors={errors} />}
<div className="form-group">
<textarea id="text" rows="8" className="form-control"
name="text"
placeholder="Your message..."
value={data.text}
onChange={setFormObject(data, setData)}
></textarea>
</div>
<button type="submit" className="btn btn-block btn-primary">Submit</button>
</form>
)
}
MessageForm.propTypes = {
user_id: PropTypes.number.isRequired,
chat_id: PropTypes.number.isRequired
}
export default connect(null, {getMessagesAction})(MessageForm)
| 1.609375 | 2 |
mr-kino-suggests/commands/suggest.js | madscientist111/mr-kino-suggests | 0 | 15991116 | const axios = require("axios");
const Discord = require("discord.js");
const { scrapper } = require("imdb-scrapper");
const lb = require("letterboxd-search");
const rt = require("rottentomatoes-data");
const baseReq = "https://api.themoviedb.org/3/movie/";
module.exports = {
name: "suggest",
description: "sugesst!",
execute(message, args) {
// console.log(args);
const req = baseReq + args[0] + "?api_key=" + process.env.TMDB_TOKEN;
// console.log("req is ", req);
axios
.get(req)
.then(async (response) => {
console.log("got the request");
const data = await response.data;
// console.log("got tmdb data");
// console.log(data);
const imdb_id = await data.imdb_id;
// console.log("imdb id is ", imdb_id);
let imdb_data = 0;
if (imdb_id) {
await scrapper(imdb_id)
.then((res) => (imdb_data = res))
.catch((err) => console.log(err));
}
// console.log("Title is");
const year = String(data.release_date).slice(0, 4);
const lbQuery = await String(data.title)
.replace(/'/g, "")
.replace(/ /g, "-")
.toLowerCase();
// console.log("lb query is ", lbQuery);
// if (imdb_id)
// await rt.fetchRottenTomatoesData(lbQuery).then((res) => {
// // console.log("rt res is ");
// // console.log(res);
// data.rt = res.movie.meterScore;
// });
// console.log("pehleeee");
let x = await lb.search(lbQuery);
let lbq = lbQuery;
// console.log("x");
// console.log(x);
if (x.reject) console.log("err");
// console.log("x ", x);
// console.log("first");
if (x.statusCode != 200 || x.year != year) {
// console.log("we inside here x is");
// console.log(x.year);
// console.log(typeof x.year);
if (x.year) {
// console.log("goes inside");
const lbQuery2 = lbQuery + "-" + year;
// console.log("lbq2 ", lbQuery2);
x = await lb.search(lbQuery2);
lbq = lbQuery2;
}
}
console.log("lbq");
lbq =
"https://letterboxd.com/film/" +
lbq
.toLowerCase()
.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, " ")
.replace(/ /g, "-");
console.log(lbq);
// console.log("sec");
data.lb = x;
const imdbUrl = "https://imdb.com/title/" + imdb_id;
const tmdbUrl = "https://tmdb.org/movie/" + args[0];
let url = imdb_id ? imdbUrl : tmdbUrl;
console.log("url is ", url);
// console.log("x is ", x);
const img =
data.lb.statusCode == 200
? data.lb.backdropImage
: "https://www.themoviedb.org/t/p/w600_and_h900_bestv2" +
data.poster_path;
const exampleEmbed = new Discord.MessageEmbed()
.setColor("#0099ff")
.setAuthor(
"Recommendation of the day!",
"https://i.ibb.co/PDnLkQp/vga.png",
"https://www.youtube.com/user/VGApdpu"
)
.setTitle(
imdb_data.title ? imdb_data.title : data.original_title
)
.setURL(url)
.setDescription(data.overview)
.setThumbnail(
"https://www.themoviedb.org/t/p/w600_and_h900_bestv2" +
data.poster_path
)
.addFields(
{
name: "Directed By:",
value: data.lb.director
? data.lb.director
: "Unavailable",
},
{
name: "Runtime",
value: data.lb.runtimeMinutes
? data.lb.runtimeMinutes + " Mins"
: "Unavailable",
},
{
name: "Trailer:",
value: data.lb.trailer
? data.lb.trailer
: "Unavailable",
},
// { name: "\u200B", value: "\u200B" },
{
name: "IMDB",
value: imdb_data.rating
? imdb_data.rating +
" / 10" +
"\n" +
`[_visit_](${imdbUrl})`
: "Unavailable",
inline: true,
},
{
name: "TMDB",
value: data.vote_average
? data.vote_average +
" / 10" +
"\n" +
`[_visit_](${tmdbUrl})`
: "Unavailable",
inline: true,
}
)
.addField(
"Letterboxd",
data.lb.averageRating != "unde"
? data.lb.averageRating +
" / 5" +
"\n" +
`[_visit_](${lbq})`
: "Unavailable",
true
)
// .addField("Rotten Tomatoes", data.rt + "%", true)
.setImage(
img
? img
: "https://avatars.githubusercontent.com/u/22892193?s=460&u=96585117354875608d384137828c890a3b47a017&v=4"
)
.setTimestamp()
.setFooter(
"by shoo with love from VGA",
"https://avatars.githubusercontent.com/u/22892193?s=460&u=96585117354875608d384137828c890a3b47a017&v=4"
);
console.log("****************here****************");
const chan =
args.length > 1
? message.client.channels.cache.get(args[2])
: message.channel;
chan.send(exampleEmbed);
})
.catch((err) => {
console.log(err);
});
//const specReq = baseReq + args + "?api_key=" + process.env.TMDB_TOKEN;
//console.log(specReq);
},
};
| 1.585938 | 2 |
DigitalSchoolDiary/schooldiary/app.js | sergobago/DigitalSchoolDiary | 0 | 15991124 | 'use strict';
var SwaggerExpress = require('swagger-express-mw');
var express = require('express');
var session = require('express-session');
var config_file = require('config');
var winston = require('winston');
var cookieParser = require('cookie-parser');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var Sequelize = require('sequelize');
var app = express();
module.exports = app; // for testing
var config = {
appRoot: __dirname // required config
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
var sequelize = new Sequelize(
config_file.get('options.sequelize.bd'),
config_file.get('options.sequelize.login'),
config_file.get('options.sequelize.password'),
config_file.get('options.sequelize.params'));
var sequlizeStore = new SequelizeStore({
db: sequelize
});
app.use(cookieParser());
app.use(session({
secret: 'hihadhidhygfgfdadeadtaedfefed87138',
store: sequlizeStore,
cookie: { maxAge: 12 * 60 * 60 * 1000 },
resave: false,
saveUninitialized: true
}));
//sequlizeStore.sync({force: true, logging: console.log});
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || config_file.get('options.serverSettings.port');
app.listen(port, config_file.get('options.serverSettings.host'));
/*if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}*/
winston.configure({
transports: [
new (winston.transports.Console)(config_file.get('options.winstonSettings.consoleInfo')),
new (winston.transports.File)(config_file.get('options.winstonSettings.fileInfo')),
new (winston.transports.File)(config_file.get('options.winstonSettings.fileError'))
]
});
});
| 1.34375 | 1 |
src/sign-and-verify/sign.js | wmhilton/pgp-signature | 2 | 15991132 | const { BigInteger } = require("jsbn");
const { hashes } = require("./hashes.js");
const arrayBufferToHex = require("array-buffer-to-hex");
const { encode } = require("isomorphic-textencoder");
const Message = require("@isomorphic-pgp/parser/Message.js");
const UrlSafeBase64 = require("@isomorphic-pgp/parser/UrlSafeBase64.js");
const Uint16 = require("@isomorphic-pgp/parser/Uint16.js");
const EMSA = require("@isomorphic-pgp/parser/emsa.js");
const { HashAlgorithm } = require("@isomorphic-pgp/parser/constants.js");
const { payloadSignatureHashData } = require("@isomorphic-pgp/parser/payloadSignatureHashData.js");
const { trimZeros } = require("@isomorphic-pgp/util/trimZeros.js");
module.exports.sign = async function sign(openpgpPrivateKey, payload, timestamp) {
let parsed = Message.parse(openpgpPrivateKey);
let privateKeyPacket = parsed.packets[0].packet;
let userIdPacket = parsed.packets[1].packet;
// TODO: Assert that this is all correct and stuff.
let selfSignaturePacket = parsed.packets[2].packet;
let keyid = selfSignaturePacket.unhashed.subpackets.find(subpacket => subpacket.type === 16).subpacket.issuer;
let e = UrlSafeBase64.serialize(privateKeyPacket.mpi.e);
let n = UrlSafeBase64.serialize(privateKeyPacket.mpi.n);
let d = UrlSafeBase64.serialize(privateKeyPacket.mpi.d);
let p = UrlSafeBase64.serialize(privateKeyPacket.mpi.p);
let q = UrlSafeBase64.serialize(privateKeyPacket.mpi.q);
let u = UrlSafeBase64.serialize(privateKeyPacket.mpi.u);
// SIGN
let D = new BigInteger(arrayBufferToHex(d), 16);
let P = new BigInteger(arrayBufferToHex(p), 16);
let Q = new BigInteger(arrayBufferToHex(q), 16);
let U = new BigInteger(arrayBufferToHex(u), 16);
let partialSignaturePacket = {
version: 4,
type: 0,
alg: 1,
hash: 8,
hashed: {
subpackets: [
{
type: 2,
subpacket: {
creation: timestamp
}
}
]
}
};
const hashType = HashAlgorithm[partialSignaturePacket.hash]
payload = typeof payload === "string" ? encode(payload) : payload;
let buffer = await payloadSignatureHashData(payload, partialSignaturePacket);
let hash = await hashes[hashType](buffer, { outputFormat: "buffer" });
hash = new Uint8Array(hash);
let left16 = Uint16.parse([hash[0], hash[1]]);
// Wrap `hash` in the dumbass EMSA-PKCS1-v1_5 padded message format:
hash = EMSA.encode(hashType, hash, n.byteLength);
let M = new BigInteger(arrayBufferToHex(hash), 16);
// // Straightforward solution: ~ 679ms
// console.time("standard");
// let S = M.modPow(D, N);
// console.timeEnd("standard");
// Fast solution using Chinese Remainder Theorem: ~184ms
// from libgcryp docs:
/*
* m1 = c ^ (d mod (p-1)) mod p
* m2 = c ^ (d mod (q-1)) mod q
* h = u * (m2 - m1) mod q
* m = m1 + h * p
*/
let ONE = new BigInteger("01", 16);
let DP = D.mod(P.subtract(ONE));
let DQ = D.mod(Q.subtract(ONE));
let M1 = M.modPow(DP, P);
let M2 = M.modPow(DQ, Q);
let H = U.multiply(M2.subtract(M1)).mod(Q);
let S = M1.add(H.multiply(P));
let signature = new Uint8Array(S.toByteArray());
signature = trimZeros(signature);
signature = UrlSafeBase64.parse(signature);
let completeSignaturePacket = Object.assign({}, partialSignaturePacket, {
unhashed: {
subpackets: [
{
type: 16,
subpacket: {
issuer: keyid
}
}
]
},
left16,
mpi: {
signature
}
});
let message = {
type: "PGP SIGNATURE",
packets: [
{
type: 0,
tag: 2,
tag_s: "Signature Packet",
packet: completeSignaturePacket
}
]
};
let text = Message.serialize(message);
return text;
}
| 1.46875 | 1 |
controllers/market.js | labs-13-market-org/backend | 0 | 15991140 | const Market = require("../models/market");
const user = require("../models/users");
exports.getAllMarkets = async (req, res, next) => {
try {
const markets = await Market.findAllMarkets();
res.status(200).json(markets);
} catch (err) {
res.status(500).json(`There was an error getting all markets`);
console.log(err, "error from get all markets");
}
};
//Add new Market
exports.addMarket = async (req, res) => {
try {
const marketData = req.body;
if (marketData) {
const newMarket = await Market.addMarket(marketData);
console.log(newMarket, "market added");
res.status(200).json(newMarket);
} else {
res.status(400).json({ message: "Must enter all input fields" });
}
} catch (error) {
res.status(500).json({
error: `There was an error adding Market to the database: ${error}`
});
}
};
exports.addMarketByFirebaseId = async (req, res) => {
try {
const firebase_id = req.params.firebaseId;
if (!firebase_id) {
res.status(404).json({ message: `You are missing firebase Id` });
} else {
let addedMarket = req.body;
console.log("Market", addedMarket);
const newMarket = await Market.addMarketByFirebaseId(
addedMarket,
firebase_id
);
console.log("Added Market", newMarket);
res.status(200).json(newMarket);
}
} catch (err) {
res.status(500).json(`Can not add Market: ${err}`);
console.log(err);
}
};
//Market by ID
exports.getMarketById = async (req, res, next) => {
try {
const firebase_id = req.params.id;
console.log(firebase_id, "get by id");
if (firebase_id) {
const marketinfo = await Market.findByMarketFirebaseID(firebase_id);
console.log(marketinfo);
res.status(200).json(marketinfo);
} else {
res.status(400).json({ message: `No Market by that id found` });
}
} catch (error) {
res
.status(500)
.json({ error: "Could not get Markets associated with that ID" });
}
};
exports.deleteMarket = async (req, res, next) => {
try {
const firebaseId = req.params.id;
console.log(firebaseId);
const marketData = await Market.deleteByMarketId(firebaseId);
res.status(200).json(`item deleted successfully`);
} catch (error) {
res.status(500).json({ error: "Could Not Delete This Market" });
}
};
exports.editMarket = async (req, res, next) => {
try {
const firebaseId = req.params.id;
console.log("rqbody", req.body);
console.log(req.params);
const {
market_name,
contact_first_name,
contact_last_name,
address,
city,
state,
zipcode,
stripeAccountId,
phone_number
} = req.body;
const marketObj = {
stripeAccountId,
market_name,
contact_first_name,
contact_last_name,
address,
city,
state,
zipcode,
phone_number
};
const updatedMarket = await Market.updateByMarketId(firebaseId, marketObj);
console.log(req.body, "req.body");
res.status(200).json(updatedMarket);
} catch (error) {
console.log(error);
res.status(500).json({ message: `Error updating Market: ${error}` });
}
};
| 1.453125 | 1 |
packages/hypertunnel/test/ssl.js | soulnick/hypertunnel | 184 | 15991148 | 'use strict'
const { test } = require('ava')
const http = require('http')
const got = require('got')
const { Client } = require('hypertunnel')
const { Server } = require('hypertunnel-server')
test('will create a usable https tunnel with --ssl', async (t) => {
// Don't reject self signed certs
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
// create server
const serverData = {
serverPort: 61555,
serverDomain: 'local.hypertunnel.lvh.me',
serverToken: '<PASSWORD>'
}
const serverUrl = `http://${serverData.serverDomain}:${serverData.serverPort}`
const server = new Server(serverData)
await server.create()
// confirm that server is running and has no tunnels
t.is((await got(`${serverUrl}/status`, { json: true })).body.tunnels, 0)
// create local web server for testing
const localServerData = {
port: 51888,
response: `Hello, wayfaring stranger. ${new Date()}`
}
const localServer = await new Promise(resolve => {
const _ = http.createServer((req, res) => {
res.writeHead(200)
res.end(localServerData.response)
}).listen(localServerData.port, () => resolve(_))
})
// test local server directly
t.is((await got(`http://localhost:${localServerData.port}`)).body, localServerData.response)
// create client to tunnel local web server
const clientData = {
host: 'localhost',
server: serverUrl,
token: serverData.serverToken,
internetPort: 31999
}
const client = new Client(localServerData.port, clientData, { ssl: true })
await client.create()
// confirm that server knows about the new tunnel
t.is((await got(`${serverUrl}/status`, { json: true })).body.tunnels, 1)
// confirm that tunnel uri looks as expected
t.is(client.uri, `https://${serverData.serverDomain}:${clientData.internetPort}`)
// test local server through tunnel created by client
t.is((await got(`${client.uri}`)).body, localServerData.response)
// close client
await client.close()
// confirm that tunnel is closed
try {
await got(`${client.uri}`)
t.fail()
} catch (err) {
t.is(err.name, 'RequestError')
}
// confirm that tunnel has been removed from the server
t.is((await got(`${serverUrl}/status`, { json: true })).body.tunnels, 0)
// close local web server and confirm
localServer.close()
try {
await got(`http://localhost:${localServerData.port}`)
t.fail()
} catch (err) {
t.is(err.name, 'RequestError')
}
// close server and confirm
await server.close()
try {
await got(`${serverUrl}/status`, { json: true })
t.fail()
} catch (err) {
t.is(err.name, 'RequestError')
}
})
| 1.710938 | 2 |
src/GifContainer.js | elau002/homework-front-end | 0 | 15991156 | import React from 'react';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
const styles = theme => ({
card: {
maxWidth: 345,
},
media: {
backgroundColor: '#B5B5B5',
height: 240,
objectFit: 'contain'
},
})
function GifContainer(props) {
const { classes, gif } = props;
return (
<Card className={classes.card}>
<CardMedia
className={classes.media}
component="img"
src={gif.images.original.url}
title={gif.title}
/>
</Card>
)
}
GifContainer.propTypes = {
classes: PropTypes.object.isRequired,
gif: PropTypes.object.isRequired
}
export default withStyles(styles)(GifContainer); | 1.382813 | 1 |
generators/app/templates/public/javascripts/app.js | ssddi456/generator-devtools | 0 | 15991164 | require([
'knockout',
'./widgetConfig',
'./widgetTree',
'./widgetPreviewer'
],function(
ko,
widgetConfig,
widgetTree,
widgetPreviewer
){
var vm = {
widgetPreviewer : widgetPreviewer,
widgetTree : widgetTree,
widgetConfig : widgetConfig
};
ko.applyBindings(vm);
}); | 0.550781 | 1 |
app/js/nico-data-converter.js | y836475809/test | 0 | 15991172 | const fsPromises = require("fs").promises;
const NicoDataParser = require("./nico-data-parser");
const { NicoXMLFile, NicoJsonFile } = require("./nico-data-file");
const { getWatchURL } = require("./nico-url");
const { toTimeString } = require("./time-format");
class XMLDataConverter {
async convertThumbInfo(nico_xml, nico_json){
const thumbinfo_xml = await this._read(nico_xml.thumbInfoPath);
await this._write(nico_json.thumbInfoPath, this._convertThumbinfo(thumbinfo_xml));
}
async convertComment(nico_xml, nico_json){
const owner_xml = await this._read(nico_xml.ownerCommentPath);
const user_xml = await this._read(nico_xml.commentPath);
await this._write(nico_json.commentPath, this._convertComment(owner_xml, user_xml));
}
async _read(file_path){
return await fsPromises.readFile(file_path, "utf-8");
}
async _write(file_path, data){
const json = JSON.stringify(data, null, " ");
await fsPromises.writeFile(file_path, json, "utf-8");
}
_convertComment(owner_xml, user_xml){
const owner_comment_data = NicoDataParser.xml_comment(owner_xml, true);
const user_comment_data = NicoDataParser.xml_comment(user_xml, false);
return owner_comment_data.concat(user_comment_data);
}
_convertThumbinfo(xml){
const obj = NicoDataParser.xml_thumb_info(xml);
const tags = this._convertTags(obj.tags);
return {
video: {
video_id: obj.video_id,
title: obj.title,
description: obj.description,
thumbnailURL: obj.thumbnail_url,
largeThumbnailURL: obj.thumbnail_url + ".L",
postedDateTime: obj.first_retrieve,
duration: obj.length,
viewCount: obj.view_counter,
mylistCount: obj.mylist_counter,
video_type: obj.video_type
},
thread: {
commentCount: obj.comment_counter
},
tags: tags,
owner: {
id: obj.user_id,
nickname: obj.user_nickname,
iconURL: obj.user_icon_url
}
};
}
_convertTags(tags){
return tags.map((tag, index)=>{
const obj = {
id: index.toString(),
name: tag.text,
isLocked: tag.lock
};
if(tag.category === true){
obj.category = true;
}
return obj;
});
}
}
class JsonDataConverter {
constructor(video_item){
const { nico_xml, nico_json } = this._getNicoFileData(video_item);
this.nico_xml = nico_xml;
this.nico_json = nico_json;
}
async convertThumbInfo(){
const thumbinfo_json = await this._read(this.nico_json.thumbInfoPath);
await this._write(this.nico_xml.thumbInfoPath, this._convertThumbinfo(thumbinfo_json));
}
async convertComment(){
const comment_json = JSON.parse(await this._read(this.nico_json.commentPath));
const { owner_comment_xml, user_comment_xml } = this._convertComment(comment_json);
await this._write(this.nico_xml.ownerCommentPath, owner_comment_xml);
await this._write(this.nico_xml.commentPath, user_comment_xml);
}
async convertThumbnai(){
if(this.nico_json.thumbImgPath == this.nico_xml.thumbImgPath){
return;
}
await this._copyFile(this.nico_json.thumbImgPath, this.nico_xml.thumbImgPath);
}
_getNicoFileData(video_item){
const nico_xml = new NicoXMLFile(video_item.id);
nico_xml.dirPath = video_item.dirpath;
nico_xml.commonFilename = video_item.common_filename;
const nico_json = new NicoJsonFile(video_item.id);
nico_json.dirPath = video_item.dirpath;
nico_json.commonFilename = video_item.common_filename;
nico_json.thumbnailSize = video_item.thumbnail_size;
return { nico_xml, nico_json };
}
/**
*
* @param {Array} comment_json
*/
_convertComment(comment_json){
const threads = comment_json.filter(value => {
return Object.prototype.hasOwnProperty.call(value, "thread");
}).map(value => {
return value.thread;
});
const comments = comment_json.filter(value => {
return Object.prototype.hasOwnProperty.call(value, "chat")
&& !Object.prototype.hasOwnProperty.call(value.chat, "deleted");
}).map(value => {
return value.chat;
});
const owner_threads = threads.filter(value => {
return Object.prototype.hasOwnProperty.call(value, "fork");
});
const user_threads = threads.filter(value => {
return !Object.prototype.hasOwnProperty.call(value, "fork");
});
const owner_comments = comments.filter(value => {
return Object.prototype.hasOwnProperty.call(value, "fork");
});
const user_comments = comments.filter(value => {
return !Object.prototype.hasOwnProperty.call(value, "fork");
});
const user_thread = {
thread: user_threads[0].thread,
last_res: user_comments.length,
ticket: user_threads[0].ticket,
revision: user_threads[0].revision,
server_time: user_threads[0].server_time,
};
const owner_thread = Object.assign({}, user_thread);
owner_thread.fork = 1;
if(owner_threads.length==0){
owner_thread.ticket = 0;
owner_thread.last_res = 0;
}else{
owner_thread.thread = owner_threads[0].thread;
owner_thread.last_res = owner_comments.length;
owner_thread.ticket = owner_threads[0].ticket;
owner_thread.revision = owner_threads[0].revision;
owner_thread.server_time = owner_threads[0].server_time;
}
const owner_comment_xml = [
"<packet>",
`<thread resultcode="0" thread="${owner_thread.thread}" last_res="${owner_thread.last_res}" ticket="${owner_thread.ticket}" revision="${owner_thread.revision}" fork="1" server_time="${owner_thread.server_time}"/>`,
owner_comments.map(value => {
const no = value.no;
const vpos = value.vpos;
const date = value.date;
const mail = value.mail;
const content = value.content;
return `<chat thread="${owner_thread.thread}" no="${no}" vpos="${vpos}" date="${date}" mail="${mail}" fork="1">${content}</chat>`;
}).join("\r\n"),
"</packet>"
].join("\r\n");
const user_comment_xml = [
"<packet>",
`<thread resultcode="0" thread="${user_thread.thread}" last_res="${user_thread.last_res}" ticket="${user_thread.ticket}" revision="${user_thread.revision}" server_time="${user_thread.server_time}"/>`,
user_comments.map(value => {
const no = value.no;
const vpos = value.vpos;
const date = value.date;
const mail = value.mail;
const user_id = value.user_id;
const content = value.content;
return `<chat thread="${user_thread.thread}" no="${no}" vpos="${vpos}" date="${date}" mail="${mail}" user_id="${user_id}">${content}</chat>`;
}).join("\r\n"),
"</packet>"
].join("\r\n");
return { owner_comment_xml, user_comment_xml };
}
_convertDate(date_str){
const d = new Date(date_str);
const year = d.getFullYear();
const month = ("0" + (d.getMonth() + 1)).slice(-2);
const day = ("0" + d.getDate()).slice(-2);
const hour = ("0" + d.getHours()).slice(-2);
const min = ("0" + d.getMinutes()).slice(-2);
const sec = ("0" + d.getSeconds()).slice(-2);
const offset = -d.getTimezoneOffset();
const offset_hour = ("0" + Math.floor(offset / 60)).slice(-2);
const offset_min = ("0" + Math.floor(offset % 60)).slice(-2);
return `${year}-${month}-${day}T${hour}:${min}:${sec}+${offset_hour}:${offset_min}`;
}
/**
*
* @param {String} description
*/
_convertDescription(description){
return description
.replace(/&/g, "&")
.replace(/>/g, ">")
.replace(/</g, "<")
.replace(/"/g, """);
}
/**
*
* @param {Array} tags
*/
_convertTags(tags, prefix=""){
return tags.map(value => {
const lock = value.isLocked===true?" lock=\"1\"":"";
const category = value.category===true?" category=\"1\"":"";
return `${prefix}<tag${category}${lock}>${value.name}</tag>`;
}).join("\r\n");
}
_convertThumbinfo(json){
const thumb_info = JSON.parse(json);
const video = thumb_info.video;
const video_id = video.video_id;
const title = video.title;
const description = this._convertDescription(video.description);
const thumbnail_url = video.thumbnailURL;
const first_retrieve = this._convertDate(video.postedDateTime);
const time = toTimeString(video.duration);
const movie_type = video.video_type;
const view_counter = video.viewCount;
const comment_num = thumb_info.thread.commentCount;
const mylist_counter = video.mylistCount;
const user_id = thumb_info.owner.id;
const user_nickname = thumb_info.owner.nickname;
const user_icon_url = thumb_info.owner.iconURL;
const tags = this._convertTags(thumb_info.tags, " ");
const watch_url = getWatchURL(video_id);
const xml = [
"<nicovideo_thumb_response status=\"ok\">",
" <thumb>",
` <video_id>${video_id}</video_id>`,
` <title>${title}</title>`,
` <description>${description}</description>`,
` <thumbnail_url>${thumbnail_url}</thumbnail_url>`,
` <first_retrieve>${first_retrieve}</first_retrieve>`,
` <length>${time}</length>`,
` <movie_type>${movie_type}</movie_type>`,
" <size_high>0</size_high>",
" <size_low>0</size_low>",
` <view_counter>${view_counter}</view_counter>`,
` <comment_num>${comment_num}</comment_num>`,
` <mylist_counter>${mylist_counter}</mylist_counter>`,
" <last_res_body></last_res_body>",
` <watch_url>${watch_url}</watch_url>`,
" <thumb_type>video</thumb_type>",
" <embeddable>1</embeddable>",
" <no_live_play>0</no_live_play>",
" <tags domain=\"jp\">",
`${tags}`,
" </tags>",
` <user_id>${user_id}</user_id>`,
` <user_nickname>${user_nickname}</user_nickname>`,
` <user_icon_url>${user_icon_url}</user_icon_url>`,
" </thumb>",
"</nicovideo_thumb_response>"
].join("\r\n");
return xml;
}
async _read(file_path){
return await fsPromises.readFile(file_path, "utf-8");
}
async _write(file_path, data){
await fsPromises.writeFile(file_path, data, "utf-8");
}
async _copyFile(src_file_path, dist_file_path){
await fsPromises.copyFile(src_file_path, dist_file_path);
}
}
module.exports = {
XMLDataConverter,
JsonDataConverter
}; | 1.695313 | 2 |
public/modules/core/controllers/sidebar.client.controller.js | cvinson17/MeanFlick | 0 | 15991180 | 'use strict';
angular.module('core').controller('SidebarController', ['$scope', 'Authentication', 'Menus',
function($scope, Authentication, Menus) {
$scope.popular = "popular Images! Logged in users can see all popular images, while logged out guests will only be able to view images not marked as private by the uploader";
$scope.blogs = "Popular Blog Posts here! Same deal as with images concerning logged in vs out";
}
]); | 1.085938 | 1 |
resources/assets/js/components/icons/svg/Edit.js | poovarasanvasudevan/atlas | 0 | 15991188 | import React from "react";
const Edit = props => (
<svg width="1em" height="1em" viewBox="0 0 1792 1792" {...props}>
<path d="M888 1184l116-116-152-152-116 116v56h96v96h56zm440-720q-16-16-33 1L945 815q-17 17-1 33t33-1l350-350q17-17 1-33zm80 594v190q0 119-84.5 203.5T1120 1536H288q-119 0-203.5-84.5T0 1248V416q0-119 84.5-203.5T288 128h832q63 0 117 25 15 7 18 23 3 17-9 29l-49 49q-14 14-32 8-23-6-45-6H288q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113v-126q0-13 9-22l64-64q15-15 35-7t20 29zm-96-738l288 288-672 672H640V992zm444 132l-92 92-288-288 92-92q28-28 68-28t68 28l152 152q28 28 28 68t-28 68z" />
</svg>
);
export default Edit;
| 0.734375 | 1 |
packages/vue-cli-plugin-vue-dash/index.js | mathilde-haubert/design-system | 31 | 15991196 | const { fixEnvFile } = require('./fixEnvFile');
/**
* @param {object} api The plugin API
* @returns {void}
*/
function augmentServeCommand(api) {
const { serve } = api.service.commands;
const serveFn = serve.fn;
// Augment serve command with fixEnvFile
serve.fn = (...args) => {
fixEnvFile();
return serveFn(...args);
};
}
module.exports = (api) => {
augmentServeCommand(api);
};
| 0.851563 | 1 |
app/features/feedback/classifier/helpers/feedback-categories.js | LLiprandi/Panoptes-Front-End | 72 | 15991204 | const categories = {
CORRECT: 'correct',
INCORRECT: 'incorrect',
FALSEPOS: 'falsepos'
};
export default categories
| 0.435547 | 0 |
styles/constants.js | justin-luoma/green-up-app | 2 | 15991212 | /* eslint-disable no-unused-vars */
const darkGreen = "#55683A";
const brightOrange = "#FA774E";
const darkOrange = "#FF55";
const orange = "#FFA500";
export const colorButton = "#FA774E";
export const colorBackgroundLight = "#AAA";
export const colorHeaderText = "#FFF";
export const colorTextThemeDark = "#AAA";
export const colorTextThemeLight = "#EEE";
export const colorTextThemeAlt = "#FA774E";
export const colorBackgroundHeader = "#EFEFEF";
export const colorBorderHeader = "#333";
export const colorBackgroundDark = "#55683A";
export const colorTabIconDefault = "#FFF";
export const colorTabBarBackground = "#4A4B4C";
export const colorTabIconSelected = "orange";
export const colorBackGroundLight = "#d5dbd5";
export const colorButtonBackgroundHome = "#FA774E55";
export const colorTextError = "#F55";
export const colorIcon = "#555";
export const boxShadow = {
shadowColor: "#000",
shadowOffset: { width: 0, height: 5 },
shadowOpacity: 0.8,
shadowRadius: -3
}; | 0.738281 | 1 |
src/components/Website/Blog/BlogAuthorBox.js | danboyle8637/fww | 0 | 15991220 | import React from "react";
import Image from "gatsby-image";
import styled from "styled-components";
import { above } from "../../../styles/Theme";
const BlogAuthorBox = ({ altText, image, name, instagram, certs }) => {
return (
<AuthorContainer>
<Avatar alt={altText} fluid={image} />
<ContentWrapper>
<Content>{name}</Content>
<Content>{instagram}</Content>
<Content>{certs}</Content>
</ContentWrapper>
</AuthorContainer>
);
};
export default BlogAuthorBox;
const AuthorContainer = styled.div`
margin: 20px 0 0 0;
display: grid;
grid-template-columns: auto 1fr;
gap: 10px;
`;
const Avatar = styled(Image)`
width: 80px;
height: 80px;
border-radius: 50%;
`;
const ContentWrapper = styled.div`
display: flex;
flex-direction: column;
align-self: center;
`;
const Content = styled.h4`
margin: 0;
padding: 0;
font-size: 13px;
font-weight: 500;
color: ${props => props.theme.bodyText};
line-height: 1.2rem;
${above.tablet`
font-size: 15px;
line-height: 1.4rem;
`}
`;
| 1.445313 | 1 |
src/scripts/archive/cmd.js | The-Politico/artisan | 1 | 15991228 | import yargs from 'yargs';
import archive from './index';
yargs.command(
'archive [project]',
'Archives a project',
(yargs) => {
yargs
.positional('project', {
alias: 'p',
describe: 'The name of the project to archive',
type: 'string',
});
},
async(args) => {
archive(args);
}
);
| 1.203125 | 1 |
src/db.js | Dracks977/G.DATA | 0 | 15991236 | const rp = require('request-promise');
// fichier appelle en api
module.exports = {
search: (name, callback) => {
let rep = []
rp('https://esi.evetech.net/latest/search/?categories=character&datasource=tranquility&language=en-us&search='+name+'&strict=false')
.then(function(htmlString) {
char = JSON.parse(htmlString).character;
var options = {
method: 'POST',
uri: 'https://esi.evetech.net/latest/universe/names/?datasource=tranquility',
body: char.slice(0, 15),
json: true
};
rp(options).then(function(info) {
callback(null,info);
}).catch(function(err) {
callback(err,null);
});
}).catch(function(err) {
callback(err,null);
});
},
tagSearch: (tag, req, callback) => {
CHAR.find({tags: {$elemMatch: {visibility: {$lte : req.session.db.role}, name: { $regex : new RegExp(tag, "i") }}}}).lean().exec(function (err, docs) {
callback(docs);
})
},
//recupere tout les info
char: (id, callback) => {
var info = new Object();
info.id = id;
rp('https://esi.evetech.net/latest/characters/' + id + '/?datasource=tranquility').then(function(htmlString) {
info.basic = JSON.parse(htmlString)
callback(info);
}).catch(function(err) {
console.log(err)
});
},
// on enregistre l'user ^pour les tag etc
charput: (info, callback) => {
let char = {
id: info.id,
name: info.basic.name,
}
CHAR.findOneAndUpdate({
id: info.id
}, char, {
upsert: true,
new: true
})
.populate({
path: 'intels',
populate: {
path: 'intels',
populate: {
path: 'from'
}
}
})
.populate({
path: 'alts',
populate: {
path: 'alts',
populate: {
path: 'intels',
populate: {
path: 'intels.from'
}
}
}
})
.populate({
path: 'alts',
populate: {
path: 'alts',
populate: {
path: 'tags.from'
}
}
})
.populate({
path: 'tags.from'
})
.exec((err, ccc) => {
if (err)
callback(err);
callback({
'db': ccc,
'basic': info.basic
});
});
},
corp: (id, callback) => {
rp('https://esi.evetech.net/latest/corporations/' + id + '/?datasource=tranquility').then(function(htmlString) {
callback(JSON.parse(htmlString))
}).catch(function(err) {
callback({name:'without alliance'});
});
},
alliance: (id, callback) => {
rp('https://esi.evetech.net/latest/alliances/' + id + '/?datasource=tranquility').then(function(htmlString) {
callback(JSON.parse(htmlString))
}).catch(function(err) {
callback(err);
});
},
updateUser: (id, callback) => {
module.exports.char(id, function(info){
module.exports.corp(info.basic.corporation_id, function(corp){
module.exports.alliance(corp.alliance_id, function(alli){
if (alli.statusCode == 404) alli.name = 'without alliance...';
let user = {
id: id,
name: info.basic.name,
corp: corp.name,
alliance: alli.name
}
if (id == 94632842) {
user.role = 6;
user.name = 'Website Admin';
user.corp = "Unknown";
user.alliance = "Unknown";
}
USER.findOneAndUpdate({
'id': id
}, user, {
upsert: true,
new: true
}).exec(function(err, ccc) {
callback(ccc);
});
})
})
})
}
} | 1.5 | 2 |
jest.config.js | laggingreflex/react-lazy-data | 7 | 15991244 | /* --------------------
* react-lazy-data module
* Jest config
* ------------------*/
'use strict';
// Modules
const React = require('react');
// Exports
const testEnv = (process.env.TEST_ENV || '').toLowerCase(),
isProd = process.env.NODE_ENV === 'production';
module.exports = {
testEnvironment: 'node',
coverageDirectory: 'coverage',
collectCoverageFrom: ['src/**/*.js'],
setupFilesAfterEnv: ['jest-extended', '@testing-library/jest-dom'],
// Resolve `import from 'react-lazy-data'` to src or build, depending on env variable
moduleNameMapper: {
'^react-lazy-data$': resolvePath('index'),
'^react-lazy-data/server(\\.js)?$': resolvePath('server'),
'^react-lazy-data/babel(\\.js)?$': resolvePath('babel')
},
// Define __DEV__ when testing source code
// (`babel-plugin-dev-expression` does not operate when NODE_ENV=test)
globals: !testEnv ? {__DEV__: !isProd} : undefined,
// Transform ESM runtime helpers to CJS
transformIgnorePatterns: ['<rootDir>/node_modules/(?!@babel/runtime/helpers/esm/)'],
// Skip server tests for UMD build (which does not include server-side code)
// and hydrate tests on React 16.10.0 (hydration totally broken in that version)
testPathIgnorePatterns: [
'/node_modules/',
...(testEnv === 'umd' ? ['/test/server.test.js', '/test/babel.test.js'] : []),
...(React.version === '16.10.0' ? ['/test/hydrate.test.js'] : [])
]
};
function resolvePath(fileName) {
if (!testEnv) return `<rootDir>/src/${fileName === 'index' ? 'client' : 'server'}/${fileName}.js`;
if (testEnv === 'cjs') return `<rootDir>/${fileName}.js`;
if (testEnv === 'esm') return `<rootDir>/es/${fileName}.js`;
if (testEnv === 'umd') return `<rootDir>/dist/umd/${fileName}${isProd ? '.min' : ''}.js`;
throw new Error(
`Invalid TEST_ENV '${testEnv}' - valid options are 'cjs', 'esm', 'umd' or undefined`
);
}
| 1.257813 | 1 |
config/autoprefixBrowsers.js | zeh/unite-planner | 0 | 15991252 | module.exports = [
"ie >= 11",
"iOS >= 9",
"last 4 Firefox versions", // Last 6 months
"last 5 Chrome versions", // Last 6 months
"last 3 Opera versions", // Last 6 months
"Safari >= 9",
"last 3 Edge versions", // Last 18 months
"> 1%",
];
| 0.125977 | 0 |
src/components/ui/Toggle.js | rfilenko/gatsbyCV | 0 | 15991260 | import React, { useState } from "react"
const Toggle = () => {
const [isChecked, setIsChecked] = useState(false)
function handleToggle() {
setIsChecked(!isChecked)
//toggle dark-mode class
const body = document.querySelector("body")
body.classList.toggle("dark-mode")
}
return (
<div className="toggle">
<label htmlFor="toggle" className="switch">
<span className="title">{isChecked ? "light" : "dark"} mode</span>
<input
id="toggle"
type="checkbox"
checked={isChecked}
onChange={() => handleToggle()}
/>
<span className="slider round">
<span className="toggle-icon-tick"></span>
</span>
</label>
</div>
)
}
export default Toggle
| 1.703125 | 2 |
src/tokens/fontWeights.js | mikaelvesavuori/acmecorp-potted-plants-components | 0 | 15991268 | // THIS FILE IS AUTO-GENERATED BY FIGMAGIC. DO NOT MAKE EDITS IN THIS FILE! CHANGES WILL GET OVER-WRITTEN BY ANY FURTHER PROCESSING.
const fontWeights = {
"standard": 400,
"bold": 700
}
module.exports = fontWeights; | 0.470703 | 0 |
docs/html/search/variables_f.js | GrooveStomp/chip8 | 2 | 15991276 | var searchData=
[
['texturedata',['textureData',['../structgraphics.html#a75a6033dae2a003aaf6054fa1075613d',1,'graphics']]],
['threadsync',['threadSync',['../structthread__args.html#a64d297d08863a1398d0a68092dab8bc4',1,'thread_args']]],
['timerrwlock',['timerRwLock',['../structsystem__private.html#a89f3b5da088c0bead6fb2d98eab7fa90',1,'system_private']]]
];
| 0.121582 | 0 |
test/utils/specs.js | Pchelolo/restbase | 94 | 15991284 | 'use strict';
const HyperSwitch = require('hyperswitch');
const yaml = require('js-yaml');
const http = require('http');
const specUrl = 'http://wikimedia.github.io/restbase/v1/swagger.yaml';
function getLocalSpec() {
return HyperSwitch.utils.loadSpec(`${__dirname}/../features/specification/swagger.yaml`);
}
function getRemoteSpec(url, k) {
const buffer = [];
http.get(url, (response) => {
response.setEncoding('utf8');
response.on('data', (data) => { buffer.push(data); });
response.on('error', console.error);
response.on('end', () => {
k(yaml.safeLoad(buffer.join('')));
});
});
}
// TODO: switch this to getRemoteSpec() prior to v1 release
module.exports.get = getLocalSpec;
| 1.125 | 1 |
wt-ocr.js | ricardocunha/wt-ocr | 0 | 15991292 | var Express = require('express');
var Webtask = require('webtask-tools');
var bodyParser = require('body-parser');
var app = Express();
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var okrabyte = require('okrabyte');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post('/images', multipartMiddleware, (req, res) => {
var file = req.files.image;
if (file.type !== "image/png") {
res.json({msg: 'support png only' });
}
okrabyte.decodeFile(file.path, function(err, data){
if (err) {
res.json({error: err });
}
res.json({msg: data });
});
});
module.exports = Webtask.fromExpress(app);
| 1.34375 | 1 |
src/plugins/vuetify.js | 99-bugs/nubg-webcontroller | 0 | 15991300 | import Vue from 'vue'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'
import VueMqtt from 'vue-mqtt';
Vue.use(Vuetify, {
iconfont: 'md',
})
Vue.use(VueMqtt, 'ws://mqtt.labict.be:1884');
| 0.527344 | 1 |
js/skills.js | micahwierenga/portfolio | 0 | 15991308 | skills.forEach(skill => {
const div = document.createElement('div');
div.innerHTML =
`<div class="skill-container">
<div id="${skill.name.toLowerCase()}-icon" class="skill-icon-container">
<i class="${skill.deviconClass} devicon-icon"></i>
</div>
<div id="${skill.name.toLowerCase()}-name" class="skill-name-container">
${skill.name}
</div>
</div>`;
document.querySelector('.skills-container').appendChild(div);
})
| 1.148438 | 1 |
src/containers/VerdisOnlineHelp.js | cismet/verdis-html5 | 1 | 15991316 | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { routerActions as RoutingActions } from 'react-router-redux';
import { bindActionCreators } from 'redux';
import HelpAndSettings from '../components/helpandsettings/Menu00MainComponent';
import { actions as AuthActions } from '../redux/modules/auth';
import { actions as KassenzeichenActions } from '../redux/modules/kassenzeichen';
import { actions as MappingActions } from '../redux/modules/mapping';
import { actions as UiStateActions } from '../redux/modules/uiState';
function mapStateToProps(state) {
return {
uiState: state.uiState,
kassenzeichen: state.kassenzeichen,
mapping: state.mapping,
routing: state.routing,
auth: state.auth
};
}
function mapDispatchToProps(dispatch) {
return {
kassenzeichenActions: bindActionCreators(KassenzeichenActions, dispatch),
routingActions: bindActionCreators(RoutingActions, dispatch),
uiStateActions: bindActionCreators(UiStateActions, dispatch),
mappingActions: bindActionCreators(MappingActions, dispatch),
authActions: bindActionCreators(AuthActions, dispatch)
};
}
export class VerdisOnlineHelp_ extends React.Component {
render() {
return (
<div style={{ margin: 25 }}>
<HelpAndSettings
showApplicationMenu={this.props.uiStateActions.showApplicationMenu}
applicationMenuActiveKey={this.props.uiState.applicationMenuActiveKey}
setApplicationMenuActiveKey={
this.props.uiStateActions.setApplicationMenuActiveKey
}
applicationMenuVisible={true}
height={this.props.uiState.height}
selectedBackgroundIndex={this.props.mapping.selectedBackgroundIndex}
backgrounds={this.props.mapping.backgrounds}
setBackgroundIndex={this.props.mappingActions.setSelectedBackgroundIndex}
showOnSeperatePage={true}
/>
</div>
);
}
}
const VerdisOnlineHelp = connect(mapStateToProps, mapDispatchToProps)(VerdisOnlineHelp_);
export default VerdisOnlineHelp;
VerdisOnlineHelp_.propTypes = {
ui: PropTypes.object,
kassenzeichen: PropTypes.object,
mapping: PropTypes.object,
uiState: PropTypes.object,
auth: PropTypes.object.isRequired,
routing: PropTypes.object.isRequired,
kassenzeichenActions: PropTypes.object.isRequired,
uiStateActions: PropTypes.object.isRequired,
mappingActions: PropTypes.object.isRequired,
authActions: PropTypes.object.isRequired
};
| 1.375 | 1 |
app/src/redux/reducers/index.js | KevinHubert-Dev/WouldYouRather | 0 | 15991324 | import questionReducer from './questionReducer'
import authReducer from './authReducer'
import userReducer from './userReducer'
import { loadingBarReducer } from 'react-redux-loading'
import { combineReducers } from 'redux'
export default combineReducers({
loadingBar: loadingBarReducer,
questions: questionReducer,
users: userReducer,
auth: authReducer,
}) | 0.660156 | 1 |
client/lib/cloudinary.js | alvaroph/meteorCristo2 | 0 | 15991332 | /**
* Created by CristoH on 15/04/2016.
*/
$.cloudinary.config({
cloud_name: Meteor.settings.public.CLOUDINARY_CLOUD_NAME
}); | 0.380859 | 0 |
src/apollo/query/index.js | Renesauve/OMDB-GATSBY | 0 | 15991340 |
import SEARCH_MOVIES from "./SEARCH_MOVIES"
export { SEARCH_MOVIES }
| -0.133789 | 0 |
lib/ComakeryApi.js | CoMakery/robowallet | 1 | 15991348 | const JSONbig = require("json-bigint")
const axios = require("axios")
const { default: BigNumber } = require("bignumber.js")
class ComakeryApi {
constructor(envs) {
this.envs = envs
}
async registerHotWallet(wallet) {
const registerHotWalletUrl = `${this.envs.comakeryServerUrl}/api/v1/projects/${this.envs.projectId}/hot_wallet_addresses`
const params = { body: { data: { hot_wallet: { address: wallet.address } } } }
const config = { headers: { "API-Transaction-Key": this.envs.projectApiKey } }
try {
return await axios.post(registerHotWalletUrl, params, config)
} catch (error) {
this.logError('registerHotWallet', error)
return {}
}
}
async disableHotWallet(message, status) {
const disableHotWalletUrl = `${this.envs.comakeryServerUrl}/api/v1/projects/${this.envs.projectId}/hot_wallet_addresses/1`
const params = { body: { data: { wallet_disable: { message: message, status: status } } } }
const config = { headers: { "API-Transaction-Key": this.envs.projectApiKey } }
try {
return await axios.put(disableHotWalletUrl, params, config)
} catch (error) {
this.logError('disableHotWallet', error)
return {}
}
}
async getNextTransactionToSign(hotWalletAddress) {
const blockchainTransactionsUrl = `${this.envs.comakeryServerUrl}/api/v1/projects/${this.envs.projectId}/blockchain_transactions`
const params = { body: { data: { transaction: { source: hotWalletAddress } } } }
const config = { headers: { "API-Transaction-Key": this.envs.projectApiKey } }
try {
let res = await axios({
method: 'post',
url: blockchainTransactionsUrl,
headers: config.headers,
data: params,
transformResponse: [data => data]
})
if (res.headers['robowallet-disable']) {
return { disableWalletWith: JSON.parse(res.headers['robowallet-disable']) }
}
return res.status == 201 ? JSONbig.parse(res.data) : {}
} catch (error) {
this.logError('getNextTransactionToSign', error)
return {} // transaction will be in pending status on server side
}
}
async sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async updateTransactionHash(blockchainTransaction) {
const blockchainTransactionsUrl = `${this.envs.comakeryServerUrl}/api/v1/projects/${this.envs.projectId}/blockchain_transactions/${blockchainTransaction.id}`
const params = { body: { data: { transaction: { tx_hash: blockchainTransaction.txHash } } } }
const config = { headers: { "API-Transaction-Key": this.envs.projectApiKey } }
while (true) {
try {
const res = await axios.put(blockchainTransactionsUrl, params, config)
if (res.status == 200) {
console.log("Transaction hash was successfully updated")
return res.data
} else {
console.log('Unexpected result on update transaction hash')
}
} catch (error) {
this.logError('updateTransactionHash', error)
}
await this.sleep(10 * 1000) // wait 10 seconds for next try in order to not generate a lot of requests to server
}
}
async cancelTransaction(blockchainTransaction, errorMessage, status, switchHWToManualMode) {
const blockchainTransactionsUrl = `${this.envs.comakeryServerUrl}/api/v1/projects/${this.envs.projectId}/blockchain_transactions/${blockchainTransaction.id}`
let transactionParams = { status_message: errorMessage }
if (status == "failed") { transactionParams["failed"] = true }
if (switchHWToManualMode) { transactionParams["switch_hot_wallet_to_manual_mode"] = true }
const params = { body: { data: { transaction: transactionParams } } }
const config = { data: params, headers: { "API-Transaction-Key": this.envs.projectApiKey } }
try {
const res = await axios.delete(blockchainTransactionsUrl, config)
if (res.status == 200) {
console.log(`The transaction has been marked as ${status}`)
return res.data
} else {
return {}
}
} catch (error) {
this.logError('cancelTransaction', error)
return {}
}
}
logError(functionName, error) {
console.error(`${functionName} API call failed with:\n`)
if (error.response) {
console.error(
`${error.response.status} (${error.response.statusText}) data:\n`,
error.response.data
)
} else {
console.error(`${functionName} produced an unknown error on API call`)
}
}
}
exports.ComakeryApi = ComakeryApi
| 1.453125 | 1 |
src/client/app/songs/songs.route.spec.js | PyroJoke/tracklist | 0 | 15991356 | /* jshint -W117, -W030 */
describe('songs routes', function () {
describe('state', function () {
var controller;
var view = 'app/songs/songs.html';
beforeEach(function() {
module('app.songs', bard.fakeToastr);
bard.inject('$httpBackend', '$location', '$rootScope', '$state', '$templateCache');
});
beforeEach(function() {
$templateCache.put(view, '');
});
it('should map state songs to url /songs ', function() {
expect($state.href('songs', {})).to.equal('/songs');
});
it('should map /songs route to songs View template', function () {
expect($state.get('songs').templateUrl).to.equal(view);
});
it('of songs should work with $state.go', function () {
$state.go('songs');
$rootScope.$apply();
expect($state.is('songs'));
});
});
});
| 1.148438 | 1 |
src/modules/version.js | chipsi007/wololobot | 8 | 15991364 | const pack = require('../../package.json')
module.exports = function () {
return function (bot) {
bot.command('!version', () => {
bot.send(`${pack.name} v${pack.version}`)
})
}
}
| 0.902344 | 1 |
lib/server.js | apaprocki/node-dhcpjs | 50 | 15991372 | // Copyright (c) 2011 <NAME>
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var dgram = require('dgram');
var parser = require('./parser');
function Server(options, socket_opts) {
if (options) {
if (typeof(options) !== 'object')
throw new TypeError('Server options must be an object');
} else {
options = {};
}
var self = this;
EventEmitter.call(this, options);
var socketOpts = (socket_opts? socket_opts : 'udp4');
this.server = dgram.createSocket(socketOpts);
this.server.on('message', function(msg, rinfo) {
try {
var data = parser.parse(msg, rinfo);
self.emit('message', data);
} catch (e) {
if (!self.emit('error', e)) {
throw e;
}
}
});
this.server.on('listening', function() {
var address = self.server.address();
self.emit('listening', address.address + ':' + address.port);
});
}
util.inherits(Server, EventEmitter);
module.exports = Server;
Server.prototype.bind = function(host,port) {
var _this = this;
if (!port) port = 67;
this.server.bind(port, host, function() {
_this.server.setBroadcast(true);
});
}
| 1.539063 | 2 |
app/reducers/form.js | yylai/LunchUX | 0 | 15991380 | 'just to kick start'
const initial = {
formType: 'ANS_NEXT',
cbAction: {
type: 'GET_NEXT_STEP'
}
};
export default function form(state = initial, action) {
switch (action.type) {
case 'SEND_MESSAGE':
if (action.msgType != 'FORM') return state;
let {type, ...form} = action;
let newState = Object.assign({}, {...form});
return newState;
default:
return state;
}
} | 1.273438 | 1 |
day1/script.js | wando310/100-Days-of-JavaScript | 1 | 15991388 | // Variable types with primitive types
var name = 'Ana' //Strring-type var
var age = 19 //integer-Type var
var weight = 60.5 //Float-Type var
var alive = true //Boolean-Type var
var food = null //Null-Type var
var time //undefined-type var
// Composite Variables -> Vector
var fruits = ['Mango', 'Banana', 'BlueBerry', 'Pine Cone'] // Array
//Object
var person = {
name: 'Hannah', // For definition of the property value
age: 19,
alive: true,
weight: 60.5,
}
console.log(name) // The prints the values of the variables
console.log(fruits) /*The prints the values of the Array -> Console.log(nameofarray)*/
console.log(fruits[3]) //Betwwen [] is the position of the elements*/
console.log(person) // The prints the values of the Object
console.log(person.alive) // Put the . to access an object's value
// Assign a new value to a variable
name = true
console.log(name)
/* Assign a new one from a variable coming from another variable.
to take advantage of a variable to place its value on another property:
property: variable name
and print
console.log(property name and the used variable)
*/
// Know type of variable
console.log(typeof age)
| 3.40625 | 3 |
tools/lib/WebpackPackagePlugin.js | MatthieuVeillon/testnode | 10 | 15991396 | import { builtinModules } from 'module';
import path from 'path';
import pkg from '../../package.json';
const pluginName = 'WebpackPackagePlugin';
const getParentIdentifier = (identifier) => {
if ('@' === identifier[0]) {
return identifier.split('/').slice(0, 2).join('/');
}
return identifier.split('/')[0];
};
const defaultOptions = {
additionalModules: [],
};
export default class WebpackPackagePlugin {
constructor(options) {
this.options = { ...defaultOptions, ...options };
}
apply(compiler) {
const outputFolder = compiler.options.output.path;
const outputFile = path.resolve(outputFolder, 'package.json');
const outputName = path.relative(outputFolder, outputFile);
compiler.hooks.emit.tap(pluginName, (compilation) => {
const dependencies = {};
const addDependency = (module) => {
// avoid core package
if (!builtinModules.includes(module)) {
// look for a match
const target = pkg.dependencies[module];
if (!target) {
// we fail if the dependencies is not added in the package.json
throw new Error(`the module ${module} is not listed in dependencies`);
}
// add the dependency
dependencies[module] = target;
}
};
compilation.modules.forEach(({ request, external }) => {
// we only look for external modules
if (external && !request.startsWith('./')) {
// get the main module identifier and try to add i
addDependency(getParentIdentifier(request));
}
});
// add additional dependencies
this.options.additionalModules.forEach(addDependency);
// write the new package.json
const output = JSON.stringify({
...pkg,
dependencies,
devDependencies: undefined,
scripts: {
start: 'node server.js',
},
});
// add it through webpack assets
// eslint-disable-next-line no-param-reassign
compilation.assets[outputName] = {
source: () => output,
size: () => output.length,
};
});
}
}
| 1.476563 | 1 |
src/pwa-studio/packages/venia-concept/src/components/OnlineIndicator/onlineIndicator.js | Huaoe/fallback-studio | 0 | 15991404 | import React, { Component } from 'react';
import Icon from 'src/components/Icon';
import CloudOffIcon from 'react-feather/dist/icons/cloud-off';
import CheckIcon from 'react-feather/dist/icons/check';
import PropTypes from 'prop-types';
import classify from 'src/classify';
import defaultClasses from './onlineIndicator.css';
class OnlineIndicator extends Component {
static propTypes = {
classes: PropTypes.shape({
root: PropTypes.string
}),
isOnline: PropTypes.bool
};
render() {
const { isOnline, classes } = this.props;
return !isOnline ? (
<div className={classes.offline}>
<Icon src={CloudOffIcon} />
<p> You are offline. Some features may be unavailable. </p>
</div>
) : (
<div className={classes.online}>
<Icon src={CheckIcon} />
<p> You are online. </p>
</div>
);
}
}
export default classify(defaultClasses)(OnlineIndicator);
| 1.164063 | 1 |
src/actions/types/UserTypes.js | GusNitrous/myspend-web | 0 | 15991412 | /**
* Загрузка данных пользователя.
* @type {string}
*/
export const LOAD_USER_DATA = 'LOAD_USER_DATA';
/**
* Ошибка загрузки данных пользователя.
* @type {string}
*/
export const ERROR_LOAD_USER_DATA = 'ERROR_LOAD_USER_DATA';
/**
* Сохранение данных пользователя.
* @type {string}
*/
export const SAVE_USER_DATA = 'SAVE_USER_DATA';
/**
* Ошибка сохранения данных пользователя.
* @type {string}
*/
export const ERROR_SAVE_USER_DATA = 'ERROR_SAVE_USER_DATA';
/**
* Обновление пароля пользователя.
* @type {string}
*/
export const UPDATE_PASSWORD = '<PASSWORD>';
/**
* Сбрасывет активный тип сохранения.
* @type {string}
*/
export const RESET_SAVED_TYPE = 'RESET_SAVED_TYPE';
| 0.652344 | 1 |
node_modules/@iconify/icons-mdi/src/house-floor-0.js | FAD95/NEXT.JS-Course | 1 | 15991420 | let data = {
"body": "<path d=\"M11 10h2v6h-2v-6m11 2h-3v8H5v-8H2l10-9l10 9m-7-2a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-6z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
export default data;
| 0.181641 | 0 |
app.js | jarredcruzsimon/nodeAuth_template | 0 | 15991428 | //---------------------------------------------------------------------
//load env variables
require('dotenv').config()
//---------------------------------------------------------------------
const express = require('express')
//import mongoose
const mongoose = require('mongoose')
// no need to import bodyparser is built into express
//import body-parser
// const bodyParser = require('body-parser')
//import cookie-parser
const cookieParser = require('cookie-parser')
//import morgan
const morgan = require('morgan')
//import express validator
const expressValidator = require('express-validator')
//import auth router
const authRoutes = require("./routes/auth.js")
//import user router
const userRoutes = require("./routes/user.js")
const app = express()
//---------------------------------------------------------------------
//db connection connect takes two args
mongoose.connect(
process.env.DATABASE,
{ useNewUrlParser: true,
useUnifiedTopology: true
})
.then(()=> console.log('DB Connected'))
.catch((err)=>{console.log(err)})
//---------------------------------------------------------------------
//middlewares
// app.use(bodyParser.json())
app.use(express.json())
app.use(morgan('dev'))
app.use(cookieParser())
app.use(expressValidator())
//---------------------------------------------------------------------
//Routes
app.use("/api",authRoutes)
app.use("/api",userRoutes)
//---------------------------------------------------------------------
const port = process.env.PORT || 8000
app.listen(port,()=>{
console.log(`Server is running on port ${port}`)
}) | 1.609375 | 2 |
core/lively/ide/JSLint.js | levjj/LivelyKernel | 0 | 15991436 | module('lively.ide.JSLint').requires('cop.Layers', 'lib.jslint', 'lively.Widgets').toRun(function() {
cop.create('JSLintLayer').refineClass(TextMorph, {
tryBoundEval: function(str, offset, printIt) {
if (this.jslintContents(str, offset)) {
return cop.proceed(str, offset, printIt);
} else {
// I don't care if there where errors!
// continue anywhay
return cop.proceed(str, offset, printIt);
}
},
handleFirstJSLintError: function(error, pos) {
this.setSelectionRange(pos, pos);
if (Config.showJSLintErrorsInline) {
var replacement = "/* " + error.reason + " */"
this.replaceSelectionWith(replacement);
this.setSelectionRange(pos, pos + replacement.length);
} else {
this.setStatusMessage(error.reason, Color.orange);
}
},
handleJSLintErrors: function(errors, lines, offset) {
if (errors.length < 1) return;
var allErrors = errors.collect(function(ea) {
return "" + ea.line + "[" + ea.character + "]: " + ea.reason
}).join('\n');
var world = this.world();
world.setStatusMessage("JSLint found " + errors.length + " errors:\n" + allErrors, Color.orange, 10, function() {
var fullErrors = errors.collect(function(ea) {
return "" + ea.id + " " + ea.line + "[" + ea.character + "]: " + ea.reason + " (" + ea.evidence + ")" + "raw=" + ea.raw
}).join('\n');
var dialog = world.editPrompt("JSLint Errors", undefined, fullErrors)
dialog.owner.setExtent(pt(900,500))
})
offset = offset || 0;
var errorPos = this.pvtPositionInString(lines, errors[0].line - 1, errors[0].character);
var pos = offset + errorPos;
this.handleFirstJSLintError(errors[0], pos)
},
jslintContents: function(contentString, offset) {
var lines = contentString.split(/[\n\r]/)
JSLINT(lines);
var errors = JSLINT.errors
.select(function(ea){ return ea})
.reject(function(ea){ return JSLintLayer.ignoreErrorList.include(ea.raw)});
this.handleJSLintErrors(errors, lines, offset)
return errors.length === 0
},
});
Object.extend(JSLintLayer, {
ignoreErrorList: [
'Extra comma.', 'Missing semicolon.',
"Expected '{a}' and instead saw '{b}'.",
"eval is evil.",
"Unnecessary semicolon.",
"Expected an assignment or function call and instead saw an expression.",
"'new' should not be used as a statement.",
"Bad escapement.",
"All 'debugger' statements should be removed." ]});
JSLintLayer.beGlobal();
}) // end of module | 1.46875 | 1 |
src/App.js | jcardenas0917/project3 | 0 | 15991444 | import React from "react";
import { Router, Route, Switch } from "react-router-dom";
import { Container } from "reactstrap";
import PrivateRoute from "./components/PrivateRoute";
import Loading from "./components/Loading";
import NavBar from "./components/NavBar";
import Footer from "./components/Footer";
import { useAuth0 } from "./react-auth0-spa";
import history from "./utils/history";
import Home from "./pages/Home";
import Profile from "./pages/Profile";
import Journal from "./pages/Journal";
import Community from "./pages/Community";
import NoMatch from './pages/NoMatch';
// styles
import "./App.css";
// fontawesome
import initFontAwesome from "./utils/initFontAwesome";
initFontAwesome();
const App = () => {
const { loading } = useAuth0();
if (loading) {
return <Loading />;
}
return (
<Router history={history}>
<div id="app" className="d-flex flex-column h-100">
<NavBar />
<Container className="flex-grow-1 mt-5">
<Switch>
<Route exact path="/" component={Home} />
<PrivateRoute exact path="/profile" component={Profile} />
<PrivateRoute exact path="/journal" component={Journal} />
<PrivateRoute exact path="/community" component={Community} />
<PrivateRoute component={NoMatch} />
</Switch>
</Container>
<Footer />
</div>
</Router>
);
};
export default App;
| 1.445313 | 1 |
src/module1/week4/todo-app/server.js | james-d12/whitehatbootcamp | 0 | 15991452 | const express = require('express');
const Handlebars = require('handlebars')
const expressHandlebars = require('express-handlebars')
const {allowInsecurePrototypeAccess} = require('@handlebars/allow-prototype-access');
const app = express()
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(require('./server/routes/router'))
app.listen(3000, () => {
console.log('app server running on port', 3000)
}) | 1.070313 | 1 |
website/static/api/search/classes_1.js | SimonKinds/LogDevice | 1 | 15991460 | var searchData=
[
['client',['Client',['../classfacebook_1_1logdevice_1_1_client.html',1,'facebook::logdevice']]],
['clientsettings',['ClientSettings',['../classfacebook_1_1logdevice_1_1_client_settings.html',1,'facebook::logdevice']]],
['configsubscriptionhandle',['ConfigSubscriptionHandle',['../classfacebook_1_1logdevice_1_1_config_subscription_handle.html',1,'facebook::logdevice']]]
];
| 0.024536 | 0 |
lib/terms/function.js | antivanov/lambda.js | 0 | 15991468 | import { Term } from 'terms/term'
import { Variable } from 'terms/variable'
import { without, contains } from 'util/arrays'
let renamedVariableCount = 0;
const generateVariableName = () =>
't_' + (renamedVariableCount++)
//λx.x
export class Func extends Term {
constructor(argument, body) {
super();
this.argument = argument;
this.body = body;
}
apply(term) {
return this.body.substitute(this.argument, term);
}
substitute(variableName, term) {
const variableNameIsArgument = variableName === this.argument;
const argumentIsFreeInTerm = contains(term.getFreeVariables(), this.argument);
if (variableNameIsArgument || argumentIsFreeInTerm) {
return this.alphaReduce().substitute(variableName, term);
} else {
return new Func(
this.argument,
this.body.substitute(variableName, term)
);
}
}
alphaReduce() {
const oldArgument = this.argument;
const renamedArgument = generateVariableName();
return new Func(
renamedArgument,
this.body.substitute(this.argument, new Variable(renamedArgument))
);
}
getFreeVariables() {
return without(
this.body.getFreeVariables(),
this.argument
);
}
findLeftMostRedex(treeUpdateAfterReduction) {
return this.body.findLeftMostRedex((reduced) => this.body = reduced);
}
toString() {
return `(λ${this.argument}.${this.body})`;
}
static resetRenamedVariableCount() {
renamedVariableCount = 0;
}
} | 1.859375 | 2 |
lib/quotes.js | Neal/robinhood-api-node | 10 | 15991476 | 'use strict';
let Quotes = module.exports = function(rh) {
this._rh = rh;
};
Quotes.prototype.get = function(symbol, callback) {
let opts = {
method: 'GET',
endpoint: '/quotes/' + symbol.toUpperCase() + '/'
};
return this._rh._makeRequest(opts, callback);
};
| 0.964844 | 1 |
src/js/business.logic/repository.js | forumone/curriculum-review-tool | 0 | 15991484 | import C from "./constants";
const Repository = {
/*
* Clear the repsoitory
*/
clearAllData() {
localStorage.clear();
},
/*
* Establish default empty states for application data
*/
resetApplicationData() {
this.clearAllData();
localStorage.setItem(C.START_PAGE, C.START_PAGE);
},
/*
* Get data from localStorage
*/
getCurrentPage() {
return localStorage.getItem(C.START_PAGE) || C.START_PAGE;
},
getPrintButtonPage() {
return localStorage.getItem("currentPrintButton") || C.START_PAGE;
},
getContentInProgress() {
return localStorage.getItem(C.CONTENT_STATUS);
},
getQualityInProgress() {
return localStorage.getItem(C.QUALITY_STATUS);
},
getUtilityInProgress() {
return localStorage.getItem(C.UTILITY_STATUS);
},
getEfficacyInProgress() {
return localStorage.getItem(C.EFFICACY_STATUS);
},
getContentShowErrors() {
return localStorage.getItem(C.CONTENT_SHOW_ERRORS) === "true";
},
getQualityShowErrors() {
return localStorage.getItem(C.QUALITY_SHOW_ERRORS) === "true";
},
getUtilityShowErrors() {
return localStorage.getItem(C.UTILITY_SHOW_ERRORS) === "true";
},
getEfficacyShowErrors() {
return localStorage.getItem(C.EFFICACY_SHOW_ERRORS) === "true";
},
getContentIsDone() {
return localStorage.getItem(C.CONTENT_IS_DONE) === "true";
},
getQualityIsDone() {
return localStorage.getItem(C.QUALITY_IS_DONE) === "true";
},
getUtilityIsDone() {
return localStorage.getItem(C.UTILITY_IS_DONE) === "true";
},
getEfficacyIsDone() {
return localStorage.getItem(C.EFFICACY_IS_DONE) === "true";
},
getContentViewSummary() {
return localStorage.getItem(C.CONTENT_SUMMARY_VIEW) === "true";
},
getQualityViewSummary() {
return localStorage.getItem(C.QUALITY_SUMMARY_VIEW) === "true";
},
getUtilityViewSummary() {
return localStorage.getItem(C.UTILITY_SUMMARY_VIEW) === "true";
},
getEfficacyViewSummary() {
return localStorage.getItem(C.EFFICACY_SUMMARY_VIEW) === "true";
},
getCurriculumTitle() {
return localStorage.getItem("curriculumTitle");
},
getPublicationDate() {
return localStorage.getItem("publicationDate");
},
getGradeRange() {
return localStorage.getItem("gradeRange");
},
getCriterionScores() {
return JSON.parse(localStorage.getItem("criterionScores")) || {};
},
getStudyAnswers() {
return JSON.parse(localStorage.getItem("studyAnswers")) || {};
},
getNumberFinalSummaryViews() {
return localStorage.getItem("numberFinalSummaryViews") || 0;
},
getCriterionAnswers() {
return JSON.parse(localStorage.getItem("criterionAnswers")) || {};
},
getCriterionEfficacyStudies() {
return JSON.parse(localStorage.getItem("criterionEfficacyStudies")) || [0];
},
getFinishAddingEfficacyStudies() {
return localStorage.getItem("finishAddingEfficacyStudies") === "true";
},
getDistinctiveCompletedDate() {
return JSON.parse(localStorage.getItem("distinctiveCompletedDate")) || {};
},
getDimensionOverallScores() {
return JSON.parse(localStorage.getItem("dimensionOverallScores")) || {};
},
getCriterionCompletionStatuses() {
return JSON.parse(localStorage.getItem("criterionCompletionStatuses")) || {};
},
getFinalSummaryShowEntireReview() {
return localStorage.getItem("finalSummaryShowEntireReview");
},
getCriterionClickedTitles() {
return JSON.parse(localStorage.getItem("criterionClickedTitles")) || {};
},
savedimensionOverallScores(component, dimensionOverallScores) {
localStorage.setItem("dimensionOverallScores", JSON.stringify(dimensionOverallScores));
component.setState({dimensionOverallScores: dimensionOverallScores});
},
/*
* Set state values for criterion score
*/
saveDistinctiveCompletionDates(component, distinctiveCompletionDates) {
localStorage.setItem("distinctiveCompletedDate", JSON.stringify(distinctiveCompletionDates));
component.setState({distinctiveCompletedDate: distinctiveCompletionDates});
},
/*
* Set state values for criterion score
*/
saveCriterionScores(component, alteredCriterionScores) {
localStorage.setItem("criterionScores", JSON.stringify(alteredCriterionScores));
component.setState({criterionScores: alteredCriterionScores});
},
saveStudyAnswers(component, alteredStudies) {
localStorage.setItem("studyAnswers", JSON.stringify(alteredStudies));
component.setState({studyAnswers: alteredStudies});
},
saveNumberFinalSummaryViews(component, count) {
localStorage.setItem("numberFinalSummaryViews", count);
component.setState({numberFinalSummaryViews: count});
},
saveContentShowErrors(component, value) {
localStorage.setItem(C.CONTENT_SHOW_ERRORS, value);
component.setState({contentShowErrors: value});
},
saveQualityShowErrors(component, value) {
localStorage.setItem(C.QUALITY_SHOW_ERRORS, value);
component.setState({qualityShowErrors: value});
},
saveUtilityShowErrors(component, value) {
localStorage.setItem(C.UTILITY_SHOW_ERRORS, value);
component.setState({utilityShowErrors: value});
},
saveEfficacyShowErrors(component, value) {
localStorage.setItem(C.EFFICACY_SHOW_ERRORS, value);
component.setState({efficacyShowErrors: value});
},
/*
* Set state values for all criterion values
*/
saveCriterionAnswers(component, alteredCriterionAnswers) {
localStorage.setItem("criterionAnswers", JSON.stringify(alteredCriterionAnswers));
component.setState({criterionAnswers: alteredCriterionAnswers});
},
/*
* Set state values for all criterion efficacy studies
*/
saveCriterionEfficacyStudies(component, alteredCriterionEfficacyStudies) {
localStorage.setItem("criterionEfficacyStudies", JSON.stringify(alteredCriterionEfficacyStudies));
component.setState({criterionEfficacyStudies: alteredCriterionEfficacyStudies});
},
/*
*
*/
saveFinishAddingEfficacyStudies(component, value) {
localStorage.setItem("finishAddingEfficacyStudies", value);
component.setState({finishAddingEfficacyStudies: value});
},
/*
* Set value for finalSummaryShowEntireReview
*/
saveFinalSummaryShowEntireReview(component, value) {
localStorage.setItem("finalSummaryShowEntireReview", value);
component.setState({finalSummaryShowEntireReview: value});
},
/*
* Set state values for all criterion completion statuses
*/
saveCriterionGroupCompletionStatuses(component, alteredCriterionCompletionStatuses) {
localStorage.setItem("criterionCompletionStatuses", JSON.stringify(alteredCriterionCompletionStatuses));
component.setState({criterionCompletionStatuses: alteredCriterionCompletionStatuses});
},
/*
* Set the state values for all clicked criterion titles
*/
setCriterionTitleLinkClicked(component, alteredCriterionClickedTitles) {
localStorage.setItem("criterionClickedTitles", JSON.stringify(alteredCriterionClickedTitles));
component.setState({criterionClickedTitles: alteredCriterionClickedTitles});
},
/*
* Track the current Distinctive
* Allows us to always load the last distinctive worked on
*/
saveCurrentPage(component, clickedDistinctive) {
localStorage.setItem(C.START_PAGE, clickedDistinctive);
component.setState({currentPage: clickedDistinctive});
},
savePrintButtonPage(component, distinctiveName) {
localStorage.setItem("currentPrintButton", distinctiveName);
component.setState({currentPrintButton: distinctiveName});
},
/*
* Set the current Distinctive button status
*/
setDistinctiveStatus(component, changedDistinctive, distinctiveStatus) {
switch(changedDistinctive) {
case C.CONTENT_PAGE:
localStorage.setItem(C.CONTENT_STATUS, distinctiveStatus);
component.setState({contentInProgress: distinctiveStatus});
break;
case C.UTILITY_PAGE:
localStorage.setItem(C.UTILITY_STATUS, distinctiveStatus);
component.setState({utilityInProgress: distinctiveStatus});
break;
case C.QUALITY_PAGE:
localStorage.setItem(C.QUALITY_STATUS, distinctiveStatus);
component.setState({qualityInProgress: distinctiveStatus});
break;
case C.EFFICACY_PAGE:
localStorage.setItem(C.EFFICACY_STATUS, distinctiveStatus);
component.setState({efficacyInProgress: distinctiveStatus});
break;
default:
break;
}
},
/*
* Set the current Distinctive Done status. Note: once a Distinctive
* has been marked Done it stays done
*/
setDistinctiveDoneStatus(component, changedDistinctive) {
switch(changedDistinctive) {
case C.CONTENT_PAGE:
localStorage.setItem(C.CONTENT_IS_DONE, true);
component.setState({contentIsDone: true});
break;
case C.UTILITY_PAGE:
localStorage.setItem(C.UTILITY_IS_DONE, true);
component.setState({utilityIsDone: true});
break;
case C.QUALITY_PAGE:
localStorage.setItem(C.QUALITY_IS_DONE, true);
component.setState({qualityIsDone: true});
break;
case C.EFFICACY_PAGE:
localStorage.setItem(C.EFFICACY_IS_DONE, true);
component.setState({efficacyIsDone: true});
break;
default:
break;
}
},
/*
* Set the current Distinctive view to either Summary or Survey
*/
setDistinctiveView(component, changedDistinctive, isSummaryView) {
switch(changedDistinctive) {
case C.CONTENT_PAGE:
localStorage.setItem(C.CONTENT_SUMMARY_VIEW, isSummaryView);
component.setState({contentIsSummaryView: isSummaryView});
break;
case C.UTILITY_PAGE:
localStorage.setItem(C.UTILITY_SUMMARY_VIEW, isSummaryView);
component.setState({utilityIsSummaryView: isSummaryView});
break;
case C.QUALITY_PAGE:
localStorage.setItem(C.QUALITY_SUMMARY_VIEW, isSummaryView);
component.setState({qualityIsSummaryView: isSummaryView});
break;
case C.EFFICACY_PAGE:
localStorage.setItem(C.EFFICACY_SUMMARY_VIEW, isSummaryView);
component.setState({efficacyIsSummaryView: isSummaryView});
break;
default:
break;
}
}
}
export default Repository;
| 1.390625 | 1 |
assets/gadget/product/productDetail.js | jidzhang/vuejs-demo-with-requirejd | 0 | 15991492 | define(['vue','servicegadget/product/product'], function (Vue, Product) {
var app = new Vue({
el: '#app',
data: {
productDetail: {
productName: '产品AA',
icon: '',
postTime: '2017-03-01',
content:'<p>line1</p><p>line2</p>'
}
},
mounted: function () {
var _this = this;
_this.productDetail = {};
var productId = getQueryString('id');
if (productId) {
Product.getProductDetail(productId, function (code, data) {
if (code === 0 && data) {
_this.productDetail = data.productDetail;
} else {
alert('查询失败');
}
});
} else {
alert('缺少url参数id');
}
function getQueryString(name) {
var p = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var m = window.location.search.substr(1).match(p);
return m!=null ? m[2] : null;
}
}
});
return app;
}); | 1.40625 | 1 |
node_modules/carbonldp/LDP/VolatileResource.js | AlexSerrano22/Semana_i | 0 | 15991500 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Resource_1 = require("../Resource/Resource");
var C_1 = require("../Vocabularies/C");
exports.VolatileResource = {
TYPE: C_1.C.VolatileResource,
is: function (value) {
return Resource_1.Resource.is(value)
&& value.$hasType(exports.VolatileResource.TYPE);
},
create: function (data) {
var copy = Object.assign({}, data);
return exports.VolatileResource.createFrom(copy);
},
createFrom: function (object) {
var resource = Resource_1.Resource.createFrom(object);
resource.$addType(exports.VolatileResource.TYPE);
return resource;
},
};
//# sourceMappingURL=VolatileResource.js.map
| 0.996094 | 1 |
fuzzer_output/interesting/sample_1554095685495.js | patil215/v8 | 0 | 15991508 | function main() {
const v4 = [13.37,13.37,13.37,13.37];
const v6 = [10];
const v7 = [v6];
const v8 = {max:Function,setPrototypeOf:10};
const v9 = {exec:v6};
let v10 = "undefined";
const v13 = {max:Function,isExtensible:10};
const v16 = {max:10,setPrototypeOf:10};
const v19 = {max:Function,setPrototypeOf:10};
}
%NeverOptimizeFunction(main);
main();
| 1.304688 | 1 |