hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
837b82bb8d9aa54917cb99525d07795a20f994f7 | 2,457 | js | JavaScript | generator.js | Datum/merkle-tree-stream | 35c33d2d499f662c52544f1de8afa04aef84c1e8 | [
"MIT"
] | null | null | null | generator.js | Datum/merkle-tree-stream | 35c33d2d499f662c52544f1de8afa04aef84c1e8 | [
"MIT"
] | null | null | null | generator.js | Datum/merkle-tree-stream | 35c33d2d499f662c52544f1de8afa04aef84c1e8 | [
"MIT"
] | null | null | null | // a more low level interface to the merkle tree stream.
// useful for certain applications the require non-streamy access to the algos.
// versioned by the same semver as the stream interface.
var flat = require('flat-tree')
module.exports = MerkleGenerator
function MerkleGenerator (opts, roots) {
if (!(this instanceof MerkleGenerator)) return new MerkleGenerator(opts, roots)
if (!opts || !opts.leaf || !opts.parent) throw new Error('opts.leaf and opts.parent required')
this.roots = roots || opts.roots || []
this.blocks = this.roots.length ? 1 + flat.rightSpan(this.roots[this.roots.length - 1].index) / 2 : 0
for (var i = 0; i < this.roots.length; i++) {
var r = this.roots[i]
if (r && !r.parent) r.parent = flat.parent(r.index)
}
this._leaf = opts.leaf
this._parent = opts.parent
}
MerkleGenerator.prototype.next = function (data, nodes) {
if (!Buffer.isBuffer(data)) data = new Buffer(data)
if (!nodes) nodes = []
var index = 2 * this.blocks++
var leaf = {
index: index,
parent: flat.parent(index),
hash: null,
size: data.length,
data: data
}
leaf.hash = this._leaf(leaf, this.roots)
this.roots.push(leaf)
nodes.push(leaf)
return this._updateRoots(nodes)
}
MerkleGenerator.prototype._updateRoots = function (nodes, merge) {
if (!Array.isArray(nodes)) {
merge = nodes
nodes = []
}
var leaf
while (this.roots.length > 1) {
var left = this.roots[this.roots.length - 2]
var right = this.roots[this.roots.length - 1]
if (left.parent !== right.parent) {
if (!merge) break
// let a copy of the right root be its own partner
left = right
right = {
index: flat.sibling(right.index),
parent: right.parent,
hash: right.hash,
size: right.size,
data: right.data
}
// don't push the copy into the roots
// this.roots.push(right)
}
this.roots.pop()
this.roots[this.roots.length - 1] = leaf = {
index: left.parent,
parent: flat.parent(left.parent),
hash: merge ? this._parent(this.roots[this.roots.length - 1], right) : this._parent(left, right), // follow merkle-tree-solidity logic and hash with left siblings parent hash instead with the copy of itself
size: left.size + right.size,
data: null
}
nodes.push(leaf)
}
return nodes
}
MerkleGenerator.prototype.finalize = function () {
return this._updateRoots(true)
}
| 27 | 212 | 0.646317 |
837c0aba3cd724faca368bbcc48e5cbd38d07ebe | 159 | js | JavaScript | _build/js/entities/square.js | jpdevries/tetris | 30f99934e604768ccce7b161eb33afe8fe5c88ee | [
"MIT"
] | null | null | null | _build/js/entities/square.js | jpdevries/tetris | 30f99934e604768ccce7b161eb33afe8fe5c88ee | [
"MIT"
] | null | null | null | _build/js/entities/square.js | jpdevries/tetris | 30f99934e604768ccce7b161eb33afe8fe5c88ee | [
"MIT"
] | null | null | null | var shape = require('./shape');
function Square() {
}
Square.prototype = new shape.Shape();
Square.prototype.constructor = Square;
exports.Square = Square;
| 15.9 | 38 | 0.710692 |
837dc943af544756f3128afa98f1399e493b0df9 | 369 | js | JavaScript | exercicios-js/funcao/lista-exercicios/desafio01.js | lucashsouza/WebModerno-Cod3r | 50872f5c089464cf970e8e5205bbf61323077c7a | [
"MIT"
] | null | null | null | exercicios-js/funcao/lista-exercicios/desafio01.js | lucashsouza/WebModerno-Cod3r | 50872f5c089464cf970e8e5205bbf61323077c7a | [
"MIT"
] | null | null | null | exercicios-js/funcao/lista-exercicios/desafio01.js | lucashsouza/WebModerno-Cod3r | 50872f5c089464cf970e8e5205bbf61323077c7a | [
"MIT"
] | null | null | null | /*
01) Crie uma função que dado dois valores (passados como parâmetros) mostre no console a soma, subtração, multiplicação e divisão desses valores.
*/
function operacao(x, y) {
console.log(`${x} + ${y} = ${x+y}`);
console.log(`${x} - ${y} = ${x-y}`);
console.log(`${x} x ${y} = ${x*y}`);
console.log(`${x} / ${y} = ${x/y}`);
}
operacao(100, 20); | 30.75 | 149 | 0.558266 |
837de6dcfb373809eec56b363b3bff7a107c6607 | 12,600 | js | JavaScript | src/features/authentication/page.js | SilencerWeb/karma | f0835c51402862cffdfb8ca6acf566b3c1fa528d | [
"Apache-2.0"
] | 3 | 2018-07-10T18:16:25.000Z | 2019-05-07T13:38:22.000Z | src/features/authentication/page.js | SilencerWeb/karma | f0835c51402862cffdfb8ca6acf566b3c1fa528d | [
"Apache-2.0"
] | null | null | null | src/features/authentication/page.js | SilencerWeb/karma | f0835c51402862cffdfb8ca6acf566b3c1fa528d | [
"Apache-2.0"
] | null | null | null | import * as React from 'react';
import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';
import * as Yup from 'yup';
import { Redirect } from 'react-router-dom';
import { Mutation } from 'react-apollo';
import { Formik } from 'formik';
import { AppConsumer } from 'index';
import { Button } from 'ui/atoms';
import { FormField } from 'ui/molecules';
import { CommonTemplate } from 'ui/templates';
import { AUTH_TOKEN } from 'constants.js';
import * as validation from 'validation';
import { SIGNUP, LOGIN } from 'graphql/mutations/authentication';
const FormFieldWrapper = styled.div`
margin-bottom: 2rem;
&:last-child {
margin-bottom: 0;
}
`;
const FormFieldsWrapper = styled.div`
margin-bottom: 4rem;
`;
const FormFooter = styled.div`
display: flex;
justify-content: flex-end;
`;
const Form = styled.form`
max-width: 30rem;
margin-right: auto;
margin-left: auto;
`;
export class AuthenticationPage extends React.Component {
state = {
type: 'signup',
validateOnBlur: false,
validateOnChange: false,
shouldRedirectToMainPage: false,
};
handleSubmitButtonClick = () => {
this.setState({
validateOnBlur: true,
validateOnChange: true,
});
};
static getDerivedStateFromProps(props, state) {
if (props.type !== state.type) {
state.type = props.type;
}
return state;
}
render() {
return (
<CommonTemplate centeredContent={ true }>
{ this.state.shouldRedirectToMainPage && <Redirect to={ '/' }/> }
<AppConsumer>
{ (context) => (
<React.Fragment>
{
this.state.type === 'signup' ?
<Mutation mutation={ SIGNUP }>
{ (signup, { loading, error, data }) => (
<React.Fragment>
{ error && <div>mutation SIGNUP got error: { error.message }</div> }
{ loading && <div>mutation SIGNUP is loading...</div> }
<Formik
validationSchema={
Yup.object().shape({
email: validation.email.required('Email is required'),
nickname: Yup.string().required('Nickname is required'),
name: Yup.string(),
password: validation.password.required('Password is required'),
confirmPassword: validation.confirmPassword.required('Password confirmation is required'),
})
}
validateOnBlur={ this.state.validateOnBlur }
validateOnChange={ this.state.validateOnChange }
onSubmit={ (values) => {
signup({
variables: {
email: values.email,
password: values.password,
nickname: values.nickname,
name: values.name,
},
}).then((response) => {
const token = response.data.signup.token;
const user = response.data.signup.user;
localStorage.setItem(AUTH_TOKEN, token);
context.login(user);
this.setState({
shouldRedirectToMainPage: true,
});
});
} }
render={
({
values,
errors,
handleChange,
handleSubmit,
}) => (
<Form onSubmit={ handleSubmit } noValidate>
<FormFieldsWrapper>
<FormFieldWrapper>
<FormField
placeholder={ 'john.doe@gmail.com' }
required
textFieldName={ 'email' }
textFieldType={ 'email' }
textFieldValue={ values.email }
label={ 'Email' }
helperText={ !!errors.email ? errors.email : null }
error={ !!errors.email }
onChange={ handleChange }
/>
</FormFieldWrapper>
<FormFieldWrapper>
<FormField
placeholder={ 'john.doe' }
required
textFieldName={ 'nickname' }
textFieldValue={ values.nickname }
label={ 'Nickname' }
helperText={ !!errors.nickname ? errors.nickname : null }
error={ !!errors.nickname }
onChange={ handleChange }
/>
</FormFieldWrapper>
<FormFieldWrapper>
<FormField
placeholder={ 'John Doe' }
textFieldName={ 'name' }
textFieldValue={ values.name }
label={ 'Name' }
helperText={ !!errors.name ? errors.name : null }
error={ !!errors.name }
onChange={ handleChange }
/>
</FormFieldWrapper>
<FormFieldWrapper>
<FormField
placeholder={ 'password123' }
required
textFieldName={ 'password' }
textFieldType={ 'password' }
textFieldValue={ values.password }
label={ 'Password' }
helperText={ !!errors.password ? errors.password : null }
error={ !!errors.password }
onChange={ handleChange }
/>
</FormFieldWrapper>
<FormFieldWrapper>
<FormField
placeholder={ 'password123' }
required
textFieldName={ 'confirmPassword' }
textFieldType={ 'password' }
textFieldValue={ values.confirmPassword }
label={ 'Confirm password' }
helperText={ !!errors.confirmPassword ? errors.confirmPassword : null }
error={ !!errors.confirmPassword }
onChange={ handleChange }
/>
</FormFieldWrapper>
</FormFieldsWrapper>
<FormFooter>
<Button onClick={ this.handleSubmitButtonClick }>Submit</Button>
</FormFooter>
</Form>
)
}
/>
</React.Fragment>
) }
</Mutation>
:
<Mutation mutation={ LOGIN }>
{ (login, { loading, error, data }) => (
<React.Fragment>
{ error && <div>mutation LOGIN got error: { error.message }</div> }
{ loading && <div>mutation LOGIN is loading...</div> }
<Formik
validationSchema={
Yup.object().shape({
login: Yup.string().required('Login is required'),
password: validation.password.required('Password is required'),
})
}
validateOnBlur={ this.state.validateOnBlur }
validateOnChange={ this.state.validateOnChange }
onSubmit={ (values) => {
login({
variables: {
login: values.login,
password: values.password,
},
}).then((response) => {
const token = response.data.login.token;
const user = response.data.login.user;
localStorage.setItem(AUTH_TOKEN, token);
context.login(user);
this.setState({
shouldRedirectToMainPage: true,
});
});
} }
render={
({
values,
errors,
handleChange,
handleSubmit,
}) => (
<Form onSubmit={ handleSubmit } noValidate>
<FormFieldsWrapper>
<FormFieldWrapper>
<FormField
placeholder={ 'john.doe' }
required
textFieldName={ 'login' }
textFieldValue={ values.login }
label={ 'Email or nickname' }
helperText={ !!errors.login ? errors.login : null }
error={ !!errors.login }
onChange={ handleChange }
/>
</FormFieldWrapper>
<FormFieldWrapper>
<FormField
placeholder={ 'password123' }
required
textFieldName={ 'password' }
textFieldType={ 'password' }
textFieldValue={ values.password }
label={ 'Password' }
helperText={ !!errors.password ? errors.password : null }
error={ !!errors.password }
onChange={ handleChange }
/>
</FormFieldWrapper>
</FormFieldsWrapper>
<FormFooter>
<Button onClick={ this.handleSubmitButtonClick }>Submit</Button>
</FormFooter>
</Form>
)
}
/>
</React.Fragment>
) }
</Mutation>
}
</React.Fragment>
) }
</AppConsumer>
</CommonTemplate>
);
}
}
AuthenticationPage.propTypes = {};
| 42 | 120 | 0.351667 |
837f172e12f91df806efa8ca3df2943f75bab58f | 6,545 | js | JavaScript | source-frontend/src/ManageSongList.js | Everstar/MusicRadio | fc3e505b546d9e6009af99ceb4e87a863dd91776 | [
"MIT"
] | null | null | null | source-frontend/src/ManageSongList.js | Everstar/MusicRadio | fc3e505b546d9e6009af99ceb4e87a863dd91776 | [
"MIT"
] | null | null | null | source-frontend/src/ManageSongList.js | Everstar/MusicRadio | fc3e505b546d9e6009af99ceb4e87a863dd91776 | [
"MIT"
] | null | null | null | /**
* Created by tsengkasing on 12/12/2016.
*/
import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
import TextField from 'material-ui/TextField';
import Dialog from 'material-ui/Dialog';
import SongListItem from './songList/SongListItem'
import API from './API';
import $ from 'jquery';
const styles = {
floatingButton : {
marginRight: 20,
marginBottom : 20,
position : 'fixed',
right : 0,
bottom : 0,
},
};
//创建新乐单
class NewSongListDialog extends React.Component {
state = {
open: false,
songlist_name : "",
description : "",
callback : null,
error_text : null,
};
handleOpen = (callback) => {
this.setState({
open: true,
callback : callback,
});
};
handleClose = () => {
this.setState({open: false});
};
handleSubmit = () => {
const URL = API.NewList;
if(this.state.songlist_name === "") {
this.setState({error_text: "This field is required"});
return;
}else
this.setState({error_text: null});
let data = {
songlist_name: this.state.songlist_name,
description: this.state.description,
};
$.ajax({
url : URL,
type : 'POST',
data : JSON.stringify(data),
contentType: 'application/json;charset=UTF-8',
headers : {
'target' : 'api',
},
success : function(data, textStatus, jqXHR) {
console.log(data.songlist_id);
this.state.callback();
}.bind(this),
error : function(xhr, textStatus) {
alert('fail');
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
console.log('createlist \nname :' + this.state.songlist_name + '\ndescription : ' + this.state.description );
this.handleClose();
};
inputName = (event) => {
this.setState({
songlist_name : event.target.value,
error_text: null
});
};
inputDescription = (event) => {
this.setState({description : event.target.value});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Submit"
primary={true}
onTouchTap={this.handleSubmit}
/>,
];
return (
<div>
<Dialog
title="Create song list"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
<TextField
hintText="Song List Name"
floatingLabelText="song list name"
value={this.state.songlist_name}
onChange={this.inputName}
errorText={this.state.error_text}
/><br />
<TextField
hintText="description"
floatingLabelText="Description"
multiLine={true}
rows={2}
value={this.state.description}
onChange={this.inputDescription}
/>
</Dialog>
</div>
);
}
}
export default class ManageSongList extends React.Component {
constructor(props) {
super(props);
this.state = {
song_lists : [],
}
};
loadData = () => {
const URL = API.SongList;
$.ajax({
url : URL,
type : 'POST',
headers : {
'target' : 'api',
},
contentType: 'application/json;charset=UTF-8',
dataType:'json',
success : function(data, textStatus, jqXHR) {
console.log(data);
this.setState({song_lists : data});
}.bind(this),
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
};
componentWillMount() {
this.loadData();
}
refresh = () => {
this.loadData();
console.log('update');
};
deleteList = (index) => {
const URL = API.DeleteList;
let data = {id : index};
$.ajax({
url : URL,
type : 'POST',
headers : {
'target' : 'api',
},
contentType: 'application/json;charset=UTF-8',
dataType:'json',
data : JSON.stringify(data),
success : function(data, textStatus, jqXHR) {
console.log(data);
alert('删除成功');
this.refresh();
}.bind(this),
error : function(xhr, textStatus) {
alert('Fail');
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
};
newListQuery = () => {
this.refs.newListDialog.handleOpen(this.refresh);
};
render() {
return (
<div style={{textAlign: 'center'}}>
{this.state.song_lists.map((list, index) => (
<SongListItem
onDelete={this.deleteList}
order={index}
key={index}
title={list.songlist_name}
author={list.author}
img_id={list.img_id}
img_url={list.img_url}
liked={list.liked}
description={list.description}
songlist_id={list.list_id}
refresh={this.refresh}
/>
))}
<FloatingActionButton style={styles.floatingButton} onTouchTap={this.newListQuery}>
<ContentAdd />
</FloatingActionButton>
<NewSongListDialog ref="newListDialog" />
</div>
);
};
} | 28.832599 | 117 | 0.453018 |
837f7381964f1a53d0ddbaaad62d7b2c4c15d5e9 | 139 | js | JavaScript | javadoc/type-search-index.js | victor-cleber/java-development-bootcamp | c7869c59095fcd6f4a50a9cf25676cf423fea95c | [
"MIT"
] | 1 | 2022-01-28T21:47:57.000Z | 2022-01-28T21:47:57.000Z | javadoc/type-search-index.js | victor-cleber/java-development-bootcamp | c7869c59095fcd6f4a50a9cf25676cf423fea95c | [
"MIT"
] | null | null | null | javadoc/type-search-index.js | victor-cleber/java-development-bootcamp | c7869c59095fcd6f4a50a9cf25676cf423fea95c | [
"MIT"
] | null | null | null | typeSearchIndex = [{"l":"All Classes","url":"allclasses-index.html"},{"p":"com.dio","l":"MyFirstProgram"},{"p":"com.dio.base","l":"Order"}] | 139 | 139 | 0.625899 |
837fcc0c83b6280a23974d15d49e9a2f4f16aa40 | 107 | js | JavaScript | keys/pdf417_keys.js | VDubber/blinkid-react-native | c85b87c87d40ae34b40d14972464e7846c38c813 | [
"MIT"
] | null | null | null | keys/pdf417_keys.js | VDubber/blinkid-react-native | c85b87c87d40ae34b40d14972464e7846c38c813 | [
"MIT"
] | null | null | null | keys/pdf417_keys.js | VDubber/blinkid-react-native | c85b87c87d40ae34b40d14972464e7846c38c813 | [
"MIT"
] | null | null | null | /***** Keys for obtaining data on PDF417 type of barcodes *****/
export const BarcodeData = "BarcodeData"; | 35.666667 | 64 | 0.700935 |
8380fcee0eec39cca988334f5f1b4129bd957593 | 4,953 | js | JavaScript | server/views/beechat/language_zh.js | wenqiangY/open_website | b5490c0483649fc2c4df2eb4d250fc60d0977afc | [
"MIT"
] | null | null | null | server/views/beechat/language_zh.js | wenqiangY/open_website | b5490c0483649fc2c4df2eb4d250fc60d0977afc | [
"MIT"
] | null | null | null | server/views/beechat/language_zh.js | wenqiangY/open_website | b5490c0483649fc2c4df2eb4d250fc60d0977afc | [
"MIT"
] | null | null | null | var x = {
lang:'zh',
title1:'Link People',
title2:'Link Blockchain',
title3:'Blockchain based messenger and ',
title4:'cryptocurrency community',
h1:'产品介绍',
c1:'BeeChat是全球首款基于区块链技术的即时通讯软件,全球最活跃的探讨区块链和加密货币的社区。<br><br>' +
'BeeChat上线三个月全球累积下载1000万次,活跃用户超过150万人,聚集了区块链行业意见领袖数百人',
h2:'产品特点',
c2_1:'全球高清通信',
c2_1_1:'全球数百个节点,无需vpn保证各个地方的通信品质',
c2_2:'特有的加密算法',
c2_2_1:'端到端加密方案,让你的隐私得到充分保护',
c2_3:'内置钱包功能',
c2_3_1:'支持各种主流数字货币完全自由的发送和接收,交易就像聊天一样简单',
c2_4:'完善的数字生活',
c2_4_1:'朋友圈,付费群,公众号,小密圈功能持续开发中',
h3:'BeeChat产品预览',
apk_down:'安卓版本下载',
ios_down:'IOS版本下载',
"public_account":"公众号",
"public_account_apply":"申请",
"public_account_login":"登录",
"pressTitle":"相关报道",
"pressList":[
{url:"https://www.jinse.com/bitcoin/207939.html",text:"【韩国】2018世界区块链大会·首尔区块链前沿技术峰会顺利闭幕"},
{url:"https://mp.weixin.qq.com/s/9lU00v7u3W1M9gaLEuaB2w",text:"【硅谷】什么 APP 能在 3 个月内有 1000 万次下载?"},
{url:"https://mp.weixin.qq.com/s/F2dPH1DyfGDzehG6gbRRlQ",text:"【专访】BeeChat 国际社区架构师Eric Johnson:用区块链重新连接世界"},
{url:"https://www.jinse.com/blockchain/202860.html",text:"【世界杯】世界杯竞猜盛宴激情开启 玩数字货币,该你登场了"},
{url:"https://mp.weixin.qq.com/s/aIO109t0esSkOsP-u3yLFA",text:"【教程】“币圈微信”之BeeChat使用攻略"},
{url:"https://mp.weixin.qq.com/s/Zk5LZxNoMb3WY-uueo_6BQ",text:"【深度】BeeChat于2018年8月上线新版区块链直播平台"},
// {url:"http://www.jinse.com/blockchain_business_news/115815.html",text:"基于量子链的全球最大的区块链通讯社区BeeChat发布新版本 打造区块链生态开放平台"},
// {url:"https://mp.weixin.qq.com/s/vsT2Fjz4eZO0u71M1Dy-sg",text:"深度测评Status、BeeChat和QBao,谁才是下一个区块链微信?"},
// {url:"https://mp.weixin.qq.com/s/1znCK-x_kAnIxw5ANn9GJw",text:"SNT和BeeChat ,区块链社交的倚天剑和屠龙刀!"},
// {url:"https://mp.weixin.qq.com/s/FYh4dTaiGvuCptu7-xCAlg",text:"粗大事啦!最近号称【币圈小微信】的BeeChat是怎么回事???"},
// {url:"https://mp.weixin.qq.com/s/G-KKTSmqxzUc1viWRYjT6g",text:"区块链宠物狗嗖地一下就来了,创世狗能拍多少钱?快来有奖竞猜"}
],
"apk_down_go_browser":"请到浏览器中打开此页面",
"apk_down_go_browser2":"无法正常显示",
"apk_down_go_browser3":'请点击右上角<br>选择"复制链接",到浏览器中打开',
"ios_install_guide":"iOS版本安装指导",
"main_func_title":"主要功能",
"main_func_content":"" +
"<ul>\n" +
" <li>3万人群聊</li>\n" +
" <li>消息和语音/视频通话服务</li>\n" +
" <li>加密货币钱包</li>\n" +
" <li>全球首款数字货币红包</li>\n" +
" <li>区块链行业新闻媒体</li>\n" +
" <li>区块链社交游戏</li>\n" +
" <li>直播平台和加密货币打赏</li>\n" +
" <li>BeeChat社区让你的数字货币投资变得极其简单、有趣。</li>\n" +
" </ul>",
"product_feature_title":"产品特点",
"product_feature_title1":"多元化社区",
"product_feature_title2":"比特信用",
"product_feature_title3":"区块链平台",
"product_feature_content1":"" +
" <p>\n" +
" <h3>国际化多元化的社区</h3>\n" +
" BeeChat支持全球三十多个语言版本,在全球拥有多元化的粉丝群体,和各种语言的粉丝群。\n" +
" </p>\n" +
" <p>\n" +
" <h3>多种数字货币流通</h3>\n" +
" BeeChat支持几十种精品数字货币在平台流通和建立粉丝群,\n" +
" 比特币、以太坊、量子、INK、CHAT和EOS等都可以在BeeChat平台上使用。\n" +
" </p>\n" +
" <p>\n" +
" <h3>社区人气旺、互动性强</h3>\n" +
" BeeChat是区块链项目上链接粉丝的最佳工具,支持最多高达30,000人的用户社群。\n" +
" 目前已有HSR、量子链、INK、CHAT、菩提、ENT、HPY、BigOne等数百个区块链项目官方社群入驻BeeChat平台。这些用户社群不仅可以帮助用户和区块链项目官方、用户和用户之间更加直接的交流,也为区块链项目提供了一个和用户面对面交流、发布新闻公告、获得大量垂直用户群体的入口。\n" +
" 目前,已有多个币圈自媒体、知名意见领袖入驻BeeChat,自媒体文章同步保存在区块链上,保障数据安全。\n" +
" 即刻加入,见证历史!",
"product_feature_content2":"" +
" <p>\n" +
" <h3>加V认证</h3>\n" +
" 对于官方社群、知名自媒体、意见领袖以及核心用户提供认证体系,保证官方信息发布的权威和用户的个人权益的实现。\n" +
" BeeChat全球首创数字货币红包,每天免费发放各种数字货币红包累积金额达百万元人民币。在海外,用户们也已经逐步适应了抢红包这种中国文化元素的网路互动方式。\n" +
" 你也可以自行发送数字货币红包,自定义红包金额和数量。\n" +
" </p>\n" +
" <p>\n" +
" <h3>比特信用</h3>\n" +
" 通过云计算、大数据和区块链技术,为每个用户评定比特信用分数,并在不同场景下为用户和官方平台提供信用服务,让每个人都能享用信用的便利,让人与人之间的关系因为新用而变得简单。\n" +
" </p>",
"product_feature_content3":"" +
" <p>\n" +
" <h3>打造区块链娱乐平台</h3>\n" +
" BeeChat目前已推出全球首款区块链社交游戏“创世神犬”,\n" +
" 未来,BeeChat会推出更多精品区块链游戏,创造更丰富多彩的娱乐化体验。\n" +
" </p>\n" +
" <p>\n" +
" <h3>区块链开发者平台</h3>\n" +
" BeeChat联合多个合作伙伴推出的区块链开发者平台即将于近期上线,\n" +
" 为区块链开发者们提供丰富的第三方工具、数据分析平台、用户接入平台、应用分发平台、测试平台和创业服务平台,以促进更多优秀的开发者加入到BeeChat生态建设的大家庭中。\n" +
" <br>\n" +
" 对于优秀的开发者,BeeChat平台还将开展一系列的扶持计划,全面助力区块链技术产业发展。\n" +
" <br>\n" +
" BeeChat作为全球最大的区块链社交社区,全面打造区块链生态开放平台,全方位为区块链用户服务\n" +
" </p>",
"video_title":"宣传片",
"video_url":"//cdn.ibeechat.com/static/videos/bc_video_zh1.mov"
};
module.exports = x; | 38.1 | 165 | 0.568948 |
8381e21d07ae1dbf33782d841e7081f865c00eb3 | 30 | js | JavaScript | javascript/analyzer/getYamlFromJavascript/tests/default/test-cases/class/declaration/extends/.js | DevSnicket/Eunice | 56fb6463e5993413980fb3657578f1267e45b6f9 | [
"MIT"
] | 9 | 2018-06-26T19:32:11.000Z | 2019-05-03T07:07:29.000Z | javascript/analyzer/getYamlFromJavascript/tests/default/test-cases/class/declaration/extends/.js | DevSnicket/Eunice | 56fb6463e5993413980fb3657578f1267e45b6f9 | [
"MIT"
] | 34 | 2018-06-18T14:07:52.000Z | 2019-08-01T07:18:51.000Z | javascript/analyzer/getYamlFromJavascript/tests/default/test-cases/class/declaration/extends/.js | DevSnicket/Eunice | 56fb6463e5993413980fb3657578f1267e45b6f9 | [
"MIT"
] | 2 | 2018-12-17T20:57:05.000Z | 2019-01-07T15:57:02.000Z | class Derived extends Base { } | 30 | 30 | 0.766667 |
8382ef9bca79729248d92c9f05f81f6deaa86217 | 573 | js | JavaScript | warehouse-space70.9cef9450fc4cbe6433a5.bundle.js | Pendome/storyBook | 4972d7156d362e24aff791d681498cc626e0c27e | [
"BSD-2-Clause"
] | null | null | null | warehouse-space70.9cef9450fc4cbe6433a5.bundle.js | Pendome/storyBook | 4972d7156d362e24aff791d681498cc626e0c27e | [
"BSD-2-Clause"
] | null | null | null | warehouse-space70.9cef9450fc4cbe6433a5.bundle.js | Pendome/storyBook | 4972d7156d362e24aff791d681498cc626e0c27e | [
"BSD-2-Clause"
] | null | null | null | (window.webpackJsonp=window.webpackJsonp||[]).push([[36],{1546:function(module,exports,__webpack_require__){var api=__webpack_require__(128),content=__webpack_require__(1678);"string"==typeof(content=content.__esModule?content.default:content)&&(content=[[module.i,content,""]]);var options={insert:"head",singleton:!1};api(content,options);module.exports=content.locals||{}},1678:function(module,exports,__webpack_require__){(module.exports=__webpack_require__(269)(!1)).push([module.i,"",""])}}]);
//# sourceMappingURL=warehouse-space70.9cef9450fc4cbe6433a5.bundle.js.map | 286.5 | 499 | 0.783595 |
83835b0002f42a532bdb2ea11f31539277c3a3fa | 150 | js | JavaScript | firebaseapp/src/components/Landing.js | MasherJames/MyBlogs | 0f11064e758941e15520373dbc8209976b6cdd7d | [
"MIT"
] | null | null | null | firebaseapp/src/components/Landing.js | MasherJames/MyBlogs | 0f11064e758941e15520373dbc8209976b6cdd7d | [
"MIT"
] | null | null | null | firebaseapp/src/components/Landing.js | MasherJames/MyBlogs | 0f11064e758941e15520373dbc8209976b6cdd7d | [
"MIT"
] | null | null | null | import React from "react";
const Landing = () => {
return (
<div>
<p>This is the landing</p>
</div>
);
};
export default Landing;
| 12.5 | 32 | 0.546667 |
83836191926876df6873c0a1a9357514ba29a85c | 511 | js | JavaScript | src/js/ui/vigenere-dom.js | mariuszskon/crypto-toolkit | ca27665d0f27d6fd8debcd63324f11d47d1f5fd5 | [
"MIT"
] | null | null | null | src/js/ui/vigenere-dom.js | mariuszskon/crypto-toolkit | ca27665d0f27d6fd8debcd63324f11d47d1f5fd5 | [
"MIT"
] | null | null | null | src/js/ui/vigenere-dom.js | mariuszskon/crypto-toolkit | ca27665d0f27d6fd8debcd63324f11d47d1f5fd5 | [
"MIT"
] | null | null | null | // vigenere-dom.js
function vigenereGetDOMValues() {
return {
input: gid("vigenere-input").value,
key: gid("vigenere-key").value
};
}
function vigenereDOMmanage(mode) {
var values = vigenereGetDOMValues();
gid("vigenere-output").innerHTML = cipher.vigenere(mode, values.input, values.key);
}
gid("vigenere-en").addEventListener("click", function() {
vigenereDOMmanage(true);
});
gid("vigenere-de").addEventListener("click", function() {
vigenereDOMmanage(false);
});
| 23.227273 | 87 | 0.67319 |
8383b73c4c10554501a40233f8219d3732ba5323 | 1,428 | js | JavaScript | src/test/unit_tests/test_chunk_fs.js | ezio-auditore/noobaa-core | 36210a06731cac661d7e51de659fb12c5aa7d6e9 | [
"Apache-2.0"
] | null | null | null | src/test/unit_tests/test_chunk_fs.js | ezio-auditore/noobaa-core | 36210a06731cac661d7e51de659fb12c5aa7d6e9 | [
"Apache-2.0"
] | null | null | null | src/test/unit_tests/test_chunk_fs.js | ezio-auditore/noobaa-core | 36210a06731cac661d7e51de659fb12c5aa7d6e9 | [
"Apache-2.0"
] | null | null | null | /* Copyright (C) 2020 NooBaa */
/* eslint-disable no-invalid-this */
'use strict';
const mocha = require('mocha');
const chunk_fs_hashing = require('../../tools/chunk_fs_hashing');
mocha.describe('ChunkFS', function() {
const RUN_TIMEOUT = 10 * 60 * 1000;
mocha.it('Concurrent ChunkFS with hash target', async function() {
const self = this;
self.timeout(RUN_TIMEOUT);
await chunk_fs_hashing.hash_target();
});
mocha.it('Concurrent ChunkFS with file target', async function() {
const self = this;
self.timeout(RUN_TIMEOUT);
await chunk_fs_hashing.file_target();
});
mocha.it('Concurrent ChunkFS with file target - produce num_chunks > 1024 && total_chunks_size < config.NSFS_BUF_SIZE', async function() {
const self = this;
self.timeout(RUN_TIMEOUT);
// The goal of this test is to produce num_chunks > 1024 && total_chunks_size < config.NSFS_BUF_SIZE
// so we will flush buffers because of reaching max num of buffers and not because we reached the max NSFS buf size
// chunk size = 100, num_chunks = (10 * 1024 * 1024)/100 < 104587, 104587 = num_chunks > 1024
// chunk size = 100, total_chunks_size after having 1024 chunks is = 100 * 1024 < config.NSFS_BUF_SIZE
const chunk_size = 100;
const parts_s = 50;
await chunk_fs_hashing.file_target(chunk_size, parts_s);
});
});
| 40.8 | 142 | 0.662465 |
838459de204d55e316976a3e6db027d496423dff | 1,240 | js | JavaScript | assets/javascripts/angular/factories/sorter.js | pivotal-cf-attic/pivotal-one-styles | 869350dfbe7e2fe4426c43824b9eea711a5c6339 | [
"BSD-2-Clause"
] | null | null | null | assets/javascripts/angular/factories/sorter.js | pivotal-cf-attic/pivotal-one-styles | 869350dfbe7e2fe4426c43824b9eea711a5c6339 | [
"BSD-2-Clause"
] | null | null | null | assets/javascripts/angular/factories/sorter.js | pivotal-cf-attic/pivotal-one-styles | 869350dfbe7e2fe4426c43824b9eea711a5c6339 | [
"BSD-2-Clause"
] | null | null | null | angular.module('ConsoleApp').factory('Sorter', [function Sorter() {
return function (collection, attribute, direction) {
var currentSort = {
attribute: attribute,
direction: direction
};
var sorter = {
currentSort: currentSort,
sortBy: function (attribute, direction) {
currentSort.attribute = attribute;
currentSort.direction = direction;
collection.sort(sortIteratorFactory(attribute, direction))
},
sortDirection: function(attribute) {
if (attribute != currentSort.attribute) {
return "none";
} else {
return currentSort.direction;
}
},
clearSort: function() {
currentSort.attribute = null;
currentSort.direction = null;
}
}
sorter.sortBy(attribute, direction);
function sortIteratorFactory(attribute, direction) {
var signChange = 1;
if (direction == 'desc') {
signChange = -1;
}
return function (a, b) {
if (a[attribute] < b[attribute]) {
return -1 * signChange;
}
if (a[attribute] > b[attribute]) {
return 1 * signChange;
}
return 0;
}
}
return sorter;
}
}]);
| 26.382979 | 67 | 0.570968 |
8385811cb89e99438e4738a07fb69c76c7b311f1 | 128 | js | JavaScript | suricata/apis/detect-pkt-data_8c.js | onosfw/apis | 3dd33b600bbd73bb1b8e0a71272efe1a45f42458 | [
"Apache-2.0"
] | null | null | null | suricata/apis/detect-pkt-data_8c.js | onosfw/apis | 3dd33b600bbd73bb1b8e0a71272efe1a45f42458 | [
"Apache-2.0"
] | null | null | null | suricata/apis/detect-pkt-data_8c.js | onosfw/apis | 3dd33b600bbd73bb1b8e0a71272efe1a45f42458 | [
"Apache-2.0"
] | null | null | null | var detect_pkt_data_8c =
[
[ "DetectPktDataRegister", "detect-pkt-data_8c.html#a43643ed52f288845d2ba144419b90218", null ]
]; | 32 | 98 | 0.773438 |
83865789f8a4956d33584f2bbc6763c7ad018012 | 767 | js | JavaScript | components/button/button.js | maatjevanderveer/personal-blog | c5a82c00bb5e4896de71ca555863104e269ec0f4 | [
"MIT"
] | null | null | null | components/button/button.js | maatjevanderveer/personal-blog | c5a82c00bb5e4896de71ca555863104e269ec0f4 | [
"MIT"
] | null | null | null | components/button/button.js | maatjevanderveer/personal-blog | c5a82c00bb5e4896de71ca555863104e269ec0f4 | [
"MIT"
] | null | null | null | import React from "react";
import PropTypes from "prop-types";
import styles from "./button.module.css";
import classnames from 'classnames';
const Button = (props) => {
const buttonClass = classnames({
[styles.base]: true,
[styles[props.variant]]: true, // either primary or secondary
[styles[props.size]]: true, // either sm, md or lg
});
return (
<button
variant={props.variant || "primary"}
className={buttonClass}
size={props.size || "md"}
onClick={props.onClick}
>
{props.label}
</button>
);
};
Button.propTypes = {
label: PropTypes.string,
size: PropTypes.oneOf(["sm", "md", "lg"]),
onClick: PropTypes.func,
variant: PropTypes.oneOf(["primary", "secondary"]),
};
export default Button;
| 23.242424 | 65 | 0.634941 |
83866656515c0a04354ec15050433b4d9b106325 | 165 | js | JavaScript | src/domain/authentication/entities/index.js | przemyslawhaptas/node-app-template | 6066eef0d07ff8accd3eb12dc3e4d623560eef62 | [
"MIT"
] | 2 | 2021-09-19T01:08:20.000Z | 2022-03-14T22:45:36.000Z | src/domain/authentication/entities/index.js | przemyslawhaptas/node-app-template | 6066eef0d07ff8accd3eb12dc3e4d623560eef62 | [
"MIT"
] | null | null | null | src/domain/authentication/entities/index.js | przemyslawhaptas/node-app-template | 6066eef0d07ff8accd3eb12dc3e4d623560eef62 | [
"MIT"
] | null | null | null | import buildApiKey, { buildPlainTextApiKey, buildUnpersistedApiKey } from './api_key';
export {
buildApiKey,
buildPlainTextApiKey,
buildUnpersistedApiKey,
};
| 20.625 | 86 | 0.781818 |
8386bbd5b14bcfd3cf0bc6dffbc78dad9dfb699c | 8,613 | js | JavaScript | src/reducers.js | evoja/redux-reducers | f3055e3f5ecd805514a8798bd52a9f01ea8d2f6e | [
"MIT"
] | null | null | null | src/reducers.js | evoja/redux-reducers | f3055e3f5ecd805514a8798bd52a9f01ea8d2f6e | [
"MIT"
] | null | null | null | src/reducers.js | evoja/redux-reducers | f3055e3f5ecd805514a8798bd52a9f01ea8d2f6e | [
"MIT"
] | null | null | null | 'use strict'
//====== Reducers ========
// What is it:
// * [en](http://rackt.org/redux/docs/basics/Reducers.html)
// * [ru](https://github.com/rajdee/redux-in-russian/blob/master/docs/basics/Reducers.md)
var me = module.exports;
var {evAssert, createExtractor, createReplacer,
ActionToNamespaceException
} = require('./utils.js')
me.NoDefaultStateError = function NoDefaultStateError(message) {
Error.apply(this, arguments)
}
/**
* Create a reducer which:
* * extracts sub-object data from state and passes to your functions
* * does not call your function if action type does not correspond,
* * on non-corresponding action it just returns the non-changed state.
*
* Config:
* {
* types: {
* type1: [{extractor1, replacer1, defaultData1, fun1}],
* },
* defaultState: someObj,
* anyType: [{extractor2, replacer2, defaultData2, fun2}]
* }
*/
me.createEvReducer = function(conf) {
var {types, defaultState, anyType} = conf
evAssert(defaultState !== undefined,
'`defaultState` must not be undefined: ' + defaultState, me.NoDefaultStateError)
evAssert(typeof types == 'object', '`types` must be an object: ' + types)
function evReducer(state, action) {
if (state === undefined) {
state = defaultState
}
var t = types[action.type] || []
if (anyType) {
t = t.concat(anyType)
}
return t.reduce(
function(st, {extractor, replacer, defaultData, fun}) {
var data = st
try {
data = extractor(data, action)
if (data === undefined) {
data = defaultData
}
data = fun(data, action, st)
data = replacer(st, data, action)
} catch (e) {
if (e instanceof ActionToNamespaceException) {
throw e
} else {
throw Error('Error reducing. ' + e.stack, e)
}
}
return data
}, state)
}
evReducer.conf = conf
evReducer.isEv = true
return evReducer
}
function getExtrep(extrep) {
if (typeof extrep == 'string') {
extrep = [createExtractor(extrep), createReplacer(extrep)]
}
var extractor, replacer;
if (Array.isArray(extrep)) {
var [extractor, replacer] = extrep
extrep = {extractor, replacer}
}
return extrep;
}
function wrapDefaultState(replacer, defaultData) {
try {
return replacer({}, defaultData, {})
} catch (e) {
if (e instanceof ActionToNamespaceException) {
return {}
}
throw Error('Error wrapping default. ' + e.stack, e)
}
}
/**
* Create a reducer which:
* * extracts sub-object data from state and passes to your function
* * if data were undefined it substitutes defaultData.
* * does not call your function if action type does not correspond,
* * on non-corresponding action it just returns the non-changed state
* or the state with default data.
*
* Parameters:
* * extrep:
* * string. if it is empty, fun works with full state.
* * [extractor, replacer]. `extractor` and `replacer` are funs.
* * {extractor: fun, replacer: fun}
* * actionTypes: may not be empty.
* * string means single type,
* * array of types [type1, type2],
* * defaultData: may not be undefined,
* * fun: main body of reducer. It may be sure that it gets non-undefined data,
*/
me.createReducer = (extrep, actionTypes, defaultData, fun) => {
if (typeof actionTypes == 'string') {
actionTypes = [actionTypes]
}
evAssert(Array.isArray(actionTypes), '`actioinTypes` must be an array: ' + actionTypes)
var {extractor, replacer} = getExtrep(extrep);
var types, anyType;
if (actionTypes.length == 0) {
anyType = [{extractor, replacer, defaultData, fun}]
types = {}
} else {
anyType = [];
types = actionTypes
.reduce(
(ts, type) => (ts[type] = [{extractor, replacer, defaultData, fun}], ts),
{})
}
var defaultState;
try {
defaultState = wrapDefaultState(replacer, defaultData)
} catch (e) {
if (e instanceof ActionToNamespaceException) {
defaultState = {}
} else {
throw e
}
}
if (defaultState === undefined) {
defaultState = {}
}
return me.createEvReducer({types, defaultState, anyType})
}
/**
* Recursive merge of default states.
* The main aim is extend undefined parts of state
* but don't change existing parts.
*/
me.mergeDefaultState = function mergeDefaultState(prev, next) {
if (prev === undefined) {
return next
}
if (prev === null
|| Array.isArray(prev)
|| typeof prev !== 'object') {
return prev
}
if (typeof next !== 'object') {
return prev
}
if (Object.keys(next).length == 0) {
return prev
}
var result = {...prev}
for (var k in next) {
result[k] = mergeDefaultState(prev[k], next[k])
}
return result
}
/**
* Combine array of evReducers
*/
me.chainEvReducers = function chainEvReducers(reducers, defaultState) {
evAssert(Array.isArray(reducers), '`reducers` must be an array: ' + reducers)
var conf = {
defaultState: defaultState !== undefined ? defaultState : {},
types: {},
anyType: []
}
reducers.forEach(function({conf: {types, anyType, defaultState}}) {
for (var type in types) {
conf.types[type] = conf.types[type]
? conf.types[type].concat(types[type])
: types[type]
}
conf.defaultState = me.mergeDefaultState(conf.defaultState, defaultState)
conf.anyType = conf.anyType.concat(anyType)
})
return me.createEvReducer(conf)
}
function isEvReducer(reducer) {
return reducer.isEv
};
/**
* Combine array of reducers.
* If every reducer is an evReducer result is also an evReducer.
*/
me.chainReducers = function chainReducers(reducers) {
if (reducers.every(isEvReducer)) {
return me.chainEvReducers(reducers)
}
return function chainReducer(state, action) {
return reducers.reduce((st, reducer) => reducer(st, action), state)
}
}
me.NoFunctionError = function(message) {
Error.apply(this, arguments)
}
function throwNoFunctionError(message) {
throw new me.NoFunctionError(message)
}
/**
* Config if arguments.length == 1:
* [[extrep1, actionTypes1, defaultData1, fun1],
* [extrep2, actionTypes2, defaultData2, fun2]]
*
* Parameters:
* * extrep:
* * string. if it is empty, fun works with full state.
* * [extractor, replacer]. `extractor` and `replacer` are funs.
* * {extractor: fun, replacer: fun}
* * actionTypes: may not be empty.
* * string means single type,
* * array of types [type1, type2],
*
*
*
* Two arguments way: (defaultState, confArr)
* Config if arguments.length == 2
* [[extrep1, actionTypes1, fun1, defaultData1],
* [extrep2, actionTypes2, fun2, defaultData2]]
*/
me.createComplexEvReducer = function createComplexReducer(a0, a1) {
var [defaultState, confArr] =
arguments.length == 1 ? [undefined, a0] // createComplexReducer(confArr)
: Array.isArray(a0) && !Array.isArray(a1) ? [a1, a0] // createComplexReducer(confArr, defaultState)
: [a0, a1] // createComplexReducer(defaultState, confArr)
var reducers = confArr.map(
function ([extrep, actionTypes, a2, a3], i) {
var [fun, defaultData] =
typeof a2 == 'function' ? [a2, a3]
: typeof a3 == 'function' ? [a3, a2]
: throwNoFunctionError(i + 'th config does not contain function', arguments[0])
return me.createReducer(extrep, actionTypes, defaultData, fun)
})
return me.chainEvReducers(reducers, defaultState)
}
/**
* Wraps evReducer to deeper version.
*
* Parameters:
* * extrep:
* * string. if it is empty, fun works with full state.
* * [extractor, replacer]. `extractor` and `replacer` are funs.
* * {extractor: fun, replacer: fun}
* * reducer: evReducer
*/
me.wrapEvReducer = function(extrep, reducer) {
extrep = getExtrep(extrep)
var ext = extrep.extractor
var rep = extrep.replacer
var wrap = ({extractor, replacer, defaultData, fun}) => {
var newExtr = (state, action) => extractor(ext(state, action), action)
var newRepl = (state, data, action) =>
rep(state, replacer(ext(state, action), data, action), action)
return {
extractor: newExtr,
replacer: newRepl,
defaultData,
fun
}
}
var rconf = reducer.conf
var conf = {}
conf.defaultState = wrapDefaultState(rep, rconf.defaultState)
conf.types = {}
for (var type in rconf.types) {
conf.types[type] = rconf.types[type].map(wrap)
}
conf.anyType = rconf.anyType.map(wrap)
return me.createEvReducer(conf)
}
| 23.59726 | 103 | 0.636944 |
838749ff1aed156db4fef88df2a9d2e8ee8f46fc | 9,661 | js | JavaScript | backend-node/mock_server.js | grzes5003/e-commerce | 7e9c7ebfe9f2876321be5020b035e931457736d7 | [
"MIT"
] | null | null | null | backend-node/mock_server.js | grzes5003/e-commerce | 7e9c7ebfe9f2876321be5020b035e931457736d7 | [
"MIT"
] | null | null | null | backend-node/mock_server.js | grzes5003/e-commerce | 7e9c7ebfe9f2876321be5020b035e931457736d7 | [
"MIT"
] | null | null | null | const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express();
const port = 4000;
const faker = require('faker');
let corsOptions = {
origin: true,
credentials: true
};
app.use(cors(corsOptions));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
const generateFakeProducts = () => {
let quantity = {
buty: 171,
spodnie: 122,
sukienki: 67,
inne: 202,
dresy: 81
}
const buty = [...Array(quantity.buty).keys()].map((x) => ({
id: x,
name: faker.commerce.productName(),
price: faker.commerce.price(),
description: faker.commerce.productDescription(),
brand: Math.floor(Math.random() * (15)),
picture: faker.image.business(),
cat: 0
}));
const spodnie = [...Array(quantity.spodnie).keys()].map((x) => ({
id: x + quantity.buty,
name: faker.commerce.productName(),
price: faker.commerce.price(),
description: faker.commerce.productDescription(),
brand: Math.floor(Math.random() * (15)),
picture: faker.image.business(),
cat: 1
}));
const sukienki = [...Array(quantity.sukienki).keys()].map((x) => ({
id: x + quantity.buty + quantity.spodnie,
name: faker.commerce.productName(),
price: faker.commerce.price(),
description: faker.commerce.productDescription(),
brand: Math.floor(Math.random() * (15)),
picture: faker.image.business(),
cat: 2
}));
const inne = [...Array(quantity.inne).keys()].map((x) => ({
id: x + quantity.buty + quantity.spodnie + quantity.sukienki,
name: faker.commerce.productName(),
price: faker.commerce.price(),
description: faker.commerce.productDescription(),
brand: Math.floor(Math.random() * (15)),
picture: faker.image.business(),
cat: 3
}));
const dresy = [...Array(quantity.dresy).keys()].map((x) => ({
id: x + quantity.buty + quantity.spodnie + quantity.sukienki + quantity.inne,
name: faker.commerce.productName(),
price: faker.commerce.price(),
description: faker.commerce.productDescription(),
brand: Math.floor(Math.random() * (15)),
picture: faker.image.business(),
cat: 4
}));
return [...buty, ...spodnie, ...sukienki, ...inne, ...dresy];
}
const products = generateFakeProducts();
const brands = [...Array(15).keys()].map((x) => ({
id: x,
name: faker.company.companyName(0)
}));
const orders = [{user: "test",desc: 'order uno',purchase_dtime: '1000-01-01 00:00:00', products: [products[1], products[10], products[20], products[30], products[40]]}];
// const fs = require('fs');
// fs.writeFileSync('products.json', JSON.stringify(products));
const users = [{id: 1, username: 'test', password: 'test', email: 'text@example.com', orders: []}];
const categories = [{id: 0, name: 'Buty'}, {id: 1, name: 'Spodnie'}, {id: 2, name: 'Sukienki'},
{id: 3, name: 'Inne'}, {id: 4, name: 'Dresy'}];
// const products = [
// {id: 0, name: "Abibasy", cat: 0, price: 102},
// {id: 1, name: "Najki", cat: 0, price: 99},
// {id: 2, name: "CCC", cat: 0, price: 265},
//
// {id: 3, name: "suknia", cat: 2, price: 10},
// {id: 4, name: "dresik", cat: 2, price: 60},
//
// {id: 5, name: "jeansy", cat: 1, price: 149},
// {id: 6, name: "zamszowe", cat: 1, price: 101},
// {id: 7, name: "orkiszowe", cat: 1, price: 999}
//
// ]
app.get('/', function (req, res) {
res.send('Hello Sir')
})
app.get('/orders/all', function (req, res) {
res.send([orders[0]]);
})
app.post('/auth/login', function (req, res) {
console.log(req.body);
if (!req.body.username || !req.body.password) {
res.status(401).send('Username or password is incorrect');
}
let filteredUsers = users.filter(user => {
return user.username === req.body.username && user.password === req.body.password;
});
if (filteredUsers.length) {
// if login details are valid return user details and fake jwt token
let user = filteredUsers[0];
let responseJson = {
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
token: 'fake-jwt-token'
};
res.cookie('token', 'more-fake-jwt-token', {httpOnly: true});
console.log("RESP: ", JSON.stringify(responseJson));
res.status(200).send(responseJson);
} else {
// else return error
res.status(401).send('Username or password is incorrect');
}
});
app.get('/users', function (req, res) {
//console.log("req: ", req.headers);
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
if (req.headers && req.headers.authorization === 'Bearer fake-jwt-token') {
res.status(200).send({ok: true, text: users});
} else {
// return 401 not authorised if token is null or invalid
res.status(401).send('Unauthorised');
}
});
app.get('/order/from/list', function (req, res) {
let idList = req.query.id;
console.log("TOKEN:: ", req.cookie);
let findProd = [];
try {
console.log('idlist: ', typeof idList)
let ids = JSON.parse(idList);
findProd = products.filter(prod => {
return Array.isArray(ids) ? ids.includes(prod.id) : prod.id === ids;
});
} catch (e) {
console.log('error: ', e);
res.status(400).send("bad req");
return;
}
console.log("USER ORDERED: ", findProd, " WITH TOKEN ");
res.status(200).send(findProd);
});
app.get('/categories', function (req, res) {
//console.log("categories/ req: ", req.headers);
res.status(200).send(categories);
});
app.get('/products/from/list', function (req, res) {
let idList = req.query.id;
let findProd = [];
try {
console.log('idlist: ', typeof idList)
let ids = JSON.parse(idList);
findProd = products.filter(prod => {
return Array.isArray(ids) ? ids.includes(prod.id) : prod.id === ids;
});
} catch (e) {
console.log('error: ', e);
res.status(400).send("bad req");
return;
}
res.status(200).send(findProd);
});
app.get('/brands', function (req, res) {
res.status(200).send(brands);
});
app.get('/products', function (req, res) {
let cats = req.query.cat;
let limit = req.query.limit;
let offset = req.query.offset;
let order = req.query.order;
let _sort = req.query.sort;
let max_num = 0;
console.log('query: ', req.query);
console.log('rest: ', limit, ' ', _sort);
let findProd = [];
try {
console.log(cats);
if (cats && cats.length) {
let c = JSON.parse(cats);
console.log('parse', c);
findProd = products.filter(prod => {
return Array.isArray(c) ? c.includes(prod.cat) : prod.cat === c;
});
// console.log('find ',findProd);
} else {
findProd = products;
}
max_num = findProd.length;
if (_sort && _sort.length) {
console.log('sort: ', _sort);
let sor = _sort;
let ord = 'asc';
if (order && order.length) {
let ord = order;
console.log('order = ', ord);
}
if (ord === 'asc' && sor === 'price') {
findProd.sort((a, b) => (a.price > b.price) ? 1 : ((b.price > a.price) ? -1 : 0));
} else if (ord === 'desc' && sor === 'price') {
findProd.sort((a, b) => (b.price > a.price) ? 1 : ((a.price > b.price) ? -1 : 0));
} else if (ord === 'asc' && sor === 'name') {
findProd.sort((a, b) => (a.name[0] > b.name[0]) ? 1 : ((b.name[0] > a.name[0]) ? -1 : 0));
} else if (ord === 'desc' && sor === 'name') {
findProd.sort((a, b) => (a.name[0] < b.name[0]) ? 1 : ((b.name[0] < a.name[0]) ? -1 : 0));
}
}
if (offset && offset.length) {
let off = JSON.parse(offset);
console.log('parse offset', off);
findProd.splice(0, off);
}
if (limit && limit.length) {
let lim = JSON.parse(limit);
console.log('parse limit', lim);
findProd = findProd.slice(0, lim);
console.log('parsed limit === ', findProd.slice(0, lim));
}
} catch (e) {
console.log('error: ', e);
res.status(400).send("bad req");
return;
}
res.status(200).send({products: findProd, numOfResults: max_num});
});
app.get('/product/:prodId', function (req, res) {
const id = req.params.prodId;
let findProd = products.filter(prod => {
return prod.id.toString() === id;
});
console.log('Found product: ', findProd);
if (findProd.length) {
res.status(200).send(findProd[0]);
return;
}
res.status(404).send("Item not found");
});
app.get('/add/to/cart/:prodId', function (req, res) {
const id = req.params.prodId;
console.log("id")
res.status(200).send({id: id, name: 'name' + id});
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
| 31.67541 | 169 | 0.548804 |
83877981241b14aae85d9f6ce9022982da36432f | 17,350 | js | JavaScript | oving11/src/index.js | odderikf/sysdevweb | f59fea96ab1ab6b5550f7aae558d3ac9580df798 | [
"MIT"
] | null | null | null | oving11/src/index.js | odderikf/sysdevweb | f59fea96ab1ab6b5550f7aae558d3ac9580df798 | [
"MIT"
] | null | null | null | oving11/src/index.js | odderikf/sysdevweb | f59fea96ab1ab6b5550f7aae558d3ac9580df798 | [
"MIT"
] | null | null | null | // @flow
/* eslint eqeqeq: "off" */
import * as React from 'react';
import { Component , sharedComponentData } from 'react-simplified';
import { HashRouter, Route, NavLink } from 'react-router-dom';
import ReactDOM from 'react-dom';
import {Alert, Button, Card, Navbar, ListGroup, Form} from './widgets';
class Student {
firstName: string;
lastName: string;
email: string;
constructor(firstName: string, lastName: string, email: string) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
class Subject {
title: string;
code: string;
students: Array<Student>;
constructor(title: string, code: string, students: Array<Student>) {
this.title = title;
this.code = code;
this.students = students;
}
}
let shared = sharedComponentData(
{ students : [
new Student('Ola', 'Jensen', 'ola.jensen@ntnu.no'),
new Student('Kari', 'Larsen', 'kari.larsen@ntnu.no'),
new Student('Odd', 'Geir', 'odd.geir@ntnu.no'),
new Student('Karl', 'Karlsen', 'karl.karlsen@ntnu.no'),
new Student('Olly', 'Arnesen', 'olly.arnesen@ntnu.no'),
new Student('Trixis', '4Kids', 'trixis.4kids@ntnu.no')
],
subjects : [],
AlertBar: null
});
Array.prototype.push.apply(shared.subjects, [
new Subject('Systemutvikling 2 med web applikasjoner', 'TDAT2003', shared.students.slice(0, 2)),
new Subject('Japansk 1', 'JAP0501', shared.students.slice(2, 4)),
new Subject('Applikasjonsutvikling for Android', 'IINI4001', shared.students.slice(0, 3)),
new Subject('Realfag for dataingeniører', 'TDAT2001', shared.students.slice(0)),
new Subject('Algoritmer og datastrukturer ', 'TDAT2005', shared.students.slice(3))
]);
class Menu extends Component {
render() {
return (
<Navbar>
<NavLink style={{color: "white"}} activeStyle={{ color: 'cyan' }} exact to="/">
React example
</NavLink>
<NavLink style={{color: "white"}} activeStyle={{ color: 'cyan' }} to="/students">
Students
</NavLink>
<NavLink style={{color: "white"}} activeStyle={{ color: 'cyan' }} to={'/subjects'}>
Subjects
</NavLink>
</Navbar>
);
}
}
class Home extends Component {
render() {
return <div>React example with static pages</div>;
}
}
class StudentList extends Component {
static defaultProps = {
students: shared.students,
addbutton: true
};
render() {
return (
<ListGroup>
{this.props.students.map(student => (
<ListGroup.Item key={student.email}>
<NavLink activeStyle={{ color: 'darkblue' }} to={'/students/' + student.email}>
{student.firstName} {student.lastName}
</NavLink>
</ListGroup.Item>
))}
</ListGroup>
);
}
}
class Students extends Component{
render() {
return (
<>
<StudentList/>
<Button value="add new student" onClick={e=>this.addStudent()} />
</>
)
}
addStudent() {
this.props.history.push("/addstudent")
}
}
class SubjectList extends Component {
static defaultProps = {
subjects: shared.subjects
};
render() {
return (
<ListGroup>
{this.props.subjects.map(subject => (
<ListGroup.Item key={subject.code}>
<NavLink activeStyle={{ color: 'darkblue' }} to={'/subjects/' + subject.code}>
{subject.code} {subject.title}
</NavLink>
</ListGroup.Item>
))}
</ListGroup>
)
}
}
class Subjects extends Component {
render() {
return (
<>
<SubjectList/>
<Button value="add new subject" onClick={e=>this.addSubject()} />
</>
)
}
addSubject() {
this.props.history.push("/addsubject")
}
}
class StudentDetails extends Component<{ match: { params: { email: string } } }> {
deleteStudent(student: Student) {
let i = shared.students.findIndex(v => v.email === student.email);
shared.students.splice(i, 1);
shared.subjects.forEach(sub => {
let j = sub.students.findIndex(w => w.email === student.email);
sub.students.splice(j, 1);
});
this.props.history.goBack();
}
editStudent(student: Student) {
this.props.history.push("/students/"+student.email+"/edit");
}
render() {
let student = shared.students.find(student => student.email === this.props.match.params.email);
if (!student) {
console.error('Student not found'); // Until we have a warning/error system (next week)
return null; // Return empty object (nothing to render)
}
return (
<div>
<Card title={student.firstName+" "+student.lastName}>
<p>Subjects:</p>
<SubjectList subjects={shared.subjects.filter(subject => (subject.students.includes(student)))}/>
<Button value="edit" onClick={e=>this.editStudent(student)}/>
<Button.Danger value="DELETE" onClick={e=>this.deleteStudent(student)}/>
</Card>
<input />
</div>
);
}
}
class StudentEdit extends Component<{ match: { params: { email: string } } }> {
constructor(props){
super(props);
let student = shared.students.find(s => s.email === this.props.match.params.email);
this.state = {
firstName: student.firstName,
lastName: student.lastName
};
}
handleSubmit(){
let student = shared.students.find(s => s.email === this.props.match.params.email);
if (!student){
shared.AlertBar.current.Danger("Student not found, possibly deleted by other user.");
return;
}
if (this.state.firstName.length < 3){
shared.AlertBar.current.Warning("First name too short");
return;
}
if (this.state.lastName.length < 3){
shared.AlertBar.current.Warning("Last name too short");
return;
}
student.firstName = this.state.firstName;
student.lastName = this.state.lastName;
this.props.history.push("/students/"+student.email);
shared.AlertBar.current.Success("Successfully edited student");
}
changeFName(v){
this.setState({firstName: v});
}
changeLName(v){
this.setState({lastName: v});
}
render() {
let student = shared.students.find(student => student.email === this.props.match.params.email);
if (!student) {
console.error('Student not found'); // Until we have a warning/error system (next week)
return null; // Return empty object (nothing to render)
}
return (
<form onSubmit={()=>this.handleSubmit()}>
<Form.Entry>
<Form.Label htmlFor="firstname">First name:</Form.Label>
<Form.Input type="text" id="firstname" autoComplete="firstname" value={this.state.firstName} onChange={e=>this.changeFName(e.target.value)}/>
</Form.Entry>
<Form.Entry>
<Form.Label htmlFor="lastname">Last name:</Form.Label>
<Form.Input type="text" id="lastname" autoComplete="family-name" value={this.state.lastName} onChange={e=>this.changeLName(e.target.value)}/>
</Form.Entry>
<Form.Submitter/>
</form>
);
}
}
class StudentAdd extends Component{
constructor(props) {
super(props);
this.state = {
firstName: "",
lastName: "",
email: ""
};
}
handleSubmit(){
if (this.state.firstName.length < 3){
shared.AlertBar.current.Warning("First name too short");
return;
}
if (this.state.lastName.length < 3){
shared.AlertBar.current.Warning("Last name too short");
return;
}
if (shared.students.find(s => s.email === this.state.email)) {
shared.AlertBar.current.Danger("Email already taken");
return;
}
let student = new Student(this.state.firstName, this.state.lastName, this.state.email);
shared.students.push(student);
this.props.history.push("/students/"+student.email);
shared.AlertBar.current.Success("Successfully added student");
}
changeFName(v){
this.setState({firstName: v});
}
changeLName(v){
this.setState({lastName: v});
}
changeEmail(v){
this.setState({email: v});
}
render() {
return (
<form onSubmit={()=>this.handleSubmit()}>
<Form.Entry>
<Form.Label htmlFor="firstname">First name:</Form.Label>
<Form.Input type="text" id="firstname" autoComplete="firstname" value={this.state.firstName} onChange={e=>this.changeFName(e.target.value)}/>
</Form.Entry>
<Form.Entry>
<Form.Label htmlFor="lastname">Last name:</Form.Label>
<Form.Input type="text" id="lastname" autoComplete="family-name" value={this.state.lastName} onChange={e=>this.changeLName(e.target.value)}/>
</Form.Entry>
<Form.Entry>
<Form.Label htmlFor="email">Last name:</Form.Label>
<Form.Input type="text" id="email" autoComplete="email" value={this.state.email} onChange={e=>this.changeEmail(e.target.value)}/>
</Form.Entry>
<Form.Submitter/>
</form>
);
}
}
class SubjectEdit extends Component<{ match: { params: { code: string } } }> {
constructor(props) {
super(props);
let subject = shared.subjects.find(s => s.code === this.props.match.params.code);
let isIncl = {};
subject.students.forEach(s => isIncl[s.email] = true);
this.state = {
title: subject.title,
students: subject.students,
isIncl: isIncl,
email: "",
};
}
handleSubmit(e){
e.preventDefault();
if ( this.state.title.length <= 3){
shared.AlertBar.current.Warning("Title too short");
return;
}
let subject = shared.subjects.find(s => s.code === this.props.match.params.code);
subject.title = this.state.title;
subject.students = this.state.students.filter( s => this.state.isIncl[s.email] );
this.props.history.push("/subjects/"+subject.code);
}
handleStudentSubmit(e) {
e.preventDefault();
let s = shared.students.find(s => s.email === this.state.email);
if (!s) {
shared.AlertBar.current.Warning("Student not found, is the email correct?");
return
}
if (this.state.students.includes(s)){
shared.AlertBar.current.Warning("Student is already registered");
return;
}
let students = this.state.students;
students.push(s);
let isIncl = this.state.isIncl;
isIncl[s.email] = true;
this.setState({students: students, isIncl: isIncl});
}
changeTitle(v){
this.setState({title: v});
}
changeStudent(t){
let student = this.state.students.find(s=> s.email === t.id);
let isIncl = this.state.isIncl;
isIncl[student.email] = t.checked;
this.setState({isIncl: isIncl});
}
changeEmail(v){
this.setState({email: v});
}
render() {
return (
<div className="two-column">
<div className="two-column-left-dominant">
<form onSubmit={(e)=>this.handleSubmit(e)} >
<Form.Entry>
<Form.Label htmlFor="title">Title:</Form.Label>
<Form.Input type="text" id="title" autoComplete="title" value={this.state.title} onChange={e=>this.changeTitle(e.target.value)}/>
</Form.Entry>
<div id="studentcheckboxes">
{(this.state.students.map(s => (
<Form.Entry>
<Form.Label htmlFor={s.email}>{s.email}</Form.Label>
<Form.Input type="checkbox" id={s.email} checked={this.state.isIncl[s.email]} onChange={e=>this.changeStudent(e.target)}/>
</Form.Entry>
)))}
</div>
<br/>
<Form.Submitter/>
</form>
</div>
<div className="two-column-right">
<form onSubmit={(e)=>this.handleStudentSubmit(e)}>
<Form.Entry>
<Form.Label htmlFor="email">Add student by email: </Form.Label>
<Form.Input type="text" id="email" value={this.state.email} onChange={e=>this.changeEmail(e.target.value)}/>
</Form.Entry>
<Form.Submitter>Add student</Form.Submitter>
</form>
</div>
</div>
);
}
}
class SubjectAdd extends Component{
constructor(props) {
super(props);
this.state = {
title: "",
students: [],
isIncl: {},
email: "",
};
}
handleSubmit(e){
e.preventDefault();
if ( this.state.title.length <= 3){
shared.AlertBar.current.Warning("Title too short");
return;
}
if ( this.state.code.length <= 5){
shared.AlertBar.current.Warning("Code too short");
return
}
if ( shared.subjects.find( s => s.code === this.state.code ) ){
shared.AlertBar.current.Danger("Code already taken");
}
let students = this.state.students.filter(s => this.state.isIncl[s.email] );
let subject = new Subject(this.state.title, this.state.code, students);
shared.subjects.push(subject);
this.props.history.push("/subjects/"+subject.code);
}
handleStudentSubmit(e) {
e.preventDefault();
let s = shared.students.find(s => s.email === this.state.email);
if (!s) {
shared.AlertBar.current.Warning("Student not found, is the email correct?");
return
}
if (this.state.students.includes(s)){
shared.AlertBar.current.Warning("Student is already registered");
return;
}
let students = this.state.students;
students.push(s);
let isIncl = this.state.isIncl;
isIncl[s.email] = true;
this.setState({students: students, isIncl: isIncl});
}
changeTitle(v){
this.setState({title: v});
}
changeStudent(t){
let student = this.state.students.find(s=> s.email === t.id);
let isIncl = this.state.isIncl;
isIncl[student.email] = t.checked;
this.setState({isIncl: isIncl});
}
changeCode(v){
this.setState({code: v});
}
changeEmail(v){
this.setState({email: v});
}
render() {
return (
<div className="two-column">
<div className="two-column-left-dominant">
<form onSubmit={(e)=>this.handleSubmit(e)} >
<Form.Entry>
<Form.Label htmlFor="title">Title:</Form.Label>
<Form.Input type="text" id="title" autoComplete="title" value={this.state.title} onChange={e=>this.changeTitle(e.target.value)}/>
</Form.Entry>
<Form.Entry>
<Form.Label htmlFor="code">Code:</Form.Label>
<Form.Input type="text" id="code" autoComplete="code" value={this.state.code} onChange={e=>this.changeCode(e.target.value)}/>
</Form.Entry>
<div id="studentcheckboxes">
{(this.state.students.map(s => (
<Form.Entry>
<Form.Label htmlFor={s.email}>{s.email}</Form.Label>
<Form.Input type="checkbox" id={s.email} checked={this.state.isIncl[s.email]} onChange={e=>this.changeStudent(e.target)}/>
</Form.Entry>
)))}
</div>
<br/>
<Form.Submitter/>
</form>
</div>
<div className="two-column-right">
<form onSubmit={(e)=>this.handleStudentSubmit(e)}>
<Form.Entry>
<Form.Label htmlFor="email">Add student by email: </Form.Label>
<Form.Input type="text" id="email" value={this.state.email} onChange={e=>this.changeEmail(e.target.value)}/>
</Form.Entry>
<Form.Submitter>Add student</Form.Submitter>
</form>
</div>
</div>
);
}
}
class SubjectDetails extends Component<{ match: { params: { code: string } } }> {
deleteSubject(subject: Subject) {
let i = shared.subjects.findIndex(v => v.code === subject.code);
shared.subjects.splice(i, 1);
this.props.history.goBack();
}
editSubject(subject: Subject) {
this.props.history.push("/editsubjects/"+subject.code);
}
render() {
let subject = shared.subjects.find(subject => subject.code === this.props.match.params.code);
if (!subject) {
console.error('subject not found');
return null;
}
return (
<div>
<Card title={subject.title} subtitle={subject.code}>
<p>Students:</p>
<StudentList students={subject.students}/>
<Button value="edit" onClick={()=>this.editSubject(subject)} />
<Button.Danger value="delete" onClick={()=>this.deleteSubject(subject)}/>
</Card>
</div>
);
}
}
const root = document.getElementById('root');
if (root) {
let alert = React.createRef();
ReactDOM.render(
<HashRouter>
<div>
<div id="fixed_top">
<Alert ref={alert}/>
</div>
<div style={{height: "10vh", "background-color": "grey"}}/>
<Menu id="menu"/>
<Route exact path="/" component={Home}/>
<Route path="/students" component={Students}/>
<Route path="/students/:email" component={StudentDetails}/>
<Route path="/subjects" component={Subjects}/>
<Route path="/subjects/:code" component={SubjectDetails}/>
<Route path="/editstudents/:email" component={StudentEdit}/>
<Route path="/editsubjects/:code" component={SubjectEdit}/>
<Route path="/addstudent" component={StudentAdd}/>
<Route path="/addsubject" component={SubjectAdd}/>
</div>
</HashRouter>,
root
);
shared.AlertBar = alert;
console.log(shared);
}
| 30.438596 | 151 | 0.598444 |
838785cbb149ed8383f0353741fe2ba1892752f7 | 3,486 | js | JavaScript | src/components/Login/Signup.js | chachaxw/lottery-front-end-project | 5ded4ee3059b66fb3abb21dd38cef4387cb1e6b5 | [
"MIT"
] | null | null | null | src/components/Login/Signup.js | chachaxw/lottery-front-end-project | 5ded4ee3059b66fb3abb21dd38cef4387cb1e6b5 | [
"MIT"
] | null | null | null | src/components/Login/Signup.js | chachaxw/lottery-front-end-project | 5ded4ee3059b66fb3abb21dd38cef4387cb1e6b5 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import { NavBar, List, InputItem, Button, Checkbox } from 'antd-mobile';
import { createForm } from 'rc-form';
import { Link } from 'react-router';
import './style.scss';
class Signup extends Component {
state = {
disabled: true,
}
onChange = () => {
this.setState({
disabled: !this.state.disabled,
});
}
onSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((error, values) => {
if (!error) {
console.log('ok', values);
} else {
console.log('error', error, values);
}
});
}
render() {
const { getFieldProps } = this.props.form;
return (
<div className="signup">
<NavBar iconName={false} leftContent={<Link to="/">
<i className="iconfont left-icon"></i>
</Link>}>
注册
</NavBar>
<List style={{marginTop: 20}}>
<InputItem
labelNumber={1}
autoComplete="off"
{...getFieldProps('username',{
trigger: 'onBlur',
rules: [{
required: true,
type: 'string',
message: '用户名不能为空'
}],
})}
placeholder="请输入您的用户名">
</InputItem>
<InputItem
labelNumber={1}
autoComplete="off"
{...getFieldProps('email',{
trigger: 'onBlur',
rules: [{
required: true,
type: 'email',
message: '邮箱不能为空'
}],
})}
placeholder="请输入您的邮箱">
</InputItem>
<InputItem
type="password"
labelNumber={1}
autoComplete="off"
{...getFieldProps('password',{
trigger: 'onBlur',
rules: [{
required: true,
message: '密码不能为空'
}],
})}
placeholder="请输入您的密码">
</InputItem>
<InputItem
type="password"
labelNumber={1}
autoComplete="off"
{...getFieldProps('repassword',{
trigger: 'onBlur',
rules: [{
required: true,
message: '密码不能为空'
}],
})}
placeholder="请确认您的密码">
</InputItem>
</List>
<List style={{marginTop: 20}}>
<InputItem
labelNumber={1}
autoComplete="off"
{...getFieldProps('mobile',{
trigger: 'onBlur',
rules: [{
required: true,
message: '手机号不能为空'
}],
})}
placeholder="请输入您的手机号">
</InputItem>
<InputItem
labelNumber={1}
autoComplete="off"
{...getFieldProps('qq',{
trigger: 'onBlur',
rules: [{
required: true,
message: 'QQ号不能为空',
}],
})}
placeholder="请输入您的QQ号">
</InputItem>
</List>
<div className="aggrement"><Checkbox onChange={this.onChange} />阅读并同意《服务条款》与《免费条约》</div>
<div style={{textAlign: 'center'}}>
<Button disabled={this.state.disabled} onClick={this.onSubmit} className="signup-btn">提交注册</Button>
</div>
</div>
)
}
};
export default Signup = createForm()(Signup);
| 26.815385 | 109 | 0.445496 |
8387e8740f0d6ecad6b085e7fbfb4d2fcd603260 | 1,785 | js | JavaScript | packages/sdk-middleware-http/src/errors.js | OlofMoriya/nodejs | 693f630b2c8700bcb68d2c79048b075c92ca558f | [
"MIT"
] | 64 | 2016-10-05T09:54:29.000Z | 2022-02-02T14:41:25.000Z | packages/sdk-middleware-http/src/errors.js | OlofMoriya/nodejs | 693f630b2c8700bcb68d2c79048b075c92ca558f | [
"MIT"
] | 1,426 | 2016-10-11T09:48:35.000Z | 2022-03-29T09:13:36.000Z | packages/sdk-middleware-http/src/errors.js | OlofMoriya/nodejs | 693f630b2c8700bcb68d2c79048b075c92ca558f | [
"MIT"
] | 43 | 2017-01-19T14:22:42.000Z | 2022-03-04T14:00:43.000Z | function defineError(statusCode, message, meta = {}) {
// eslint-disable-next-line no-multi-assign
this.status = this.statusCode = this.code = statusCode
this.message = message
Object.assign(this, meta)
this.name = this.constructor.name
// eslint-disable-next-line no-proto
this.constructor.prototype.__proto__ = Error.prototype
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor)
}
/* eslint-disable max-len, flowtype/require-parameter-type */
export function NetworkError(...args) {
defineError.call(
this,
0 /* special code to indicate network errors */,
...args
)
}
export function HttpError(...args) {
defineError.call(this, /* code will be passed as arg */ ...args)
}
export function BadRequest(...args) {
defineError.call(this, 400, ...args)
}
export function Unauthorized(...args) {
defineError.call(this, 401, ...args)
}
export function Forbidden(...args) {
defineError.call(this, 403, ...args)
}
export function NotFound(...args) {
defineError.call(this, 404, ...args)
}
export function ConcurrentModification(...args) {
defineError.call(this, 409, ...args)
}
export function InternalServerError(...args) {
defineError.call(this, 500, ...args)
}
export function ServiceUnavailable(...args) {
defineError.call(this, 503, ...args)
}
/* eslint-enable max-len */
export default function getErrorByCode(code) {
switch (code) {
case 0:
return NetworkError
case 400:
return BadRequest
case 401:
return Unauthorized
case 403:
return Forbidden
case 404:
return NotFound
case 409:
return ConcurrentModification
case 500:
return InternalServerError
case 503:
return ServiceUnavailable
default:
return undefined
}
}
| 25.5 | 78 | 0.691317 |
838871f17565b1e56699fc0f9d731e9dd2ba6614 | 2,233 | js | JavaScript | main.js | eduard9x/DRmail | 4dbc6fb2a13ddf0a5714ef73b3e7b1733bf24dbf | [
"MIT"
] | 1 | 2016-06-26T17:26:53.000Z | 2016-06-26T17:26:53.000Z | main.js | eduard9x/DRmail | 4dbc6fb2a13ddf0a5714ef73b3e7b1733bf24dbf | [
"MIT"
] | null | null | null | main.js | eduard9x/DRmail | 4dbc6fb2a13ddf0a5714ef73b3e7b1733bf24dbf | [
"MIT"
] | null | null | null | var gmail;
function refresh(f) {
if( (/in/.test(document.readyState)) || (typeof Gmail === undefined) ) {
setTimeout('refresh(' + f + ')', 10);
} else {
f();
}
}
function confirmSave(notification, result){
console.log('This seems to me as: ' + result + '% positive. ');
var answer = confirm(notification);
if (answer){
console.log("message undo = TRUE");
document.getElementById('link_undo').click();
}else{
console.log("message undo = FALSE");
}
};
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent||tmp.innerText;
}
function MoodyChecker(message){
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","64e94ab8a26a4601ae5d242ad5b59e03");
},
type: "POST",
// Request body
data: '{"documents":[{"language":"en","id":"1","text":"' + message + '"}]}',
})
.done(function(data) {
var result = data.documents[0].score;
result = parseInt(result * 1000) / 10;
if(result > 50) {
console.log('This seems to me as: ' + result + '% positive. ');
}else{
var notification = "Hi, this email might not leave a positive impression. Would you rather undo it, have a short break and write a friendlier email afterwards?";
confirmSave(notification, result);
}
})
.fail(function() {
alert('Something went wrong. Please try again.');
});
}
var main = function(){
gmail = new Gmail();
console.log('Hello,', gmail.get.user_email());
gmail.observe.before('send_message', function(url, body, data, xhr){
var message = data.body;
message = strip(message);
message = message.replace(/["']/g, "");
console.log('message was:', message);
MoodyChecker(message);
});
gmail.observe.after('send_message', function(url, body, data, xhr){
console.log("Message has been sent");
});
}
refresh(main);
| 28.265823 | 170 | 0.600537 |
83887d04ceb6816e51b034c26a2f03df01f9e4eb | 725 | js | JavaScript | docs/SoundFontInfoLib/search/functions_15.js | kant/SoundFonts | a5d678e2cfbd299e460db4f7ec747fcb6554512f | [
"MIT"
] | 41 | 2019-01-04T07:09:03.000Z | 2022-03-15T05:36:23.000Z | docs/SoundFontInfoLib/search/functions_15.js | kant/SoundFonts | a5d678e2cfbd299e460db4f7ec747fcb6554512f | [
"MIT"
] | 2 | 2020-12-02T22:31:01.000Z | 2021-12-30T19:58:21.000Z | docs/SoundFontInfoLib/search/functions_15.js | kant/SoundFonts | a5d678e2cfbd299e460db4f7ec747fcb6554512f | [
"MIT"
] | 7 | 2019-01-04T07:09:09.000Z | 2022-02-25T13:31:47.000Z | var searchData=
[
['zone_1491',['Zone',['../class_s_f2_1_1_render_1_1_zone.html#ac1f1b5568d7ef42570f4546b628c5d22',1,'SF2::Render::Zone']]],
['zonecollection_1492',['ZoneCollection',['../class_s_f2_1_1_render_1_1_zone_collection.html#af490a0f3d5071309b49d980ebb5ea134',1,'SF2::Render::ZoneCollection']]],
['zonecount_1493',['zoneCount',['../class_s_f2_1_1_entity_1_1_instrument.html#aaf2607fdce54e63ae5c54d865515b3c8',1,'SF2::Entity::Instrument::zoneCount()'],['../class_s_f2_1_1_entity_1_1_preset.html#a91c864a2dd76d97d5723b43851430428',1,'SF2::Entity::Preset::zoneCount()']]],
['zones_1494',['zones',['../class_s_f2_1_1_render_1_1_with_zones.html#a17aa85527f72334f09d2c969f03a88c6',1,'SF2::Render::WithZones']]]
];
| 90.625 | 275 | 0.783448 |
83888e58df054a7c57e91463beea806fe2191840 | 668 | js | JavaScript | index.js | azizasm/CMSVideoCalling | e81321f932501f9236e7c6ed811ecc673ee7a784 | [
"MIT"
] | null | null | null | index.js | azizasm/CMSVideoCalling | e81321f932501f9236e7c6ed811ecc673ee7a784 | [
"MIT"
] | null | null | null | index.js | azizasm/CMSVideoCalling | e81321f932501f9236e7c6ed811ecc673ee7a784 | [
"MIT"
] | null | null | null | var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var express = require('express');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use('/public', express.static('public'));
io.on('connection', function(socket){
// console.log('connection');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('READ_MYKAD', function (from, msg) {
console.log('SERVER_ONLY msg', from, ' saying ', msg);
socket.emit('MYKAD_PAGE', 'yada ya');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
| 22.266667 | 58 | 0.622754 |
8388e8ddf478ce11a36c4c348b97855e70763012 | 733 | js | JavaScript | Docs/html/search/all_3.js | geronimoj/PhysicsTutorial | f31ebda015e43850bd3d5a02f79ab5f4596fbfda | [
"MIT"
] | null | null | null | Docs/html/search/all_3.js | geronimoj/PhysicsTutorial | f31ebda015e43850bd3d5a02f79ab5f4596fbfda | [
"MIT"
] | null | null | null | Docs/html/search/all_3.js | geronimoj/PhysicsTutorial | f31ebda015e43850bd3d5a02f79ab5f4596fbfda | [
"MIT"
] | null | null | null | var searchData=
[
['debug_20',['DEBUG',['../_plane_8cpp.html#ad72dbcf6d0153db1b8d8a58001feed83',1,'Plane.cpp']]],
['draw_21',['draw',['../class_physics_app.html#a76195807dc109de9009980431884b320',1,'PhysicsApp']]],
['draw_22',['Draw',['../class_box.html#a309d54fdeea398925f6341fab3e0ea84',1,'Box::Draw()'],['../class_physics_object.html#a993187e5476cd2e231cdec4b6176f8b4',1,'PhysicsObject::Draw()'],['../class_physics_scene.html#a54b84a544bfa19e4f5bcbbbc8e425aaf',1,'PhysicsScene::Draw()'],['../class_plane.html#affcf658d3125b05c1c3ec7ab9b8086ae',1,'Plane::Draw()'],['../class_sphere.html#ae7c208cca0c269de15283dca82ce6310',1,'Sphere::Draw()'],['../class_spring.html#a369742d3910fdf035dd28cabcbde921f',1,'Spring::Draw()']]]
];
| 104.714286 | 510 | 0.750341 |
838a07b207815bed76e9435f28e24a1d4d73c067 | 102 | js | JavaScript | frontend/src/components/Blink/presenter.js | junngo/fluentday | b906b109a406ad1e03da3158ebbf58b45d9e88f4 | [
"MIT"
] | null | null | null | frontend/src/components/Blink/presenter.js | junngo/fluentday | b906b109a406ad1e03da3158ebbf58b45d9e88f4 | [
"MIT"
] | 4 | 2021-03-10T11:15:23.000Z | 2022-02-27T01:16:48.000Z | frontend/src/components/Blink/presenter.js | junngo/fluentday | b906b109a406ad1e03da3158ebbf58b45d9e88f4 | [
"MIT"
] | null | null | null | import React from "react";
const Blink = (props, context) => <h1>Blink</h1>;
export default Blink;
| 14.571429 | 49 | 0.676471 |
838a93eaaa965b66b3545598647a375d335a2fe6 | 10,006 | js | JavaScript | my-app/src/index.js | Adyvan/ReactTestApp | 0a940eb8f34018549bc883bb12407bff37021aa4 | [
"MIT"
] | null | null | null | my-app/src/index.js | Adyvan/ReactTestApp | 0a940eb8f34018549bc883bb12407bff37021aa4 | [
"MIT"
] | null | null | null | my-app/src/index.js | Adyvan/ReactTestApp | 0a940eb8f34018549bc883bb12407bff37021aa4 | [
"MIT"
] | null | null | null | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const XValue = 1;
const OValue = 4;
const Lines = [
[0, 4, 8], // 0
[2, 4, 6], // 1
[0, 1, 2], // 2
[3, 4, 5], // 3
[6, 7, 8], // 4
[0, 3, 6], // 5
[1, 4, 7], // 6
[2, 5, 8], // 7
];
const positionLines = [
[0,2,5], //0
[6,2], //1
[1,2,7], //2
[3,5], //3
[0,1,3,6],//4
[3,7], //5
[1,4,5], //6
[4,6], //7
[0,4,7], //8
];
function Square(props) {
const className = ((props.value && props.value.isWin) ? "square-win" : "square");
return (
<button className={className} onClick={props.onClick}>
{props.value && (props.value.value === XValue) ? "X" : props.value && (props.value.value === OValue) ? "0" : '' }
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
onClick={()=> this.props.onClick(i)}
/>
);
}
renderLine(i) {
let elements = Array(3);
for(let row = 0; row < 3; row++)
{
elements.push(this.renderSquare(i * 3 + row));
}
return (
<div className="board-row">
{elements}
</div>
);
}
render() {
let elements = Array(3);
for(let line = 0; line < 3; line++)
{
elements.push(this.renderLine(line));
}
return (
<div className='board'>
{elements}
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
const firstStep = getRandomBool();
this.state = {
history: [{
squares: Array(9).fill(null),
}],
stepNumber:0,
xIsNext: firstStep,
orderInverse: false,
firstStep: firstStep,
};
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: ((step % 2) === 0) ? this.state.firstStep : !this.state.firstStep,
});
}
botStep(squares) {
let index = calculateNextStep(squares);
if(index !== null) {
this.handleClick(index);
}
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (!calculateFinishGame(squares, history.length) && !squares[i]) {
if(!squares[i]){
squares[i] = {
value: null,
isWin: false,
};
}
squares[i].value = this.state.xIsNext ? XValue : OValue;
this.setState({
history: history.concat([{
squares: squares,
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
}
onValueChange = (event) => {
this.setState({
orderInverse: !this.state.orderInverse,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateFinishGame(current.squares, history.length);
let canGoBot = true;
let status = 'Следующий ход: ' + (this.state.xIsNext ? 'X' : '0');
if (winner) {
status = 'Выиграл ' + (winner.won === XValue ? 'X' : '0');
canGoBot = false;
} else if(this.state.stepNumber === 9) {
status = 'Ничья'
canGoBot =false;
}
let moves = history.map((step, move) => {
const desc = move
? 'Перейти к ходу #' + move + ' ' + getLastPosition(history, move)
: 'К началу игры';
const className = (move === this.state.stepNumber ? "btn-select" : "none");
return (
<li key={move} >
<button className={className} onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
)
});
if(this.state.orderInverse) {
moves = moves.reverse();
}
if(!this.state.xIsNext && canGoBot)
{
setTimeout(() => {this.botStep(current.squares)},200);
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<div>
<input
type="checkbox"
value="inverse"
checked={this.state.orderInverse}
onChange={this.onValueChange}
/>
Inverse Order
</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
function calculateNextStep(squares) {
var prioritySquares = squares.slice().map((x,i) => { return {
grade: gratePosition(i, squares),
index: i,
}}).sort((a,b) => {
if (a.grade > b.grade) return -1;
if (a.grade < b.grade) return 1;
return 0;
})
let prioritySquare = maxInRandomInArray(prioritySquares.slice(), (x)=> x.grade);
return prioritySquare.index === -1 ? null : prioritySquare.index;
}
function gratePosition(x, squares)
{
if(squares[x]?.value)
{
return -1;
}
let lineGarateSumm = gratePositionByLines(x, squares).reduce((p,c) => p * c);
return lineGarateSumm;
}
function gratePositionByLines(x, squares)
{
let value = positionLines[x].map((line, i) => lineGrateValue(x, line, squares));
return value;
}
function allValueLines(squares)
{
let lines = Array(Lines.length).fill(0);
for (let index = 0; index < Lines.length; index++) {
lines[index] = Lines[index].map((x)=> (squares[x]?.value ?? 0)).reduce((p,c) => p + c);
}
return lines;
}
function lineGrateValue(squareTargetIndex, lineIndex, squares)
{
let summ = 0;
let emptyIndex = Array(2).fill(null)
for (let i = 0; i < Lines[lineIndex].length; i++) {
const squareIndex = Lines[lineIndex][i];
const value = squares[squareIndex];
if(value) {
summ += value.value;
} else if(squareIndex !== squareTargetIndex) {
emptyIndex.push(i);
}
}
const linesValues = checkNextStep(squares, squareTargetIndex);
const grade = [1, 2, 4, 8, 18, 32];
let value = grade[0];
switch (summ) {
case 8: // 0 0 []
value = grade[5]
break;
case 2: // X X []
value = grade[4]
break;
case 4: // 0 [] []
value = grade[3];
break;
case 0: // [] [] []
value = grade[1];
break;
case 1: // X [] []
value = grade[1];
break;
default:
value = grade[0];
}
if(1 < countInArray(linesValues, (x)=> x === 8))
{
value++;
}
if((summ !== 8 || summ !== 2) && !countInArray(linesValues, (x)=> x === 12))
{
if(0 < countInArray(linesValues, (x)=> x === 2))
{
value = 1;
} else if(countInArray(emptyIndex, (x)=> x !== null)) {
for (let index = 0; index < emptyIndex.length; index++) {
let lines2Values = checkNext2Steps(squares, Lines[lineIndex][emptyIndex[index]], squareTargetIndex)
if(1 < countInArray(lines2Values, (x)=> x === 2) && !countInArray(lines2Values, (x)=> x === 8)) // lose case on next 2 step
{
value = 0;
break;
}
}
}
}
return value;
}
function checkNext2Steps(oldSquares, NewXpos, NewOpos)
{
var sCopy = oldSquares.slice();
sCopy[NewXpos] = {
value: XValue,
isWin: false,
};
sCopy[NewOpos] = {
value: OValue,
isWin: false,
};
const linesValues = allValueLines(sCopy);
return linesValues;
}
function checkNextStep(oldSquares, NewOpos)
{
var sCopy = oldSquares.slice();
sCopy[NewOpos] = {
value: OValue,
isWin: false,
};
const linesValues = allValueLines(sCopy);
return linesValues;
}
function gradeIndex(line, squares)
{
let index = line.map((x, i) => { return {
index: x,
grade: (!(squares[x]?.value) ? gratePosition(x) : -1),
}}).sort((a,b) => {
if (a.grade > b.grade) return -1;
if (a.grade < b.grade) return 1;
return 0;
}).shift();
return index?.index;
}
function calculateFinishGame(squares) {
for (let i = 0; i < Lines.length; i++) {
const [a, b, c] = Lines[i];
if (squares[a] && squares[a].value
&& squares[b] && squares[b].value
&& squares[c] && squares[c].value
&& squares[a].value === squares[b].value && squares[a].value === squares[c].value) {
squares[a] = Object.create(squares[a]);
squares[b] = Object.create(squares[b]);
squares[c] = Object.create(squares[c]);
squares[a].isWin = true;
squares[b].isWin = true;
squares[c].isWin = true;
return { won: squares[a].value };
}
}
return null;
}
function getLastPosition(history, move)
{
if(!move || move > history.length)
{
return null;
}
const previus = history[move - 1].squares.slice();
const current = history[move].squares.slice();
let index = 0;
for (let i = 0; i < previus.length; i++) {
if(previus[i] !== current[i])
{
index = i;
break;
}
}
return '('+ (Math.floor(index / 3) + 1) +','+ (index % 3 + 1) +')';
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function getRandomBool() {
return Math.random() > 0.5;
}
function countInArray(array, func)
{
let count = 0;
for (let index = 0; index < array.length; index++) {
if(func(array[index])){
count++
}
}
return count;
}
function maxInRandomInArray(array, funcGetValue)
{
let max = getMax(array, funcGetValue);
let item = null;
if(max)
{
var items = array.filter(x => funcGetValue(x) === max.value);
item = items[getRandomInt(0, items.length)];
}
return item;
}
function getMax(array, funcGetValue)
{
let max = {
value:Number.MIN_VALUE,
index:-1
};
for (let index = 0; index < array.length; index++) {
const elementValue = funcGetValue(array[index]);
if(elementValue > max.value)
{
max.value = elementValue;
max.index = index;
}
}
return max;
} | 23.108545 | 131 | 0.54997 |
838c3868d11dedc4ba0724d40c49ea26851d8604 | 1,277 | js | JavaScript | src/component/HeroBlock/HeroBlock.js | ReneDrie/horizontal-scroll | be369d087fd3c614d2353835da70fca9f8e1fc73 | [
"MIT"
] | 1 | 2020-03-05T13:39:42.000Z | 2020-03-05T13:39:42.000Z | src/component/HeroBlock/HeroBlock.js | ReneDrie/horizontal-scroll | be369d087fd3c614d2353835da70fca9f8e1fc73 | [
"MIT"
] | 7 | 2020-07-19T19:13:01.000Z | 2022-02-27T00:41:44.000Z | src/component/HeroBlock/HeroBlock.js | ReneDrie/horizontal-scroll | be369d087fd3c614d2353835da70fca9f8e1fc73 | [
"MIT"
] | 1 | 2020-03-05T11:25:59.000Z | 2020-03-05T11:25:59.000Z | import { AbstractTransitionComponent } from 'vue-transition-component';
import { TweenLite } from 'gsap';
import HeroBlockTransitionController from './HeroBlockTransitionController';
import AbstractScrollBlock from '../../util/scroll/AbstractScrollBlock';
// @vue/component
export default {
name: 'HeroBlock',
extends: AbstractTransitionComponent,
mixins: [AbstractScrollBlock],
methods: {
handleAllComponentsReady() {
this.transitionController = new HeroBlockTransitionController(this);
this.isReady();
},
onViewUpdate(xOffset) {
// We make the "Title" and the "Background" sticky with code here
const max = this.$el.offsetWidth - this.$refs.background.offsetWidth;
TweenLite.set(this.$refs.title, {
x: Math.min(max, Math.max(0, xOffset)),
});
// Added some parralax at the end
TweenLite.set(this.$refs.background, {
x: xOffset < max ? xOffset : max + (xOffset - max) / 2,
});
// Ugly calculation to start later and speed up the text animation
const textProgress = Math.max(0, Math.min(1, this.progress * 3 - 1));
TweenLite.set(this.$refs.titleText, {
backgroundPosition: `-${this.$refs.titleText.offsetWidth * textProgress}px 0`,
});
},
},
};
| 34.513514 | 86 | 0.670321 |
838c448979cdeb7270ce7917c061cd5ebdec34cd | 844 | js | JavaScript | src/components/Messages/MessageSeparator/index.js | mybigjsdream/livechat | ac1f3ff3bc44caa96b3b17bd7112c3fd657e8b2d | [
"MIT"
] | null | null | null | src/components/Messages/MessageSeparator/index.js | mybigjsdream/livechat | ac1f3ff3bc44caa96b3b17bd7112c3fd657e8b2d | [
"MIT"
] | null | null | null | src/components/Messages/MessageSeparator/index.js | mybigjsdream/livechat | ac1f3ff3bc44caa96b3b17bd7112c3fd657e8b2d | [
"MIT"
] | null | null | null | import format from "date-fns/format";
import { parseISO } from "date-fns/fp";
import { createClassName, memo } from "../../helpers";
import styles from "./styles.scss";
export const MessageSeparator = memo(
({ date, unread, use: Element = "div", className, style = {} }) => (
<Element
className={createClassName(
styles,
"separator",
{
date: !!date && !unread,
unread: !date && !!unread,
},
[className]
)}
style={style}
>
<hr className={createClassName(styles, "separator__line")} />
{(date || unread) && (
<span className={createClassName(styles, "separator__text")}>
{(!!date && format(parseISO(date), "yyyy/MM/dd").toUpperCase()) ||
(unread && I18n.t("unread messages"))}
</span>
)}
<hr className={createClassName(styles, "separator__line")} />
</Element>
)
);
| 26.375 | 71 | 0.60545 |
838d5688ee1408f3f21916b260e6d049091026ea | 1,253 | js | JavaScript | languages/account.js | ServantJS/servantjs-panel | ee47f41d76daaa1a258c33177198a5d7b9328fb6 | [
"Apache-2.0"
] | null | null | null | languages/account.js | ServantJS/servantjs-panel | ee47f41d76daaa1a258c33177198a5d7b9328fb6 | [
"Apache-2.0"
] | null | null | null | languages/account.js | ServantJS/servantjs-panel | ee47f41d76daaa1a258c33177198a5d7b9328fb6 | [
"Apache-2.0"
] | null | null | null | exports.ru = {
signin: {
title: 'Вход',
formTitle: 'Вход в личный кабинет',
help: 'Введите имя пользователя и пароль.',
email: 'Электронная почта',
password: 'Пароль',
remember: 'Запомнить',
action: 'Вход',
forget: 'Забыли пароль?',
forgetClick: 'не волнуйтесь, нажмите ',
here: 'здесь',
forgetClickEnd: ', чтобы восстановить пароль.',
noAccount: 'Еще не зарегистрированы ?',
createAccount: 'Создать аккаунт',
controllerMsg: {
incorrect: 'Неверные имя пользователя или пароль!'
}
}
};
exports.us = {
signin: {
title: 'Login',
formTitle: 'Login to your account',
help: 'Enter any username and password.',
email: 'Email',
password: 'Password',
remember: 'Remember me',
action: 'Sign In',
forget: 'Forgot your password ?',
forgetClick: 'no worries, click ',
here: 'here',
forgetClickEnd: 'to reset your password.',
noAccount: 'Don\'t have an account yet ?',
createAccount: 'Create an account',
controllerMsg: {
incorrect: 'Incorrect username or password.'
}
}
}; | 25.06 | 62 | 0.547486 |
838f0a908c695218bdf94a56af8db367a9763a83 | 3,568 | js | JavaScript | src/js/plugin-bridge/PluginTestUtils.js | janczer/dcos-ui | 8d22d2c1b47ed41901ea2269a469491cab7090e2 | [
"Apache-2.0"
] | null | null | null | src/js/plugin-bridge/PluginTestUtils.js | janczer/dcos-ui | 8d22d2c1b47ed41901ea2269a469491cab7090e2 | [
"Apache-2.0"
] | null | null | null | src/js/plugin-bridge/PluginTestUtils.js | janczer/dcos-ui | 8d22d2c1b47ed41901ea2269a469491cab7090e2 | [
"Apache-2.0"
] | null | null | null | import path from "path";
import PluginSDK from "PluginSDK";
import Loader from "./Loader";
let _plugins = {};
let _externalPlugins = {};
let pluginsList;
let externalPluginsList;
const externalPluginsDir = path.resolve(
process.env.npm_config_externalplugins || "plugins"
);
try {
pluginsList = require("#PLUGINS");
} catch (err) {
pluginsList = {};
}
try {
externalPluginsList = require(externalPluginsDir);
} catch (err) {
externalPluginsList = {};
}
function __getAvailablePlugins() {
return {
pluginsList: _plugins,
externalPluginsList: _externalPlugins
};
}
function __setMockPlugins(plugins) {
_plugins = {};
_externalPlugins = {};
Object.keys(plugins).forEach(function(pluginID) {
if (pluginID in externalPluginsList) {
_externalPlugins[pluginID] = plugins[pluginID];
} else {
_plugins[pluginID] = plugins[pluginID];
}
});
}
// Add custom methods for testing
Loader.__setMockPlugins = __setMockPlugins;
// Rewire so PluginSDK loads the mocked version. But still provide access
// to original method for PluginTestUtils to load actual plugins
Loader.__getAvailablePlugins = function() {
return {
pluginsList,
externalPluginsList
};
};
Loader.getAvailablePlugins = __getAvailablePlugins;
/**
* Loads whatever plugins are passed in. Could be Mocks
* @param {Object} plugins - Plugin name to Config
*/
function loadPlugins(plugins) {
var availablePlugins = {};
var pluginConfig = {};
Object.keys(plugins).forEach(function(pluginID) {
availablePlugins[pluginID] = plugins[pluginID].module;
pluginConfig[pluginID] = plugins[pluginID].config;
});
Loader.__setMockPlugins(availablePlugins);
PluginSDK.initialize(pluginConfig);
}
/**
* Finds actual plugins by name and loads them
* @param {Object} plugins - Map of name to config
*/
function loadPluginsByName(plugins) {
const pluginsToLoad = {};
const { pluginsList, externalPluginsList } = Loader.__getAvailablePlugins();
Object.keys(plugins).forEach(function(pluginID) {
if (!(pluginID in pluginsList) && !(pluginID in externalPluginsList)) {
throw new Error(`${pluginID} does not exist. Failed to load.`);
}
let path;
// Default to always selecting internal plugin if same pluginID
// exists in external plugins. This makes mocking easier.
if (pluginID in pluginsList) {
path = pluginsList[pluginID];
} else {
path = externalPluginsList[pluginID];
}
pluginsToLoad[pluginID] = {
module: path,
config: plugins[pluginID]
};
});
loadPlugins(pluginsToLoad);
}
/**
* Finds and returns the SDK for a specific plugin
* @param {String} pluginID - ID of plugin
* @param {Object} config - configuration
* @param {Boolean} loadPlugin
* @return {PluginSDK} - SDK for plugin with pluginID
*/
function getSDK(pluginID, config, loadPlugin = false) {
// Load plugin first so it can register it's reducer
// if it has one.
if (loadPlugin) {
loadPluginsByName({
[pluginID]: config
});
}
// Get SDK for pluginID.
return PluginSDK.__getSDK(pluginID, config);
}
/**
* Add reducer to Store. Could be an actual plugin reducer or a mock for test
* cases that require specific state.
* @param {String} root - Root key for which reducer will manage state
* @param {Function} reducer - Reducer function
*/
function addReducer(root, reducer) {
PluginSDK.__addReducer(root, reducer);
}
const TestUtils = {
addReducer,
getSDK,
loadPlugins,
loadPluginsByName
};
module.exports = TestUtils;
| 24.951049 | 78 | 0.698991 |
838f54201042c5239b013e8c26b10f92ff1045fd | 796 | js | JavaScript | src/events/guild/messageDelete.js | MrLambs/Lamb-Companion-On-Discord | db086eebe653e3affcc689f39bed5e5df8d30aea | [
"MIT"
] | null | null | null | src/events/guild/messageDelete.js | MrLambs/Lamb-Companion-On-Discord | db086eebe653e3affcc689f39bed5e5df8d30aea | [
"MIT"
] | null | null | null | src/events/guild/messageDelete.js | MrLambs/Lamb-Companion-On-Discord | db086eebe653e3affcc689f39bed5e5df8d30aea | [
"MIT"
] | null | null | null | const { MessageEmbed } = require('discord.js');
const { logs_color } = require('../../util/jsons/colors.json');
module.exports = async (bot, message) => {
let guild = message.guild
let found = guild.channels.cache.find(channel => channel.name == 'mod-logs💬')
if (message.author.bot || message.channel.type === "dm") return;
if (message.content.startsWith('!purge')) return;
if (found) {
let embed = new MessageEmbed()
.setColor(logs_color)
.setTitle('Message Deleted')
.setDescription(`Deleted message in ${message.channel}`)
.addField('Message Content:', `${message.content || `Unavailable`}`)
.addField('Message Author:', `${message.author}`)
.setTimestamp()
found.send(embed)
}
}; | 41.894737 | 81 | 0.601759 |
838fdf2446111c3a2dc66ef93fc92fe701b4a2c4 | 814 | js | JavaScript | src/v1/partner/order/route.js | rolldone/ractive-webpack-boilerplate | 81b82e7b3900a62a88aca694bc8a35a73e3a2ceb | [
"MIT"
] | null | null | null | src/v1/partner/order/route.js | rolldone/ractive-webpack-boilerplate | 81b82e7b3900a62a88aca694bc8a35a73e3a2ceb | [
"MIT"
] | null | null | null | src/v1/partner/order/route.js | rolldone/ractive-webpack-boilerplate | 81b82e7b3900a62a88aca694bc8a35a73e3a2ceb | [
"MIT"
] | null | null | null | module.exports = function(router){
router.addRoute('/order/orders',()=>{
return new Promise((resolve)=>{
require.ensure([],()=>resolve(require('./OrdersSelf').default));
})
},{
name : 'order.self.orders'
})
router.addRoute('/order/orders',()=>{
return new Promise((resolve)=>{
require.ensure([],()=>resolve(require('./OrderDetailSelf').default));
})
},{
name : 'order.self.view'
})
router.addRoute('/order/orders',()=>{
return new Promise((resolve)=>{
require.ensure([],()=>resolve(require('./Orders').default));
})
},{
name : 'order.orders'
})
router.addRoute('/order/:id/detail',()=>{
return new Promise((resolve)=>{
require.ensure([],()=>resolve(require('./OrderDetail').default));
})
},{
name : 'order.detail'
})
} | 27.133333 | 75 | 0.571253 |
839088c4492be52a997e79f43acc6bada5647c3d | 4,219 | js | JavaScript | Project_3_API/BlockController.js | cristiam86/blockchain-dev-udacity | a3db54f40755407fa476ebd29ab7d5973bf76161 | [
"MIT"
] | null | null | null | Project_3_API/BlockController.js | cristiam86/blockchain-dev-udacity | a3db54f40755407fa476ebd29ab7d5973bf76161 | [
"MIT"
] | null | null | null | Project_3_API/BlockController.js | cristiam86/blockchain-dev-udacity | a3db54f40755407fa476ebd29ab7d5973bf76161 | [
"MIT"
] | null | null | null | const SHA256 = require('crypto-js/sha256');
const BlockClass = require('./Block.js');
const Level = require('./Level.js');
/**
* Controller Definition to encapsulate routes to work with blocks
*/
class BlockController {
/**
* Constructor to create a new BlockController, you need to initialize all your endpoints here
* @param {*} app
*/
constructor(app) {
this.app = app;
this.db = new Level.Level();
this._getChain().then(chain => {
this.blocks = chain;
console.log("Constructor -> chain", chain)
if (this.blocks.length === 0) {
this._generateGenesisBlock()
}
});
this.blocks = [];
// this.initializeMockData(); //Only needed for testing
this.getBlockByHeight();
this.postNewBlock();
}
/**
* Implement a GET Endpoint to retrieve a block by index, url: "/block/:index"
*/
getBlockByHeight() {
this.app.get("/block/:height", (req, res) => {
const {params: {height}} = req;
if (height >= 0 && height < this.blocks.length) {
res.send(this.blocks[height]);
} else {
res.status(404).send(`You must specify a height between 0 and ${this.blocks.length-1}`);
}
});
}
/**
* Implement a POST Endpoint to add a new Block, url: "/block:data"
*/
postNewBlock() {
this.app.post("/block", (req, res) => {
if(req.body && typeof req.body.body === "string" && req.body.body != "") {
const newBlock = this._getNewBlock(req.body.body);
this._saveBlockToDB(newBlock).then(newBlockKey => {
if (newBlockKey === newBlock.height) {
res.send(newBlock);
} else {
res.status(503).send('There was a problem saving your block. Please try again');
}
});
} else {
this._returnInvalidData(res);
}
});
}
_generateGenesisBlock() {
const newBlock = this._getNewBlock("First block in the chain - Genesis block");
this._saveBlockToDB(newBlock);
}
_returnInvalidData(res) {
res.status(503).send('invalid data');
}
/**
* Helper method to initialize a Mock dataset. It adds 10 test blocks to the blocks array.
*/
// initializeMockData() {
// if(this.blocks.length === 0){
// for (let index = 0; index < 10; index++) {
// this.blocks.push(this._getNewBlock());
// }
// }
// }
_getNewBlock(data) {
const index = this.blocks.length;
let prevBlockHash = "";
if(index > 0){
const prevBlock = { ...this.blocks[index-1] };
prevBlock.hash = "";
prevBlockHash = SHA256(JSON.stringify(prevBlock)).toString();
}
let blockAux = new BlockClass.Block(data || `Test Data #${index}`);
blockAux.height = index;
blockAux.time = new Date().getTime().toString().slice(0,-3);
blockAux.previousBlockHash = prevBlockHash;
blockAux.hash = SHA256(JSON.stringify(blockAux)).toString();
return blockAux;
}
_getChain(){
return new Promise((resolve, reject) => {
this.db.getAll().then(chain => {
const parsedChain = chain
.sort((a,b) => parseInt(a.key) - parseInt(b.key))
.map((block) => JSON.parse(block.value));
resolve(parsedChain);
})
})
}
_saveBlockToDB(newBlock){
return new Promise((resolve, reject) => {
this.db.addLevelDBData(newBlock.height, JSON.stringify(newBlock)).then(key => {
this.blocks.push(newBlock);
resolve(key);
}).catch(error => {
console.log("addBlock -> getBlockHeight -> addLevelDBData -> error", error)
})
})
}
}
/**
* Exporting the BlockController class
* @param {*} app
*/
module.exports = (app) => { return new BlockController(app);} | 31.962121 | 104 | 0.521925 |
8390e03a27a2d2c7f9dc261650a150f4dd5b0e3a | 885 | js | JavaScript | common/db.js | antirek/beebon | be9f5aad14ba8169b5b2e3d11515bde5a80e909d | [
"MIT"
] | 3 | 2018-01-21T15:47:52.000Z | 2018-03-23T04:42:11.000Z | common/db.js | antirek/beebon | be9f5aad14ba8169b5b2e3d11515bde5a80e909d | [
"MIT"
] | 9 | 2018-01-31T04:53:36.000Z | 2021-11-02T05:17:38.000Z | common/db.js | antirek/beebon | be9f5aad14ba8169b5b2e3d11515bde5a80e909d | [
"MIT"
] | 1 | 2019-08-13T01:21:04.000Z | 2019-08-13T01:21:04.000Z | const mysql = require('mysql2')
function Db (config) {
return new Promise((resolve) => {
let conn = mysql.createConnection(config.mysql)
function handleDisconnect (connection) {
connection.on('error', (err) => {
if (!err.fatal) {
return
}
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
throw err
}
setTimeout(() => {
conn = mysql.createConnection(config.mysql)
handleDisconnect(conn)
}, 1000)
})
}
handleDisconnect(conn)
function Query (query, params = {}) {
return new Promise((resolve, reject) => {
conn.query(query, params, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result)
}
})
})
}
resolve({
query: Query
})
})
}
module.exports = Db
| 20.581395 | 54 | 0.505085 |
8390f3166f7f0d703cf43a8a1407b39f61e5ad62 | 1,822 | js | JavaScript | src/components/Covidinfo/index.js | jaydeepkhatri/PewNews | e4424a578983b868ecd4915a03bbaeac6c27cd8f | [
"MIT"
] | null | null | null | src/components/Covidinfo/index.js | jaydeepkhatri/PewNews | e4424a578983b868ecd4915a03bbaeac6c27cd8f | [
"MIT"
] | null | null | null | src/components/Covidinfo/index.js | jaydeepkhatri/PewNews | e4424a578983b868ecd4915a03bbaeac6c27cd8f | [
"MIT"
] | null | null | null | import { useState, useEffect } from "react";
import axios from "axios";
const Covidinfo = () => {
const [covidData, setCovidData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get('https://covid2019-api.herokuapp.com/v2/current')
.then(
(e) => {
console.log(e.data.data);
const covidata = e.data.data.slice(0, 3);
setLoading(false);
setCovidData(covidata);
}
)
}, [])
return (
<>
{loading ? <h2>Loading Corona Data</h2> :
covidData.map((country, index) =>
<div className="covidcountry" key={index} >
<h3 className="country">{country.location}</h3>
<div className="cases">
<div className="confirmed">
<p>Confirmed</p>
<span>{country.confirmed}</span>
</div>
<div className="active">
<p>Active</p>
<span>{country.active}</span>
</div>
<div className="recovered">
<p>Recovered</p>
<span>{country.recovered}</span>
</div>
<div className="death">
<p>Death</p>
<span>{country.deaths}</span>
</div>
</div>
</div>
)
}
</>
)
}
export default Covidinfo; | 33.740741 | 71 | 0.363886 |
8391c29dd6c2d0cd98d0ab30445f0768798c351e | 3,852 | js | JavaScript | core/testing/triplets_test.js | ceremetrix/X | f59beb2c202986657617bf82e658de19b251b85a | [
"MIT"
] | 460 | 2015-01-09T01:40:25.000Z | 2022-03-31T14:05:30.000Z | core/testing/triplets_test.js | ceremetrix/X | f59beb2c202986657617bf82e658de19b251b85a | [
"MIT"
] | 59 | 2015-01-13T09:17:31.000Z | 2022-03-18T23:21:16.000Z | core/testing/triplets_test.js | ceremetrix/X | f59beb2c202986657617bf82e658de19b251b85a | [
"MIT"
] | 186 | 2015-01-07T18:19:14.000Z | 2022-03-30T08:52:15.000Z | goog.require('X.base');
goog.require('X.triplets');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.asserts');
/**
* Test for X.triplets.classname
*/
function testXtripletsClassname() {
var t = new X.triplets(1);
assertEquals(t.classname, 'triplets');
}
/**
* Test for X.triplets.add()
*/
function testXtripletsAdd() {
var t = new X.triplets(9);
if (X.DEV !== undefined) {
// a fresh X.triplets container should be clean
assertFalse(t._dirty);
}
var t0 = [1, 2, 3];
var t1 = [4, 5, 6];
var t2 = [7,8.100000381469727,9.199999809265137];
// add some triplets
t.add(t0[0], t0[1], t0[2]);
t.add(t1[0], t1[1], t1[2]);
t.add(t2[0], t2[1], t2[2]);
if (X.DEV !== undefined) {
// the triplets container should be dirty now
assertTrue(t._dirty);
}
// check if we can get the exact values again
assertArrayEquals(t.get(0), t0);
assertArrayEquals(t.get(1), t1);
assertArrayEquals(t.get(2), t2);
}
/**
* Test for X.triplets.get()
*/
function testXtripletsGet() {
var t = new X.triplets(9);
assertArrayEquals(t.get(666), [undefined,undefined,undefined]);
assertArrayEquals(t.get(-1), [undefined,undefined,undefined]);
}
/**
* Test for X.triplets.remove()
*/
function testXtripletsRemove() {
var t = new X.triplets(3);
var t0 = [1, 2, 3];
// add a triplet
t.add(t0[0], t0[1], t0[2]);
// check if we can get the exact values again
assertArrayEquals(t.get(0), t0);
// .. now let's remove it
var exceptionThrown = false;
try {
t.remove(0);
} catch (e) {
exceptionThrown = true;
}
assertTrue(exceptionThrown);
// NOTE: this is not implemented yet so should fail
//
// // .. getting it should now fail
// var exceptionThrown = false;
// try {
// t.get(0);
// } catch (e) {
// exceptionThrown = true;
// }
// assertTrue(exceptionThrown);
//
// // .. let's try to remove it again which should result in an exception
// exceptionThrown = false;
// try {
// t.remove(0);
// } catch (e) {
// exceptionThrown = true;
// }
// assertTrue(exceptionThrown);
}
/**
* Test for X.triplets.clear()
*/
function testXtripletsClear() {
var t = new X.triplets(300);
var _caseNumber = 100;
var i;
for (i = 0; i < _caseNumber; i++) {
// add a lot of triplets
var a = Math.random(i);
var b = Math.random(i);
var c = Math.random(i);
t.add(a, b, c);
}
// clear the whole container
t.clear();
// the container should be empty now but still have a fixed size
assertEquals(t.length, 300);
assertEquals(t.count, 100);
// add another triplet
var t0 = [1, 2, 3];
t.add(t0[0], t0[1], t0[2]);
// the count and length should be adjusted
assertEquals(t.length, 303);
assertEquals(t.count, 101);
}
/**
* Test for X.triplets.count()
*/
function testXtripletsCount() {
var _caseNumber = parseInt((Math.random() * 10) + 1, 10);
var t = new X.triplets(_caseNumber * 3);
// the empty container should have count 0
assertEquals(t.count, 0);
var i;
for (i = 0; i < _caseNumber; i++) {
// add a lot of triplets
var a = Math.random(i);
var b = Math.random(i);
var c = Math.random(i);
t.add(a, b, c);
}
assertEquals(t.count, _caseNumber);
}
/**
* Test for X.triplets.length()
*/
function testXtripletsLength() {
var _caseNumber = parseInt((Math.random() * 10) + 1, 10);
var t = new X.triplets(_caseNumber * 3);
// the empty container should have count 0
assertEquals(t.length, 0);
var i;
for (i = 0; i < _caseNumber; i++) {
// add a lot of triplets
var a = Math.random(i);
var b = Math.random(i);
var c = Math.random(i);
t.add(a, b, c);
}
assertEquals(t.length, _caseNumber * 3);
}
| 19.164179 | 74 | 0.591641 |
83926abf20e580f96c0839a64794d770386ccc68 | 206 | js | JavaScript | src/pages/couponPlant/define.js | WangxinsHub/couponSystem | e766d4abb1dda0615523a3f59278c118abb76b6e | [
"MIT"
] | null | null | null | src/pages/couponPlant/define.js | WangxinsHub/couponSystem | e766d4abb1dda0615523a3f59278c118abb76b6e | [
"MIT"
] | 1 | 2020-06-16T05:52:16.000Z | 2020-06-16T05:52:16.000Z | src/pages/couponPlant/define.js | starWangx/couponSystem | e766d4abb1dda0615523a3f59278c118abb76b6e | [
"MIT"
] | null | null | null | /**
* 所有定义的参数,全写再index.js太长了,单独写一个文件
* 主要涵盖:面包屑,搜索,分页
*/
export default {
/*面包屑导航*/
breadMenu: [{
path: '',
title: '权益'
}, {
path: '',
title: '第三方平台'
}],
} | 14.714286 | 33 | 0.436893 |
83928cdd17de245ded8b6b12ef61f3889749d389 | 5,289 | js | JavaScript | Source/Quartzmin/Content/Scripts/global.js | jinweijie/Quartzmin | 246a4fe64339ad8cdd4b2c6c7d2336cb110d8300 | [
"MIT"
] | 397 | 2019-01-05T12:06:43.000Z | 2022-03-30T10:49:44.000Z | Source/Quartzmin/Content/Scripts/global.js | jinweijie/Quartzmin | 246a4fe64339ad8cdd4b2c6c7d2336cb110d8300 | [
"MIT"
] | 77 | 2020-06-22T03:32:50.000Z | 2022-03-23T11:40:27.000Z | Source/Quartzmin/Content/Scripts/global.js | jinweijie/Quartzmin | 246a4fe64339ad8cdd4b2c6c7d2336cb110d8300 | [
"MIT"
] | 142 | 2019-01-15T01:11:02.000Z | 2022-03-30T19:16:35.000Z | if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
if (!Array.prototype.fill) {
Object.defineProperty(Array.prototype, 'fill', {
value: function (value) {
// Steps 1-2.
if (!this) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
// Steps 3-5.
var len = O.length >>> 0;
// Steps 6-7.
var start = arguments[1];
var relativeStart = start >> 0;
// Step 8.
var k = relativeStart < 0 ?
Math.max(len + relativeStart, 0) :
Math.min(relativeStart, len);
// Steps 9-10.
var end = arguments[2];
var relativeEnd = end === undefined ?
len : end >> 0;
// Step 11.
var final = relativeEnd < 0 ?
Math.max(len + relativeEnd, 0) :
Math.min(relativeEnd, len);
// Step 12.
while (k < final) {
O[k] = value;
k++;
}
// Step 13.
return O;
}
});
}
function getErrorMessage(e) {
var statusNum = '';
var statusText = e.statusText;
if (e.responseJSON && e.responseJSON.ExceptionMessage)
statusText = e.responseJSON.ExceptionMessage;
if (e.status > 0)
statusNum = ' (' + e.status + ')';
const msg =
'<div class="ui negative message">' +
'<i class="close icon"></i>' +
'<div class="header">An error occured' + statusNum +
'</div><p>' + statusText + '</p></div>';
return msg;
}
function initErrorMessage(errorElements) {
$(this)
.transition('fade in')
.find('.close')
.on('click', function () {
if (errorElements) {
errorElements.removeClass('error');
}
$(this).closest('.message').transition('fade');
});
return $(this);
}
function prependErrorMessage(e, parent) {
parent.prepend(initErrorMessage.call($(getErrorMessage(e))));
}
function initDimmer() {
return $('#dimmer').dimmer({ closable: false, duration: 100, opacity: 1 });
}
function deleteItem(key, msgParent, delUrl, redirUrl) {
$('#delete-dialog')
.modal({
duration: 250,
onApprove: function () {
$('#dimmer').dimmer('show');
$.ajax({
type: 'POST', url: delUrl,
data: JSON.stringify(key),
contentType: 'application/json', cache: false,
success: function () {
document.location = redirUrl;
},
error: function (e) {
$('#dimmer').dimmer('hide');
prependErrorMessage(e, msgParent);
}
});
}
})
.modal('show');
}
function initHistogramTooltips(elements) {
elements.each(function () {
const tooltip = $(this).data('tooltip-html');
if (tooltip) {
$(this).popup({
html: '<div class="histogram-tooltip">' + tooltip + '</div>',
hoverable: true,
transition: 'fade',
delay: 200
});
}
});
}
function initCronLiveDescription(url, $cronInput, $cronDesc, $nextCronDates) {
function describeCron() {
$.ajax({
type: 'POST', url: url, timeout: 5000,
data: $cronInput.val(), contentType: 'text/plain', dataType: 'json',
success: function (data) {
$cronDesc.text(data.Description);
var nextHtml = data.Next.join('<br>');
if (nextHtml === '') $nextCronDates.hide(); else {
$nextCronDates.show();
$nextCronDates.popup({ html: '<div class="header">Scheduled dates</div><div class="content">' + nextHtml + '</div>' });
}
},
error: function (e) { $cronDesc.text('Error occured.'); }
});
}
var cronDescTimer;
$cronInput.on('input', function (e) {
window.clearTimeout(cronDescTimer);
searchcronDescTimerTimer = window.setTimeout(function () {
cronDescTimer = null;
describeCron();
}, 250);
});
describeCron();
}
function loadAdditionalData(rowIndex, url) {
function applyAdditionalData(element) {
const row = rowIndex[element.data('row')];
if (row) {
element.find('>td').each(function () {
row.find('.' + $(this).attr('class')).html($(this).html());
});
}
}
$.ajax({ // obtain additional data on background - this can take longer
url: url, dataType: "html", cache: false,
success: function (data) {
$(data).find('>tbody>tr').each(function () {
applyAdditionalData($(this));
});
initHistogramTooltips($('.histogram > .bar'));
}
});
}
| 28.744565 | 139 | 0.484213 |
83941da6c2e104268090a14a2d18e6649e555dcc | 1,469 | js | JavaScript | dist/cidades/cidades.module.js | xitao-moura/absoluta-api | a84886d81d8ac3e8e149d1e350c91bb90397cb0e | [
"MIT"
] | null | null | null | dist/cidades/cidades.module.js | xitao-moura/absoluta-api | a84886d81d8ac3e8e149d1e350c91bb90397cb0e | [
"MIT"
] | null | null | null | dist/cidades/cidades.module.js | xitao-moura/absoluta-api | a84886d81d8ac3e8e149d1e350c91bb90397cb0e | [
"MIT"
] | null | null | null | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CidadesModule = void 0;
const common_1 = require("@nestjs/common");
const mongoose_1 = require("@nestjs/mongoose");
const cidades_controller_1 = require("./cidades.controller");
const cidades_service_1 = require("./cidades.service");
const cidades_schema_1 = require("./interfaces/cidades.schema");
let CidadesModule = class CidadesModule {
};
CidadesModule = __decorate([
common_1.Module({
imports: [
mongoose_1.MongooseModule.forFeature([{ name: 'Cidade', schema: cidades_schema_1.CidadeSchema }])
],
exports: [cidades_service_1.CidadesService],
controllers: [cidades_controller_1.CidadesController],
providers: [cidades_service_1.CidadesService]
})
], CidadesModule);
exports.CidadesModule = CidadesModule;
//# sourceMappingURL=cidades.module.js.map | 52.464286 | 150 | 0.682097 |
839626fd247c8585a92828d864a2e12ac7ddb866 | 11,128 | js | JavaScript | src/index.js | ginareeena/phaser3-project-template | b64158b0042473d58cebd64125377c41488de3bb | [
"MIT"
] | null | null | null | src/index.js | ginareeena/phaser3-project-template | b64158b0042473d58cebd64125377c41488de3bb | [
"MIT"
] | null | null | null | src/index.js | ginareeena/phaser3-project-template | b64158b0042473d58cebd64125377c41488de3bb | [
"MIT"
] | null | null | null | import Phaser from "phaser";
let cat;
let highScore = 0;
let score = 0;
let health = 5;
let healthPercentage = 1;
class MyGame extends Phaser.Scene {
constructor() {
super();
this.gameOver = false;
this.playedBefore = false;
}
preload() {
this.load.spritesheet("cat", "./src/assets/pusheenWalk.png", {
frameWidth: 300,
height: 300,
});
this.load.image("background", "./src/assets/grassDarkHand.png");
this.load.image("ground", "./src/assets/groundT.png");
this.load.image("donut", "./src/assets/skyDonut4.png");
this.load.image("skyDonut", "./src/assets/skyDonut4.png");
this.load.image("fireDonut", "./src/assets/fireDonut8.png");
this.load.image("healthDonut", "./src/assets/healthDonutSt.png");
this.load.image("gameOver", "./src/assets/gameOverPA.png");
this.load.image("startScreen", "./src/assets/startScreenFINsm.jpg");
this.load.image("left-cap", "./src/assets/barL.png");
this.load.image("middle", "./src/assets/barM.png");
this.load.image("right-cap", "./src/assets/barR.png");
this.load.image("left-cap-shadow", "./src/assets/barShadowL.png");
this.load.image("middle-shadow", "./src/assets/barShadowM.png");
this.load.image("right-cap-shadow", "./src/assets/barShadowR.png");
}
init() {
this.fullWidth = 200;
}
create() {
this.cameras.main.backgroundColor.setTo(255, 255, 255);
// CREATES ELEMENTS:
// Grass
this.add.image(400, 300, "background");
// Health Bar Shadow
let leftShadowCap = this.add
.image(18, 75, "left-cap-shadow")
.setOrigin(0, 0.5);
let middleShadowCap = this.add
.image(leftShadowCap.x + leftShadowCap.width, 75, "middle-shadow")
.setOrigin(0, 0.5);
middleShadowCap.displayWidth = this.fullWidth;
this.add
.image(
middleShadowCap.x + middleShadowCap.displayWidth,
75,
"right-cap-shadow"
)
.setOrigin(0, 0.5);
// Health Bar Color
this.leftCap = this.add.image(18, 75, "left-cap").setOrigin(0, 0.5);
this.middle = this.add
.image(this.leftCap.x + this.leftCap.width, 75, "middle")
.setOrigin(0, 0.5);
this.rightCap = this.add
.image(this.middle.x + this.middle.displayWidth, 75, "right-cap")
.setOrigin(0, 0.5);
this.setMeterPercentage(1);
// Cat
cat = this.physics.add.sprite(400, 300, "cat", 0);
// Fire Donuts
let fireDonuts = this.physics.add.group();
// Health Donuts
let healthDonuts = this.physics.add.group();
//Regular Donuts
let donuts = this.physics.add.group();
// Sky Donuts
let skyDonuts = this.physics.add.group();
//Initial Donut
let firstDonut = this.physics.add.sprite(100, 255, "donut").setScale(0.3);
// Ground
let ground = this.physics.add.staticSprite(400, 525, "ground");
ground.displayWidth = this.sys.game.config.width;
this.startScreen = this.add.image(400, 300, "startScreen");
// Score Text
this.scoreText = this.add.text(18, 16, "score: 0", {
fontSize: "32px",
fill: "#000",
});
this.highScoreText = this.add.text(620, 16, "high score: " + highScore, {
fontSize: "18px",
fill: "#000",
});
this.highScoreText.setVisible(false);
this.scoreText.setVisible(false);
if (this.playedBefore === false) {
this.input.on("pointerdown", () => {
this.startScreen.visible = false;
this.highScoreText.setVisible(true);
this.scoreText.setVisible(true);
healthPercentage = 1;
health = 5;
});
} else {
this.startScreen.visible = false;
this.highScoreText.setVisible(true);
this.scoreText.setVisible(true);
healthPercentage = 1;
health = 5;
}
// Cat Settings:
// hitbox size
cat.setBodySize(185, 123);
// hitbox center
cat.setOffset(45, 125);
// placement
cat.setOrigin(0.5, 0.58);
// can't walk off screen
cat.setCollideWorldBounds(true);
cat.setGravityY(-600);
cat.setImmovable();
// Cat Animations
this.anims.create({
key: "sit",
repeat: 4,
frameRate: 2.5,
frames: this.anims.generateFrameNumbers("cat", {
start: 0,
end: 1,
}),
});
this.anims.create({
key: "sleep",
repeat: -1,
frameRate: 2.5,
frames: this.anims.generateFrameNumbers("cat", {
start: 2,
end: 3,
}),
});
this.anims.create({
key: "leftWalk",
repeat: -1,
frameRate: 2.5,
frames: this.anims.generateFrameNumbers("cat", {
start: 4,
end: 5,
}),
});
this.anims.create({
key: "rightWalk",
repeat: -1,
frameRate: 2.5,
frames: this.anims.generateFrameNumbers("cat", {
start: 6,
end: 7,
}),
});
//keyboard input listeners:
this.cursors = this.input.keyboard.createCursorKeys();
this.asleep = true;
this.clickNum = 0;
// initial animation cycle
// game begins with cat asleep
cat.on("animationcomplete", () => {
cat.anims.play("sleep");
this.asleep = true;
this.clickNum = 0;
});
cat.play("sleep");
cat.setInteractive();
this.input.on("gameobjectdown", this.wakeUp, this);
// creates more donuts
donuts.children.iterate(function (child) {
child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));
});
function collectDonut(cat, donut) {
donut.disableBody(true, true);
if (health > 3) {
cat.clearTint();
}
score += 5;
this.scoreText.setText("Score: " + score);
if (donuts.countActive(true) === 0 && !this.gameOver) {
let b =
cat.x < 400
? Phaser.Math.Between(400, 800)
: Phaser.Math.Between(0, 400);
let a =
cat.x < 400
? Phaser.Math.Between(400, 800)
: Phaser.Math.Between(0, 400);
let c =
cat.x < 400
? Phaser.Math.Between(400, 800)
: Phaser.Math.Between(0, 400);
let fireDonut = fireDonuts.create(a, 2, "fireDonut").setScale(0.3);
let skyDonut = skyDonuts.create(b, 3, "skyDonut").setScale(0.3);
let healthDonut = healthDonuts
.create(c, 1, "healthDonut")
.setScale(0.3);
fireDonut.setBounce(1);
skyDonut.setBounce(1);
healthDonut.setBounce(1);
skyDonut.setCollideWorldBounds(true);
fireDonut.setCollideWorldBounds(true);
healthDonut.setCollideWorldBounds(true);
fireDonut.setVelocity(Phaser.Math.Between(-200, 200, 20));
skyDonut.setVelocity(Phaser.Math.Between(-200, 200, 20));
healthDonut.setVelocity(Phaser.Math.Between(-200, 200, 20));
}
}
// Gameover
let gameOverPic = this.add.image(400, 300, "gameOver");
gameOverPic.visible = false;
function addHealth(cat, healthDonut) {
healthDonut.disableBody(true, true);
cat.clearTint();
if (health < 5) {
health += 1;
healthPercentage += 0.2;
console.log("addedHealth!");
console.log("health is now:", health);
console.log("healthpercentage is now:", healthPercentage);
this.setMeterPercentage(healthPercentage);
} else {
score += 2;
}
}
function donutBurn(cat, fireDonut) {
console.log("donut burn!");
cat.setTint(0xff0000);
if (health <= 3) {
fireDonut.disableBody(true, true);
cat.setTint(0xff0000);
}
health -= 1;
healthPercentage -= 0.2;
console.log("health:", health);
console.log("healthPercentage:", healthPercentage);
this.setMeterPercentage(healthPercentage);
if (health <= 0) {
cat.setTint(0xff0000);
healthPercentage = 0;
health = 0;
this.setMeterPercentage(0);
this.setMeterPercentageAnimated(0);
this.physics.pause();
cat.anims.stop();
this.gameOver = true;
highScore = highScore > score ? highScore : score;
score = 0;
this.highScoreText.setText("high score: " + highScore);
gameOverPic.visible = true;
this.playedBefore = true;
this.input.on("pointerdown", () => {
this.scene.start(this);
});
} else if (health >= 1) {
this.setMeterPercentage(healthPercentage);
}
}
// Adds collision to the ground:
this.physics.add.collider(donuts, ground);
// adding first donut
this.physics.add.collider(firstDonut, ground);
//Adds collision behavior between cat and assets
this.physics.add.overlap(cat, firstDonut, collectDonut, null, this);
this.physics.add.overlap(cat, donuts, collectDonut, null, this);
this.physics.add.overlap(cat, skyDonuts, collectDonut, null, this);
this.physics.add.collider(cat, healthDonuts, addHealth, null, this);
this.physics.add.collider(cat, fireDonuts, donutBurn, null, this);
if (!gameOverPic.visible) {
this.gameOver = false;
}
this.setMeterPercentage(1);
}
//hit bar animations
makeBar(x, y, color) {
//draw the bar
let bar = this.add.graphics();
//color the bar
bar.fillStyle(color, 1);
//fill the bar with a rectangle
bar.fillRect(0, 0, 200, 50);
//position the bar
bar.x = x;
bar.y = y;
//return the bar
return bar;
}
setValue(bar, percentage) {
//scale the bar
bar.scaleX = percentage / 100;
}
setMeterPercentage(percent = 1) {
const width = this.fullWidth * percent;
this.middle.displayWidth = width;
this.rightCap.x = this.middle.x + this.middle.displayWidth;
}
setMeterPercentageAnimated(percent = 1, duration = 1000) {
const width = this.fullWidth * percent;
this.tweens.add({
targets: this.middle,
displayWidth: width,
duration,
ease: Phaser.Math.Easing.Sine.Out,
onUpdate: () => {
this.rightCap.x = this.middle.x + this.middle.displayWidth;
this.leftCap.visible = this.middle.displayWidth > 0;
this.middle.visible = this.middle.displayWidth > 0;
this.rightCap.visible = this.middle.displayWidth > 0;
},
});
}
update() {
if (!this.asleep && !this.gameOver) {
if (this.cursors.left.isDown) {
cat.x -= 5;
cat.anims.play("leftWalk", true);
} else if (this.cursors.right.isDown) {
cat.anims.play("rightWalk", true);
cat.x += 5;
} else if (this.cursors.up.isDown) {
cat.y -= 5;
} else if (this.cursors.down.isDown) {
cat.y += 5;
} else {
}
}
}
wakeUp(pointer, cat) {
if (this.clickNum === 3) {
cat.anims.play("leftWalk");
}
if (!this.asleep) {
this.clickNum += 1;
}
if (this.asleep) {
cat.anims.play("sit");
this.asleep = false;
}
}
}
let game = new Phaser.Game({
type: Phaser.AUTO,
width: 800,
height: 600,
parent: "phaser-game",
scene: [MyGame],
physics: { default: "arcade", arcade: { gravity: { y: 600 }, debug: false } },
});
game.play;
| 26.432304 | 80 | 0.590762 |
83969643b167c4977e400db4fbd6f92d9e8198d4 | 7,173 | js | JavaScript | App.js | sayarsamanta/ReactNative-Demo | 2bac2b6abbad9ad8be5e4f6e3ac83c1cea26a340 | [
"Apache-2.0"
] | null | null | null | App.js | sayarsamanta/ReactNative-Demo | 2bac2b6abbad9ad8be5e4f6e3ac83c1cea26a340 | [
"Apache-2.0"
] | null | null | null | App.js | sayarsamanta/ReactNative-Demo | 2bac2b6abbad9ad8be5e4f6e3ac83c1cea26a340 | [
"Apache-2.0"
] | null | null | null |
/**
* Created by Sayar Samanta on 27th Nov
*/
import React, { useEffect, useState } from 'react';
import { FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { AntDesign } from '@expo/vector-icons';
import {Feather} from '@expo/vector-icons';
import ListItem from './ListItem';
import { TextInput,Headline,Button } from 'react-native-paper';
import Modal from "react-native-modal";
import { moderateScale, scale } from 'react-native-size-matters';
const STORAGE_KEY = '@save_details';
export default function App() {
/**
* Array declaration
*/
const [detailArray,setDetailArray] = useState([
{name:'Test1',phn:'9999999999'},
{name:'Test2',phn:'9999999998'},
{name:'ATest3',phn:'9999999997'},
{name:'BTest4',phn:'9999999996'},
{name:'CTest5',phn:'9999999995'},
{name:'DTest6',phn:'9999999994'},
{name:'ETest7',phn:'9999999993'},
{name:'FTest8',phn:'9999999992'},
{name:'GTest9',phn:'9999999991'},
{name:'HTest10',phn:'9999999981'},
{name:'ITest11',phn:'9999999982'},
{name:'JTest12',phn:'9999999983'},
{name:'KTest13',phn:'9999999984'},
{name:'LTest14',phn:'9999999985'},
{name:'MTest15',phn:'9999999986'},
{name:'NTest16',phn:'9999999987'},
{name:'OTest17',phn:'9999999988'},
{name:'PTest18',phn:'9999999989'},
{name:'QTest19',phn:'9999999970'},
{name:'RTest20',phn:'9999999990'}])
const [userArray,setUserArray] = useState([])
const [loading,setLoading] = useState(false)
const [modalVisible, setModalVisible] = useState(false);
const [name, setName] = useState('');
const [phnNumber, setPhnNumber] = useState('');
useEffect(()=>{
//saveData()
initiateArray()
},[])
useEffect(()=>{
getData()
},[])
/**
* saving the array in local storage
*/
const saveData = async () => {
try {
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(detailArray))
//alert('Data successfully saved')
} catch (e) {
alert(e)
}
}
/**
* getting the array from local storage
*/
const getData = async () =>{
try {
const myArray = await AsyncStorage.getItem(STORAGE_KEY);
if (myArray !== null) {
// We have data!!
console.log('message',JSON.parse(myArray));
setDetailArray(JSON.parse(myArray))
}
} catch (e) {
alert(e)
}
}
/**
* initiating the array with first 5 items
*/
const initiateArray = () =>{
const items = detailArray.slice(0,5)
setUserArray(items)
}
/**
* adding infinite scrolling
*/
const addInfiniteItem = () =>{
//alert('came here')
setLoading(true)
if(userArray.length< detailArray.length)
{
const items = detailArray.slice(userArray.length,userArray.length+5)
console.log(items)
console.log(userArray)
setUserArray(userArray.concat(items))
setLoading(false)
}
else{
setLoading(false)
}
}
/**
* adding new user to list
*/
const addItemToArray = () =>{
let userObj = {}
userObj.name = name;
userObj.phn = phnNumber
console.log(userObj)
if(name =='' || phnNumber==''){
alert('Please fill all the required fields!')
}
else{
if(detailArray.some(item=>item.name==name || item.phn == phnNumber)){
alert('User already exists!')
}
else{
detailArray.push(userObj)
saveData()
initiateArray()
toggleModal()
}
}
}
const toggleModal = () => {
setModalVisible(!modalVisible);
};
/**
*
* @returns footer component of flatlist
*/
const footer = () =>{
return loading ? <View><Text>Loading...</Text></View> : null
}
return (
<View style={styles.container}>
<View style={styles.parentContainer}>
<Feather name="users" size={scale(15)} color="#A9A9A9" style={{flex:.5,marginTop:3}}/>
<Text style={{flex:8.8,fontSize:scale(13.5),fontWeight:'bold',color:'#696969'}}>
Team members
</Text>
<AntDesign name="infocirlce" size={scale(20)} color="#3CB371" style={{flex:.7,marginTop:3}} />
</View>
<View style={styles.childContainer}>
<FlatList
data={userArray}
keyExtractor={(item) => item.name.toString()}
renderItem={({ item }) => (
<ListItem
item={item}
/>
)}
ListFooterComponent={footer}
onEndReachedThreshold={0.1}
onEndReached={()=>{addInfiniteItem()}}
style={styles.flatlist}
showsVerticalScrollIndicator={false}
contentContainerStyle={{paddingBottom:moderateScale(20)}}
/>
</View>
<View style={styles.addButtonView}>
<Pressable onPress={()=>{toggleModal()}} style={styles.buttonStyle}>
<Text style={{color:'#fff'}}>
{'Add members'}
</Text>
</Pressable>
</View>
<Modal isVisible={modalVisible}
style={styles.modalStyle}
coverScreen={true}
onBackButtonPress={toggleModal}
animationIn={'slideInUp'}
useNativeDriver={true}
>
<View style={{ padding:moderateScale(10)}}>
<Pressable onPress={()=>{setModalVisible(false)}}>
<Text style={{color:'#000'}}>
{'Back'}
</Text>
</Pressable>
<Headline>
{'Add user'}
</Headline>
<TextInput
mode={'outlined'}
label="*Name"
value={name}
onChangeText={text => setName(text)}
//outlineColor={'#9c3353'}
activeOutlineColor={'#9c3353'}
style={styles.textInput}
/>
<TextInput
mode={'outlined'}
keyboardType='numeric'
label="*Phone number"
value={phnNumber}
maxLength={10}
onChangeText={text => setPhnNumber(text)}
activeOutlineColor={'#9c3353'}
//outlineColor={'#9c3353'}
style={styles.textInput}
/>
<Button mode="contained" onPress={() => addItemToArray()} style={styles.addButton}>
Add
</Button>
</View>
</Modal>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
padding:moderateScale(10)
},
parentContainer: {
flex:.5,
flexDirection:'row',
justifyContent:'center',
paddingHorizontal:moderateScale(5)
},
childContainer: {
flex:6.5
},
textInput:{
backgroundColor:'#fff',
color:'#9c3353',
height:scale(50)
},
addButton:{
backgroundColor:'#9c3353',
marginTop:moderateScale(20)
},
modalStyle:{
backgroundColor:'#fff',
margin: 0,
justifyContent:'flex-start'
},
addButtonView:{
flex:3,
justifyContent:'center',
alignItems:'center'
},
buttonStyle:{
height:scale(30),
width:scale(130),
backgroundColor:'#9c3353',
justifyContent:'center',
alignItems:'center',
borderRadius:15
},
flatlist:{
height:scale(270),flexGrow:0,padding:moderateScale(5)
}
});
| 25.98913 | 102 | 0.582183 |
8397e7871c7e947237f0ca8c97e064beb48026f3 | 3,487 | js | JavaScript | src/lib/test.js | hacknlove/cuchito | 8949a65d73a8a93f69cccfe067f9bbf4d28416a7 | [
"MIT"
] | null | null | null | src/lib/test.js | hacknlove/cuchito | 8949a65d73a8a93f69cccfe067f9bbf4d28416a7 | [
"MIT"
] | 1 | 2022-01-22T12:44:34.000Z | 2022-01-22T12:44:34.000Z | src/lib/test.js | hacknlove/cuchito | 8949a65d73a8a93f69cccfe067f9bbf4d28416a7 | [
"MIT"
] | null | null | null | const chalk = require('chalk');
const error = chalk.red;
exports.beforeRequest = async function beforeRequest(req, res, next) {
if (!req.conf.test || !req.conf.test.beforeRequest) {
return next();
}
await req.conf.test.beforeRequest({ request: req.request }).catch((err) => {
console.error(error('beforeRequest', req.request.path))
console.error(err);
process.exit(1);
});
next();
};
exports.requestSchema = async function requestSchema(req, res, next) {
if (!req.conf.test || !req.conf.test.requestSchema) {
return next();
}
const validation = req.conf.test.requestSchema.validate({
headers: req.request.headers,
body: req.request.body,
params: req.request.params,
query: req.request.query,
});
if (validation.error) {
console.error(error('requestSchema', req.request.path));
console.error(validation.error);
if (req.conf.test.requestSchema.exitOnError) {
process.exit(1);
}
req.request.error = validation.error;
}
};
exports.request = async function request(req, res, next) {
if (!req.conf.test || !req.conf.test.request) {
return next();
}
await req.conf.test.request({ request: req.request }).catch((err) => {
console.error(error('request', req.request.path));
console.error(err);
process.exit(1);
});
next();
};
exports.afterRequest = async function afterRequest(req, res, next) {
if (!req.conf.test || !req.conf.test.afterRequest) {
return next();
}
await req.conf.test.afterRequest({ request: req.request }).catch((err) => {
console.error(error('afterRequest', req.request.path));
console.error(err);
process.exit(1);
});
next();
};
exports.beforeResponse = async function beforeResponse(req, res, next) {
if (!req.conf.test || !req.conf.test.beforeResponse) {
return next();
}
await req.conf.test.beforeResponse({
request: req.originalRequest || req.request,
response: req.response,
}).catch((err) => {
console.error(error('beforeRequest', req.request.path));
console.error(err);
process.exit(1);
});
next();
};
exports.responseSchema = function responseSchema(req, res, next) {
if (!req.conf.test || !req.conf.test.responseSchema) {
return next();
}
const validation = req.conf.test.responseSchema.validate({
status: req.response.status,
headers: req.response.headers,
body: req.response.body,
});
if (validation.error) {
console.error(error('responseSchema', req.request.path));
console.error(validation.error);
if (req.conf.test.responseSchema.exitOnError) {
console.error(validation.error);
process.exit(1);
}
req.response.error = validation.error;
}};
exports.response = async function response(req, res, next) {
if (!req.conf.test || !req.conf.test.response) {
return next();
}
await req.conf.test.response({ request: req.originalRequest || req.request, response: req.response }).catch((err) => {
console.error(error('response', req.request.path));
console.error(err);
process.exit(1);
});
next();
};
exports.afterResponse = async function afterResponse(req, res, next) {
if (!req.conf.test || !req.conf.test.afterResponse) {
return next();
}
await req.conf.test.afterResponse({ request: req.originalRequest || req.request, response: req.response }).catch((err) => {
console.error(error('afterResponse', req.request.path));
console.error(err);
process.exit(1);
});
next();
};
| 28.581967 | 125 | 0.65988 |
839806243e04111afe98c3ab5c40f1db63244e49 | 67 | js | JavaScript | lib/verbs.js | floofjs/floof | 20c1b9b33cc67ae02ce2ce5a0319cbcbbf66f9fd | [
"MIT"
] | 1 | 2017-12-01T23:53:32.000Z | 2017-12-01T23:53:32.000Z | lib/verbs.js | floofjs/floof | 20c1b9b33cc67ae02ce2ce5a0319cbcbbf66f9fd | [
"MIT"
] | null | null | null | lib/verbs.js | floofjs/floof | 20c1b9b33cc67ae02ce2ce5a0319cbcbbf66f9fd | [
"MIT"
] | null | null | null | module.exports = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']; | 67 | 67 | 0.567164 |
83983316fed6bcdc87958c4b843715c6e9bf2f4d | 1,602 | js | JavaScript | src/editor/util/getFontHash.js | kslf/fonteditor | 2302a3773f05887dcda3b6c13d242fdb8941d68b | [
"MIT"
] | null | null | null | src/editor/util/getFontHash.js | kslf/fonteditor | 2302a3773f05887dcda3b6c13d242fdb8941d68b | [
"MIT"
] | null | null | null | src/editor/util/getFontHash.js | kslf/fonteditor | 2302a3773f05887dcda3b6c13d242fdb8941d68b | [
"MIT"
] | null | null | null | /**
* @file getFontHash.js
* @author mengke01
* @date
* @description
* 获取font的hashcode
*/
define(
function(require) {
/**
* 获取glyf的hashcode
*
* @param {Object} font glyf字体结构
* @return {number} hashcode
*/
function getFontHash(font) {
var splice = Array.prototype.splice;
var sequence = [
font.advanceWidth || 0
];
// contours
if (font.contours && font.contours.length) {
font.contours.forEach(function(contour) {
contour.forEach(function(p) {
sequence.push(p.x);
sequence.push(p.y);
sequence.push(p.onCurve ? 1 : 0);
});
});
}
if (font.unicode && font.unicode.length) {
splice.apply(sequence, [sequence.length, 0].concat(font.unicode));
}
if (font.name && font.name.length) {
splice.apply(sequence, [sequence.length, 0].concat(font.name.split('').map(function(c) {
return c.charCodeAt(0);
})));
}
// 使用BKDR算法计算哈希
// http://www.cnblogs.com/uvsjoh/archive/2012/03/27/2420120.html
var seed = 131;
var hash = 0;
for (var i = 0, l = sequence.length; i < l ; i++) {
hash = 0x7FFFFFFF & (hash * seed + sequence[i]);
}
return hash;
}
return getFontHash;
}
); | 26.262295 | 104 | 0.44819 |
8398932986c3c345e696f34d68603f1b86037597 | 286 | js | JavaScript | test.js | SaptakBhoumik/sparrow | 717216f600739381e80c3fd3f2a4aa1381a7571e | [
"MIT"
] | 4 | 2022-02-06T19:10:56.000Z | 2022-02-08T13:58:10.000Z | test.js | SaptakBhoumik/sparrow | 717216f600739381e80c3fd3f2a4aa1381a7571e | [
"MIT"
] | null | null | null | test.js | SaptakBhoumik/sparrow | 717216f600739381e80c3fd3f2a4aa1381a7571e | [
"MIT"
] | null | null | null | // program to display fibonacci sequence using recursion
function fibonacci(num) {
if(num < 2) {
return num;
}
else {
return fibonacci(num-1) + fibonacci(num - 2);
}
}
const nTerms = 15;
for(let i = 0; i < nTerms; i++) {
console.log(fibonacci(i));
} | 20.428571 | 56 | 0.583916 |
8398ed5cf5f89861965399bb708da73601956f11 | 2,394 | js | JavaScript | script.js | cybind/html-crawler | d342923828626a3020fac2d1a940ac8632106142 | [
"MIT"
] | null | null | null | script.js | cybind/html-crawler | d342923828626a3020fac2d1a940ac8632106142 | [
"MIT"
] | null | null | null | script.js | cybind/html-crawler | d342923828626a3020fac2d1a940ac8632106142 | [
"MIT"
] | null | null | null | var endpoint = 'http://localhost:3000/auth';
// var endpoint = 'http://localhost:3000/process';
highlightLinks();
addCrawlButton();
function highlightLinks() {
$('a').addClass('crawler-link');
$('a').click(function() {
if ($(this).hasClass('selected'))
$(this).removeClass('selected');
else
$(this).addClass('selected');
return false;
});
}
function addCrawlButton() {
$('body').append('<button class="apply-crawl-button">Crawl</button>');
$('.apply-crawl-button').click(function() {
$(this).addClass('in-progress');
crawl();
});
}
function crawl() {
var linksToSend = [];
var links = $('a.crawler-link.selected');
for (var i = 0; i < links.length; i++) {
var href = $(links[i]).attr('href');
var text = $(links[i]).text();
console.log('Crawling "' + text + '" (' + href + ')');
linksToSend.push(href);
}
var data = {
links: linksToSend
}
console.log(data);
$.ajax({
type: "POST",
url: endpoint,
data: data,
success: function() {
console.log('Links has been sent!');
$('.apply-crawl-button').removeClass('in-progress');
window.open(endpoint);
},
error: function(jqXHR, textStatus, err) {
console.log('text status ' + textStatus + ', err ' + err)
$('.apply-crawl-button').removeClass('in-progress');
},
dataType: 'json'
});
}
/* Helper functions */
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
} | 24.428571 | 85 | 0.497911 |
83995c3f24c4c6b965cb9530de21789f31ec1831 | 1,399 | js | JavaScript | src/redux/works/selectors.js | enterthevoid/liven | 6c3e739bc80efbbf7eebd68b1b86ff37f78fcf83 | [
"MIT"
] | null | null | null | src/redux/works/selectors.js | enterthevoid/liven | 6c3e739bc80efbbf7eebd68b1b86ff37f78fcf83 | [
"MIT"
] | null | null | null | src/redux/works/selectors.js | enterthevoid/liven | 6c3e739bc80efbbf7eebd68b1b86ff37f78fcf83 | [
"MIT"
] | null | null | null | import { createSelector } from "reselect";
const selectWorksDomain = (state) => {
return state.works;
};
const makeSelectWorkById = () => (state, id) =>
selectWorksDomain(state).worksList[id];
const makeSelectWorksIdList = () =>
createSelector(selectWorksDomain, (state) => state.worksLoadedIdList);
const makeSelectWorksList = () =>
createSelector(selectWorksDomain, (state) =>
state.worksLoadedIdList.reduce((carry, id) => {
carry[id] = state.worksList[id];
return carry;
}, {})
);
const makeSelectWorksCount = () =>
createSelector(selectWorksDomain, (state) => state.worksCount);
const makeSelectWorksLoadedCount = () =>
createSelector(selectWorksDomain, (state) => state.worksLoadedCount);
const makeSelectWorksLoading = () =>
createSelector(selectWorksDomain, (state) => state.worksLoading);
const makeSelectWorkCreating = () =>
createSelector(selectWorksDomain, (state) => state.workCreating);
const makeSelectWorkUpdating = () =>
createSelector(selectWorksDomain, (state) => state.workUpdating);
const makeSelectWorkDeleting = () =>
createSelector(selectWorksDomain, (state) => state.workDeleting);
export {
makeSelectWorkById,
makeSelectWorksIdList,
makeSelectWorksList,
makeSelectWorksCount,
makeSelectWorksLoadedCount,
makeSelectWorksLoading,
makeSelectWorkCreating,
makeSelectWorkUpdating,
makeSelectWorkDeleting,
};
| 27.98 | 72 | 0.738385 |
8399f36642cc5c815a5b0dd8cb1eea7e76fc4c36 | 596 | js | JavaScript | client/src/App.js | ezemog1996/El-Fuego-Eatery | 40da0f40bb346cb42633b945bbe02a65a6525c71 | [
"Unlicense"
] | null | null | null | client/src/App.js | ezemog1996/El-Fuego-Eatery | 40da0f40bb346cb42633b945bbe02a65a6525c71 | [
"Unlicense"
] | null | null | null | client/src/App.js | ezemog1996/El-Fuego-Eatery | 40da0f40bb346cb42633b945bbe02a65a6525c71 | [
"Unlicense"
] | null | null | null | import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Home from "./pages/Home";
import Admin from "./pages/Admin";
import Login from "./pages/Login";
import Navbar from "./components/Navbar/Navbar.js";
function App() {
return (
<Router>
<div>
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/admin" component={Admin} />
{/* <Route exact path="/login" component={Login} /> */}
</Switch>
</div>
</Router>
);
}
export default App;
| 24.833333 | 74 | 0.588926 |
839a55e482e13c8e12ab52a8835e24cf1404ad5c | 1,110 | js | JavaScript | src/components/Curtain.js | HuminPiotr/AM-Cleaning-Service | 3f0e72e834301188d3062092339851e034a4174c | [
"RSA-MD"
] | null | null | null | src/components/Curtain.js | HuminPiotr/AM-Cleaning-Service | 3f0e72e834301188d3062092339851e034a4174c | [
"RSA-MD"
] | null | null | null | src/components/Curtain.js | HuminPiotr/AM-Cleaning-Service | 3f0e72e834301188d3062092339851e034a4174c | [
"RSA-MD"
] | null | null | null | import React, {Component} from 'react';
import styled from 'styled-components'
// CSS //
const StyledCurtian = styled.div`
width:100vw;
height: 100vh;
max-height: 1600px;
background: #fff;
position: absolute;
top:0;
right: 17%;
@keyframes animCurtain {
0%{
transform: translateX(0);
}
50%{
opacity: 1;
}
60%{
opacity: 0.5;
}
100%{
transform: translateX(-100%);
opacity: 0;
}
}
@media(max-width: 640px){
display: none;
}
`
// COMPONENT //
class Curtian extends Component {
componentDidMount() {
const curtain = document.querySelector('.curtain');
const observer = new IntersectionObserver((entries) => {
if(entries[0].isIntersecting){
entries[0].target.style.animation = `animCurtain .8s ease-out forwards`;
}
}, {threshold: 0.5})
observer.observe(curtain);
}
render(){
return(
<StyledCurtian className="curtain"></StyledCurtian>
)
}
}
export default Curtian; | 18.5 | 84 | 0.554054 |
839ba378cadee577c9c7579d1873805e75f51248 | 1,107 | js | JavaScript | Graphics/js/lib.js | tub99/Graphics-Library | 74e083fcdab6c379af5a427b50d6f8470929ccd8 | [
"MIT"
] | null | null | null | Graphics/js/lib.js | tub99/Graphics-Library | 74e083fcdab6c379af5a427b50d6f8470929ccd8 | [
"MIT"
] | null | null | null | Graphics/js/lib.js | tub99/Graphics-Library | 74e083fcdab6c379af5a427b50d6f8470929ccd8 | [
"MIT"
] | null | null | null | ////G is a namespace Object
var G = function(el){
this._el = document.querySelector(el);
} || {};
// Scene is the place we want to draw svg
G.Scene = function(el,w,h){
this.obj_str = "";
this._w = w || "100%";
this._h = h || "100%";
//checking if a div element doesn't exist it creates one with 'canvas' class
if(typeof el !== "string" || el === "" || this._el === "")
{
document.write('<div class="canvas"></div>');
}
// fetches the element on which we want to draw
var element = this._el || el || ".canvas";
this._el = document.querySelector(element);
};
// Appends the svg as string
G.Scene.prototype.add = function(obj){
this.obj_str += obj.output();
};
// This creates the total svg that was acquired from the shapes
// val parameter contains the svg string of the elements
G.Scene.prototype.render = function(val)
{
this._svgval = val || this.obj_str;
return this._el.innerHTML = '<svg version="1.1" baseProfile="full" width="'+this._w+'" height="'+this._h+'" xmlns="http://www.w3.org/2000/svg">'+this._svgval+'</svg>';
};
| 35.709677 | 175 | 0.617886 |
839ca3ec016093f3bac962d869db7a24b3bc28d7 | 2,544 | js | JavaScript | src/torchvision/datasets/utilities.js | raghavmecheri/COMS4995 | 00d8c89d1b22b4256fd062b1068b3bd722af7644 | [
"MIT"
] | 12 | 2020-12-28T15:56:26.000Z | 2022-02-14T09:05:17.000Z | src/torchvision/datasets/utilities.js | raghavmecheri/ptjs | 00d8c89d1b22b4256fd062b1068b3bd722af7644 | [
"MIT"
] | 17 | 2020-09-30T09:35:06.000Z | 2020-11-10T06:27:52.000Z | src/torchvision/datasets/utilities.js | raghavmecheri/COMS4995 | 00d8c89d1b22b4256fd062b1068b3bd722af7644 | [
"MIT"
] | 1 | 2020-11-08T02:22:37.000Z | 2020-11-08T02:22:37.000Z | /**
* @module utilities
* @summary Collection of utility functions used for Dataset manipulation and management
* @exports hasFileAllowedExtension Used to check if a file compiles with the allowed extensions
* @exports makeDataset Create a list of instances in the required format for the DatasetFolder
*/
const { lstatSync, readdirSync, existsSync } = require("fs");
const { join, resolve } = require("path");
/**
* Helper method used to check if a file has an allowed extension
* @param {String} filePath The target filepath being loaded
* @param {string[]} extensions A list of allowed extensions for the filepath
* @returns {Boolean} Whether the file has an allowed extension or not
*/
export const hasFileAllowedExtension = (filePath, extensions) =>
extensions.some((extension) => filePath.endsWith(extension));
/**
* Given a root directory of a dataset, iterate over subfolders, and construct the actual dataset while also checking if the files are valid, and if they are allowed
* @param {String} rootDir Base directory for the dataset
* @param {{ String: Number }} classToIdx Mapping from class to index
* @param {string[]} extensions A list of allowed file extensions that may be loaded
* @param {Function} isValidFile A function to check if a file is valid and is to be loaded
* @returns {Array.<{path: String, classIndex: Number }>} A list of loaded object pointers to files
*
*/
export const makeDataset = (
rootDir,
classToIdx,
extensions = null,
isValidFile = null
) => {
const instances = [];
const absolutePath = resolve(rootDir);
const bothNone = extensions === null && isValidFile === null;
const bothSomething = extensions !== null && isValidFile !== null;
if (bothNone || bothSomething)
throw new Error(
"Both extensions and isValidFile cannot be None or not None at the same time"
);
let validFile = isValidFile;
if (extensions !== null) {
validFile = (filePath) => hasFileAllowedExtension(filePath, extensions);
}
const classes = Object.keys(classToIdx).sort();
classes.forEach((targetClass) => {
const classIndex = classToIdx[targetClass];
const targetDir = join(absolutePath, targetClass);
if (lstatSync(targetDir).isDirectory()) {
const entries = readdirSync(targetDir);
entries.forEach((entry) => {
const filePath = join(targetDir, entry);
if (existsSync(filePath) && validFile(filePath)) {
instances.push({ path: filePath, classIndex });
}
});
}
});
return instances;
};
| 37.411765 | 165 | 0.705582 |
839cf93ce2127ade3ad55f97b44ded29ffb48027 | 5,196 | js | JavaScript | src/components/TickerToSignup/Ticker/index.js | grundeinkommensbuero/grundeinkommensbuero.github.io | b578d3350eb37587d6477faa1073848f25703b40 | [
"MIT"
] | 1 | 2020-11-17T14:36:52.000Z | 2020-11-17T14:36:52.000Z | src/components/TickerToSignup/Ticker/index.js | grundeinkommensbuero/website | bc97543f2dca3a7e34560bfc53ba989374bcd584 | [
"MIT"
] | 112 | 2019-08-02T06:51:20.000Z | 2022-03-30T09:09:41.000Z | src/components/TickerToSignup/Ticker/index.js | grundeinkommensbuero/grundeinkommensbuero.github.io | b578d3350eb37587d6477faa1073848f25703b40 | [
"MIT"
] | 2 | 2020-01-13T11:07:29.000Z | 2020-07-28T13:39:01.000Z | import React, { useContext, useState, useEffect } from 'react';
import cN from 'classnames';
import Reel from 'react-reel';
import * as s from './style.module.less';
import { MunicipalityContext } from '../../../context/Municipality';
import * as u from './utils';
import './reelstyle.less';
export const Ticker = ({ tickerDescription }) => {
const { statsSummary, refreshContextStats } = useContext(MunicipalityContext);
const [timerIsReady, setTimerIsReady] = useState(false);
const [peopleCount, setPeopleCount] = useState(0);
const [municipalityCount, setMunicipalityCount] = useState(0);
const [updatedSummary, setUpdatedSummary] = useState(0);
const [timePassedInIntervalInPercent, setTimePassedInIntervalInPercent] =
useState(0);
const prevTimestamp = new Date(statsSummary?.previous.timestamp);
const currTimestamp = new Date(statsSummary?.timestamp);
useEffect(() => {
if (statsSummary && statsSummary.previous) {
u.calcTickerValues({
prevTimestamp,
currTimestamp,
setTimePassedInIntervalInPercent,
});
setTimerIsReady(true);
setUpdatedSummary(updatedSummary + 1);
}
}, [statsSummary]);
useEffect(() => {
let updateTickerTimeout;
const timerConf = {
numberBetweenOneAndThree: Math.floor(Math.random() * 3) + 1,
interval: 3000,
};
// Set timer in a range of 3 to 9 seconds
const randomTimer = timerConf.numberBetweenOneAndThree * timerConf.interval;
if (timerIsReady && timePassedInIntervalInPercent <= 1) {
// Set timeout to display data in the Ticker Comp
// console.log('Timer set to:', randomTimer, 'ms');
updateTickerTimeout = setTimeout(() => {
u.calcTickerValues({
prevTimestamp,
currTimestamp,
setTimePassedInIntervalInPercent,
});
}, randomTimer);
}
// Clear Timeout when done
return () => {
clearTimeout(updateTickerTimeout);
};
}, [updatedSummary]);
useEffect(() => {
if (statsSummary && statsSummary.previous) {
u.updateTicker({
statsSummary,
timePassedInIntervalInPercent,
setPeopleCount,
setMunicipalityCount,
updatedSummary,
setUpdatedSummary,
refreshContextStats,
});
}
}, [timePassedInIntervalInPercent]);
return (
<TickerDisplay
prefixText="Schon"
highlight1={peopleCount}
inBetween1="Menschen in"
// inBetween2="in"
highlight2={municipalityCount}
suffixHighlight2="Orten sind dabei."
tickerDescription={tickerDescription}
/>
);
};
const TickerDisplay = ({
prefixText,
highlight1,
inBetween1,
inBetween2,
highlight2,
suffixHighlight2,
tickerDescription,
}) => {
return (
<section className={s.contentContainer}>
<div className={s.slotMachine}>
<div className={s.counterContainer}>
{prefixText && (
<span
className={cN(
s.counterLabelSlotMachine,
s.counterLabelMarginRight,
s.bold
)}
>
{prefixText}{' '}
</span>
)}
<div className={s.numbersContainer}>
<Reel text={u.numberWithDots(highlight1)} />
</div>
{inBetween1 && (
<h2
className={cN(
s.counterLabelSlotMachine,
s.counterLabelMarginLeft
)}
>
{inBetween1}
</h2>
)}
</div>
<div className={cN(s.counterContainer)}>
{typeof highlight2 !== 'string' && (
<>
{inBetween2 && (
<h2
className={cN(
s.counterLabelSlotMachine,
s.counterLabelMarginRight
)}
>
{inBetween2}
</h2>
)}
<div className={s.numbersContainer}>
<Reel text={u.numberWithDots(highlight2)} />
</div>
{suffixHighlight2 && (
<h2
className={cN(
s.counterLabelSlotMachine,
s.counterLabelMarginLeft
)}
>
{suffixHighlight2}
</h2>
)}
</>
)}
{typeof highlight2 === 'string' && (
<>
<h2
className={cN(
s.counterLabelSlotMachine,
s.counterLabelMarginRight,
s.noMarginTop
)}
>
{inBetween2 && <span>{inBetween2} </span>}
<span className={s.highlightHeadline}>{highlight2}</span>
{/* TODO: implement point */}
{/* {suffixHighlight2 && <span>{suffixHighlight2}</span>} */}
</h2>
</>
)}
</div>
{tickerDescription && (
<p className={s.actionText}>{tickerDescription}</p>
)}
</div>
</section>
);
};
// Needed for lazy loading
export default Ticker;
| 28.393443 | 80 | 0.537336 |
839d1822dcd409954827d01086384baf582bb696 | 4,222 | js | JavaScript | src/components/Product/Product.js | sergeykiskinfl/pineapplepi | 33a2b492e86922ddee6767c08169b99f9e5d05af | [
"Apache-2.0"
] | null | null | null | src/components/Product/Product.js | sergeykiskinfl/pineapplepi | 33a2b492e86922ddee6767c08169b99f9e5d05af | [
"Apache-2.0"
] | null | null | null | src/components/Product/Product.js | sergeykiskinfl/pineapplepi | 33a2b492e86922ddee6767c08169b99f9e5d05af | [
"Apache-2.0"
] | null | null | null | // React stuff
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import GroupOfFabs from "./GroupOfFabs";
// Redux stuff
import { connect } from "react-redux";
import {
increaseQuantity,
decreaseQuantity
} from "../../redux/actions/cartActions";
// MUI stuff
import Box from "@material-ui/core/Box";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import CardHeader from "@material-ui/core/CardHeader";
import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import KeyboardArrowDownIcon from "@material-ui/icons/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@material-ui/icons/KeyboardArrowUp";
import withStyles from "@material-ui/core/styles/withStyles";
const styles = theme => ({
...theme.spreadThis,
cardInCart: {
...theme.spreadThis.card,
minHeight: 580
}
});
// A product component
class Product extends Component {
state = {
quantityCart: this.props.product.quantity
};
increaseQuantityCart = id => {
this.props.increaseQuantity(id);
const quantity = this.props.product.quantity;
this.setState({ quantityCart: quantity });
};
decreaseQuantityCart = id => {
this.props.decreaseQuantity(id);
const quantity = this.props.product.quantity;
this.setState({ quantityCart: quantity });
};
render() {
const {
classes,
product: {
id,
name,
specification: { CPU, GPU, Memory },
imageUrl,
price,
quantity
},
inCart,
inComparison
} = this.props;
let description = (
<>
{CPU}
<br />
{GPU}
<br />
{Memory}
<br />
</>
);
let quantityFrame = quantity && (
<Box className={classes.containerFlexRow}>
<Typography variant="h5" className={classes.price}>
Quantity: {this.state.quantityCart}
</Typography>
<Box className={classes.containerFlexColumn}>
<IconButton
size="small"
color="secondary"
aria-label="increase"
onClick={() => {
this.increaseQuantityCart(id);
}}
data-cy={`increase ${id}`}
>
<KeyboardArrowUpIcon fontSize="inherit" />
</IconButton>
<IconButton
size="small"
color="secondary"
aria-label="decrease"
onClick={() => {
this.decreaseQuantityCart(id);
}}
data-cy={`decrease ${id}`}
>
<KeyboardArrowDownIcon fontSize="inherit" />
</IconButton>
</Box>
</Box>
);
return (
<Card className={inCart ? classes.cardInCart : classes.card}>
<CardHeader title={name} titleTypographyProps={{ variant: "h6" }} />
<CardMedia image={imageUrl} className={classes.cardImage} />
<CardContent className={classes.cardContent}>
<Typography variant="body1">{description}</Typography>
<Typography
variant="h5"
className={classes.price}
component={Link}
to={`/product/${id}`}
data-cy={`full decription ${id}`}
>
View more...
</Typography>
<Typography variant="h5" className={classes.price}>
Price: {price}$
</Typography>
{quantityFrame}
</CardContent>
<GroupOfFabs inCart={inCart} inComparison={inComparison} id={id} />
</Card>
);
}
}
const mapActionsToProps = {
increaseQuantity,
decreaseQuantity
};
Product.propTypes = {
/**
* Increase the item quantity
*/
increaseQuantity: PropTypes.func.isRequired,
/**
* Decrease the item quantity
*/
decreaseQuantity: PropTypes.func.isRequired,
/**
* The selected item
*/
product: PropTypes.object.isRequired,
/**
* Styles of the component
*/
classes: PropTypes.object.isRequired
};
export default connect(null, mapActionsToProps)(withStyles(styles)(Product));
| 25.90184 | 77 | 0.596874 |
839d3451fe7924c58a42386530c89bac790efcc4 | 1,625 | js | JavaScript | lib/git-json-merge.js | funkis/git-json-merge | 817434a380ad54eba9fff40199fb18f0d99e3a7c | [
"MIT"
] | null | null | null | lib/git-json-merge.js | funkis/git-json-merge | 817434a380ad54eba9fff40199fb18f0d99e3a7c | [
"MIT"
] | null | null | null | lib/git-json-merge.js | funkis/git-json-merge | 817434a380ad54eba9fff40199fb18f0d99e3a7c | [
"MIT"
] | null | null | null | var fs = require("fs");
var xdiff = require("xdiff");
var detectIndent = require("detect-indent");
var getId = obj => obj.id;
var custom_xdiff = xdiff.customize(getId);
var _ = require("lodash");
var encoding = "utf-8";
function mergeJsonFiles(oursFileName, baseFileName, theirsFileName) {
var oursJson = fs.readFileSync(oursFileName, encoding);
var baseJson = fs.readFileSync(baseFileName, encoding);
var theirsJson = fs.readFileSync(theirsFileName, encoding);
var newOursJson = mergeJson(oursJson, baseJson, theirsJson);
fs.writeFileSync(oursFileName, newOursJson, encoding);
}
function mergeJson(oursJson, baseJson, theirsJson) {
var oursIndent = detectIndent(oursJson).indent;
var baseIndent = detectIndent(baseJson).indent;
var theirsIndent = detectIndent(theirsJson).indent;
var newOursIndent = selectIndent(oursIndent, baseIndent, theirsIndent);
var ours = JSON.parse(oursJson);
var base = JSON.parse(baseJson);
var theirs = JSON.parse(theirsJson);
var newOurs = merge(ours, base, theirs);
var newOursJson = JSON.stringify(newOurs, null, newOursIndent);
return newOursJson;
}
function merge(ours, base, theirs) {
// var diff = custom_xdiff.diff(ours, theirs);
// if (diff) {
// return custom_xdiff.patch(ours, diff);
// }
return _.unionBy(ours, theirs, obj => obj.id);
}
function selectIndent(oursIndent, baseIndent, theirsIndent) {
return oursIndent !== baseIndent ? oursIndent : theirsIndent !== baseIndent ? theirsIndent : baseIndent;
}
module.exports = {
mergeJsonFiles: mergeJsonFiles,
mergeJson: mergeJson,
merge: merge,
selectIndent: selectIndent,
};
| 31.862745 | 106 | 0.735385 |
839de932bb09a6ea1daa7b4e743a62ccfd494481 | 2,015 | js | JavaScript | lib/index.js | thecrash/ps-react-library | c514d2c297c61ba3becfbabc85b3d5dad712ff70 | [
"MIT"
] | null | null | null | lib/index.js | thecrash/ps-react-library | c514d2c297c61ba3becfbabc85b3d5dad712ff70 | [
"MIT"
] | null | null | null | lib/index.js | thecrash/ps-react-library | c514d2c297c61ba3becfbabc85b3d5dad712ff70 | [
"MIT"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "HelloWorld", {
enumerable: true,
get: function get() {
return _HelloWorld.default;
}
});
Object.defineProperty(exports, "EyeIcon", {
enumerable: true,
get: function get() {
return _EyeIcon.default;
}
});
Object.defineProperty(exports, "Label", {
enumerable: true,
get: function get() {
return _Label.default;
}
});
Object.defineProperty(exports, "TextInput", {
enumerable: true,
get: function get() {
return _TextInput.default;
}
});
Object.defineProperty(exports, "TextInputBEM", {
enumerable: true,
get: function get() {
return _TextInputBEM.default;
}
});
Object.defineProperty(exports, "TextInputCSSModules", {
enumerable: true,
get: function get() {
return _TextInputCSSModules.default;
}
});
Object.defineProperty(exports, "PasswordInput", {
enumerable: true,
get: function get() {
return _PasswordInput.default;
}
});
Object.defineProperty(exports, "ProgressBar", {
enumerable: true,
get: function get() {
return _ProgressBar.default;
}
});
Object.defineProperty(exports, "RegistrationForm", {
enumerable: true,
get: function get() {
return _RegistrationForm.default;
}
});
var _HelloWorld = _interopRequireDefault(require("./HelloWorld"));
var _EyeIcon = _interopRequireDefault(require("./EyeIcon"));
var _Label = _interopRequireDefault(require("./Label"));
var _TextInput = _interopRequireDefault(require("./TextInput"));
var _TextInputBEM = _interopRequireDefault(require("./TextInputBEM"));
var _TextInputCSSModules = _interopRequireDefault(require("./TextInputCSSModules"));
var _PasswordInput = _interopRequireDefault(require("./PasswordInput"));
var _ProgressBar = _interopRequireDefault(require("./ProgressBar"));
var _RegistrationForm = _interopRequireDefault(require("./RegistrationForm"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | 25.506329 | 95 | 0.719107 |
839ec57a61b6a0d7b9ba7eaa93d083b70a585fc5 | 2,886 | js | JavaScript | examples/app.js | rifkihp/virtual-scroll | 51c9286dda5beee23a0e5b05ee06150322e05e51 | [
"MIT"
] | 4 | 2017-01-24T14:06:20.000Z | 2021-07-12T07:22:38.000Z | examples/app.js | rifkihp/virtual-scroll | 51c9286dda5beee23a0e5b05ee06150322e05e51 | [
"MIT"
] | 58 | 2016-07-19T15:08:58.000Z | 2020-05-24T20:09:37.000Z | examples/app.js | rifkihp/virtual-scroll | 51c9286dda5beee23a0e5b05ee06150322e05e51 | [
"MIT"
] | null | null | null | import VirtualScroll from '../src/VirtualScroll';
let listSource = [];
for (let i = 0; i < 3000; i++) listSource.push({ itemId: i });
let virtualScroll1 = new VirtualScroll({
// DOMnode the list will be renderd inside
root: document.getElementsByClassName('list')[0],
// itemHeight
itemHeight: 50,
// ARRAY containg all the objects to be displayed inside the list
source: listSource,
/**
* FUNCTION to be called while creating a single item
*
* @param {object} itemNodes empty object provided by the list logic
* @param {DOMnode} itemContainer item container provided by the list logic
*/
createItemFn: (itemNodes, itemContainer) => {
// EXAMPLE
itemNodes.text1 = document.createElement('span');
itemNodes.text1.style.height = '50px';
itemNodes.text1.style.borderTop = '1px solid black';
itemNodes.text1.style.borderBottom = '1px solid black';
itemNodes.text1.style.width = '100%';
itemContainer.appendChild(itemNodes.text1);
},
/**
* FUNCTION to be called while updating a single item
*
* @param {object} itemNodes object previously filled by createItemFn()
* @param {DOMnode} itemContainer item container provided by the list logic
* @param {object} itemData object inside listSource array at the current index
*/
updateItemFn: (itemNodes, itemContainer, itemData) => {
// EXAMPLE
itemNodes.text1.innerHTML = "ITEM Number "+itemData.itemId
}
});
let virtualScroll2 = new VirtualScroll({
// DOMnode the list will be renderd inside
root: document.getElementsByClassName('list')[1],
itemHeight: 70,
// ARRAY containg all the objects to be displayed inside the list
source: listSource,
/**
* FUNCTION to be called while creating a single item
*
* @param {object} itemNodes empty object provided by the list logic
* @param {DOMnode} itemContainer item container provided by the list logic
*/
createItemFn: (itemNodes, itemContainer) => {
// EXAMPLE
itemNodes.text1 = document.createElement('span');
itemNodes.text1.style.height = '70px';
itemNodes.text1.style.borderTop = '1px solid black';
itemNodes.text1.style.borderBottom = '1px solid black';
itemNodes.text1.style.width = '100%';
itemContainer.appendChild(itemNodes.text1);
},
/**
* FUNCTION to be called while updating a single item
*
* @param {object} itemNodes object previously filled by createItemFn()
* @param {DOMnode} itemContainer item container provided by the list logic
* @param {object} itemData object inside listSource array at the current index
*/
updateItemFn: (itemNodes, itemContainer, itemData) => {
// EXAMPLE
// update itemNodes.text1 with itemData.itemId
itemNodes.text1.innerHTML = "ITEM Number "+itemData.itemId
}
});
window.list = virtualScroll1;
| 34.357143 | 90 | 0.689882 |
83a01a9b0115a16f25dd3cc47a5db07d347e38db | 86 | js | JavaScript | docs/search--/s_1956.js | Zalexanninev15/VitNX | 43f2dd04b8ba97c4a78ae51a99e7980a6b9b85a9 | [
"MIT"
] | 2 | 2022-01-25T12:09:46.000Z | 2022-01-27T11:26:48.000Z | docs/search--/s_1956.js | Zalexanninev15/VitNX | 43f2dd04b8ba97c4a78ae51a99e7980a6b9b85a9 | [
"MIT"
] | null | null | null | docs/search--/s_1956.js | Zalexanninev15/VitNX | 43f2dd04b8ba97c4a78ae51a99e7980a6b9b85a9 | [
"MIT"
] | null | null | null | search_result['1956']=["topic_00000000000006F3.html","ERROR_DS_DRA_GENERIC Field",""]; | 86 | 86 | 0.790698 |
83a096b2943327393b699a36d6dca78d6e7225e4 | 1,839 | js | JavaScript | src/utils/request.js | wxc-lD/vue3-vite-demo | c269c7b68bc24be1a73532e410c06ff14b597307 | [
"MIT"
] | null | null | null | src/utils/request.js | wxc-lD/vue3-vite-demo | c269c7b68bc24be1a73532e410c06ff14b597307 | [
"MIT"
] | null | null | null | src/utils/request.js | wxc-lD/vue3-vite-demo | c269c7b68bc24be1a73532e410c06ff14b597307 | [
"MIT"
] | 1 | 2021-06-17T14:54:06.000Z | 2021-06-17T14:54:06.000Z | /*
* Copyright (c) 2021 fuzzy
* 项目名称:vue3-vite-demo
* 文件名称:request.js
* 创建日期:2021年06月16日
* 创建作者:fuzzy
*/
import axios from 'axios'
import {
ElMessage,
ElMessageBox
} from 'element-plus'
import storage from '@/utils/storage.js'
import {router} from '@/router/index.js'
const {
clearSession,
getSession
} = storage
// 配置新建一个 axios 实例
const service = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json'
}
})
// 添加请求拦截器
service.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么 token
if (getSession('token')) {
config.headers.common.Authorization = getSession('token')
}
// config.data = qs.stringify(config.data)
return config
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error)
}
)
// 添加响应拦截器
service.interceptors.response.use(
(response) => {
// 对响应数据做点什么
const res = response.data
if (res.code && res.code !== 0) {
// `token` 过期或者账号已在别处登录
if (res.code === 401 || res.code === -1) {
clearSession() // 清除浏览器全部临时缓存
router.push('/login') // 去登录页面
ElMessageBox.alert(res.msg, '提示', {})
.then(() => {
})
.catch(() => {
})
return Promise.reject(service.interceptors.response)
}
return response.data
} else {
return Promise.reject(service.interceptors.response)
}
},
(error) => {
// 对响应错误做点什么
if (error.message.indexOf('timeout') !== -1) {
ElMessage.error('网络超时')
} else if (error.message === 'Network Error') {
ElMessage.error('网络连接错误')
} else {
if (error.response.data) ElMessage.error(error.response.statusText)
else ElMessage.error('接口路径找不到')
}
return Promise.reject(error)
}
)
// 导出 axios 实例
export default service
| 21.635294 | 73 | 0.604676 |
83a0b7e1a1ba62426014e6cf91ed1eb39d44a749 | 2,368 | js | JavaScript | utils/Transaction.js | dtilik/yjs | ccaedda93fabb754049c2b88195cddcbcc23dfa6 | [
"MIT"
] | null | null | null | utils/Transaction.js | dtilik/yjs | ccaedda93fabb754049c2b88195cddcbcc23dfa6 | [
"MIT"
] | 1 | 2019-02-23T23:31:48.000Z | 2019-02-23T23:31:48.000Z | utils/Transaction.js | dtilik/yjs | ccaedda93fabb754049c2b88195cddcbcc23dfa6 | [
"MIT"
] | null | null | null | /**
* @module utils
*/
import * as encoding from '../lib/encoding.js'
import { Y } from '../utils/Y.js' // eslint-disable-line
import { Item } from '../structs/Item.js' // eslint-disable-line
import { Type } from '../structs/Type.js' // eslint-disable-line
import { YEvent } from './YEvent.js' // eslint-disable-line
/**
* A transaction is created for every change on the Yjs model. It is possible
* to bundle changes on the Yjs model in a single transaction to
* minimize the number on messages sent and the number of observer calls.
* If possible the user of this library should bundle as many changes as
* possible. Here is an example to illustrate the advantages of bundling:
*
* @example
* const map = y.define('map', YMap)
* // Log content when change is triggered
* map.observe(() => {
* console.log('change triggered')
* })
* // Each change on the map type triggers a log message:
* map.set('a', 0) // => "change triggered"
* map.set('b', 0) // => "change triggered"
* // When put in a transaction, it will trigger the log after the transaction:
* y.transact(() => {
* map.set('a', 1)
* map.set('b', 1)
* }) // => "change triggered"
*
*/
export class Transaction {
constructor (y) {
/**
* @type {Y} The Yjs instance.
*/
this.y = y
/**
* All new types that are added during a transaction.
* @type {Set<Item>}
*/
this.newTypes = new Set()
/**
* All types that were directly modified (property added or child
* inserted/deleted). New types are not included in this Set.
* Maps from type to parentSubs (`item._parentSub = null` for YArray)
* @type {Map<Type|Y,String>}
*/
this.changedTypes = new Map()
// TODO: rename deletedTypes
/**
* Set of all deleted Types and Structs.
* @type {Set<Item>}
*/
this.deletedStructs = new Set()
/**
* Saves the old state set of the Yjs instance. If a state was modified,
* the original value is saved here.
* @type {Map<Number,Number>}
*/
this.beforeState = new Map()
/**
* Stores the events for the types that observe also child elements.
* It is mainly used by `observeDeep`.
* @type {Map<Type,Array<YEvent>>}
*/
this.changedParentTypes = new Map()
this.encodedStructsLen = 0
this.encodedStructs = encoding.createEncoder()
}
}
| 32.438356 | 79 | 0.629645 |
83a21e586e4f8df816453806039b1ee8dc5fb790 | 313 | js | JavaScript | src/lang/translations/index.js | DbgKinggg/gohan-go-nft | 2a6672389f530d66a23583ad8691ede76f306987 | [
"MIT"
] | 2 | 2022-03-12T12:06:46.000Z | 2022-03-21T01:49:35.000Z | src/lang/translations/index.js | DbgKinggg/gohan-go-nft | 2a6672389f530d66a23583ad8691ede76f306987 | [
"MIT"
] | null | null | null | src/lang/translations/index.js | DbgKinggg/gohan-go-nft | 2a6672389f530d66a23583ad8691ede76f306987 | [
"MIT"
] | null | null | null | export default {
en: {
name: "English",
load: () => {
return import("./en.json");
},
},
zh_Hans: {
name: "简体中文",
load: () => {
return import("./zh_Hans.json");
},
},
zh_Hant: {
name: "繁體中文",
load: () => {
return import("./zh_Hant.json");
},
},
};
| 14.904762 | 38 | 0.421725 |
83a290538edc46ac5f3b29d4faeaeabd7847fa26 | 703 | js | JavaScript | static/html/structt4_1_1pdf_1_1border_1_1effect.js | AdobeDocs/dc-testing | a69533527c3646ea8b0072b35df51ae50b07dae5 | [
"Apache-2.0"
] | null | null | null | static/html/structt4_1_1pdf_1_1border_1_1effect.js | AdobeDocs/dc-testing | a69533527c3646ea8b0072b35df51ae50b07dae5 | [
"Apache-2.0"
] | 9 | 2021-10-14T05:18:57.000Z | 2022-03-10T05:39:14.000Z | static/html/structt4_1_1pdf_1_1border_1_1effect.js | AdobeDocs/dc-testing | a69533527c3646ea8b0072b35df51ae50b07dae5 | [
"Apache-2.0"
] | null | null | null | var structt4_1_1pdf_1_1border_1_1effect =
[
[ "style", "structt4_1_1pdf_1_1border_1_1effect.html#a287452c10bb75e81f07efa630d9f63a6", [
[ "cloudy", "structt4_1_1pdf_1_1border_1_1effect.html#a287452c10bb75e81f07efa630d9f63a6af3639baeb4530db03ef930eb16073f61", null ]
] ],
[ "effect", "structt4_1_1pdf_1_1border_1_1effect.html#a29f5675e12124d9978adeb5a556c4b4b", null ],
[ "operator==", "structt4_1_1pdf_1_1border_1_1effect.html#a5c45bd09341ec1aef2af4f3339198b8c", null ],
[ "m_intensity", "structt4_1_1pdf_1_1border_1_1effect.html#a8b14ba5bcb802b9734c15b560b915c7c", null ],
[ "m_style", "structt4_1_1pdf_1_1border_1_1effect.html#a8a3c1e3da3cd9a31a39184bf63458d01", null ]
]; | 70.3 | 135 | 0.805121 |
83a2a786d3cd3aa5c83a623b0878bd2918d7777c | 2,455 | js | JavaScript | src/kibi_plugins/kibi_sequential_join_vis/public/kibi_sequential_join_vis_params.js | rpatil524/kibi | ef015f25a559bf1623a5376fd24c68cd221fe240 | [
"Apache-2.0"
] | 546 | 2015-09-14T17:51:46.000Z | 2021-11-02T00:48:01.000Z | src/kibi_plugins/kibi_sequential_join_vis/public/kibi_sequential_join_vis_params.js | rpatil524/kibi | ef015f25a559bf1623a5376fd24c68cd221fe240 | [
"Apache-2.0"
] | 102 | 2015-09-28T14:14:32.000Z | 2020-07-21T21:23:20.000Z | src/kibi_plugins/kibi_sequential_join_vis/public/kibi_sequential_join_vis_params.js | rpatil524/kibi | ef015f25a559bf1623a5376fd24c68cd221fe240 | [
"Apache-2.0"
] | 144 | 2015-09-13T16:41:41.000Z | 2020-06-26T20:32:33.000Z | import 'ui/kibi/directives/kibi_select';
import 'ui/kibi/directives/kibi_array_param';
import 'ui/kibi/directives/kibi_menu_template';
import _ from 'lodash';
import menuTemplateHtml from 'ui/kibi/directives/kibi_menu_template_sequential_join_vis.html';
import template from 'plugins/kibi_sequential_join_vis/kibi_sequential_join_vis_params.html';
import { uiModules } from 'ui/modules';
uiModules
.get('kibana/kibi_kibi_sequential_join_vis')
.directive('kibiSequentialJoinVisParams', function (Private, createNotifier, ontologyClient) {
return {
restrict: 'E',
template,
link: function ($scope) {
const notify = createNotifier({
location: 'Siren Relational filter params'
});
$scope.focused = [];
ontologyClient.getRelations()
.then((relations) => {
$scope.getLabel = function (relationId) {
if (relationId) {
const rel = _.find(relations, (rel) => {
return rel.id === relationId;
});
if (rel) {
return rel.directLabel;
}
}
};
_.each($scope.vis.params.buttons, (button) => {
if (!button.indexRelationId) {
return;
}
const found = _.find(relations, 'id', button.indexRelationId);
if (!found) {
notify.error('Could not find relation: ' + button.indexRelationId + '. Check relations configuration.');
delete button.indexRelationId;
}
$scope.focused.push(false);
});
const filteredRelations = _(relations)
.each((rel) => {
if (!rel.onSelect) {
rel.onSelect = function (buttonIndex) {
const button = $scope.vis.params.buttons[buttonIndex];
button.indexRelationId = rel.id;
button.sourceDashboardId = null;
button.targetDashboardId = null;
};
}
})
.sortBy(function (rel) {
return rel.domain.id;
})
.sortBy((rel) => rel.directLabel)
.value();
$scope.menu = {
template: menuTemplateHtml,
relations: filteredRelations,
onFocus: function (index) {
_.fill($scope.focused, false);
$scope.focused[index] = true;
},
onBlur: function (index) {
_.fill($scope.focused, false);
},
};
});
}
};
});
| 30.308642 | 116 | 0.564969 |
83a3174e33d13b079dad2c1698a1f937312d4fd9 | 3,994 | js | JavaScript | src/dependencies/ModuleDependencyTemplateAsResolveName.js | Beven91/webpack-node-module-plugin | 92ef544e4555241e2565aabc58d99587dcd35e23 | [
"MIT"
] | 4 | 2017-06-02T05:54:44.000Z | 2018-02-27T09:04:35.000Z | src/dependencies/ModuleDependencyTemplateAsResolveName.js | Beven91/webpack-node-module-plugin | 92ef544e4555241e2565aabc58d99587dcd35e23 | [
"MIT"
] | 1 | 2017-10-12T08:47:10.000Z | 2017-12-29T09:28:07.000Z | src/dependencies/ModuleDependencyTemplateAsResolveName.js | Beven91/webpack-node-module-plugin | 92ef544e4555241e2565aabc58d99587dcd35e23 | [
"MIT"
] | null | null | null | /**
* 名称:webpack 模块引用标识符模板
* 日期:2017-06-01
* 描述:用于替换CommonJsRequireDependency.Template
* 从而实现 require(模块名称) 而不是require(模块id)
*/
var path = require('path')
var NameResolve = require('./NameResolve');
var CommonJsRequireDependency = require('webpack/lib/dependencies/CommonJsRequireDependency.js')
var resolveExtensions = [];
var resolveAlias = {};
var ProjectRoot = null;
var ORIGINAL_REQUIRE_JS = require.extensions['.js'];
/**
* webpack require 使用模块名称作为模块标识
* 用于替换 ModuleDependencyTemplateAsId 模板
*/
function ModuleDependencyTemplateAsResolveName() {
}
/**
* 依赖模块引用替换处理
*/
ModuleDependencyTemplateAsResolveName.prototype.apply = function (dep, source) {
if (!dep.range) return
var module = dep.module
var request = dep.userRequest
var content = request
var resource = module.resource;
var sourcePath = source._source._name
var isRequirejs = (request.indexOf('./') > -1 || request.indexOf('../') > -1) || request.indexOf('image!') == 0;
var cExtName = path.extname(content);
var extName = path.extname(resource || content)
var hasAssets = Object.keys(module.assets || {}).length > 0;
if(path.extname(sourcePath)==='.css'){
return;
}
if (path.isAbsolute(content)) {
content = this.absoluteResolve(content, sourcePath);
} else if (resource && isRequirejs) {
content = this.relativeResolve(sourcePath, resource);
} else if (hasAssets && extName && extName != '.js') {
content = this.assetsResolve(content, extName);
} else if (content.indexOf('/') > -1 && cExtName !== extName && cExtName !== '.js') {
content = this.moduleFileResolve(content, resource, extName);
} else if (extName !== '' && extName !== '.js') {
var info = path.parse(content)
content = path.join(info.dir, info.name + extName + '.js').replace(/\\/g, '/');
}
content = resolveAlias[content] || content;
source.replace(dep.range[0], dep.range[1] - 1, '\'' + content + '\'');
}
/**
* 绝对路径引用处理 require('d:/as/aa.js')
*/
ModuleDependencyTemplateAsResolveName.prototype.absoluteResolve = function (content, sourcePath) {
var holder = "node_modules/";
var index = content.indexOf(holder);
if (index > -1) {
return content.substring(index + holder.length);
} else {
return this.relativeResolve(sourcePath, content)
}
}
/**
* 相对require处理 例如: require('./xxx')
*/
ModuleDependencyTemplateAsResolveName.prototype.relativeResolve = function (sourcePath, resource) {
sourcePath = sourcePath.split('!').pop();
sourcePath = path.dirname(sourcePath)
var movedSourcePath = NameResolve.moveToProjectRoot(ProjectRoot, sourcePath);
var movedSource = NameResolve.moveToProjectRoot(ProjectRoot,resource);
var content = path.relative(movedSourcePath, movedSource)
var extName = path.extname(resource).replace(/\s/g, '')
var info = path.parse(content)
extName = !extName ? extName + '.js' : extName;
content = path.join(info.dir, info.name + extName)
content = './' + content.replace(/\\/g, '/')
return content;
}
/**
* 静态资源 require require('./a.jpg')
*/
ModuleDependencyTemplateAsResolveName.prototype.assetsResolve = function (request, extName) {
var info = path.parse(request)
request = path.join(info.dir, info.name + extName + '.js')
return request.replace(/\\/g, '/')
}
/**
* 模块下文件引用处理 require('webpack/lib/NormalModule.js')
*/
ModuleDependencyTemplateAsResolveName.prototype.moduleFileResolve = function (content, resource, extName) {
var resolve = (extName == '.js' ? resource : require.resolve(content)).replace(/\\/g, '/');
var usePath = resolve.split('node_modules/').pop()
return usePath;
}
// 覆盖默认模板
CommonJsRequireDependency.Template = ModuleDependencyTemplateAsResolveName
module.exports.setOptions = function (options,projectRoot) {
var resolve = options.resolve || {};
ProjectRoot = projectRoot;
resolveExtensions = resolve.extensions || [];
resolveAlias = resolve.alias;
resolveExtensions.forEach(function (ext) {
require.extensions[ext] = ORIGINAL_REQUIRE_JS;
})
} | 34.730435 | 114 | 0.698548 |
83a326f18561571faa80a880885bfc9e6cd7e9bc | 228 | js | JavaScript | src/shared/components/forms/components/FormField/styles.js | Blizzt/blizzt.io | a7178c379acee26269a51725f65a7e2b1ba44422 | [
"MIT"
] | null | null | null | src/shared/components/forms/components/FormField/styles.js | Blizzt/blizzt.io | a7178c379acee26269a51725f65a7e2b1ba44422 | [
"MIT"
] | null | null | null | src/shared/components/forms/components/FormField/styles.js | Blizzt/blizzt.io | a7178c379acee26269a51725f65a7e2b1ba44422 | [
"MIT"
] | null | null | null | // Dependencies
import styled from 'styled-components';
export const Layout = styled.div``;
export const Label = styled.h5`
font-size: 14px;
line-height: 20px;
`;
export const Container = styled.div`
margin-top: 4px;
`;
| 16.285714 | 39 | 0.70614 |
83a34bda4dc3124c975e3f06249b7b66ae2080e3 | 1,599 | js | JavaScript | index.js | mjhlybmwq/IconCSSToJSON | 94d258208cc06f1999c6fad1ffcf3baf8c55e161 | [
"MIT"
] | null | null | null | index.js | mjhlybmwq/IconCSSToJSON | 94d258208cc06f1999c6fad1ffcf3baf8c55e161 | [
"MIT"
] | null | null | null | index.js | mjhlybmwq/IconCSSToJSON | 94d258208cc06f1999c6fad1ffcf3baf8c55e161 | [
"MIT"
] | null | null | null | #! /usr/bin/env node
var css = require('css');
var argvs = require('minimist')(process.argv.slice(2));
var fs = require('fs');
var path = require('path');
var DEFAULT_PREFIX = "icon";
if(argvs._.length == 0) {
console.error("no css file");
process.exit();
}
if(argvs._.length > 1) {
console.error("more than one css file");
process.exit();
}
var outputFile = argvs.o || argvs.output_file;
if(!outputFile) {
console.error("out put file must be specified");
process.exit();
}
outputFile = path.join(process.cwd(), outputFile);
var cssFile = path.join(process.cwd(), argvs._[0]);
var cssContent = fs.readFileSync(cssFile, "utf8");
var cssObj = css.parse(cssContent);
var rules = cssObj.stylesheet.rules;
var prefix = argvs.prefix || DEFAULT_PREFIX;
var result = {};
var prefixReg = new RegExp("^." + prefix + "-", 'i');
for(var i = 0; i < rules.length; i++) {
var rule = rules[i];
if(!rule.selectors) {
continue;
}
if(rule.selectors.length > 1) {
continue;
}
var selector = rule.selectors[0];
if(!prefixReg.test(selector)) {
continue;
}
var key = selector.replace(prefixReg, "");
key = key.replace(/\:before$/g, "");
if(rule.declarations.length > 1) {
continue;
}
if(rule.declarations.length == 0) {
continue;
}
var declaration = rule.declarations[0];
if(declaration.property != "content") {
continue;
}
var value = declaration.value;
value = value.replace(/\"/g, "");
value = value.replace(/\\/g, "&#x");
result[key] = value;
}
fs.writeFileSync(outputFile, JSON.stringify(result));
process.exit();
| 19.035714 | 55 | 0.634146 |
83a3f114922a792f0d5a5f16c70d3484b913dcdb | 996 | js | JavaScript | bin/semantic-release-github-pr.js | pmowrer/semantic-release-github-pr | 8d7a71c8b452826a8b69df34721186e02dbe90ed | [
"MIT"
] | 17 | 2020-01-31T21:43:18.000Z | 2022-03-12T07:06:30.000Z | bin/semantic-release-github-pr.js | Updater/semantic-release-github-pr | 8d7a71c8b452826a8b69df34721186e02dbe90ed | [
"MIT"
] | 34 | 2017-12-05T00:46:59.000Z | 2019-07-19T05:07:39.000Z | bin/semantic-release-github-pr.js | Updater/semantic-release-github-pr | 8d7a71c8b452826a8b69df34721186e02dbe90ed | [
"MIT"
] | 4 | 2018-04-26T02:29:42.000Z | 2019-06-02T05:19:08.000Z | #!/usr/bin/env node
const execa = require('execa');
const envCi = require('env-ci');
const { argv } = process;
const { resolve } = require('path');
const { getCurrentBranchName } = require('../src/git-utils');
(async function() {
const plugins = `${resolve(__dirname, '../src/index.js')}`;
const currentBranchName = await getCurrentBranchName();
// If we're in a "detached HEAD" state, assume we're running on CI.
const branch =
currentBranchName !== 'HEAD' ? currentBranchName : envCi().prBranch;
const args = argv.slice(2).concat([
// We want to run on pull request builds, but `semantic-release` won't
// let us unless we pass `--no-ci`.
// https://github.com/semantic-release/semantic-release/issues/584
`--no-ci`,
// Set `dry-run` to keep `semantic-release` from publishing an actual release.
`--dry-run`,
`--branches=${branch}`,
`--extends=${plugins}`,
]);
execa('semantic-release', args, { stdio: 'inherit', preferLocal: true });
})();
| 35.571429 | 82 | 0.64759 |
83a3f2c01888a4c0c137be3276aeca6e70036523 | 1,338 | js | JavaScript | doc/html/search/all_c.js | astagi/sol-verificaC19-sdk-cpp-linux | fc95e5ad423e1ace5dc2f46c175605fd3bc28eea | [
"Apache-2.0"
] | null | null | null | doc/html/search/all_c.js | astagi/sol-verificaC19-sdk-cpp-linux | fc95e5ad423e1ace5dc2f46c175605fd3bc28eea | [
"Apache-2.0"
] | null | null | null | doc/html/search/all_c.js | astagi/sol-verificaC19-sdk-cpp-linux | fc95e5ad423e1ace5dc2f46c175605fd3bc28eea | [
"Apache-2.0"
] | null | null | null | var searchData=
[
['test_62',['test',['../classverificaC19Sdk_1_1CertificateModel.html#aca0bec1feacde03902c5a64af6b79420',1,'verificaC19Sdk::CertificateModel']]],
['testingcentre_63',['testingCentre',['../classverificaC19Sdk_1_1TestModel.html#a2e47619b1fa1c9e29292c046bb093209',1,'verificaC19Sdk::TestModel']]],
['testmanufacturer_64',['testManufacturer',['../classverificaC19Sdk_1_1TestModel.html#aef5126a4ca1571ca29319d6b13eeccc8',1,'verificaC19Sdk::TestModel']]],
['testmodel_65',['TestModel',['../classverificaC19Sdk_1_1TestModel.html',1,'verificaC19Sdk']]],
['testname_66',['testName',['../classverificaC19Sdk_1_1TestModel.html#a6b9ed1fb52450c8db4b2721e2e22d043',1,'verificaC19Sdk::TestModel']]],
['testresult_67',['testResult',['../classverificaC19Sdk_1_1TestModel.html#a4dde0737bebbfe215570423e9fe303f9',1,'verificaC19Sdk::TestModel']]],
['timestamp_68',['timeStamp',['../classverificaC19Sdk_1_1CertificateSimple.html#ab2be1b822069c0f21da92ce2e750b358',1,'verificaC19Sdk::CertificateSimple']]],
['totalseriesofdoses_69',['totalSeriesOfDoses',['../classverificaC19Sdk_1_1VaccinationModel.html#af8e46ede58f914d08f1e1fbf13f73bcf',1,'verificaC19Sdk::VaccinationModel']]],
['typeoftest_70',['typeOfTest',['../classverificaC19Sdk_1_1TestModel.html#a5db71b0311b37aff687cf6c5193ee16d',1,'verificaC19Sdk::TestModel']]]
];
| 102.923077 | 174 | 0.801943 |
83a4553db7027d8f71c66b537643763e2aff1d30 | 2,121 | js | JavaScript | src/scenes/App/scenes/MapOverview/components/LeaderboardContainer/components/Leaderboard/index.js | laurirasanen/tempus-website | 24df3500f204517ad23557487420adc19bee8163 | [
"MIT"
] | null | null | null | src/scenes/App/scenes/MapOverview/components/LeaderboardContainer/components/Leaderboard/index.js | laurirasanen/tempus-website | 24df3500f204517ad23557487420adc19bee8163 | [
"MIT"
] | null | null | null | src/scenes/App/scenes/MapOverview/components/LeaderboardContainer/components/Leaderboard/index.js | laurirasanen/tempus-website | 24df3500f204517ad23557487420adc19bee8163 | [
"MIT"
] | null | null | null | import React from 'react'
import {CLASSINDEX_TO_NAME} from 'root/constants/TFClasses'
import Col from 'react-bootstrap/lib/Col'
import LeaderboardItem from './components/LeaderboardItem'
import {Scrollbars} from 'react-custom-scrollbars'
import './styles.styl'
export default class Leaderboard extends React.Component {
loadMore() {
console.log(this.props.playerClass)
}
renderLeaderboard() {
const {data} = this.props
if (data.size === 0) {
return (
<div className="no-records">
No one has completed this.
</div>
)
}
const firstPlace = data.get(0)
return (
<table>
<tbody>
{data.map((data, idx) =>
<LeaderboardItem
key={idx}
data={data}
firstPlace={firstPlace}
/>
)}
</tbody>
</table>
)
}
render() {
const {playerClass, tier} = this.props
const tfClass = CLASSINDEX_TO_NAME[playerClass]
const tfClassLower = tfClass.toLowerCase()
return (
<div className="MapOverview-LeaderboardContainer-Leaderboard">
<header className="clearfix">
<h4>
<span className={'tf-icon sm ' + tfClassLower} /> {tfClass}
<span> | </span>
<span className={'tier tier-' + tier}>Tier {tier}</span>
</h4>
</header>
<main>
<Scrollbars renderThumbVertical={({style, ...props}) =>
<div {...props}
style={{...style,
backgroundColor: 'rgba(255, 255, 255, 0.4)',
cursor: 'pointer',
borderRadius: '4px'
}}
/>
}>
{this.renderLeaderboard()}
</Scrollbars>
</main>
<div className="leaderboard-footer">
</div>
</div>
)
}
}
// <div className="load-more-button-container">
// <button className="load-more-button" onClick={this.loadMore.bind(this)}>
// Load more
// </button>
// </div>
| 26.5125 | 77 | 0.517209 |
83a5cb7ef4f04702a62a15cd4409aec828a22a79 | 6,983 | js | JavaScript | prcon3dj/PRCON3_dj/static/PRCON3_dj/js/UI_main.js | MiloLug/prcon3 | 4e767b545aea10942f66926f35e5a85c43a237f7 | [
"BSD-3-Clause-Clear"
] | 1 | 2018-11-04T06:48:04.000Z | 2018-11-04T06:48:04.000Z | prcon3dj/PRCON3_dj/static/PRCON3_dj/js/UI_main.js | MiloLug/prcon3 | 4e767b545aea10942f66926f35e5a85c43a237f7 | [
"BSD-3-Clause-Clear"
] | null | null | null | prcon3dj/PRCON3_dj/static/PRCON3_dj/js/UI_main.js | MiloLug/prcon3 | 4e767b545aea10942f66926f35e5a85c43a237f7 | [
"BSD-3-Clause-Clear"
] | null | null | null | (function(){
"use stict";
A({
addFromText: function (txt, pos) {
var a = this.a(),
el = document.createElement('div');
el.innerHTML = txt;
el.children.all(function (elem) {
elem.paste({
in: a,
pos: pos
});
});
return a;
},
br: function get() {
var a = this.a();
a.parentNode.insertAfter(A.createElem("br"),a);
return a;
}
})
window.UI = {
toTopLayer: function (elem) {
elem = elem.a();
var tl = elem.parentNode.child("[toplayer]");
tl && tl.opt({
toplayer_queue: UI.getLargestLayer(elem.parentNode) + 1,
toplayer: ""
});
elem.opt({
toplayer_queue: "",
toplayer: "."
});
return elem;
},
getAct: function (act, text, args) {
var el = (".sources>" + "[act=" + act + "]"),
txt = text||el.all(function(sr){return sr.html();}).return[0]||window.JS_SRC[act],
_ = args||{};
return Preprocess({
js: function (t) {
return Function("selfAct,_", t + "\n;")(el, _);
},
set: function (t) {
return Function("selfAct,_", "return " + t + ";")(el, _);
},
scrollplane: function(t) {
var txt=t.split(","),attrs,tL,y,x;
t=txt.splice(0,1)[0];
tL=t.toLowerCase();
attrs=t.match(/attrs.*?[\s\S\t\r\n\v]*?:(.*)/mi);
txt=txt.join(",");
y=tL.indexOf("y");
y=y>-1&&(attrs?y<attrs.index:true);
x=tL.indexOf("x");
x=x>-1&&(attrs?x<attrs.index:true);
return "<f-scrollplane "+(attrs?attrs[1]:"")+" >"+txt+"</f-scrollplane>"
+(y?"<f-scroll-y><f-wheel></f-wheel></f-scroll-y>":"")
+(x?"<f-scroll-x><f-wheel></f-wheel></f-scroll-x>":"");
}
}, {
start: "@",
bodyStart: "::",
end: "::@"
}, txt);
},
getLargestLayer: function (TH, elem) {
var tl = 0,
cur = 0,
re;
TH.child("[toplayer_queue]", !0).all(function (el) {
tl = parseFloat(el.opt("toplayer_queue"));
if (cur < tl)
cur = tl,
re = el;
});
return elem ? re : cur;
},
setSrcToPlace: function (act, demult, text) {
var src = "[act=" + act + "]",
req = false;
if (demult ? (".srcplace>" + src).a(!0).length < 1 : true) {
UI.toTopLayer(req = ".srcplace".addElem("div", {
act: act,
class: "back",
_TXT: UI.getAct(act, text)
}));
} else {
req=UI.toTopLayer((".srcplace>" + src).a());
}
return req;
},
setLSToPlace: function (elem, set) {
var req = false;
elem = elem.child(".lsplace", !1, !0) || elem.addElem("div", {
class: "lsplace"
});
set ?
elem.child(".loadscreen", !0).length < 1 && (
req = true,
elem.addElem("div", {
class: "loadscreen",
_TXT: UI.getAct("loadscreen")
}))
: elem.html("");
return req;
},
easyCancel: function (TH) {
var el = TH.parent(function (el) {
return el.hasClass("back");
}),
tl = el.parentNode.child("[toplayer]") !== el ? false : UI.getLargestLayer(el.parentNode, true);
el.remElem();
tl && UI.toTopLayer(tl);
},
closeDialog: function (uid) {
uid = (".dialog[uid=" + uid + "]").a();
if (!uid)
return;
(uid = [
uid,
uid.previousElement
], uid[0]).remElem();
if (!".dialogback".a().children.length)
".dialogback".opt({
hidden: "."
});
else
UI.toTopLayer(uid[1]);
},
dialogPanel: function (param) {
window.focus();
var s = A.args({
content: [{
type: "message",
text: "Warning!!!"
}, {
type: "button",
btntext: "ok",
btnID: "ok"
}, {
type: "button",
btntext: "cancel",
btnID: "cancel"
}
],
//onEnter:"ok",
//onEsc:"cancel",
func: function () {}
}, param),
dialog = ".dialogback".addElem("div", {
class: "dialog",
uid: UID.get(),
_TXT: "<f-scrollplane></f-scrollplane><f-scroll-y no='.'><f-wheel></f-wheel></f-scroll-y><div class='downmenu'></div>"
}),
bc,
inpcount = 0,
fn = function (e) {
var data = {
pressed: e.toElement.opt("bid"),
values: {},
checked: {},
fileLists: {}
}
dialog.child("f-scrollplane>input,f-scrollplane>textarea", !0).all(function (el) {
data.values[el.opt("iid")] = el.val();
});
dialog.child("f-scrollplane>.uploaderstyle>input", !0).all(function (el) {
data.fileLists[el.opt("uid")] = el.files;
});
dialog.child("f-scrollplane>.chbstyle>input", !0).all(function (el) {
data.checked[el.opt("cid")] = el.checked;
});
UI.closeDialog(dialog.opt("uid"));
s.func(data);
};
UI.toTopLayer(dialog);
".dialogback".opt({
hidden: ""
});
bc = dialog.child("f-scrollplane");
s.content.all(function (el, ind) {
switch (el.type) {
case "message":
bc.addElem("pre", {
class: "message",
_TXT: el.text
}).opt(el.opt||{});
break;
case "button":
"[act=dialogInputSrc]>button".copy({
pasteIn: dialog.child(".downmenu")
}).opt({
bid: el.btnID,
_TXT: el.btntext,
_LIS: [{
click: fn
}
],
onEnter: el.btnID === s.onEnter ? "." : "",
onEsc: el.btnID === s.onEsc ? "." : ""
}).opt(el.opt || {});
break;
case "textarea":
case "input":
("[act=dialogInputSrc]>" + el.type).copy({
pasteIn: bc
}).opt({
iid: el.inpID
}).opt(el.opt || {})[inpcount < 1 ? (inpcount++, "focus") : "a"]();
break;
case "checkbox":
"[act=dialogInputSrc]>.chbstyle".copy({
pasteIn: bc,
deep: true
}).br.child("input").opt({
cid: el.chcID
}).opt(el.opt || {}).parentNode.child("text").html = el.chctext;
break;
case "uploader":
var upl="[act=dialogInputSrc]>.uploaderstyle".copy({
pasteIn: bc
}).child("input").opt({
uid: el.uplID,
accept: el.accept||"",
multiple: el.multiple?"true":""
}).opt(el.opt || {}),
uplTxt =upl.parentNode.child("div");
uplTxt.html=el.upltext||"";
upl.addEventListener("change",function(){
var txt="";
for(var i=0, len=upl.files.length; i < len; i++){
txt+=upl.files[i].name+"<br>";
}
uplTxt.html=txt;
});
break;
}
});
},
errors: function (errors, next) {
(next = function () {
if (!errors.length)
return;
var er = errors.splice(0, 1)[0],
up = function (msg) {
UI.dialogPanel({
content: [{
type: "message",
text: msg
}, {
type: "button",
btnID: "ok",
btntext: "ok"
}
],
onEnter: "ok",
onEsc: "ok",
func: function () {
next();
}
});
};
if(er==="no password")
er="wrong password";
up(er.tr);
})();
}
}
})(); | 25.578755 | 123 | 0.485035 |
83a5cc34e3a9a968315ca444fe25dcf3e058c7a0 | 1,810 | js | JavaScript | client/src/components/general/spinner/Spinner.js | alecspringel/booking-app | 6a6719b63ae27ebda40e5795df6c1c83e28bf667 | [
"MIT"
] | 2 | 2020-10-28T01:27:03.000Z | 2020-10-28T01:48:44.000Z | client/src/components/general/spinner/Spinner.js | alecspringel/booking-app | 6a6719b63ae27ebda40e5795df6c1c83e28bf667 | [
"MIT"
] | null | null | null | client/src/components/general/spinner/Spinner.js | alecspringel/booking-app | 6a6719b63ae27ebda40e5795df6c1c83e28bf667 | [
"MIT"
] | null | null | null | /**
* @fileoverview A React Spinner component
* @exports JSX.Element
*/
import React, { useState, useEffect } from "react";
import "./spinner.css";
/**
* @name Spinner
* @extends `IconButton`
* @description Renders a `Spinner` component into an `IconButton`.
* @param {string} props.className The default class of the button.
* @param {string} props.addClass Add extra class styles to overwrite default class.
* @param {number} props.width Width of the button.
* @param {number} props.height Height of the button.
* @param {number} props.size The size of the width and height of the `Spinner`.
* @param {string} props.color A single color for the `Spinner`.
* @param {[string]} props.colors An array of color hex strings for the `Spinner`. It overides `props.color`.
* @param {string} props.duration The duration of a complete revolution of the `Spinner` in seconds.
* @param {number} props.depth The thickness of the `Spinner` border.
* @param {function} props.onClick onclick event function of the button.
* @return {JSX.Element} A rotating spinner icon.
*/
export default function Spinner(props) {
const [counter, setCounter] = useState(0);
useEffect(() => {
const x = setTimeout(() => {
setCounter(counter + 1);
}, props.duration || 450);
return () => {
clearTimeout(x);
};
});
const className = `spinner ${props.addClass || ""}`;
const color = props.colors
? `${props.colors[counter % props.colors.length]} `
: props.color || "#3b73ff";
const style = {
borderColor: `${color.repeat(3)} transparent`,
width: props.size || 0,
height: props.size || 0,
animationDuration: props.duration,
borderWidth: props.thickness || 1,
borderStyle: "solid",
};
return <span className={className} style={style}></span>;
}
| 33.518519 | 109 | 0.671823 |
83a5f013c820889a8838035beb496823db0a01ff | 2,141 | js | JavaScript | src/app.js | ser163/tole-front | a1ed6535715da75180ccace584a12ee0a41537f9 | [
"MIT"
] | 1 | 2021-06-11T04:22:41.000Z | 2021-06-11T04:22:41.000Z | src/app.js | ser163/tole-front | a1ed6535715da75180ccace584a12ee0a41537f9 | [
"MIT"
] | null | null | null | src/app.js | ser163/tole-front | a1ed6535715da75180ccace584a12ee0a41537f9 | [
"MIT"
] | null | null | null | import './assets/styles/main.scss';
export default function () {
this.FesApp.set('FesName', '$i18n.title');
// 设置退出逻辑
this.on('fes_logout', () => {
this.FesApp.setRole('unLogin');
this.FesStorage.set('userLogin', false);
this.FesFesx.clear();
});
// 设置logo点击事件
this.on('fes_logo_click', () => {
window.Toast('你点击了LOGO');
});
// 设置路由钩子
this.FesApp.setBeforeRouter((from, to, next) => {
next();
});
// this.FesApp.setAfterRouter((route) => {
// console.log(`您浏览到了${route.path}`);
// });
// 设置当前角色
if (!this.FesStorage.get('userLogin') === true) {
this.setRole('unLogin');
}
// 设置AJAX配置
this.FesApi.option({
});
this.FesApi.setError({
// 身份验证失败时。重新登录
401: function(response){
this.FesApp.setRole('unLogin');
this.FesStorage.set('userLogin', false);
this.FesFesx.clear();
},
})
// 设置响应结构
this.FesApi.setResponse({
successCode: '0',
codePath: 'code',
messagePath: 'msg',
resultPath: 'result'
});
// 设置请求拦截器
// 自动添加token
const that = this
const ReqEject = this.FesApi.setReqInterceptor(function (config) {
// 判断是否有token
if (that.FesFesx.get('token')) {
config.headers.Authorization = that.FesFesx.get('token')
}
return config
})
// 响应拦截器.刷新token
const ResEject = this.FesApi.setResInterceptor((response) => {
if(response.headers.hasOwnProperty('authorization')) {
console.log("refresh token")
this.FesFesx.set('token', response.headers.authorization)
}
return response
}, (error) => {
switch(error.response.status){
// 对得到的状态码的处理,具体的设置视自己的情况而定
case 401:
console.log('401 身份认证失败')
this.FesApp.setRole('unLogin');
this.FesStorage.set('userLogin', false);
this.FesFesx.clear();
break
default:
console.log('其他错误')
break
}
})
}
| 23.788889 | 70 | 0.530126 |
83a6469a186c86f3488d8c073d0ccf6346a1f534 | 1,251 | js | JavaScript | web/src/providers/context/AuthContext.js | jacebenson/news.jace.pro | ec382dd9ff5f16f8e1eeda9f7bd776a19c9f5b89 | [
"MIT"
] | 3 | 2022-03-12T07:23:52.000Z | 2022-03-23T02:58:40.000Z | web/src/providers/context/AuthContext.js | jacebenson/news.jace.pro | ec382dd9ff5f16f8e1eeda9f7bd776a19c9f5b89 | [
"MIT"
] | 9 | 2022-02-25T06:09:43.000Z | 2022-03-23T03:12:34.000Z | web/src/providers/context/AuthContext.js | jacebenson/news.jace.pro | ec382dd9ff5f16f8e1eeda9f7bd776a19c9f5b89 | [
"MIT"
] | 2 | 2022-03-02T04:25:15.000Z | 2022-03-22T18:44:44.000Z | import { useAuth } from '@redwoodjs/auth'
const AuthContext = React.createContext()
const AuthContextProvider = ({ children }) => {
/**
* loading: boolean;
isAuthenticated: boolean;
currentUser: null | CurrentUser;
userMetadata: null | SupportedUserMetadata;
logIn(options?: unknown): Promise<any>;
logOut(options?: unknown): Promise<any>;
signUp(options?: unknown): Promise<any>;
getToken(): Promise<null | string>;
getCurrentUser(): Promise<null | CurrentUser>;
hasRole(role: string | string[]): boolean;
reauthenticate(): Promise<void>;
forgotPassword(username: string): Promise<any>;
resetPassword(options?: unknown): Promise<any>;
validateResetToken(resetToken: string | null): Promise<any>;
client?: SupportedAuthClients;
type?: SupportedAuthTypes;
hasError: boolean;
error?: Error;
*/
const { loading, isAuthenticated, currentUser, logIn, logOut, hasRole } =
useAuth()
const [auth, setAuth] = React.useState({
loading,
isAuthenticated,
currentUser,
logIn,
logOut,
hasRole,
})
return (
<AuthContext.Provider value={[auth, setAuth]}>
{children}
</AuthContext.Provider>
)
}
export { AuthContext, AuthContextProvider }
| 30.512195 | 75 | 0.673861 |
83a703128c207c8301f41e4accff2187e459cec9 | 232 | js | JavaScript | src/components/btn/btn.js | smithavt14/wetech-site | c2102e99d44c383f0ae3a7cfadc9992c8e3f3a34 | [
"RSA-MD"
] | null | null | null | src/components/btn/btn.js | smithavt14/wetech-site | c2102e99d44c383f0ae3a7cfadc9992c8e3f3a34 | [
"RSA-MD"
] | null | null | null | src/components/btn/btn.js | smithavt14/wetech-site | c2102e99d44c383f0ae3a7cfadc9992c8e3f3a34 | [
"RSA-MD"
] | null | null | null | import React from "react"
import styles from "./btn.module.css"
import cx from "classnames"
export default function Button(props) {
return (
<div className={cx(styles.btn, styles.btnPrimary)}>
{props.content}
</div>
)
} | 21.090909 | 53 | 0.698276 |
83a751790934d80dd80a9b263170bc00cf709702 | 1,775 | js | JavaScript | src/features/restaurants/components/restaurants-info-card.component.js | vinhdps/MealsToGo | b6befffc556682e2f4868690773e2854b6dae7f5 | [
"MIT"
] | null | null | null | src/features/restaurants/components/restaurants-info-card.component.js | vinhdps/MealsToGo | b6befffc556682e2f4868690773e2854b6dae7f5 | [
"MIT"
] | null | null | null | src/features/restaurants/components/restaurants-info-card.component.js | vinhdps/MealsToGo | b6befffc556682e2f4868690773e2854b6dae7f5 | [
"MIT"
] | 1 | 2021-05-13T16:02:24.000Z | 2021-05-13T16:02:24.000Z | import React from "react";
import {
RestaurantCard,
CardPicture,
CardInfo,
LeftSection,
RightSection,
Rating,
Star,
Opening,
Icon,
} from "./restaurants-info-card.styles";
import { Text } from "../../../components/typography/text.components";
import { Spacer } from "../../../components/spacer/spacer.components";
import { Favourite } from "../../../components/favourite/favourite.components";
import star from "../../../../assets/star";
import open from "../../../../assets/open";
export const RestaurantInfoCard = ({ restaurant }) => {
const {
name = "Some Restaurant",
icon = "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/lodging-71.png",
photos = [
"https://www.foodiesfeed.com/wp-content/uploads/2019/06/top-view-for-box-of-2-burgers-home-made-600x899.jpg",
],
address = "100 Random Street Hanoi Vietnam",
isOpenNow = true,
rating = 5,
//isClosedTemporarily = true,
placeId,
} = restaurant;
const ratingArray = Array.from(new Array(Math.floor(rating)));
return (
<RestaurantCard elevation={5}>
<Favourite restaurant={restaurant} />
<CardPicture key={name} source={{ uri: photos[0] }} />
<CardInfo>
<LeftSection>
<Text variant="label">{name}</Text>
<Rating>
{ratingArray.map((_, index) => (
<Star key={`star-${placeId}-${index}`} xml={star} />
))}
</Rating>
<Text variant="description">{address}</Text>
</LeftSection>
<RightSection>
<Spacer position="right" size="l">
{isOpenNow && <Opening xml={open} />}
</Spacer>
<Icon source={{ uri: icon }} />
</RightSection>
</CardInfo>
</RestaurantCard>
);
};
| 30.603448 | 115 | 0.592113 |
83a7b9e56980753faea6ca70feae649500873488 | 15,121 | js | JavaScript | Best Pandemic Movies to Binge in Quarantine – dailyaccessnews.com_files/single.js | alexgmartin/spigot-case-study | 21a888081d4d5a638b4c7ca39150814d1e9e1f29 | [
"Apache-2.0"
] | null | null | null | Best Pandemic Movies to Binge in Quarantine – dailyaccessnews.com_files/single.js | alexgmartin/spigot-case-study | 21a888081d4d5a638b4c7ca39150814d1e9e1f29 | [
"Apache-2.0"
] | null | null | null | Best Pandemic Movies to Binge in Quarantine – dailyaccessnews.com_files/single.js | alexgmartin/spigot-case-study | 21a888081d4d5a638b4c7ca39150814d1e9e1f29 | [
"Apache-2.0"
] | null | null | null | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");!function(t){"use strict";var e=t.fn.jquery.split(" ")[0].split(".");if(e[0]<2&&e[1]<9||1==e[0]&&9==e[1]&&e[2]<1||e[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),function(t){"use strict";var e=function(t,e){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",t,e)};e.VERSION="3.4.0",e.TRANSITION_DURATION=150,e.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},e.prototype.init=function(e,o,i){if(this.enabled=!0,this.type=e,this.$element=t(o),this.options=this.getOptions(i),this.$viewport=this.options.viewport&&t(document).find(t.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var n=this.options.trigger.split(" "),s=n.length;s--;){var r=n[s];if("click"==r)this.$element.on("click."+this.type,this.options.selector,t.proxy(this.toggle,this));else if("manual"!=r){var a="hover"==r?"mouseenter":"focusin",l="hover"==r?"mouseleave":"focusout";this.$element.on(a+"."+this.type,this.options.selector,t.proxy(this.enter,this)),this.$element.on(l+"."+this.type,this.options.selector,t.proxy(this.leave,this))}}this.options.selector?this._options=t.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},e.prototype.getDefaults=function(){return e.DEFAULTS},e.prototype.getOptions=function(e){return(e=t.extend({},this.getDefaults(),this.$element.data(),e)).delay&&"number"==typeof e.delay&&(e.delay={show:e.delay,hide:e.delay}),e},e.prototype.getDelegateOptions=function(){var e={},o=this.getDefaults();return this._options&&t.each(this._options,function(t,i){o[t]!=i&&(e[t]=i)}),e},e.prototype.enter=function(e){var o=e instanceof this.constructor?e:t(e.currentTarget).data("bs."+this.type);if(o||(o=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,o)),e instanceof t.Event&&(o.inState["focusin"==e.type?"focus":"hover"]=!0),o.tip().hasClass("in")||"in"==o.hoverState)o.hoverState="in";else{if(clearTimeout(o.timeout),o.hoverState="in",!o.options.delay||!o.options.delay.show)return o.show();o.timeout=setTimeout(function(){"in"==o.hoverState&&o.show()},o.options.delay.show)}},e.prototype.isInStateTrue=function(){for(var t in this.inState)if(this.inState[t])return!0;return!1},e.prototype.leave=function(e){var o=e instanceof this.constructor?e:t(e.currentTarget).data("bs."+this.type);if(o||(o=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,o)),e instanceof t.Event&&(o.inState["focusout"==e.type?"focus":"hover"]=!1),!o.isInStateTrue()){if(clearTimeout(o.timeout),o.hoverState="out",!o.options.delay||!o.options.delay.hide)return o.hide();o.timeout=setTimeout(function(){"out"==o.hoverState&&o.hide()},o.options.delay.hide)}},e.prototype.show=function(){var o=t.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(o);var i=t.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(o.isDefaultPrevented()||!i)return;var n=this,s=this.tip(),r=this.getUID(this.type);this.setContent(),s.attr("id",r),this.$element.attr("aria-describedby",r),this.options.animation&&s.addClass("fade");var a="function"==typeof this.options.placement?this.options.placement.call(this,s[0],this.$element[0]):this.options.placement,l=/\s?auto?\s?/i,h=l.test(a);h&&(a=a.replace(l,"")||"top"),s.detach().css({top:0,left:0,display:"block"}).addClass(a).data("bs."+this.type,this),this.options.container?s.appendTo(t(document).find(this.options.container)):s.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var p=this.getPosition(),c=s[0].offsetWidth,d=s[0].offsetHeight;if(h){var u=a,f=this.getPosition(this.$viewport);a="bottom"==a&&p.bottom+d>f.bottom?"top":"top"==a&&p.top-d<f.top?"bottom":"right"==a&&p.right+c>f.width?"left":"left"==a&&p.left-c<f.left?"right":a,s.removeClass(u).addClass(a)}var m=this.getCalculatedOffset(a,p,c,d);this.applyPlacement(m,a);var g=function(){var t=n.hoverState;n.$element.trigger("shown.bs."+n.type),n.hoverState=null,"out"==t&&n.leave(n)};t.support.transition&&this.$tip.hasClass("fade")?s.one("bsTransitionEnd",g).emulateTransitionEnd(e.TRANSITION_DURATION):g()}},e.prototype.applyPlacement=function(e,o){var i=this.tip(),n=i[0].offsetWidth,s=i[0].offsetHeight,r=parseInt(i.css("margin-top"),10),a=parseInt(i.css("margin-left"),10);isNaN(r)&&(r=0),isNaN(a)&&(a=0),e.top+=r,e.left+=a,t.offset.setOffset(i[0],t.extend({using:function(t){i.css({top:Math.round(t.top),left:Math.round(t.left)})}},e),0),i.addClass("in");var l=i[0].offsetWidth,h=i[0].offsetHeight;"top"==o&&h!=s&&(e.top=e.top+s-h);var p=this.getViewportAdjustedDelta(o,e,l,h);p.left?e.left+=p.left:e.top+=p.top;var c=/top|bottom/.test(o),d=c?2*p.left-n+l:2*p.top-s+h,u=c?"offsetWidth":"offsetHeight";i.offset(e),this.replaceArrow(d,i[0][u],c)},e.prototype.replaceArrow=function(t,e,o){this.arrow().css(o?"left":"top",50*(1-t/e)+"%").css(o?"top":"left","")},e.prototype.setContent=function(){var t=this.tip(),e=this.getTitle();t.find(".tooltip-inner")[this.options.html?"html":"text"](e),t.removeClass("fade in top bottom left right")},e.prototype.hide=function(o){function i(){"in"!=n.hoverState&&s.detach(),n.$element&&n.$element.removeAttr("aria-describedby").trigger("hidden.bs."+n.type),o&&o()}var n=this,s=t(this.$tip),r=t.Event("hide.bs."+this.type);return this.$element.trigger(r),r.isDefaultPrevented()?void 0:(s.removeClass("in"),t.support.transition&&s.hasClass("fade")?s.one("bsTransitionEnd",i).emulateTransitionEnd(e.TRANSITION_DURATION):i(),this.hoverState=null,this)},e.prototype.fixTitle=function(){var t=this.$element;(t.attr("title")||"string"!=typeof t.attr("data-original-title"))&&t.attr("data-original-title",t.attr("title")||"").attr("title","")},e.prototype.hasContent=function(){return this.getTitle()},e.prototype.getPosition=function(e){var o=(e=e||this.$element)[0],i="BODY"==o.tagName,n=o.getBoundingClientRect();null==n.width&&(n=t.extend({},n,{width:n.right-n.left,height:n.bottom-n.top}));var s=window.SVGElement&&o instanceof window.SVGElement,r=i?{top:0,left:0}:s?null:e.offset(),a={scroll:i?document.documentElement.scrollTop||document.body.scrollTop:e.scrollTop()},l=i?{width:t(window).width(),height:t(window).height()}:null;return t.extend({},n,a,l,r)},e.prototype.getCalculatedOffset=function(t,e,o,i){return"bottom"==t?{top:e.top+e.height,left:e.left+e.width/2-o/2}:"top"==t?{top:e.top-i,left:e.left+e.width/2-o/2}:"left"==t?{top:e.top+e.height/2-i/2,left:e.left-o}:{top:e.top+e.height/2-i/2,left:e.left+e.width}},e.prototype.getViewportAdjustedDelta=function(t,e,o,i){var n={top:0,left:0};if(!this.$viewport)return n;var s=this.options.viewport&&this.options.viewport.padding||0,r=this.getPosition(this.$viewport);if(/right|left/.test(t)){var a=e.top-s-r.scroll,l=e.top+s-r.scroll+i;a<r.top?n.top=r.top-a:l>r.top+r.height&&(n.top=r.top+r.height-l)}else{var h=e.left-s,p=e.left+s+o;h<r.left?n.left=r.left-h:p>r.right&&(n.left=r.left+r.width-p)}return n},e.prototype.getTitle=function(){var t=this.$element,e=this.options;return t.attr("data-original-title")||("function"==typeof e.title?e.title.call(t[0]):e.title)},e.prototype.getUID=function(t){do t+=~~(1e6*Math.random());while(document.getElementById(t));return t},e.prototype.tip=function(){if(!this.$tip&&(this.$tip=t(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},e.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},e.prototype.enable=function(){this.enabled=!0},e.prototype.disable=function(){this.enabled=!1},e.prototype.toggleEnabled=function(){this.enabled=!this.enabled},e.prototype.toggle=function(e){var o=this;e&&((o=t(e.currentTarget).data("bs."+this.type))||(o=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,o))),e?(o.inState.click=!o.inState.click,o.isInStateTrue()?o.enter(o):o.leave(o)):o.tip().hasClass("in")?o.leave(o):o.enter(o)},e.prototype.destroy=function(){var t=this;clearTimeout(this.timeout),this.hide(function(){t.$element.off("."+t.type).removeData("bs."+t.type),t.$tip&&t.$tip.detach(),t.$tip=null,t.$arrow=null,t.$viewport=null,t.$element=null})};var o=t.fn.tietooltip;t.fn.tietooltip=function(o){return this.each(function(){var i=t(this),n=i.data("bs.tooltip"),s="object"==typeof o&&o;!n&&/destroy|hide/.test(o)||(n||i.data("bs.tooltip",n=new e(this,s)),"string"==typeof o&&n[o]())})},t.fn.tietooltip.Constructor=e,t.fn.tietooltip.noConflict=function(){return t.fn.tooltip=o,this}}(jQuery);var $the_post=jQuery("#the-post"),$postContent=$the_post.find(".entry");$doc.ready(function(){"use strict";function t(t){var e;if(!t)var t=window.event;return t.which?e=3==t.which:t.button&&(e=2==t.button),e}function e(){var t="";return window.getSelection?t=window.getSelection().toString():document.selection&&"Control"!=document.selection.type&&(t=document.selection.createRange().text),t}if($doc.on("click","#toggle-post-button",function(){return $postContent.toggleClass("is-expanded"),jQuery(this).hide(),!1}),$doc.on("click",".print-share-btn",function(){return window.print(),!1}),tie.responsive_tables&&$the_post.find("table").wrap('<div class="table-is-responsive"></div>'),jQuery('[data-toggle="tooltip"]').tietooltip(),$doc.on("click",".share-links a:not(.email-share-btn)",function(){var t=jQuery(this).attr("href");return"#"!=t?(window.open(t,"TIEshare","height=450,width=760,resizable=0,toolbar=0,menubar=0,status=0,location=0,scrollbars=0"),!1):void 0}),tie.is_sticky_video&&jQuery("#the-sticky-video").length){var o=jQuery("#the-sticky-video"),i=o.offset().top,n=tie.sticky_desktop?60:0,n=$body.hasClass("admin-bar")?n+32:n,s=Math.floor(i+o.outerHeight()-n),r=$window.width();jQuery(".video-close-btn").click(function(){o.removeClass("video-is-sticky").addClass("stop-sticky")}),$window.on("resize load",function(){if(i=o.offset().top,s=Math.floor(i+o.outerHeight()-n),r=$window.width(),$body.hasClass("has-sidebar")){var t=jQuery(".sidebar"),e=t.width(),a=$body.hasClass("magazine2")&&$body.hasClass("sidebar-right")?40:15,l=$window.width()-(t.offset().left+e);o.find(".featured-area-inner").css({width:e,height:e*(9/16),right:l-a,left:"auto",top:n+20})}}).on("scroll",function(){o.hasClass("stop-sticky")||o.toggleClass("video-is-sticky",$window.scrollTop()>s&&r>992)})}tie.reading_indicator&&$postContent.length&&$postContent.imagesLoaded(function(){var t=$postContent.height(),e=$window.height();$window.scroll(function(){var o=0,i=$postContent.offset().top,n=$window.scrollTop();n>i&&(o=100*(n-i)/(t-e)),jQuery("#reading-position-indicator").css("width",o+"%")})});var a=jQuery("#check-also-box");if(a.length){tie_animate_element(a);var l=$the_post.outerHeight(),h=!1;$window.scroll(function(){if(!h){var t=$window.scrollTop();t>l?a.addClass("show-check-also"):a.removeClass("show-check-also")}})}jQuery("#check-also-close").on("click",function(){return a.removeClass("show-check-also"),h=!0,!1}),tie.select_share&&($postContent.mousedown(function(o){$body.attr("mouse-top",o.clientY+window.pageYOffset),$body.attr("mouse-left",o.clientX),!t(o)&&e().length&&(jQuery(".fly-text-share").remove(),document.getSelection().removeAllRanges())}),$postContent.mouseup(function(o){var i=(jQuery(o.target),e()),n=i;if(i.length>3&&!t(o)){var s=$body.attr("mouse-top"),r=o.clientY+window.pageYOffset;parseInt(s)<parseInt(r)&&(r=s);var a=$body.attr("mouse-left"),l=o.clientX,h=parseInt(a)+(parseInt(l)-parseInt(a))/2,p=window.location.href.split("?")[0],c=114;i=i.substring(0,c),tie.twitter_username&&(c-=tie.twitter_username.length+2,i=i.substring(0,c),i=i+" @"+tie.twitter_username);var d="";tie.select_share_twitter&&(d+='<a href="https://twitter.com/share?url='+encodeURIComponent(p)+"&text="+encodeURIComponent(i)+"\" class='fa fa-twitter' onclick=\"window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;\"></a>"),tie.select_share_facebook&&tie.facebook_app_id&&(d+='<a href="https://www.facebook.com/dialog/feed?app_id='+tie.facebook_app_id+"&link="+encodeURIComponent(p)+"&quote="+encodeURIComponent(n)+"\" class='fa fa-facebook' onclick=\"window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;\"></a>"),tie.select_share_linkedin&&(d+='<a href="https://www.linkedin.com/shareArticle?mini=true&url='+encodeURIComponent(p)+"&summary="+encodeURIComponent(n)+"\" class='fa fa-linkedin' onclick=\"window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;\"></a>"),tie.select_share_email&&(d+='<a href="mailto:?body='+encodeURIComponent(n)+" "+encodeURIComponent(p)+"\" class='fa fa-envelope' onclick=\"window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;\"></a>"),""!=d&&$body.append('<div class="fly-text-share">'+d+"</div>"),jQuery(".fly-text-share").css({position:"absolute",top:parseInt(r)-60,left:parseInt(h)}).show()}})),$doc.on("mousemove",".taq-user-rate-active",function(t){var e=jQuery(this);if(e.hasClass("rated-done"))return!1;t.offsetX||(t.offsetX=t.clientX-jQuery(t.target).offset().left);var o=t.offsetX,i=e.width(),n=Math.round(o/i*100);e.find(".user-rate-image span").attr("data-user-rate",n).css("width",n+"%")}),$doc.on("click",".taq-user-rate-active",function(){var t=jQuery(this),e=t.parent(),o=e.find(".taq-count"),i=t.attr("data-id"),n=o.text();if(t.hasClass("rated-done")||t.hasClass("rated-in-progress"))return!1;t.addClass("rated-in-progress");var s=t.find(".user-rate-image span").data("user-rate");t.find(".user-rate-image").hide(),t.append('<span class="taq-load">'+tie.ajax_loader+"</span>"),s>=95&&(s=100);var r=5*s/100;return jQuery.post(taqyeem.ajaxurl,{action:"taqyeem_rate_post",post:i,value:r},function(){t.addClass("rated-done").attr("data-rate",s),t.find(".user-rate-image span").width(s+"%"),jQuery(".taq-load").fadeOut(function(){e.find(".taq-score").html(r),o.length?(n=parseInt(n)+1,o.html(n)):e.find("small").hide(),e.find("strong").html(taqyeem.your_rating),t.find(".user-rate-image").fadeIn()})},"html"),!1}),$doc.on("mouseleave",".taq-user-rate-active",function(){var t=jQuery(this);if(t.hasClass("rated-done"))return!1;var e=t.attr("data-rate");t.find(".user-rate-image span").css("width",e+"%")})});
| 7,560.5 | 15,120 | 0.716553 |
83a7eefa0b889b8d09b8d8891ae4f3936ff668a3 | 2,984 | js | JavaScript | src/dom/renderer.js | matthewtoast/runiq-vdom | a87938e2f6d1fc25c027210b1051ad15154f9ebd | [
"0BSD"
] | 1 | 2015-12-24T00:51:45.000Z | 2015-12-24T00:51:45.000Z | src/dom/renderer.js | matthewtoast/runiq-vdom | a87938e2f6d1fc25c027210b1051ad15154f9ebd | [
"0BSD"
] | null | null | null | src/dom/renderer.js | matthewtoast/runiq-vdom | a87938e2f6d1fc25c027210b1051ad15154f9ebd | [
"0BSD"
] | null | null | null | 'use strict'
var H = require('virtual-dom/h');
var Diff = require('virtual-dom/diff');
var Patch = require('virtual-dom/patch');
var CreateElement = require('virtual-dom/create-element');
var DEPRECATED_PROPS = {
'webkitMovementX': true,
'webkitMovementY': true,
'keyLocation': true
};
var UNSERIALIZABLE_TYPES = {
'object': true,
'function': true
};
var EVENT_ATTR_PREFIX = 'on';
function Renderer() {
this.element = null;
this.context = null;
this.previous = null;
this.root = null;
}
function _descend(children, ctx, inst) {
var out = [];
for (var i = 0; i < children.length; i++) {
var child = children[i];
out.push(_render(child, ctx, inst));
}
return out;
}
function _synthesizeEvent(rawEvent, inst) {
var syntheticEvent = {};
if (rawEvent.target) {
syntheticEvent.target = _synthesizeEvent(rawEvent.target);
}
for (var propName in rawEvent) {
if (!(propName in DEPRECATED_PROPS)) {
var propValue = rawEvent[propName];
if (!((typeof propValue) in UNSERIALIZABLE_TYPES)) {
syntheticEvent[propName] = propValue;
}
}
}
return syntheticEvent;
}
function _processProperties(obj, ctx, inst) {
var out = {};
if (obj.id) out.id = obj.id;
var attrs = obj.attributes || {};
// HACK: I don't remember why this is needed, but removing
// this condition causes the styles not to render... :(
if (attrs.style) {
// If attrs.style is a string (cssText), leave it alone
// and it will be automatically applied as style
if (typeof attrs.style === 'object') {
out.style = attrs.style;
delete attrs.style;
}
}
for (var name in attrs) {
if (name.slice(0, 2) === EVENT_ATTR_PREFIX) {
var message = attrs[name];
delete attrs[name];
out[name] = function(event) {
var syntheticEvent = _synthesizeEvent(event, inst)
ctx.send(message, syntheticEvent);
};
}
}
out.attributes = attrs;
return out;
}
function _render(obj, ctx, inst) {
var innerPieces = [].concat(obj.content, _descend(obj.children, ctx, inst));
var virtualProps = _processProperties(obj, ctx, inst);
var virtualEl = H(obj.name, virtualProps, innerPieces);
return virtualEl;
}
Renderer.prototype.render = function(id, name, payload, via) {
var tree = _render(payload, this.context, this);
if (this.root) {
var patches = Diff(this.previous, tree);
this.root = Patch(this.root, patches);
}
else {
this.root = CreateElement(tree);
this.element.appendChild(this.root);
}
this.previous = tree;
};
Renderer.prototype.mountElement = function(element) {
this.element = element;
};
Renderer.prototype.attachContext = function(context) {
this.context = context;
};
module.exports = Renderer;
| 26.642857 | 80 | 0.607239 |
83a85b59c2f9b6a8fefca4363747bf757987c18e | 894 | js | JavaScript | projects/shojo/src/assets/js/imageResize.js | calibur-tv/arthur | d0a372d195a85e3d0c15922ab38a6f5cb694650c | [
"MIT"
] | null | null | null | projects/shojo/src/assets/js/imageResize.js | calibur-tv/arthur | d0a372d195a85e3d0c15922ab38a6f5cb694650c | [
"MIT"
] | null | null | null | projects/shojo/src/assets/js/imageResize.js | calibur-tv/arthur | d0a372d195a85e3d0c15922ab38a6f5cb694650c | [
"MIT"
] | null | null | null | export default (url, { width, height, rule, webP }) => {
if (!url) {
return ''
}
if (/imageMogr2/.test(url) || url.startsWith('data')) {
return url
}
const link = url.startsWith('http') ? url : `https://m1.calibur.tv/${url}`
const format = webP ? '/format/webp' : ''
const mode = rule === undefined || rule === '' ? 1 : parseInt(rule)
if ((mode === 1 && !width) || (!width && !height)) {
return `${link}?imageMogr2/auto-orient/strip${format}`
}
let w
let h
const DPR = typeof window === 'undefined' ? 2 : window.devicePixelRatio
if (mode === 1) {
w = `/w/${(width * DPR) | 0}`
h = height ? `/h/${(height * DPR) | 0}` : `/h/${(width * DPR) | 0}`
} else {
w = width ? `/w/${(width * DPR) | 0}` : ''
h = height ? `/h/${(height * DPR) | 0}` : ''
}
return `${link}?imageMogr2/auto-orient/strip|imageView2/${mode}${w}${h}${format}`
}
| 27.9375 | 83 | 0.52349 |
83a877a18281785eba19e4a67d82558f9c43d166 | 1,582 | js | JavaScript | tools.js | payfast-api/core | 6552ab8e69c9b4438222242d8d12b475cbc3fdc4 | [
"MIT"
] | null | null | null | tools.js | payfast-api/core | 6552ab8e69c9b4438222242d8d12b475cbc3fdc4 | [
"MIT"
] | null | null | null | tools.js | payfast-api/core | 6552ab8e69c9b4438222242d8d12b475cbc3fdc4 | [
"MIT"
] | 3 | 2020-07-01T01:36:49.000Z | 2021-05-25T09:38:35.000Z | var md5 = require('md5');
exports.urlencode = async (params) => {
let result = [];
Object.keys(params).sort().map(key => {
params[key] = encodeURIComponent(params[key]);
params[key] = params[key].replace(/\%20/g, '+');
result.push(key + "=" + params[key]);
});
return await result.join('&');
};
exports.signature = async (headers, body) => {
var merge = {};
if (typeof(body) != "object") {
body = {};
};
Object.keys(body).map(key => {
merge[key] = body[key];
});
if (typeof(headers) != "object") {
headers = {};
};
Object.keys(headers).map(key => {
merge[key] = headers[key];
});
var signature = [];
Object.keys(merge).sort().map(key => {
merge[key] = encodeURIComponent(merge[key]);
merge[key] = merge[key].replace(/\%20/g, '+');
signature.push(key + "=" + merge[key]);
});
headers.signature = md5(signature.join('&'));
return {
'body': body,
'headers': headers
};
};
exports.csvtojson = async (csv) => {
csv = csv.split('"').join('');
let data = [];
let lines = await csv.split('"').join('').split('\n');
let headers = lines[0].toLowerCase().split(',').map(key => key.trim());
lines.splice(0, 1);
lines.map(line => {
var tmp = {};
line = line.split(',').map(key => key.trim());
for (let i = 0; i < headers.length; i++) {
tmp[headers[i]] = line[i];
};
data.push(tmp);
});
return await data;
}; | 23.969697 | 75 | 0.490518 |
83a9701be5c07f4a978c2ba4b52866252a99dcac | 2,339 | js | JavaScript | sources/src/yoast/search-metadata-previews/snippet-preview/ProductDataMobile.js | jvega190/yoast-plugin | b15e1dc4789db0b18a460aa8db7dba0372298cf6 | [
"MIT"
] | null | null | null | sources/src/yoast/search-metadata-previews/snippet-preview/ProductDataMobile.js | jvega190/yoast-plugin | b15e1dc4789db0b18a460aa8db7dba0372298cf6 | [
"MIT"
] | null | null | null | sources/src/yoast/search-metadata-previews/snippet-preview/ProductDataMobile.js | jvega190/yoast-plugin | b15e1dc4789db0b18a460aa8db7dba0372298cf6 | [
"MIT"
] | null | null | null | import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { __ } from "@wordpress/i18n";
import { round, capitalize } from "lodash";
import { StarRating } from "../../components";
const ProductData = styled.div`
display: flex;
margin-top: -16px;
line-height: 1.6;
`;
const ProductDataCell50 = styled.div`
flex: 1;
max-width: 50%;
`;
const ProductDataCell25 = styled.div`
flex: 1;
max-width: 25%;
`;
const ProductDataInnerLower = styled.div`
color: #70757a;
`;
/**
* Renders ProductData component.
*
* @param {Object} props The props.
*
* @returns {React.Component} The StarRating Component.
*/
function ProductDataMobile( props ) {
const { shoppingData } = props;
return (
<ProductData>
{ ( shoppingData.rating > 0 ) &&
<ProductDataCell50 className="yoast-shopping-data-preview__column">
<div className="yoast-shopping-data-preview__upper">{ __( "Rating", "yoast-components" ) }</div>
<ProductDataInnerLower className="yoast-shopping-data-preview__lower">
<span>{ round( ( shoppingData.rating * 2 ), 1 ) }/10 </span>
<StarRating rating={ shoppingData.rating } />
<span> ({ shoppingData.reviewCount })</span>
</ProductDataInnerLower>
</ProductDataCell50>
}
{ ( shoppingData.price ) &&
<ProductDataCell25 className="yoast-shopping-data-preview__column">
<div className="yoast-shopping-data-preview__upper">{ __( "Price", "yoast-components" ) }</div>
<ProductDataInnerLower
className="yoast-shopping-data-preview__lower"
dangerouslySetInnerHTML={ { __html: shoppingData.price } }
/>
</ProductDataCell25>
}
{ ( shoppingData.availability ) &&
<ProductDataCell25 className="yoast-shopping-data-preview__column">
<div className="yoast-shopping-data-preview__upper">{ __( "Availability", "yoast-components" ) }</div>
<ProductDataInnerLower className="yoast-shopping-data-preview__lower">
{ capitalize( shoppingData.availability ) }
</ProductDataInnerLower>
</ProductDataCell25>
}
</ProductData>
);
}
export default ProductDataMobile;
ProductDataMobile.propTypes = {
shoppingData: PropTypes.shape( {
rating: PropTypes.number,
reviewCount: PropTypes.number,
availability: PropTypes.string,
price: PropTypes.string,
} ).isRequired,
};
| 28.52439 | 107 | 0.695596 |
83a997c5009e3820d7203c67f606c6e08671ff07 | 1,381 | js | JavaScript | lib/axiom/fs/stream/writable_stream.js | samkenxstream/axiom | a9fad51fecd1de0d839085958e26a344944155ef | [
"Apache-2.0"
] | 56 | 2015-03-25T19:52:29.000Z | 2021-07-03T22:42:54.000Z | lib/axiom/fs/stream/writable_stream.js | samkenxstream/axiom | a9fad51fecd1de0d839085958e26a344944155ef | [
"Apache-2.0"
] | 88 | 2015-03-25T17:25:09.000Z | 2022-01-17T19:02:18.000Z | lib/axiom/fs/stream/writable_stream.js | samkenxstream/axiom | a9fad51fecd1de0d839085958e26a344944155ef | [
"Apache-2.0"
] | 25 | 2015-03-25T17:10:47.000Z | 2022-03-14T23:31:37.000Z | // Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AxiomEvent from 'axiom/core/event';
/** @typedef function():void */
export var WriteCallback;
/**
* Interface similar to node.js writable stream.
*
* @interface
*/
export var WritableStream = function() {};
/**
* Fires when end() has been called and all data has been flushed.
*
* @type {!AxiomEvent}
*/
WritableStream.prototype.onFinish;
/**
* Write a value to the stream.
*
* @param {!*} value
* @param {WriteCallback=} opt_callback Callback invoked when the value has
* been consumed by the underlying transport.
* @return {void}
*/
WritableStream.prototype.write = function(value, opt_callback) {};
/**
* Close the stream when there is no more data to write.
*
* @return {void}
*/
WritableStream.prototype.end = function() {};
| 27.62 | 76 | 0.708907 |
83aa2fe6bdc8f389553dc14b18db5f97e94b3b8a | 1,079 | js | JavaScript | packages/wiplib/src/operations/brightnessAndContrastAdjustment.js | cocoli89/WebImageProcessing | b771c24bccffd8926b09eaf3099b27bc39e8aec0 | [
"MIT"
] | 14 | 2019-02-21T09:21:02.000Z | 2019-07-23T06:16:19.000Z | packages/wiplib/src/operations/brightnessAndContrastAdjustment.js | cocoli89/WebImageProcessing | b771c24bccffd8926b09eaf3099b27bc39e8aec0 | [
"MIT"
] | 1 | 2019-04-05T20:09:04.000Z | 2019-04-05T20:22:26.000Z | packages/wiplib/src/operations/brightnessAndContrastAdjustment.js | cocoli89/WebImageProcessing | b771c24bccffd8926b09eaf3099b27bc39e8aec0 | [
"MIT"
] | 2 | 2019-05-31T18:43:32.000Z | 2021-07-17T03:41:12.000Z | import { createLookupTable, applyLookupTable } from "./transformImage";
/**
* Changes the contrast and the brightness of the given image
*
* @param {RgbaImageBuffer} imgBuffer Image to transform
* @param {number[]} oldBrightnesses Previous brightnesses of the image
* @param {number[]} oldContrasts Previous contrasts of the image
* @param {number[]} newBrightnesses New brightnesses of the image
* @param {number[]} newContrasts New contrasts of the image
* @returns {RgbaImageBuffer} Transformed image
*/
export function brightnessAndContrastAdjustment(
imgBuffer,
oldBrightnesses,
oldContrasts,
newBrightnesses,
newContrasts
) {
const lookupTable = createLookupTable(dim => {
const slope = newContrasts[dim] / oldContrasts[dim];
const yIntercept = newBrightnesses[dim] - slope * oldBrightnesses[dim];
return value => {
const newValue = Math.round(slope * value + yIntercept);
const clippedValue = Math.min(Math.max(newValue, 0), 255);
return clippedValue;
};
});
return applyLookupTable(imgBuffer, lookupTable);
}
| 32.69697 | 75 | 0.729379 |
83aa3611d8d5b233e1408a683b87c43f14d1933f | 1,377 | js | JavaScript | web/src/quiz/Quiz.js | Luke-Vear/nettaton | ae80017d5e48188bf83eec336ea27380b21c900f | [
"MIT"
] | 2 | 2017-09-18T10:49:26.000Z | 2018-03-25T18:13:22.000Z | web/src/quiz/Quiz.js | Luke-Vear/nettaton | ae80017d5e48188bf83eec336ea27380b21c900f | [
"MIT"
] | 1 | 2018-11-11T07:36:21.000Z | 2018-11-11T07:36:21.000Z | web/src/quiz/Quiz.js | Luke-Vear/nettaton | ae80017d5e48188bf83eec336ea27380b21c900f | [
"MIT"
] | 3 | 2018-02-16T10:01:50.000Z | 2018-11-11T00:55:57.000Z | import React from 'react'
import { connect } from 'react-redux'
import { actions } from './redux'
import { BusyButton } from '../components/BusyButton'
import { ResultDisplay } from '../components/ResultDisplay'
import { AnswerField } from '../components/AnswerField'
import { QuestionDisplay } from '../components/QuestionDisplay'
export const Quiz = ({ busy, question, answer, correct, error, newQuestion, sendAnswer, updateAnswer }) =>
<div>
<QuestionDisplay busy={busy} correct={correct} question={question} error={error} />
<ResultDisplay correct={correct} />
<AnswerField question={question} onChange={updateAnswer} />
<BusyButton text={'Next'} busy={busy} color='primary' onClick={newQuestion} />
<BusyButton text={'Send'} busy={busy || question === null} color='secondary' onClick={() => sendAnswer(question, answer)} />
</div>
const mapStateToProps = state => ({
busy: state.quiz.busy,
question: state.quiz.question,
answer: state.quiz.answer,
correct: state.quiz.correct,
error: state.quiz.error
})
const mapDispatchToProps = dispatch => ({
newQuestion: () => dispatch(actions.newQuestionRequest()),
sendAnswer: (question, answer) => dispatch(actions.sendAnswerRequest(question, answer)),
updateAnswer: (answer) => dispatch(actions.answerUpdate(answer))
})
export default connect(mapStateToProps, mapDispatchToProps)(Quiz)
| 41.727273 | 128 | 0.718954 |
5d07c4559ae9a89190565fdc9fe510cadfe1cd32 | 235 | js | JavaScript | controllers/utils/isEmpty.js | PeterAyad/Backend-API | 5d3988944d33c1b909abc15bf3719497c9b435b2 | [
"MIT"
] | 7 | 2022-01-06T17:20:54.000Z | 2022-03-15T16:37:06.000Z | controllers/utils/isEmpty.js | TumblrX/Backend-API | 5d3988944d33c1b909abc15bf3719497c9b435b2 | [
"MIT"
] | null | null | null | controllers/utils/isEmpty.js | TumblrX/Backend-API | 5d3988944d33c1b909abc15bf3719497c9b435b2 | [
"MIT"
] | 2 | 2022-01-06T14:20:20.000Z | 2022-01-06T18:07:15.000Z | module.exports = function(strIn) {
if (strIn === undefined) {
return true;
} else if (strIn == null) {
return true;
} else if (strIn == '') {
return true;
} else {
return false;
}
};
| 19.583333 | 34 | 0.480851 |
5d084ed6d652183cc98db2f5fd6e6750525a193f | 302 | js | JavaScript | src/services/credentials.js | oleg19960606/react4 | a7b55456506f704071c6cf7477d4d12ae93cdb72 | [
"MIT"
] | 331 | 2018-04-06T13:11:04.000Z | 2022-03-17T13:51:55.000Z | src/services/credentials.js | cor/vue-testing-examples | ab9d206ec74c1764438926b01082f9efde457f0d | [
"MIT"
] | 6 | 2021-11-05T04:20:53.000Z | 2022-02-27T20:13:27.000Z | src/services/credentials.js | cor/vue-testing-examples | ab9d206ec74c1764438926b01082f9efde457f0d | [
"MIT"
] | 36 | 2018-09-03T12:36:42.000Z | 2021-05-14T15:32:10.000Z | import { Register } from '@di';
export const CREDENTIALS_SERVICE_ID = Symbol('credentialsService');
@Register(CREDENTIALS_SERVICE_ID)
export default class CredentialsService {
sanitize (input) {
if (input && input.trim) {
return input.trim();
} else {
return input;
}
}
}
| 20.133333 | 67 | 0.668874 |
5d0943c69e5b2d4bd01b7e7221e6c357132a23e5 | 586 | js | JavaScript | web/src/core/components/Page/Page.js | xvicmanx/activities-app | 091e3c8f1a6bf0a0517b82305f7a5e56aae50780 | [
"MIT"
] | 2 | 2020-12-11T02:56:10.000Z | 2020-12-14T21:36:50.000Z | web/src/core/components/Page/Page.js | xvicmanx/activities-app | 091e3c8f1a6bf0a0517b82305f7a5e56aae50780 | [
"MIT"
] | null | null | null | web/src/core/components/Page/Page.js | xvicmanx/activities-app | 091e3c8f1a6bf0a0517b82305f7a5e56aae50780 | [
"MIT"
] | 1 | 2020-12-14T19:36:20.000Z | 2020-12-14T19:36:20.000Z | // @flow
import React from 'react';
import type { Node } from 'react';
import { Heading } from 'react-bulma-components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import './Page.css';
type Props = {
title: string,
icon: any,
children: Node,
};
const Page = ({ title, icon, children }: Props): React$Element<'div'> => (
<div className="Page">
<Heading className="Page__Title">
<FontAwesomeIcon icon={icon} className="Title-Icon" /> {title}
</Heading>
<div className="Page__Content">{children}</div>
</div>
);
export default Page;
| 22.538462 | 74 | 0.658703 |
5d09fefc0c13a9bf9d3b5f2b3da2191ff9972c94 | 6,384 | js | JavaScript | services/dsrp-web/src/selectors/applicationSelectors.js | bcgov/dormant-site-reclamation-program | 4710434174a204a292a3128d92c8daf1de2a65a6 | [
"Apache-2.0"
] | null | null | null | services/dsrp-web/src/selectors/applicationSelectors.js | bcgov/dormant-site-reclamation-program | 4710434174a204a292a3128d92c8daf1de2a65a6 | [
"Apache-2.0"
] | 9 | 2020-05-06T23:29:43.000Z | 2022-03-14T22:58:17.000Z | services/dsrp-web/src/selectors/applicationSelectors.js | bcgov/dormant-site-reclamation-program | 4710434174a204a292a3128d92c8daf1de2a65a6 | [
"Apache-2.0"
] | 3 | 2020-05-08T16:54:22.000Z | 2021-01-27T17:28:49.000Z | import {
startCase,
camelCase,
isObjectLike,
isEmpty,
isArrayLike,
sum,
get,
startsWith,
endsWith,
flatten,
} from "lodash";
import { createSelector } from "reselect";
import * as applicationReducer from "../reducers/applicationReducer";
import { getWells, getLiabilities, getNominatedWells } from "@/selectors/OGCSelectors";
import { contractedWorkIdSorter } from "@/utils/helpers";
import { APPLICATION_PHASE_CODES } from "@/constants/strings";
import CONTRACT_WORK_SECTIONS from "@/constants/contract_work_sections";
export const {
getApplications,
getApplication,
getApplicationApprovedContractedWork,
getApplicationsApprovedContractedWork,
getPageData,
} = applicationReducer;
const getLMR = (workType, liability) => {
if (!liability) {
return null;
}
if (startsWith(workType, "abandonment")) {
return liability.abandonment_liability;
}
if (endsWith(workType, "investigation")) {
return liability.assessment_liability;
}
if (startsWith(workType, "reclamation")) {
return liability.reclamation_liability;
}
if (startsWith(workType, "remediation")) {
return liability.remediation_liability;
}
};
// return an array of contracted_work on well sites
export const getApplicationsWellSitesContractedWork = createSelector(
[getApplications, getWells, getLiabilities, getNominatedWells],
(applications, wells, liabilities, nominatedWells) => {
if (isEmpty(applications) || !isArrayLike(applications)) {
return [];
}
let wellSitesContractedWork = [];
applications.map((application) => {
if (isEmpty(application) || isEmpty(application.json)) {
return;
}
const filteredWells =
application.application_phase_code === APPLICATION_PHASE_CODES.INITIAL
? wells
: nominatedWells;
const wellSites = application.json.well_sites;
if (isEmpty(wellSites) || !isArrayLike(wellSites)) {
return;
}
const reviewJson = (isObjectLike(application.review_json) && application.review_json) || null;
const estimatedCostOverrides =
(isObjectLike(application.estimated_cost_overrides) &&
application.estimated_cost_overrides) ||
null;
wellSites.map((site, index) => {
if (isEmpty(site)) {
return;
}
const wellAuthorizationNumber =
(isObjectLike(site.details) && site.details.well_authorization_number) || null;
const priorityCriteria =
(isObjectLike(site.site_conditions) && Object.values(site.site_conditions).length) || 0;
const reviewJsonWellSite =
(reviewJson &&
wellAuthorizationNumber &&
isArrayLike(reviewJson.well_sites) &&
isObjectLike(reviewJson.well_sites[index]) &&
reviewJson.well_sites[index][wellAuthorizationNumber]) ||
null;
const contractedWork = (isObjectLike(site.contracted_work) && site.contracted_work) || {};
Object.keys(contractedWork).map((type) => {
const amountFields = flatten(
CONTRACT_WORK_SECTIONS.find(
(cws) => cws.formSectionName === type
).subSections.map((ss) => ss.amountFields.map((af) => af.fieldName))
);
let estimatedCostArray = [];
amountFields.map((field) => {
if (field in contractedWork[type]) {
estimatedCostArray.push(contractedWork[type][field]);
}
});
const contractedWorkStatusCode = get(
reviewJsonWellSite,
`contracted_work.${type}.contracted_work_status_code`,
null
);
const maxSharedCost = 100000;
const shouldSharedCostBeZero = !(contractedWorkStatusCode === "APPROVED");
const workId = contractedWork[type].work_id;
const estimatedCostOverride =
estimatedCostOverrides && workId in estimatedCostOverrides
? estimatedCostOverrides[workId]
: null;
const calculatedSharedCostOverride =
estimatedCostOverride !== null ? (estimatedCostOverride / 2).toFixed(2) : null;
const sharedCostOverride =
calculatedSharedCostOverride > maxSharedCost
? maxSharedCost
: calculatedSharedCostOverride;
const sharedCostOverrideByStatus = shouldSharedCostBeZero ? 0 : sharedCostOverride;
const calculatedSharedCost = (sum(estimatedCostArray) / 2).toFixed(2);
const sharedCost =
calculatedSharedCost > maxSharedCost ? maxSharedCost : calculatedSharedCost;
const sharedCostByStatus = shouldSharedCostBeZero ? 0 : sharedCost;
const OGCStatus = !isEmpty(filteredWells[wellAuthorizationNumber])
? filteredWells[wellAuthorizationNumber].current_status
: null;
const location = !isEmpty(filteredWells[wellAuthorizationNumber])
? filteredWells[wellAuthorizationNumber].surface_location
: null;
const liability = !isEmpty(liabilities[wellAuthorizationNumber])
? liabilities[wellAuthorizationNumber]
: null;
const wellSiteContractedWorkType = {
key: `${application.guid}.${wellAuthorizationNumber}.${type}`,
well_index: index,
application_guid: application.guid,
work_id: workId,
well_authorization_number: wellAuthorizationNumber,
contracted_work_type: type,
contracted_work_type_description: startCase(camelCase(type)),
priority_criteria: priorityCriteria,
completion_date: contractedWork[type].planned_end_date,
est_cost: sum(estimatedCostArray),
est_shared_cost: sharedCostByStatus,
est_cost_override: estimatedCostOverride,
est_shared_cost_override: sharedCostOverrideByStatus,
LMR: getLMR(type, liability),
OGC_status: OGCStatus,
location,
contracted_work_status_code: contractedWorkStatusCode || "NOT_STARTED",
review_json: reviewJson,
};
wellSitesContractedWork.push(wellSiteContractedWorkType);
});
});
});
wellSitesContractedWork = wellSitesContractedWork.sort(contractedWorkIdSorter);
return wellSitesContractedWork;
}
);
| 36.901734 | 100 | 0.658521 |
5d0b698457b0407a90ec7d1f76edca32506295a1 | 52 | js | JavaScript | test/projects/large/b806.js | homobel/makebird-node | 07f9621883a2247e538fb8d8e3824a403b5154b7 | [
"MIT"
] | 4 | 2015-02-22T22:08:52.000Z | 2018-05-12T18:08:21.000Z | test/projects/large/b806.js | homobel/makebird-node | 07f9621883a2247e538fb8d8e3824a403b5154b7 | [
"MIT"
] | null | null | null | test/projects/large/b806.js | homobel/makebird-node | 07f9621883a2247e538fb8d8e3824a403b5154b7 | [
"MIT"
] | null | null | null | //~ name b806
alert(b806);
//~ component b807.js
| 7.428571 | 21 | 0.615385 |
5d0be4cddfcd3727109218e2c18c21e81e7e0467 | 935 | js | JavaScript | packages/app/modules/oauth/oauth.reducer.js | LorenzoHiver-LV/LvConnect | 35ba943facf7a91418886428c72f7ae36dd46b32 | [
"MIT"
] | 1 | 2021-05-25T15:50:04.000Z | 2021-05-25T15:50:04.000Z | packages/app/modules/oauth/oauth.reducer.js | LorenzoHiver-LV/LvConnect | 35ba943facf7a91418886428c72f7ae36dd46b32 | [
"MIT"
] | 41 | 2019-02-19T12:11:09.000Z | 2022-02-26T09:56:25.000Z | packages/app/modules/oauth/oauth.reducer.js | isabella232/LvConnect | 3a5a2bce2196422971f350e9f314ddd360d738a6 | [
"MIT"
] | 3 | 2020-02-05T15:08:20.000Z | 2020-12-03T11:53:18.000Z | // @flow
import { FETCH_PERMISSIONS_ERROR, FETCH_PERMISSIONS_START, FETCH_PERMISSIONS_SUCCESS } from './oauth.actions';
type PermissionDetails = {
application: App,
permissionsToAllow: Array<string>,
redirectTo: string,
}
export type OAuthState = {
error: false | Error,
loading: boolean,
result: PermissionDetails | null,
}
const initialState = {
error: false,
loading: false,
result: null,
};
export default (state: OAuthState = initialState, { type, payload }: ReduxAction) => {
switch (type) {
case FETCH_PERMISSIONS_START:
return {
...state,
error: false,
loading: true,
};
case FETCH_PERMISSIONS_SUCCESS:
return {
...state,
result: payload,
loading: false,
};
case FETCH_PERMISSIONS_ERROR:
return {
...state,
error: payload,
loading: false,
};
default:
return state;
}
};
| 19.893617 | 110 | 0.618182 |
5d0c388ca8b46c5e334f2b6182494ad91410f73e | 7,553 | js | JavaScript | client/apps/descriptor/collections/formatunit.js | coll-gate/collgate | 8c2ff1c59adda2bf318040f588c05263317a2812 | [
"MIT"
] | 2 | 2017-07-04T16:19:09.000Z | 2019-08-16T04:54:47.000Z | client/apps/descriptor/collections/formatunit.js | coll-gate/collgate | 8c2ff1c59adda2bf318040f588c05263317a2812 | [
"MIT"
] | null | null | null | client/apps/descriptor/collections/formatunit.js | coll-gate/collgate | 8c2ff1c59adda2bf318040f588c05263317a2812 | [
"MIT"
] | 1 | 2018-04-13T08:28:09.000Z | 2018-04-13T08:28:09.000Z | /**
* @file formatunit.js
* @brief Descriptor type format unit collection
* @author Frédéric SCHERMA (INRA UMR1095)
* @date 2017-01-04
* @copyright Copyright (c) 2017 INRA/CIRAD
* @license MIT (see LICENSE file)
* @details
*/
let FormatUnitModel = require('../models/formatunit');
let Collection = Backbone.Collection.extend({
url: window.application.url(['descriptor', 'format', 'unit']),
model: FormatUnitModel,
initialize: function(models, options) {
Collection.__super__.initialize.apply(this, arguments);
this.models = [];
this.lookup = {};
for (let i = 0; i < this.items.length; ++i) {
let model = this.items[i];
this.lookup[model.id] = model.label;
this.models.push(new FormatUnitModel({
id: model.id,
value: model.id,
group: model.group,
label: model.label
}));
}
},
parse: function(data) {
this.groups = data.groups;
return data.items;
},
toJSON: function() {
let results = [];
let groups = {};
// init groups
for (let i = 0; i < this.groups.length; ++i) {
let group = this.groups[i];
groups[group.group] = {id: -1, value: "", label: group.label, options: []};
results.push(groups[group.group]);
}
for (let i = 0; i < this.models.length; ++i) {
let model = this.models[i];
let group = groups[model.get('group')];
if (model.id) {
group.options.push({
id: model.get('id'),
value: model.get('value'),
label: model.get('label')
});
}
}
return results;
},
groups: [
{group: 'chroma', label: _t('Chroma')},
{group: 'common', label: _t('Common')},
{group: 'grain', label: _t('Grain')},
{group: 'meter', label: _t('Meter')},
{group: 'weight', label: _t('Weight')},
{group: 'plant_and_plot', label: _t('Plant and plot')},
{group: 'quantity_and_volume', label: _t('Quantity and volume')},
{group: 'surface', label: _t('Surface')},
{group: 'time', label: _t('Time', {context: 'concept'})}
],
items: [
{id: 'chroma_L_value', group: 'chroma', label: _t("L value")},
{id: 'chroma_a_value', group: 'chroma', label: _t("a value")},
{id: 'chroma_b_value', group: 'chroma', label: _t("b value")},
{id: 'degree_celsius',group: 'common', label: _t("°C")},
{id: 'category', group: 'common', label: _t("Category")},
{id: 'custom', group: 'common', label: _t("Custom")},
{id: 'joule', group: 'common', label: _t("J (joule)")},
{id: 'norm1', group: 'common', label: _t("Norm 1")},
{id: 'note', group: 'common', label: _t("Note")},
{id: 'percent', group: 'common', label: _t("% (percent)")},
{id: 'scale', group: 'common', label: _t("Scale")},
{id: 'gram_per_100_grain', group: 'grain', label: _t("g/100 grain")},
{id: 'gram_per_200_grain', group: 'grain', label: _t("g/200 grain")},
{id: 'gram_per_1000_grain', group: 'grain', label: _t("g/1000 grain")},
{id: 'grain_per_meter2', group: 'grain', label: _t("grain/m²")},
{id: 'grain_per_spike', group: 'grain', label: _t("grain/spike")},
{id: 'grain_per_spikelet', group: 'grain', label: _t("grain/spikelet")},
{id: 'micrometer', group: 'meter', label: _t("um")},
{id: 'millimeter', group: 'meter', label: _t("mm")},
{id: 'centimeter', group: 'meter', label: _t("cm")},
{id: 'decimeter', group: 'meter', label: _t("dm")},
{id: 'meter', group: 'meter', label: _t("m")},
{id: 'kilometer', group: 'meter', label: _t("km")},
{id: 'gram', group: 'weight', label: _t("g")},
{id: 'kilogram', group: 'weight', label: _t("kg")},
{id: 'plant_per_meter', group: 'plant_and_plot', label: _t("plant/m")},
{id: 'plant_per_meter2', group: 'plant_and_plot', label: _t("plant/m²")},
{id: 'plant_per_hectare', group: 'plant_and_plot', label: _t("plant/ha")},
{id: 'plant_per_plot', group: 'plant_and_plot', label: _t("plant/plot")},
{id: 'gram_per_plant', group: 'plant_and_plot', label: _t("g/plant")},
{id: 'gram_per_plot', group: 'plant_and_plot', label: _t("g/plot")},
{id: 'kilogram_per_plot', group: 'plant_and_plot', label: _t("kg/plot")},
{id: 'stoma_per_millimeter2', group: 'plant_and_plot', label: _t("stoma/mm²")},
{id: 'node', group: 'plant_and_plot', label: _t("node")},
{id: 'spikelet', group: 'plant_and_plot', label: _t("spikelet")},
{id: 'spike_per_meter2', group: 'plant_and_plot', label: _t("spike/m²")},
{id: 'tiller_per_meter', group: 'plant_and_plot', label: _t("tiller/m")},
{id: 'tiller_per_meter2', group: 'plant_and_plot', label: _t("tiller/m²")},
{id: 'milliliter', group: 'quantity_and_volume', label: _t("ml")},
{id: 'milliliter_per_percent', group: 'quantity_and_volume', label: _t("ml/%")},
{id: 'ppm', group: 'quantity_and_volume', label: _t("ppm")},
{id: 'milligram_per_kilogram', group: 'quantity_and_volume', label: _t("mg/kg")},
{id: 'gram_per_kilogram', group: 'quantity_and_volume', label: _t("g/kg")},
{id: 'gram_per_meter2', group: 'quantity_and_volume', label: _t("g/m²")},
{id: 'kilogram_per_hectare', group: 'quantity_and_volume', label: _t("kh/ha")},
{id: 'ton_per_hectare', group: 'quantity_and_volume', label: _t("t/ha")},
{id: 'gram_per_liter', group: 'quantity_and_volume', label: _t("g/l")},
{id: 'kilogram_per_hectolitre', group: 'quantity_and_volume', label: _t("kg/hl")},
{id: 'millimol_per_meter2_per_second', group: 'quantity_and_volume', label: _t("mmol/m²/s")},
{id: 'gram_per_meter2_per_day', group: 'quantity_and_volume', label: _t("g/m²/day")},
{id: 'ccl', group: 'quantity_and_volume', label: _t("CCl (chlore)")},
{id: 'delta_13c', group: 'quantity_and_volume', label: _t("delta 13C (carbon)")},
{id: 'millimeter2', group: 'surface', label: _t("mm²")},
{id: 'centimeter2', group: 'surface', label: _t("cm²")},
{id: 'meter2', group: 'surface', label: _t("m²")},
{id: 'hectare', group: 'surface', label: _t("ha")},
{id: 'kilometer2', group: 'surface', label: _t("km²")},
{id: 'millisecond', group: 'time', label: _t("ms")},
{id: 'second', group: 'time', label: _t("s")},
{id: 'minute', group: 'time', label: _t("min")},
{id: 'hour', group: 'time', label: _t("hour")},
{id: 'day', group: 'time', label: _t("day")},
{id: 'month', group: 'time', label: _t("month")},
{id: 'year', group: 'time', label: _t("year")},
{id: 'date', group: 'time', label: _t("Date")},
{id: 'time', group: 'time', label: _t("Time")},
{id: 'datetime', group: 'time', label: _t("Date Time")},
{id: 'percent_per_minute', group: 'time', label: _t("%/min")},
{id: 'percent_per_hour', group: 'time', label: _t("%/hour")},
{id: 'percent_per_day', group: 'time', label: _t("%/day")}
],
findLabel: function(value) {
return this.lookup[value];
//let res = this.findWhere({value: value});
//return res ? res.get('label') : '';
},
});
module.exports = Collection;
| 44.958333 | 101 | 0.548259 |
5d0d24629012cdc8723fe062e4c5a007e2d50565 | 1,205 | js | JavaScript | viz/rating_distributions/yelp/ratings_global_variables.js | rchurch4/georgetown-data-science-fall-2015 | b27ef028a37514bde9f96ab28aee15ba455101db | [
"MIT"
] | null | null | null | viz/rating_distributions/yelp/ratings_global_variables.js | rchurch4/georgetown-data-science-fall-2015 | b27ef028a37514bde9f96ab28aee15ba455101db | [
"MIT"
] | null | null | null | viz/rating_distributions/yelp/ratings_global_variables.js | rchurch4/georgetown-data-science-fall-2015 | b27ef028a37514bde9f96ab28aee15ba455101db | [
"MIT"
] | null | null | null | // Ratings Distribution - Local vs. Non-local d3 Bar Graphs
// Global Variables
// Version 1.3
// References:
// 1) d3 bar graph template: http://bl.ocks.org/mbostock/3885304
// 1b) d3 bar graph tutorial: https://github.com/mbostock/d3/wiki/Selections#data
// 2) using a div container for svg: professor singh's js5.html example
// 3) updating d3 data: http://bl.ocks.org/d3noob/7030f35b72de721622b8
// 3b) updating d3 data: http://bl.ocks.org/RandomEtc/cff3610e7dd47bef2d01#index.html
// 4) meaning of "+" operator in javascript: http://stackoverflow.com/questions/26950879/d3-operator-before-object-call
// 5) understanding javascript: http://www.w3schools.com/js/
// 6) event listener for button: http://stackoverflow.com/questions/21685943/change-button-text-using-d3js
// global variables
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%") | 36.515152 | 119 | 0.696266 |
5d0dc2eabfe37920d83beb31ca1d5cac0ded648f | 247 | js | JavaScript | app/redux/Header/tests/saga.test.js | girards/React-Redux-Boilerplate | 5b73a7369b9df0c04bb92eb52c5368cf1863eab4 | [
"MIT"
] | null | null | null | app/redux/Header/tests/saga.test.js | girards/React-Redux-Boilerplate | 5b73a7369b9df0c04bb92eb52c5368cf1863eab4 | [
"MIT"
] | null | null | null | app/redux/Header/tests/saga.test.js | girards/React-Redux-Boilerplate | 5b73a7369b9df0c04bb92eb52c5368cf1863eab4 | [
"MIT"
] | null | null | null | /**
* Test sagas
*/
/* eslint-disable redux-saga/yield-effects */
// import { take, call, put, select } from 'redux-saga/effects';
// import headerSaga from '../saga';
// const generator = headerSaga();
describe('headerSaga Saga', () => {});
| 20.583333 | 64 | 0.631579 |
5d0dcbcdc634bc1d024e6b5c7c2d46603684f150 | 533 | js | JavaScript | node_modules/crownstone-cloud/dist/rest/sections/firmware.js | MJKoedam/crownstone-homey | e840ca18ef47c1eca56eb06336b772eac50669b8 | [
"MIT"
] | 2 | 2018-09-30T15:03:53.000Z | 2021-02-16T10:41:28.000Z | node_modules/crownstone-cloud/dist/rest/sections/firmware.js | crownstone/crownstone-homey | 53606a03ac431f5640b55e97d3dde47b0966827b | [
"MIT"
] | 8 | 2019-01-23T17:15:10.000Z | 2022-02-27T12:07:25.000Z | node_modules/crownstone-cloud/dist/rest/sections/firmware.js | mrquincle/crownstone-homey | 6c4b755ec54c0fbbb048e43b4491efe0f07a5ec5 | [
"MIT"
] | 3 | 2018-09-30T15:01:51.000Z | 2021-02-16T10:37:04.000Z | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cloudApiBase_1 = require("./cloudApiBase");
exports.firmware = {
getFirmwareDetails: function (version, hardwareVersion) {
return cloudApiBase_1.cloudApiBase._setupRequest('GET', '/Firmwares?version=' + version + '&hardwareVersion=' + hardwareVersion);
},
getLatestAvailableFirmware: function () {
return cloudApiBase_1.cloudApiBase._setupRequest('GET', '/Firmwares/latest');
},
};
//# sourceMappingURL=firmware.js.map | 44.416667 | 137 | 0.718574 |
5d0e58785d26067316e577299e3a782c278735b2 | 400 | js | JavaScript | webpack/plugins/html-to-disk.js | fengzilong/siji-riot | 553be368e3215614fed16f52982ecda463e370df | [
"MIT"
] | null | null | null | webpack/plugins/html-to-disk.js | fengzilong/siji-riot | 553be368e3215614fed16f52982ecda463e370df | [
"MIT"
] | null | null | null | webpack/plugins/html-to-disk.js | fengzilong/siji-riot | 553be368e3215614fed16f52982ecda463e370df | [
"MIT"
] | null | null | null | import fs from 'fs';
export default class HtmlToDiskPlugin {
constructor( options={} ){
this.options = options;
}
apply( compiler ){
compiler.plugin('compilation', function( compilation ){
compilation.plugin('html-webpack-plugin-after-html-processing', function (data, callback) {
fs.writeFile('index.html', data.html, {
encoding: 'utf8'
});
callback();
});
});
}
}
| 22.222222 | 94 | 0.655 |
5d0e73016da71d118f85dde9cc005687ffd25bf1 | 400 | js | JavaScript | script.js | harshrawat20/Product-Landing-Page | 50c98e26a038acb95e892ec53dc2dbb4f67601d4 | [
"MIT"
] | null | null | null | script.js | harshrawat20/Product-Landing-Page | 50c98e26a038acb95e892ec53dc2dbb4f67601d4 | [
"MIT"
] | null | null | null | script.js | harshrawat20/Product-Landing-Page | 50c98e26a038acb95e892ec53dc2dbb4f67601d4 | [
"MIT"
] | null | null | null | var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("nav-bar").style.top = "0";
} else {
document.getElementById("nav-bar").style.top = "-100vh";
}
prevScrollpos = currentScrollPos;
}
function scrollUp() {
window.scrollTo({ top: 0, behavior: 'smooth'});
} | 28.571429 | 60 | 0.7025 |
5d0ec32e58eab2f21c4f16220d7e27e62df76458 | 1,194 | js | JavaScript | test/helpers/factories/conversation.js | DoSomething/slothie | b789fa139b7c8c2c50fb99585110d784a9c6a84c | [
"MIT"
] | 2 | 2016-11-28T14:57:45.000Z | 2017-08-15T07:12:25.000Z | test/helpers/factories/conversation.js | DoSomething/gamb | b789fa139b7c8c2c50fb99585110d784a9c6a84c | [
"MIT"
] | 419 | 2016-08-10T14:56:37.000Z | 2022-02-27T11:22:24.000Z | test/helpers/factories/conversation.js | DoSomething/slothie | b789fa139b7c8c2c50fb99585110d784a9c6a84c | [
"MIT"
] | 1 | 2020-01-11T04:03:57.000Z | 2020-01-11T04:03:57.000Z | 'use strict';
const ObjectID = require('mongoose').Types.ObjectId;
const Conversation = require('../../../app/models/Conversation');
const messageFactory = require('./message');
const stubs = require('../stubs');
module.exports.getRawConversationData = function getRawConversationData(platformString) {
const platform = platformString || stubs.getPlatform();
const id = new ObjectID();
const date = new Date();
return {
id,
_id: id,
platform,
userId: stubs.getUserId(),
platformUserId: stubs.getMobileNumber(),
topic: stubs.getTopic(),
createdAt: date,
updatedAt: date,
lastOutboundMessage: messageFactory.getValidMessage(),
lastReceivedBroadcastId: stubs.getContentfulId(),
};
};
module.exports.getValidConversation = function getValidConversation(platformString) {
return new Conversation(exports.getRawConversationData(platformString));
};
module.exports.getValidSupportConversation = function getValidSupportConversation() {
const conversation = module.exports.getValidConversation();
conversation.topic = 'support';
conversation.lastOutboundMessage = messageFactory.getValidOutboundNoReplyMessage();
return conversation;
};
| 32.27027 | 89 | 0.751256 |
5d0eea91dc289652621cef25d118409589eda2a6 | 611 | js | JavaScript | src/js/coremvc/comps/editor/lib/tinymce_wro_loader.js | titus0039/tetra-ui | 52356d749ff677c873bf536f8f8dec814e6039c2 | [
"Unlicense",
"MIT"
] | null | null | null | src/js/coremvc/comps/editor/lib/tinymce_wro_loader.js | titus0039/tetra-ui | 52356d749ff677c873bf536f8f8dec814e6039c2 | [
"Unlicense",
"MIT"
] | null | null | null | src/js/coremvc/comps/editor/lib/tinymce_wro_loader.js | titus0039/tetra-ui | 52356d749ff677c873bf536f8f8dec814e6039c2 | [
"Unlicense",
"MIT"
] | null | null | null | var sTinyMCERegistry = {
baseURI:"/javascript/coremvc/apps/comp_editor/lib/tiny_mce",
files: [
'tiny_mce.js',
'langs/en.js',
'themes/advanced/editor_template.js',
'themes/advanced/langs/en.js'/*,
'themes/advanced/skins/default/ui.css'*/
],
registerResources:function() {
tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(this.baseURI);
tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL);
for(var i = 0; i < this.files.length; i++) {
tinymce.ScriptLoader.markDone(tinyMCE.baseURI.toAbsolute(this.files[i]));
}
}
};
sTinyMCERegistry.registerResources(); | 30.55 | 91 | 0.721768 |
5d0f4f91423c6d4c505551ed4ec504850dc69676 | 138 | js | JavaScript | renren-admin/src/main/resources/statics/plugins/treegrid/jquery.treegrid.bootstrap3.js | jiujunkeji/resource-catalog | f1f5a155ee0193ebaee0d09e321a351cdd1f5c4a | [
"Apache-2.0"
] | null | null | null | renren-admin/src/main/resources/statics/plugins/treegrid/jquery.treegrid.bootstrap3.js | jiujunkeji/resource-catalog | f1f5a155ee0193ebaee0d09e321a351cdd1f5c4a | [
"Apache-2.0"
] | 2 | 2021-04-22T16:53:30.000Z | 2021-09-20T20:50:51.000Z | renren-admin/src/main/resources/statics/plugins/treegrid/jquery.treegrid.bootstrap3.js | jiujunkeji/resource-catalog | f1f5a155ee0193ebaee0d09e321a351cdd1f5c4a | [
"Apache-2.0"
] | null | null | null | $.extend($.fn.treegrid.defaults, {
expanderExpandedClass: 'el-icon-arrow-down',
expanderCollapsedClass: 'el-icon-arrow-right'
});
| 27.6 | 49 | 0.710145 |
5d10323ce6ca460e8aa79090a410203d9d7302d0 | 198 | js | JavaScript | client/src/main.js | mu-mo/weixin-login | bf61639bdf670ba125f326a41a5d8c0972505007 | [
"MIT"
] | 2 | 2019-04-18T15:12:13.000Z | 2020-08-18T23:07:52.000Z | client/src/main.js | mu-mo/weixin-login | bf61639bdf670ba125f326a41a5d8c0972505007 | [
"MIT"
] | null | null | null | client/src/main.js | mu-mo/weixin-login | bf61639bdf670ba125f326a41a5d8c0972505007 | [
"MIT"
] | null | null | null | import Vue from 'vue';
import router from '@/router';
import store from '@/store/';
import '@/common/common.scss';
// eslint-disable-next-line no-new
new Vue({
el: '#app',
router,
store,
});
| 16.5 | 34 | 0.646465 |