text
stringlengths 7
3.69M
|
|---|
self.__precacheManifest = [
{
"revision": "4ab22eca4053c14a34e4bdb6390deae9",
"url": "/img/faces/face-5.jpg"
},
{
"revision": "6be21e8a1b7d63048728851c6003e189",
"url": "/img/sidebar-1.jpg"
},
{
"revision": "897b4cf909210560a84398d36da51983",
"url": "/img/sidebar-4.jpg"
},
{
"revision": "15e709362b6ae1025fa0",
"url": "/js/chunk-vendors.621234aa.js"
},
{
"revision": "7a4ce7cc040fc1cb8176cde106e9232f",
"url": "/img/sidebar-2.jpg"
},
{
"revision": "cd253e23ed052deeb80b42d2ed772183",
"url": "/img/sidebar-3.jpg"
},
{
"revision": "9ebea76ee1225f00d882b21547a7b49f",
"url": "/img/sidebar-5.jpg"
},
{
"revision": "735ab4f94fbcd57074377afca324c813",
"url": "/robots.txt"
},
{
"revision": "c2a605fbc0e687b2e1b4b90a7c445cdd",
"url": "/img/vue-logo.png"
},
{
"revision": "44bf13a71a4db6e15913fe8af9296711",
"url": "/img/tim_80x80.png"
},
{
"revision": "8f293614be4e9c63fba0",
"url": "/js/app.ddf45cac.js"
},
{
"revision": "cc373acb96c7560e9d0b40845e693130",
"url": "/index.html"
},
{
"revision": "b06871f281fee6b241d60582ae9369b9",
"url": "/fonts/fontawesome-webfont.b06871f2.ttf"
},
{
"revision": "b0dc05d015e91e7d28d79cd0056fe555",
"url": "/fonts/nucleo-icons.b0dc05d0.ttf"
},
{
"revision": "dc0cdfac3187d5fe800b249201cdf9b0",
"url": "/img/nucleo-icons.dc0cdfac.svg"
},
{
"revision": "ff208b8d733e61a630992ee2b72c9c1c",
"url": "/fonts/nucleo-icons.ff208b8d.woff2"
},
{
"revision": "43b98081492ac3bcb4a1fac6cf709403",
"url": "/img/faces/tim_vector.jpe"
},
{
"revision": "a9615bac158705203261e8348f574cc8",
"url": "/img/default-avatar.png"
},
{
"revision": "bf1684a30a86ba1b222aab3acff16356",
"url": "/img/faces/face-7.jpg"
},
{
"revision": "a9615bac158705203261e8348f574cc8",
"url": "/img/faces/face-0.jpg"
},
{
"revision": "912ec66d7572ff821749319396470bde",
"url": "/img/fontawesome-webfont.912ec66d.svg"
},
{
"revision": "4b87e628f4ef9988718860890b2a682f",
"url": "/img/faces/face-6.jpg"
},
{
"revision": "996d8248f580f8e26e6c45c67da9b5a6",
"url": "/img/favicon.png"
},
{
"revision": "0ec8f86a54dce32152eaa33e932b9c97",
"url": "/img/loading-bubbles.svg"
},
{
"revision": "d27fbc90c2e644dfdc9765640dc713b9",
"url": "/img/mask.png"
},
{
"revision": "f575a04ebbb31b5798a4c54783e745a2",
"url": "/img/new_logo.png"
},
{
"revision": "0b68eb8f1cde1fc9987a9196df05b96a",
"url": "/img/faces/face-4.jpg"
},
{
"revision": "0e953b1ea6d6e3addd7210e9c7c420a7",
"url": "/img/faces/face-2.jpg"
},
{
"revision": "ce7a6b79aa55041f7ae36f6ce22231fe",
"url": "/img/faces/face-3.jpg"
},
{
"revision": "99e58416b89637502b40ac8350eed85a",
"url": "/img/faces/face-1.jpg"
},
{
"revision": "af7ae505a9eed503f8b8e6982036873e",
"url": "/fonts/fontawesome-webfont.af7ae505.woff2"
},
{
"revision": "fee66e712a8a08eef5805a46892932ad",
"url": "/fonts/fontawesome-webfont.fee66e71.woff"
},
{
"revision": "8224e0160e362e117cbe00495919e2af",
"url": "/fonts/nucleo-icons.8224e016.eot"
},
{
"revision": "674f50d287a8c48dc19ba404d20fe713",
"url": "/fonts/fontawesome-webfont.674f50d2.eot"
},
{
"revision": "732389ded34cb9c52dd88271f1345af9",
"url": "/fonts/element-icons.732389de.ttf"
},
{
"revision": "535877f50039c0cb49a6196a5b7517cd",
"url": "/fonts/element-icons.535877f5.woff"
},
{
"revision": "996d8248f580f8e26e6c45c67da9b5a6",
"url": "/favicon.png"
},
{
"revision": "15e709362b6ae1025fa0",
"url": "/css/chunk-vendors.e1f3b964.css"
},
{
"revision": "8f293614be4e9c63fba0",
"url": "/css/app.7967d5c5.css"
},
{
"revision": "be74132f42ae1d3502f9a9b9fff68ac1",
"url": "/Dashboard.PNG"
},
{
"revision": "d41d8cd98f00b204e9800998ecf8427e",
"url": "/.gitkeep"
}
];
|
import React from 'react'
import identity from 'ramda/src/identity'
const Td = ({ cellData, transformer = identity }) => (
<td>{transformer(cellData)}</td>
)
export default Td
|
../../../../../shared/src/generic/PornstarList/index.js
|
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { compose } from 'redux';
import get from 'lodash.get';
import { Form, Button, Input, Select, message } from 'antd';
import formStyle from '../../antdTheme/form/style/index.less';
import buttonStyle from '../../antdTheme/button/style/index.less';
import inputStyle from '../../antdTheme/input/style/index.less';
import selectStyle from '../../antdTheme/select/style/index.less';
import tableStyle from '../../antdTheme/table/style/index.less';
import paginationStyle from '../../antdTheme/pagination/style/index.less';
import uploadStyle from '../../antdTheme/upload/style/index.less';
import messageStyle from '../../antdTheme/message/style/index.less'; // eslint-disable-line
import Query from '../../components/Query';
import { connect } from '../../store/redux';
import { commonReducer } from '../../store/common.reducer';
import { commonAction } from '../../store/common.action';
import s from './createNew.css';
const StateName = 'CreateNew';
const FormItem = Form.Item;
const { Option } = Select;
const defaultState = {
importBulk: 0,
table: {
current: 1,
pageSize: 10,
},
cityCodeValue: '320100',
cityCodeName: '南京市',
};
// 操作栏
class CreateNew extends React.Component {
// 触发标签事件的函数声明
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields(async (err, values) => {
if (!err) {
console.log('Received values of form: ', values);
this.props.commonAction({
userData: values,
});
const dataQuery = values;
let result;
try {
result = await this.saveQueryFun.fetch({
data: dataQuery,
});
} catch (e) {
message.error('保存失败!', 1);
}
// 新增单位
if (result) {
if (get(result, 'code', '') === 200) {
if (get(result, 'data.resultcode', '') === '0') {
message.success('保存成功', 1);
const questData = {
pageSize: this.props.table.pageSize || 10,
pageNum: this.props.table.current || 1,
};
this.props.query.fetch({ data: questData });
const actionOpts = {
type: `procurementAccount.drawer`,
isGlobal: true,
};
this.props.commonAction({ visible: false }, actionOpts);
} else {
message.error(get(result, 'data.msg', '保存失败!'));
}
} else {
message.error('保存失败!', 1);
}
}
}
});
};
handleSelectChange = value => {
console.log(value);
this.props.form.setFieldsValue({
note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
});
};
// 检测账号
testAccount = () => {
this.props.form.validateFields(['unitNo'], {}, (errors, values) => {
if (!errors) {
const dataQuery = values;
this.props.commonAction({
userData: dataQuery,
});
// 调用检测账号接口
this.testAccountQuery
.fetch({
data: dataQuery,
})
.then(result => {
if (result.code !== 200) {
message.error(result.message, 1);
}
});
}
});
};
// 检测
testFun = () => {
this.props.form.validateFields(['buName'], {}, (errors, values) => {
if (!errors) {
const dataQuery = values;
this.props.commonAction({
userData: dataQuery,
});
this.testQuery
.fetch({
data: dataQuery,
})
.then(result => {
if (result.code !== 200) {
message.error(result.message, 1);
}
});
}
});
};
// 返回列表
returnList = () => {
const actionOpts = { type: `procurementAccount.drawer`, isGlobal: true };
this.props.commonAction({ visible: false }, actionOpts);
};
selectChange = value => {
const cityData = get(this.props.cityData, 'data.data') || [];
if (value !== 4) {
for (const item of cityData) {
if (value === item.locationId) {
this.props.commonAction({
cityCodeValue: item.locationCode,
cityCodeName: item.locationName,
});
this.props.form.setFieldsValue({
city: item.locationCode,
county: '0',
});
this.countySelect.fetch({
data: {
code: item.locationCode,
},
});
}
}
} else if (value === 4) {
this.props.commonAction({
cityCodeValue: '',
cityCodeName: '',
});
this.props.form.setFieldsValue({
city: '',
county: '0',
});
this.countySelect.fetch({
data: {
code: '4',
},
});
}
};
render() {
const { getFieldDecorator } = this.props.form;
const {
testData,
testNameData,
optionList,
cityCodeValue,
cityCodeName,
} = this.props;
const countyDataTrue = get(this.props.countyData, 'data.data') || [];
const testDataMsg = JSON.parse(get(testData, 'data.message', '{}') || '{}');
const testNameDataMsg = JSON.parse(
get(testNameData, 'data.message', '{}') || '{}',
);
return (
<Form onSubmit={this.handleSubmit} className={s.createContentL}>
<Query
onRef={query => {
this.testAccountQuery = query;
}}
auto={false}
method="get"
statePath={`${StateName}.testData`}
url="{apiUrl}/op/v1/buyers/chkUnitNo"
/>
{/* 检测单位名称 */}
<Query
onRef={query => {
this.testQuery = query;
}}
auto={false}
method="post"
statePath={`${StateName}.testNameData`}
url="{apiUrl}/op/v1/buyers/checkBuHasReg"
/>
{/* 所属区域市级 */}
<Query
onRef={query => {
this.citySelect = query;
}}
method="get"
statePath={`${StateName}.cityData`}
url="{apiUrl}/op/v1/buyers/selCityByCode"
/>
{/* 所属区域区级 */}
<Query
onRef={query => {
this.countySelect = query;
}}
data={{
code: '320100',
}}
method="get"
statePath={`${StateName}.countyData`}
url="{apiUrl}/op/v1/buyers/selCountyByCode"
/>
{/* 保存添加 */}
<Query
onRef={query => {
this.saveQueryFun = query;
}}
auto={false}
method="post"
statePath={`${StateName}.saveQuery`}
url="{apiUrl}/op/v1/buyers/accountSave"
/>
<div className="detail-container">
<table className="edit-table" style={{ width: '100%' }}>
<tbody>
<tr>
<td className="required label" style={{ width: 109 }}>
登陆账号:
</td>
<td colSpan={3}>
<FormItem>
{getFieldDecorator('unitNo', {
rules: [
{ required: true, message: '请填写预算单位编码' },
],
})(
<Input
style={{ width: 400 }}
placeholder="请输入登录账号"
/>,
)}
</FormItem>
<Button type="primary" onClick={this.testAccount}>
检测账号
</Button>
{get(testData, 'data.code', '') === 200 && (
<p
className={`${s.redHint} ${
testDataMsg.resultcode !== '0' ? s.alert : ''
}`}
>
{testDataMsg.msg}
</p>
)}
</td>
</tr>
<tr>
<td />
<td colSpan={3}>
<p className={s.extra}>
账号由省份简称(江苏-js)+ 行政区号( 南京市-雨花区-320114
)财政预算管理系统-预算单位编码 (998333024) 组成。
</p>
</td>
</tr>
<tr>
<td className="required label">单位名称:</td>
<td colSpan={3}>
<FormItem>
{getFieldDecorator('buName', {
rules: [{ required: true, message: '请填写单位名称' }],
})(
<Input
style={{ width: 400 }}
placeholder="请输入单位名称"
/>,
)}
</FormItem>
<Button type="primary" onClick={this.testFun}>
检测
</Button>
{get(testNameData, 'data.code', '') === 200 && (
<p
className={`${s.redHint} ${
testNameDataMsg.resultcode !== '200' ? s.alert : ''
}`}
>
{testNameDataMsg.msg}
</p>
)}
</td>
</tr>
<tr>
<td className="label">社会信用代码:</td>
<td colSpan={3}>
<FormItem>
{getFieldDecorator('buLicenseId', {
rules: [{ required: false }],
initialValue: '',
})(
<Input
style={{ width: 400 }}
placeholder="请输入社会信用代码"
/>,
)}
</FormItem>
</td>
</tr>
<tr>
<td className="required label" style={{ width: 70 }}>
联系人:
</td>
<td style={{ width: 250 }}>
<FormItem>
{getFieldDecorator('contractName', {
rules: [{ required: true, message: '请填写联系人' }],
})(
<Input
style={{ width: 180 }}
placeholder="请输入联系人"
/>,
)}
</FormItem>
</td>
<td className="label" style={{ width: 109 }}>
联系人手机号:
</td>
<td>
<FormItem>
{getFieldDecorator('contractPhone', {
initialValue: '',
rules: [
{ required: false },
{ pattern: /^1\d{10}$/, message: '手机号格式不正确' },
],
})(
<Input
type="phone"
style={{ width: 180 }}
placeholder="请输入联系人手机号"
/>,
)}
</FormItem>
</td>
</tr>
<tr>
<td className="label">邮箱:</td>
<td>
<FormItem>
{getFieldDecorator('contractEmail', {
initialValue: '',
rules: [
{ required: false },
{
pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
message: '邮箱格式不正确',
},
],
})(
<Input style={{ width: 180 }} placeholder="请输入邮箱" />,
)}
</FormItem>
</td>
<td className="required label">所属云集:</td>
<td>
<FormItem>
{getFieldDecorator('guzhu', {
rules: [{ required: true, message: '请选择所属云集' }],
initialValue: 1,
})(
<Select
style={{ width: 180 }}
onChange={this.selectChange}
>
{optionList}
</Select>,
)}
</FormItem>
</td>
</tr>
<tr>
<td className="label">所属地域:</td>
<td colSpan={3}>
<FormItem>
{getFieldDecorator('city', {
initialValue: '320100',
})(
<Select style={{ width: 180 }}>
<Option value={cityCodeValue}>{cityCodeName}</Option>
</Select>,
)}
</FormItem>
<FormItem>
{getFieldDecorator('county', {
initialValue: '0',
})(
<Select style={{ width: 180, marginLeft: 25 }}>
<Option key="county_1" value="0">
--请选择--
</Option>
{countyDataTrue.length > 0 &&
countyDataTrue.map(item => (
<Option
key={`county_${item.locationCode}`}
value={item.locationCode}
>
{item.locationName}
</Option>
))}
</Select>,
)}
</FormItem>
</td>
</tr>
</tbody>
</table>
<Button type="primary" htmlType="submit" size="large">
保存
</Button>
<span className={s.returnListClass} onClick={this.returnList}>
返回列表
</span>
</div>
</Form>
);
}
}
const WrappedCreateNew = Form.create()(CreateNew);
const mapState = state => ({
...state[StateName],
});
const mapDispatch = {
commonAction: commonAction(StateName),
};
export default compose(
withStyles(
s,
formStyle,
buttonStyle,
inputStyle,
selectStyle,
paginationStyle,
uploadStyle,
tableStyle,
messageStyle,
),
connect(
StateName,
commonReducer(StateName, defaultState),
mapState,
mapDispatch,
),
Form.create(),
)(WrappedCreateNew);
|
'use strict';
describe('BasicSelector Test Self', function() {
it('basic attribute', function() {
browser.get('test/e2e/testee/basic_selector/web/self.html')
.then(function(){
browser.waitForAngular();
browser.sleep(2000);
});
var list = element.all(by.css('.demo1 .selector>li'));
expect(list.count()).toBe(6);
expect(list.get(0).getText()).toBe("南京");
var values = ["南京","苏州","南通","泰州","上海","广州"];
list.each(function(item,index){
item.getText().then(function(text){
expect(text).toBe(values[index]);
});
});
expect(list.get(0).getCssValue("float")).toBe("left");
});
it('test least',function(){
var list=element.all(by.css('.demo1 .selector .selected-item'));
expect(list.count()).toBe(2);//当前选中2项
element(by.css(".least")).sendKeys("3",protractor.Key.ENTER);
expect(list.count()).toBe(3);//设置选中最小值3,此时选中项为3个
});
it('test add',function(){
var list=element.all(by.css('.demo1 .selector>li'));
// var obj=element(by.css('.demo1 .selector div i'));
expect(list.count()).toBe(6);//添加前6个备选项
element(by.css('.demo1 .selector div i')).click();
browser.sleep(2000);
element(by.css('.demo1 .selector div input')).sendKeys("天津",protractor.Key.ENTER);
expect(list.count()).toBe(7);//添加后 7个备选项
});
it('test 正则属性 错误输入',function(){
var list=element.all(by.css('.demo1 .selector>li'));
expect(list.count()).toBe(7);
element(by.css(".getReg")).sendKeys("^[1-9]{1,3}$",protractor.Key.ENTER);//设置正则规则
element(by.css(".option .restrict")).click();//开启正则
element(by.css('.demo1 .selector div i')).click();//点击添加按钮
element(by.css('.demo1 .selector div input')).sendKeys("a",protractor.Key.ENTER);//输入内容
expect(list.count()).toBe(7);
});
it('test 正则属性 正确输入',function(){
var list=element.all(by.css('.demo1 .selector>li'));
expect(list.count()).toBe(7);
element(by.css(".getReg")).sendKeys("^[1-9]{1,3}$",protractor.Key.ENTER);//设置正则规则
element(by.css(".option .restrict")).click();//开启正则
element(by.css('.demo1 .selector div i')).click();//点击添加按钮
element(by.css('.demo1 .selector div input')).sendKeys("233",protractor.Key.ENTER);//输入内容
expect(list.count()).toBe(8);
});
it('test search',function(){
var searchInput=element.all(by.css('.demo1 .search input'));
var list = element.all(by.css('.demo1 .selector>li'));
expect(searchInput.count()).toBe(1);
element(by.css(".option .search")).click();//使用搜索功能
element(by.css('.demo1 .search input')).sendKeys("南");
expect(list.count()).toBe(2);//根据关键字 搜索2项结果
});
it('test select event',function(){
browser.get('test/e2e/testee/basic_selector/web/self.html')
.then(function(){
browser.waitForAngular();
browser.sleep(2000);
});
var list=element.all(by.css(".demo1 .selector>li"));
expect(list.count()).toBe(6);
list.each(function(item,index){
item.click();
});
});
it('test multiple',function(){
var sellist=element.all(by.css('.demo1 .selector .selected-item'));
var list= element.all(by.css('.demo1 .selector>li'));
expect(sellist.count()).toBe(4);
element(by.css(".option .multiple")).click();//单选
expect(sellist.count()).toBe(1);
sellist.click();//均未选择的状态
list.each(function(item,index){
item.click();
//每次点击都会验证选中项数量(label 在base中已经验证)
expect(sellist.count()).toBe(1);
});
});
it('test label-field',function(){
var list=element.all(by.css('.demo1 .selector>li'));
expect(list.get(0).getText()).toBe("南京");
element(by.css(".option .labelToId")).click();
var ids=['0','1','2','3','4','5'];
list.each(function(item,index){
item.getText().then(function(text){
expect(text).toBe(ids[index]);
});
});
});
it('设置editable 为 false,则dom无 添加按钮',function(){
element(by.css(".option .editable")).click();
var sect=element(by.css(".demo1 .selector .ng-hide"));
expect(sect.getCssValue("display")).toBe("none");
});
it("test demo2",function(){
var list=element.all(by.css(".demo2 .selector>li"));
expect(list.count()).toBe(6);
list.each(function(item,index){
item.click();
});
expect(element(by.css(".test-ds span")).getText()).toBe("广州");
});
});
|
import React from 'react';
import Article from './Article';
function Content(props) {
return props.articlesList.map(item => (
<Article
key = {item.id}
title = {item.title}
text = {item.text}
/>
)
);
}
export default Content;
|
/*
* Toady
* Copyright (c) 2013 Tom Frost
*/
// Dependencies
var config = require('config');
var irc = require('irc');
var client = new irc.Client(
config.server.host,
config.identity.nick,
{
userName: config.identity.user,
realName: config.identity.name,
port: config.server.port || 6667,
password: config.server.password || null,
debug: true,
showErrors: true,
autoRejoin: true,
autoConnect: false,
channels: config.server.channels || [],
secure: config.server.ssl || false,
selfSigned: true,
certExpired: true,
floodProtection: !!config.server.floodDelay,
floodProtectionDelay: config.server.floodDelay,
stripColors: true,
channelPrefixes: '&#',
messageSplit: config.server.messageLength || 512
});
module.exports = client;
|
/**
* use fast-json-stringify accelerate JSON serialization
*/
const fastJson = require('fast-json-stringify')
const obj = {
name: 'levin',
age: 26,
city: 'shenzhen',
skill: ['java', 'javascript']
}
console.time('json')
for (let i = 0; i < 1000000; i++) {
JSON.stringify(obj)
}
console.timeEnd('json')
const stringify = fastJson({
title: 'Example Schema',
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' },
city: { type: 'string' },
skill: {
type: 'array',
items: {
type: 'string',
uniqueItems: true
}
}
}
})
console.time('fastjson')
for (let i = 0; i < 1000000; i++) {
stringify(obj)
}
console.timeEnd('fastjson')
|
( function( angular ) {
'use strict';
/**
MIT Licensed.
Copyright (c) 2011 Andy Hume (http://andyhume.net, andyhume@gmail.com).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software''), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var win = window;
var doc = win.document;
var compareFunction = {
'min-width': function( a, b ) {
return a > b;
},
'max-width': function( a, b ) {
return a < b;
}
};
function memoize ( f ) {
return function() {
var args = Array.prototype.slice.call( arguments );
f.memoize = f.memoize || {};
return ( args in f.memoize ) ?
f.memoize[ args ] :
f.memoize[ args ] = f.apply( this, args );
};
}
var emsToPixels = memoize( function( em, scope ) {
var test = doc.createElement( 'div' );
test.style.fontSize = '1em';
test.style.margin = '0';
test.style.padding = '0';
test.style.border = 'none';
test.style.width = '1em';
scope.appendChild( test );
var val = test.offsetWidth;
scope.removeChild( test );
return Math.round( val * em );
} );
function getDefaultWidth ( el, className ) {
var test = el.cloneNode( true );
test.className = ( ' ' + test.className + ' ' ).replace( ' ' + className + ' ', ' ' );
test.style.height = 0;
test.style.visibility = 'hidden';
test.style.overflow = 'hidden';
test.style.clear = 'both';
var parent = el.parentNode;
parent.insertBefore( test, el );
var val = test.offsetWidth;
parent.removeChild( test );
return val;
}
function ngSelectorQueries () {
function extractRules ( value ) {
var rule = /(.*):([0-9]*)(px|em)=(.*)/.exec( value );
return rule;
}
function getUnit ( value ) {
var split = /px|em/.exec( value );
return split[ 0 ];
}
function applyRules ( el, minWidth, maxWidth, className, unit ) {
var dimension = minWidth || maxWidth;
var ruleName = minWidth ? 'min-width' : 'max-width';
dimension = dimension.split( unit )[ 0 ];
// Get a target width value in pixels.
var width = parseInt( dimension );
if ( unit === 'em' ) {
width = emsToPixels( parseFloat( dimension ), el );
}
// Calculate the width of the target without the class added.
var defaultWidth = getDefaultWidth( el, className );
// Test current width against target width and add/remove class values.
if ( compareFunction[ ruleName ]( defaultWidth, width ) ) {
if ( el.className.indexOf( className ) < 0 ) {
el.className += ' ' + className;
}
} else {
var clsName = el.className
.replace( new RegExp( '(^| )' + className + '( |$)' ), '$1' );
clsName = clsName.replace( / $/, '' );
el.className = clsName;
}
}
function selectorQueriesInit ( /*element, minWidth, maxWidth, className, unit*/ ) {
var args = arguments;
applyRules.apply( null, args );
if ( win.addEventListener ) {
win.addEventListener( 'resize', function onResize() {
return applyRules.apply( null, args );
}, false );
}
// Allow for resizing text after the page has loaded.
var currentEm = emsToPixels( 1, doc.body );
win.setInterval( function() {
var newEm = emsToPixels( 1, doc.body );
if ( newEm !== currentEm ) {
applyRules.apply( null, args );
currentEm = newEm;
}
}, 100 );
}
function link ( scope, element, attrs ) {
var minWidth = attrs.ngSqMinWidth;
var maxWidth = attrs.ngSqMaxWidth;
var className = attrs.ngSqClass;
var unit;
var argsRegistry = [];
var querySplit;
function rulesIterator( key, callback ) {
var query = querySplit[ key ];
var rules = extractRules( query );
var ruleArgs = {};
ruleArgs.minWidth = rules[ 1 ] === 'min-width' ? rules[ 2 ] : undefined;
ruleArgs.maxWidth = rules[ 1 ] === 'max-width' ? rules[ 2 ] : undefined;
ruleArgs.className = rules[ 4 ];
ruleArgs.unit = rules[ 3 ];
if ( typeof callback === 'function' ) {
callback( element[ 0 ],
ruleArgs.minWidth,
ruleArgs.maxWidth,
ruleArgs.className,
ruleArgs.unit );
}
argsRegistry.push( ruleArgs );
}
// Classical style or multiple args
if ( !!attrs.ngSq ) {
querySplit = attrs.ngSq.split( ' ' );
querySplit.forEach( function iterator( value, key ) {
rulesIterator( key, selectorQueriesInit );
} );
} else {
unit = getUnit( minWidth || maxWidth );
selectorQueriesInit( element[ 0 ], minWidth, maxWidth, className, unit );
}
scope.$on( '$destroy', function onDestroy() {
if ( argsRegistry.length ) {
argsRegistry.forEach( function( value ) {
win.removeEventListener( 'resize', function onResize() {
return applyRules( element[ 0 ],
value.minWidth,
value.maxWidth,
value.className,
value.unit );
} );
} );
} else {
win.removeEventListener( 'resize', function onResize() {
return applyRules( element[ 0 ], minWidth, maxWidth, className, unit );
} );
}
} );
}
return {
restrict: 'A',
link: link
};
}
angular.module( 'ngSelectorQueries', [] )
.directive( 'ngSq', ngSelectorQueries );
} )( window.angular );
|
function assert(cond, ...args) {
if (!cond) console.log(...args);
}
if (!ArrayBuffer.transfer) {
ArrayBuffer.transfer = function(source, length) {
if (!(source instanceof ArrayBuffer))
throw new TypeError('Source must be an instance of ArrayBuffer');
if (length <= source.byteLength)
return source.slice(0, length);
var sourceView = new Uint8Array(source),
destView = new Uint8Array(new ArrayBuffer(length));
destView.set(sourceView);
return destView.buffer;
};
}
/**
* Creates a new Uint8Array based on two different ArrayBuffers
*
* @private
* @param {ArrayBuffers} buffer1 The first buffer.
* @param {ArrayBuffers} buffer2 The second buffer.
* @return {ArrayBuffers} The new ArrayBuffer created out of the two.
*/
if (!Uint8Array.append) {
Uint8Array.append = function(buffer1, buffer2) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp;
};
}
export function encodeNetMsg(msg, addedHeader, msgStructure) {
addedHeader = new Uint8Array(addedHeader);
function enm(msg, msgStructure) {
if (msgStructure.type=="array") {
assert(msg.length<=255);
let len = msg.length;
let msgData = new Uint8Array(0);
for (let val of msg) {
msgData = Uint8Array.append(msgData, enm(val,msgStructure.content));
}
if (msgStructure.length==="dynamic") {
let ne = new Uint8Array(msgData.byteLength+1);
ne.set(msgData,1);
ne[0] = len;
msgData = ne;
}
else {
assert(len == msgStructure.length);
}
return msgData;
}
else if (msgStructure.type=="object") {
let msgData =new Uint8Array();
for (let msgStruct of msgStructure.values){
let val = msg[msgStruct.name];
msgData = Uint8Array.append(msgData,enm(val,msgStruct));
}
return msgData;
}
else {
let msgData;
if (msgStructure.type=="ubyte") {
assert(msg<256&&msg>=0);
assert(msg%1==0);
msgData = new Uint8Array(1);
msgData[0] = msg;
}
else if (msgStructure.type=="ushort") {
assert(msg<256&&msg>=0);
assert(msg%1==0);
msgData = new Uint16Array(1);
msgData[0] = msg;
msgData = msgData.buffer;
}
else if (msgStructure.type=="float") {
assert(msg<256&&msg>=0);
msgData = new Float32Array(1);
msgData[0] = msg;
msgData = msgData.buffer;
}
return msgData;
}
}
let msgBody = enm(msg, msgStructure);
let msgLen = (1+addedHeader.length+msgBody.length);
assert(msgLen<256);
let msgData = new Uint8Array(msgLen);
msgData[0] = msgLen;
msgData.set(addedHeader,1);
msgData.set(msgBody,1+addedHeader.length);
return msgData;
}
export function decodeNetMsg(msgData, addedHeader, msgStructure) {
function dnm(msgData,msgStructure) {
var d = dnm;
var offset = 0;
if (msgStructure.type=="array") {
let len;
if (msgStructure.length==="dynamic") {
len = msgData[0];
offset++;
}
else {
len = msgStructure.length;
}
let msg = [];
for (var val=0;val<len;val++) {
let body,used;
let rd = dnm(msgData.slice(offset), msgStructure.content);
body = rd.msg;
used = rd.offset;
msg.push(body);
offset+=used;
}
return {msg:msg,offset:offset};
}
else if (msgStructure.type=="object") {
let msg = {};
for (let val of msgStructure.values){
let body,used;
let rd = dnm(msgData.slice(offset), val);
body = rd.msg;
used = rd.offset;
msg[val.name] = body;
offset+=used;
}
return {msg:msg,offset:offset};
}
else {
if (msgStructure.type=="ubyte") {
return {msg:msgData[0],offset:1};
}
else if (msgStructure.type=="ushort") {
return {offset:2,msg:(new Uint16Array(msgData.buffer.slice(0,2)))[0]};
}
else if (msgStructure.type=="float") {
return {offset:4,msg:(new Float32Array(msgData.buffer.slice(0,4)))[0]};
}
}
}
assert(msgData.slice(1,addedHeader.length)==addedHeader);
dnm(msgData.slice(1+addedHeader.length), msgStructure);
let msg,used;
let rd = dnm(msgData.slice(1+addedHeader.length), msgStructure);
msg = rd.msg;
used = rd.offset;
assert(used+1+addedHeader.length==msgData.length);
return msg;
}
/**
Sample msgStructure
var msgStructure = {
type:"object",
values:[{type:"array",name:"components",length:"dynamic",content:{type:"ubyte"}}],
}
*/
|
import { makeStyles } from "@material-ui/core";
import { useGoogleAuthLogin } from "../../fooks/useGoogleAuthLogin";
export const GoogleAuth = () => {
const login=useGoogleAuthLogin()
const classes = useStyles();
return (
<>
<img
onClick={() => {
login();
}}
src="https://developers.google.com/identity/images/btn_google_signin_dark_normal_web.png?hl=ja"
alt="Googleからログイン"
className={classes.img}
/>
</>
);
};
const useStyles = makeStyles((theme) => ({
img: {
marginTop: 20,
},
}));
|
$(document).ready(function() {
var height = $('.navbar-header').height();
$('#start-content').css('margin-top', height);
});
var firebaseConfig = {
apiKey: "AIzaSyAuPuaJCP08o5JKW09F1XUWAy5GIiJ_cf8",
authDomain: "link-save-d79c8.firebaseapp.com",
databaseURL: "https://link-save-d79c8-default-rtdb.firebaseio.com",
projectId: "link-save-d79c8",
storageBucket: "link-save-d79c8.appspot.com",
messagingSenderId: "567380847437",
appId: "1:567380847437:web:eaca395ec37919f2f8a504",
measurementId: "G-RWXYFREXB0"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var user_ID = '';
//invokes firebase authentication.
const auth = firebase.auth();
document.querySelector("#show-register").addEventListener("click", () => {
showRegistration();
});
const showRegistration = () => {
document.querySelector("#registration-page").classList.remove("hide");
document.querySelector("#login-page").classList.add("hide");
document.querySelector("#homepage").classList.add("hide");
// document.querySelector(".show-signout").classList.add("hide");
$('.show-signout').hide()
};
document.querySelector("#show-login").addEventListener("click", () => {
showLogin();
});
const showLogin = () => {
document.querySelector("#registration-page").classList.add("hide");
document.querySelector("#login-page").classList.remove("hide");
document.querySelector("#homepage").classList.add("hide");
// document.querySelector(".show-signout").classList.add("hide");
$('.show-signout').hide()
};
document.querySelector(".signout").addEventListener("click", () => {
signOut();
});
const register = () => {
const email = document.querySelector("#registration-email").value;
const reemail = document.querySelector("#registration-reemail").value;
const password = document.querySelector("#registration-password").value;
if (email.trim() == "") {
alert("Enter Email");
} else if (password.trim().length < 7) {
alert("Password must be at least 7 characters");
} else if (email != reemail) {
alert("emails do not match");
} else {
auth
.createUserWithEmailAndPassword(email, password)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
// ...
});
}
};
document.querySelector("#register").addEventListener("click", () => {
register();
});
//register when you hit the enter key
document
.querySelector("#registration-password")
.addEventListener("keyup", (e) => {
if (event.keyCode === 13) {
e.preventDefault();
register();
}
});
const login = () => {
const email = document.querySelector("#login-email").value;
const password = document.querySelector("#login-password").value;
if (email.trim() == "") {
alert("Enter Email");
} else if (password.trim() == "") {
alert("Enter Password");
} else {
authenticate(email, password);
}
};
document.querySelector("#login").addEventListener("click", () => {
login();
});
//sign in when you hit enter
document
.querySelector("#login-password")
.addEventListener("keyup", (e) => {
if (event.keyCode === 13) {
e.preventDefault();
login();
}
});
const authenticate = (email, password) => {
const auth = firebase.auth();
auth.signInWithEmailAndPassword(email, password);
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
});
};
const showHomepage = () => {
document.querySelector("#registration-page").classList.add("hide");
document.querySelector("#login-page").classList.add("hide");
document.querySelector("#homepage").classList.remove("hide");
// document.querySelector(".show-signout").classList.remove("hide");
$('.show-signout').show()
};
const signOut = () => {
firebase
.auth()
.signOut()
.then(function() {
location.reload();
})
.catch(function(error) {
alert("error signing out, check network connection");
});
};
auth.onAuthStateChanged((firebaseUser) => {
if (firebaseUser) {
showHomepage();
user_ID = firebaseUser.uid
$('#email_login').html(firebaseUser.email)
loadData()
}
});
document
.querySelector("#forgot-password")
.addEventListener("click", () => {
const email = document.querySelector("#login-email").value;
if (email.trim() == "") {
alert("Enter Email");
} else {
forgotPassword(email);
}
});
const forgotPassword = (email) => {
auth
.sendPasswordResetEmail(email)
.then(function() {
alert("email sent");
})
.catch(function(error) {
alert("invalid email or bad network connection");
});
};
// Ready to function
// var config = {
// apiKey: "AIzaSyAuPuaJCP08o5JKW09F1XUWAy5GIiJ_cf8",
// authDomain: "link-save-d79c8.firebaseapp.com",
// databaseURL: "https://link-save-d79c8-default-rtdb.firebaseio.com",
// projectId: "link-save-d79c8",
// storageBucket: "link-save-d79c8.appspot.com",
// messagingSenderId: "567380847437",
// appId: "1:567380847437:web:eaca395ec37919f2f8a504",
// measurementId: "G-RWXYFREXB0"
// };
// firebase.initializeApp(config);
//create firebase database reference
var dbRef = firebase.database();
var contactsRef = dbRef.ref('contacts');;
function loadData() {
//load older conatcts as well as any newly added one...
contactsRef.orderByChild('userId').equalTo(user_ID).on("child_added", function(snap) {
console.log("added", snap.key, snap.val());
$('#contacts').append(contactHtmlFromObject(snap.val()));
});
}
//save contact
$('.addValue').on("click", function(event) {
event.preventDefault();
if ($('#name').val() != '' || $('#email').val() != '') {
contactsRef.push({
name: $('#name').val().replace(/<[^>]*>/ig, ""),
email: $('#email').val().replace(/<[^>]*>/ig, ""),
location: {
city: $('#city').val().replace(/<[^>]*>/ig, ""),
state: $('#state').val().replace(/<[^>]*>/ig, ""),
zip: $('#zip').val().replace(/<[^>]*>/ig, "")
},
time: new Date().getTime(),
userId: user_ID
})
contactForm.reset();
} else {
alert('Please fill atlease name or email!');
}
});
//prepare conatct object's HTML
function contactHtmlFromObject(contact) {
console.log(contact);
var html = '';
html += '<li class="list-group-item contact">';
html += '<div>';
if (contact.name != '') {
html += '<p class="lead">' + contact.name + '</p>';
}
html += '<p><a href="' + contact.email + '" target="_blank">' + contact.email + '</a></p>';
if (contact.location.city != '') {
html += '<p><small title="' + contact.location.zip + '">' + contact.location.city + ', ' + contact.location.state + '</small></p>';
}
if (contact.time != undefined) {
var d = new Date(contact.time);
html += '<p>' + d.toLocaleString() + '</p>';
}
html += '</div>';
html += '</li>';
return html;
}
|
const mongoose = require("mongoose");
// Function to connect MongoDB, And 1st parameter is pass the URL for the Database
// single call back function - err to ensure connectivity status
mongoose.connect(
"mongodb://localhost:27017/PhDstudentDB",
{ useNewUrlParser: true },
err => {
if (!err) {
console.log("MongoDB connected Succeeded.");
} else {
console.log("Error in DB connection : " + err);
}
}
);
require("./school.model");
require("./department.model");
require("./teacher.model");
require("./school_Department.model");
require("./student.model");
require("./studentHome.model");
require("./studentLogin.model");
require("./studentAuth.model");
require("./studentReport.model");
require("./studentReport.model");
require("./studentSupervisior.model");
require("./teacherAuth.model");
require("./teacherLogin.model");
require("./researchCommittee.model");
require("./drcCrc.model");
require("./doctoralCommittee.model");
require("./bet.model");
require("./adminAuth.model");
require("./adminLogin.model");
require("./studentFilter.model");
require("./studentFilterType.model");
require("./studentFilterSem.model");
|
import React from 'react'
import CVCard from '../components/CVCard'
import CVCompetenceCard from '../components/CVCompetenceCard'
import '../style/CVStyle.css'
const CV = () => {
return (
<div className="CV">
<div className="content">
<h1>Curriculum Vitae</h1>
<CVCompetenceCard />
<h2>Employments</h2>
<CVCard date="08 / 2021 - 07 / 2022" position="Technical Student" employer="CERN" location="Geneva">
<p>Building set of components and APIs for integrating ML pipelines with the Monitoring Service. Its goal is providing unified platform where data scientists can focus on building and training their anomaly detection monitoring algorithms.</p>
</CVCard>
<CVCard date="04 / 2019 - 03 / 2020" position="Working Student" employer="Sovanta AG" location="Heidelberg">
<p>Working student at sovanta AG in the Data Lab/AI department in Heidelberg, Germany. Projects where focused on NLU and Chatbot technology with Rasa and Tensorflow.</p>
</CVCard>
<CVCard date="09 / 2018 - 02 / 2019" position="Internship" employer="SNP Business Landscape Management GmbH" location="Heidelberg">
<p>Internship at SNP Business Landscape Management GmbH in Heidelberg, Germany. Subject of my work was email classification within the SAP Solution Manager with the SAP HANA database.</p>
</CVCard>
<CVCard date="Summer 2018" position="Freelancer" employer="GC Solution GmbH" location="Speyer and Barcelona">
<p>Freelancer as web developer at GC Solution GmbH in Speyer, Germany and Barcelona, Spain. My work involved project architecture, frontend as well as backend development.</p>
</CVCard>
<h2>Scholarships</h2>
<CVCard date="09 / 2020 - 08 / 2021" employer="Karlsruhe University of Applied Sciences in cooperation with Vector GmbH">
<p>Scholarship program to support the leading students of the Karlsruhe University of Applied Sciences.</p>
</CVCard>
<h2>Education</h2>
<CVCard date="Since 03 / 2020" position="Master of Science in CS" employer="Karlsruhe University of Applied Sciences">
<p><b>Current Grade: 1.3</b>*</p>
<p>Relevant courses:</p>
<ul>
<li>Artificial Intelligence (1.0)</li>
<li>Machine Learning (1.3)</li>
<li>Business English C1 (1.0)</li>
</ul>
</CVCard>
<CVCard date="09 / 2016 - 02 / 2020" position="Bachelor of Science in CS" employer="Mannheim University of Applied Sciences">
<p><b>Final Grade: 1.4</b></p>
<p>Relevant courses:</p>
<ul>
<li>Scientific Computing (1.0)</li>
<li>AI for Autonomous Systems (1.3)</li>
<li>Image Processing (1.0)</li>
</ul>
<p>Bachelor´s thesis: Evaluation of On-Device Training of neural networks</p>
</CVCard>
<CVCard date="09 / 2008 - 08 / 2013" position="Member of Hector Seminar" location="Mannheim">
<p>Member of Hector Seminar in Mannheim, a seminar to support students with special talents in science</p>
</CVCard>
<CVCard date="09 / 2006 - 06 / 2015" position="Abitur" employer="Hebel-Gymnasium Schwetzingen">
<p><b>Final Grade: 2.1</b></p>
<p>Relevant subjects in the final exam:</p>
<ul>
<li>Math (0.7)</li>
<li>Physics (1.0)</li>
</ul>
</CVCard>
<p>*Grades: 1.0-1.5 very good, 1.6-2.5 good, 2.6-3.5 satisfactory, 3.6-4.0 sufficient</p>
</div>
</div>
)
}
export default CV
|
import React from 'react'
import {Bar} from 'react-chartjs-2'
import 'chartjs-plugin-annotation'
import TableItems from './tableItems'
const Chart = (props) => {
const dataUnsorted = props.selectedGraph.set;
const nombrePrueba = props.selectedGraph.name;
// sort by value
const data = dataUnsorted.sort(function (a, b) {
return a.FECHARESULTADO - b.FECHARESULTADO;
})
const fechaResultado = data.map((e) => {
return e.FECHARESULTADO
});
const resultado = data.map((e) => {
return e.RESULTADO
})
const colorResultado = resultado.map((e) => {
if (e < data[0].INFERIOR) {
return '#FFDE21'
} else if (e > data[0].SUPERIOR) {
return '#D12229'
} else {
return '#016FB9'
}
})
const colorBorde = resultado.map((e) => {
if (e < data[0].INFERIOR) {
return 'rgba(255, 206, 86, 1)'
} else if (e > data[0].SUPERIOR) {
return 'rgba(255,99,132,1)'
} else {
return 'rgba(54, 162, 235, 1)'
}
})
const chartData = {
labels: fechaResultado,
datasets: [{
label: nombrePrueba,
data: resultado,
backgroundColor: colorResultado,
borderColor: colorBorde,
borderWidth: 1
}]
}
const displayTitle = true,
displayLegend = false,
legendPosition = 'right';
const yMin = data[0].INFERIOR,
yMax = data[0].SUPERIOR;
const tableItems = props.selectedGraph.set.map((e) => {
return(
< TableItems key={e.NUMOT}item={e} />
)
})
return(
<div>
<div className="Chart">
<Bar
data={chartData}
width={100}
height={50}
options={{
maintainAspectRatio:true,
title: {
display: displayTitle,
text: 'Histograma',
fontSize: 36
},
legend: {
display: displayLegend,
position: legendPosition
},
events: false,
tooltips:{
enabled: false
},
annotation: {
annotations: [{
type: 'box',
drawTime: 'beforeDatasetsDraw',
id: 'region-1',
mode: "horizontal",
yScaleID: 'y-axis-0',
yMin: yMin,
yMax: yMax,
backgroundColor: 'rgba(200,230,201,0.5)'
}]
},
animation: {
onComplete: function() {
var ctx = this.chart.ctx;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
var chart = this;
var datasets = this.config.data.datasets;
datasets.forEach(function(dataset, i) {
ctx.font = "24px Lobster Two";
ctx.fillStyle = "#4F4C4D";
chart.getDatasetMeta(i).data.forEach(function(p, j) {
ctx.fillText(datasets[i].data[j], p._model.x, p._model.y - 20);
});
});
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}}
/>
</div>
<div>
<table className="table table-bordered table-striped">
<thead>
<tr>
<th>Orden</th>
<th>Fecha</th>
<th>Resultado</th>
<th>Unidad</th>
<th>Referencia</th>
</tr>
</thead>
<tbody>
{tableItems}
</tbody>
</table>
</div>
</div>
)
}
export default Chart;
|
hsalsa20 = function() {};
hsalsa20.ROUNDS = 20;
hsalsa20.rotate = function(u, c)
{
return (u << c) | (u >>> (32 - c));
};
hsalsa20.load_littleendian = function(x, offset)
{
return (parseInt(x[offset])&0xff) |
(((parseInt(x[offset + 1])&0xff)) << 8) |
(((parseInt(x[offset + 2])&0xff)) << 16) |
(((parseInt(x[offset + 3])&0xff)) << 24);
};
hsalsa20.store_littleendian = function(x, offset, u)
{
x[offset] = toByte(u); u >>>= 8;
x[offset + 1] = toByte(u); u >>>= 8;
x[offset + 2] = toByte(u); u >>>= 8;
x[offset + 3] = toByte(u);
};
hsalsa20.crypto_core = function(outv, inv, k, c)
{
var x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
var j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15;
var i;
j0 = x0 = this.load_littleendian(c, 0);
j1 = x1 = this.load_littleendian(k, 0);
j2 = x2 = this.load_littleendian(k, 4);
j3 = x3 = this.load_littleendian(k, 8);
j4 = x4 = this.load_littleendian(k, 12);
j5 = x5 = this.load_littleendian(c, 4);
if (inv != null)
{
j6 = x6 = this.load_littleendian(inv, 0);
j7 = x7 = this.load_littleendian(inv, 4);
j8 = x8 = this.load_littleendian(inv, 8);
j9 = x9 = this.load_littleendian(inv, 12);
}
else
{
j6 = x6 = j7 = x7 = j8 = x8 = j9 = x9 = 0;
}
j10 = x10 = this.load_littleendian(c, 8);
j11 = x11 = this.load_littleendian(k, 16);
j12 = x12 = this.load_littleendian(k, 20);
j13 = x13 = this.load_littleendian(k, 24);
j14 = x14 = this.load_littleendian(k, 28);
j15 = x15 = this.load_littleendian(c, 12);
for (i = this.ROUNDS; i > 0; i -= 2)
{
x4 ^= this.rotate(x0 + x12, 7);
x8 ^= this.rotate(x4 + x0, 9);
x12 ^= this.rotate(x8 + x4, 13);
x0 ^= this.rotate(x12 + x8, 18);
x9 ^= this.rotate(x5 + x1, 7);
x13 ^= this.rotate(x9 + x5, 9);
x1 ^= this.rotate(x13 + x9, 13);
x5 ^= this.rotate(x1 + x13, 18);
x14 ^= this.rotate(x10 + x6, 7);
x2 ^= this.rotate(x14 + x10, 9);
x6 ^= this.rotate(x2 + x14, 13);
x10 ^= this.rotate(x6 + x2, 18);
x3 ^= this.rotate(x15 + x11, 7);
x7 ^= this.rotate(x3 + x15, 9);
x11 ^= this.rotate(x7 + x3, 13);
x15 ^= this.rotate(x11 + x7, 18);
x1 ^= this.rotate(x0 + x3, 7);
x2 ^= this.rotate(x1 + x0, 9);
x3 ^= this.rotate(x2 + x1, 13);
x0 ^= this.rotate(x3 + x2, 18);
x6 ^= this.rotate(x5 + x4, 7);
x7 ^= this.rotate(x6 + x5, 9);
x4 ^= this.rotate(x7 + x6, 13);
x5 ^= this.rotate(x4 + x7, 18);
x11 ^= this.rotate(x10 + x9, 7);
x8 ^= this.rotate(x11 + x10, 9);
x9 ^= this.rotate(x8 + x11, 13);
x10 ^= this.rotate(x9 + x8, 18);
x12 ^= this.rotate(x15 + x14, 7);
x13 ^= this.rotate(x12 + x15, 9);
x14 ^= this.rotate(x13 + x12, 13);
x15 ^= this.rotate(x14 + x13, 18);
}
x0 += j0;
x1 += j1;
x2 += j2;
x3 += j3;
x4 += j4;
x5 += j5;
x6 += j6;
x7 += j7;
x8 += j8;
x9 += j9;
x10 += j10;
x11 += j11;
x12 += j12;
x13 += j13;
x14 += j14;
x15 += j15;
x0 -= this.load_littleendian(c, 0);
x5 -= this.load_littleendian(c, 4);
x10 -= this.load_littleendian(c, 8);
x15 -= this.load_littleendian(c, 12);
if (inv !== undefined /* null*/)
{
x6 -= this.load_littleendian(inv, 0);
x7 -= this.load_littleendian(inv, 4);
x8 -= this.load_littleendian(inv, 8);
x9 -= this.load_littleendian(inv, 12);
}
this.store_littleendian(outv, 0, x0);
this.store_littleendian(outv, 4, x5);
this.store_littleendian(outv, 8, x10);
this.store_littleendian(outv, 12, x15);
this.store_littleendian(outv, 16, x6);
this.store_littleendian(outv, 20, x7);
this.store_littleendian(outv, 24, x8);
this.store_littleendian(outv, 28, x9);
return 0;
};
|
/* eslint-disable no-unused-expressions */
import {getRequest, postRequest} from "../request";
import {CLEAR_QUERIES, CLEAR_QUERY, QUERY, REQUEST_FAILED, UPDATE_SNACK, UPDATE_SPIN} from "../constants";
import SnackType from "../model/SnackType";
import { requestUrls } from "../constants/requestUrls";
export const getQuery = (getQueryInput) => dispatch =>
new Promise((resolve, reject) => {
let {requestName, saveToStore, requestParams, pathVars, callBackPrepare, spin, storeName} = getQueryInput;
let url = requestUrls[requestName];
pathVars ? pathVars.forEach(variable => url = url + "/" + variable) : null;
spin ? dispatch({type: UPDATE_SPIN, spin: spin}) : null;
getRequest(url, requestParams)
.then(res => {
saveToStore ?
dispatch({
type: QUERY,
addition: {[storeName ? storeName : requestName]: (callBackPrepare ? callBackPrepare(res.data) : res.data)}
}) : null;
spin ? dispatch({type: UPDATE_SPIN, spin: false}) : null;
resolve(res);
})
.catch(err => {
notifyError(err);
spin ? dispatch({type: UPDATE_SPIN, spin: false}) : null;
reject(err);
})
});
export const postQuery = (postQueryInput) => dispatch =>
new Promise((resolve, reject) => {
let {requestName, saveToStore, requestParams, pathVars, callBackPrepare, spin, storeName, data} = postQueryInput;
let url = requestUrls[requestName];
pathVars ? pathVars.forEach(variable => url = url + "/" + variable) : null;
spin ? dispatch({type: UPDATE_SPIN, spin: spin}) : null;
postRequest(url, data, requestParams)
.then(res => {
saveToStore ?
dispatch({
type: QUERY,
addition: {[storeName ? storeName : requestName]: (callBackPrepare ? callBackPrepare(res.data) : res.data)}
}) : null;
spin ? dispatch({type: UPDATE_SPIN, spin: false}) : null;
resolve(res);
})
.catch(err => {
notifyError(err);
spin ? dispatch({type: UPDATE_SPIN, spin: false}) : null;
reject(err);
})
});
export const clearQueries = () => {
return {type: CLEAR_QUERIES}
};
export const clearQuery = (queryName) => {
return {type: CLEAR_QUERY, queryName: queryName}
};
const notifyError = (err) => dispatch => {
if (err && err.response && err.response.data && err.response.data.Message)
dispatch({type: UPDATE_SNACK, snack:{type:SnackType.ERROR, message: err.response.data.Message}});
else
dispatch({type: UPDATE_SNACK, snack:{type:SnackType.ERROR, message: REQUEST_FAILED}});
};
|
import MainNavigation from "./MainNavigation";
import classes from "./Layout.module.css";
import { Slider } from "../../Slider";
import "../../scss/Main.css";
import MainFooter from "./MainFooter";
import News from "./News";
function Layout(props) {
return (
<div>
<MainNavigation />
<div>
<div className={classes.container}>
<News />
<div className={classes.newcontainer}>
<div>
<Slider></Slider>
</div>
<div>
<main className={classes.main}>{props.children}</main>
</div>
</div>
</div>
</div>
<MainFooter />
</div>
);
}
export default Layout;
|
//############### DASHBOARD COMPLETE STATE ###############//
export const getFullObjectOfTheState = () => {
return {
dashboard: {
rooms:{
actual: 0,
pagination: ['asdf2kf0asdfnasdf90', 'pqioerp0923klfqpsd890u2n', 'mcio-029na98-2in'],
byId: {
'asdf2kf0asdfnasdf90': {
type: ['GS', 'GS', 'GS', 'GS', 'GS', 'GS', 'GS', 'GS'],
text: 'Surrounding People',
widgets: [1]
}
}
},
widgets: {
byId:{
1: {
type: 'GS',
position: 1,
text: 'Lina Familly',
attached: true,
id: 1
},
2: {
type: 'GS',
position: null,
text: 'My family',
attached: false,
id: 2
},
3: {
type: 'GS',
position: null,
text: 'Friends',
attached: false,
id: 3
}
},
isFetching: false
}
}
};
};
//############### PAGINATION CONTAINER ###############//
// Pagination container test state
export const getPaginationStateObject = () => {
return {
dashboard: {
rooms:{
actual: 1,
pagination: ['asdf2kf0asdfnasdf90', 'pqioerp0923klfqpsd890u2n', 'mcio-029na98-2in']
}
}
};
};
//############### ROOM REDUCER ###############//
// After FETCH_WIDGETS_SUCCESS the new state of the rooms reducer. We get that applying 'widgetsFetchedData 'mock action response
export const getRoomStateObject = () => ({
actual: 0,
pagination: ['asdf2kf0asdfnasdf90'],
byId: {
'asdf2kf0asdfnasdf90': {
type: ['GS', 'GS', 'GS', 'GS', 'GS', 'GS', 'GS', 'GS'],
text: 'Surrounding People',
widgets: [1]
}
},
editMode: false
});
// After UNIT_WIDGET_EDIT action, the new state of the reducer.
export const getRoomStateAfterDisconnectTheWidget = () => ({
actual: 0,
pagination: ['asdf2kf0asdfnasdf90'],
byId: {
'asdf2kf0asdfnasdf90': {
type: ['GS', 'GS', 'GS', 'GS', 'GS', 'GS', 'GS', 'GS'],
text: 'Surrounding People',
widgets: []
}
},
editMode: false
});
// Pagination state for the room selector in roomReducer test
export const getPaginationState = () => ({
pagination: ['asdf2kf0asdfnasdf90', 'pqioerp0923klfqpsd890u2n', 'mcio-029na98-2in']
});
//############### WIDGET REDUCER ###############//
//After FETCH_WIDGETS_SUCCESS the new state of the widgets reducer. We get that applying 'widgetsFetchedData' mock action response
export const getWidgetStateObject = () => ({
byId: {
1: {
type: 'GS',
position: 1,
text: 'Lina Familly',
attached: true,
id: 1
}
},
isFetching: false,
restQueue: []
});
// We use getFullObjectOfTheState object and we have to extract all the disconnected widgets
export const getDisconnectedWidgetsObject = () => {
return [
{
type: 'GS',
position: null,
text: 'My family',
attached: false,
id: 2
},
{
type: 'GS',
position: null,
text: 'Friends',
attached: false,
id: 3
}
]
};
// Non attached a widget
export const nonAttachedWidget = (restQueue) => ({
byId: {
1: {
type: 'GS',
position: null,
text: 'Lina Familly',
attached: false,
id: 1
}
},
isFetching: false,
restQueue
});
// Attach a widget
export const attachedWidget = (restQueue) => ({
byId: {
1: {
type: 'GS',
position: 3,
text: 'Lina Familly',
attached: true,
id: 1
}
},
isFetching: false,
restQueue
});
|
const assert = require('assert');
function G() { while(false) {} };
function F(x) {
G();
const z = arguments;
function H() {
x = 10;
}
return x;
}
assert(F(42) === 42);
|
import React, { Component, Fragment } from 'react'
import { render } from 'react-dom'
import { Table } from 'reactstrap'
function TableViewer(props) {
const headers = Object.keys(props.data[0])
const { keyCol } = props
return <Table striped bordered hover onClick={props.onClick}>
<thead>
<tr>
{headers.map(hd => <th key={hd}>{hd}</th>)}
</tr>
</thead>
<tbody>
{props.data.map(row => <tr key={JSON.stringify(row)}>
{keyCol && <th scope="row">{row[keyCol]}</th>}
{headers.filter(hd => hd != keyCol).map(hd => <td key={hd}>{row[hd]}</td>)}
</tr>)}
</tbody>
</Table>
}
class ActiveTableViewer extends Component {
state = { tableData: this.props.data, keyCol: this.props.keyCol }
onClick(ev) {
console.log(ev)
this.setState({ tableData: this.state.tableData.reverse() })
}
render() {
return <TableViewer onClick={this.onClick.bind(this)} data={this.state.tableData} keyCol={this.state.keyCol} />
}
}
fetch("fakeData.json")
.then(res => res.json())
.then(fakeData => render(<ActiveTableViewer data={fakeData} keyCol="name" />, document.getElementById("app")))
.catch(e => console.error(e))
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import bento from './bento.png'
class LandingPage extends Component {
render() {
return (
<div className="landingpage">
<p>This is an app for you to contribute, update, and of course, browse restaurants that fit various dietary needs.</p><br />
<p>We are just getting started. For now, please choose between: Keto, Mediterranean, and Plant-based diet.</p><br />
<p>There is no ad or complicated functions to confuse you. Simple but functional.</p><br />
<p>Click here: <button><Link to="/home"><img src={ bento } alt='bento box icon'/></Link></button> to start your healthy diet today!</p>
</div>
);
}
}
export default LandingPage;
|
/*************************** for User-Profile **********************************/
var usertoken = localStorage.token;
var FBtoken = localStorage.accessToken;
var email, uid, name;
var os;
// document.addEventListener("deviceready", onDeviceReady, false);
// function onDeviceReady() {
// os = device.platform;
// }
// $(window).load(function(){
// os = device.platform;
// });
$(document).ready(function() {
var urlProfile;
if (typeof usertoken != "undefined") {
var profileTemp = '<h3>${name}</h3><p>Favoritvirksomheder: ${favouredCompany}</p><p>GEMTE OPSLAG: ${favouredDeals}</p>';
$.template("Profile", profileTemp);
urlProfile = 'http://rappit.dk/api/profile.json?token=' + usertoken;
$.ajax({
datatype: "JSON",
url: urlProfile,
jsonp: "$callback",
beforeSend: function() {
$('.overlay-loader').show();
},
success: function(data) {
$('.overlay-loader').hide();
var userProfile = data;
$(".profileDetails").empty();
$.tmpl('Profile', userProfile).appendTo(".profileDetails");
}
});
}
if (typeof FBtoken != "undefined") {
profileTemp = '<h3></h3><p>Favoritvirksomheder: ${favouredCompany}</p><p>GEMTE OPSLAG: ${favouredDeals}</p><p>Likes: ${reccemended}</p>';
$.template("Profile", profileTemp);
urlProfile = 'http://rappit.dk/api/profile.json?ftoken=' + FBtoken;
$.ajax({
datatype: "JSON",
url: urlProfile,
jsonp: "$callback",
beforeSend: function() {
$('.overlay-loader').show()
},
success: function(data) {
var userProfile = data;
$.template("Profile", profileTemp);
$.tmpl('Profile', userProfile).appendTo(".profileDetails");
}
}).done(function() {
FacebookInAppBrowser.graphApi('/me?fields=name,email,picture.height(200).width(200)', function(response) {
if (response) {
$('.profileDetails h3').html(response.name);
$('.fbimage').attr('src', response.picture.data.url);
localStorage.setItem('pro', response.picture.data.url)
var splitword = $('.profileDetails h3').html();
var splitName = splitword.split(' ');
var finalname;
if (typeof splitName[2] != "undefined") {
finalname = splitName[0] + " " + splitName[1][0] + " " + splitName[2][0];
$('.profileDetails h3').html(finalname);
} else {
finalname = splitName[0] + " " + splitName[1][0];
$('.profileDetails h3').html(finalname);
}
}
});
});
}
function alertDismissed() {
// alert(1);
localStorage.setItem('inCount', 0);
location.href = 'index.html';
}
}); //End of profile js
|
const redis = require('redis');
const fetch = require('node-fetch');
var subscriber = redis.createClient('redis://redis:6379');
subscriber.on("message", function(channel, message) {
body = JSON.parse(message);
fetch(body.address,
{
method: 'POST',
body: JSON.stringify(body.body),
headers: {"Content-Type": "application/json"}
}).then(function(response) {
return;
}).catch(function(err) {
console.error(err);
return;
});
});
subscriber.subscribe("worker");
|
import React from 'react';
import "./Loader.css";
export const Loader = () => {
return (
<>
<div className="loader-wrapper">
<div className="loadingio-spinner-ellipsis-vs2gffnmha"><div className="ldio-66naq67fyfq">
<div></div><div></div><div></div><div></div><div></div>
</div></div>
</div>
</>
);
}
|
export default function ({ $axios, redirect , app }) {
$axios.onRequest(config => {
//console.log('Making request to ' + config.url)
});
$axios.onError(err => {
console.log(err.response.data.message);
console.log(err.response.data.exception);
console.log(err.response.data.file);
console.log(err.response.data.line);
// const code = parseInt(err.response && err.response.status);
redirect('/error');
});
}
|
const ShipResource = function(capacity) {
this.remaining = capacity;
};
ShipResource.prototype = {
subtract(val) {
this.remaining = this.remaining - val;
}
};
export default ShipResource;
|
// https://www.youtube.com/watch?v=g8E2XikfTqA menu music
// https://www.youtube.com/watch?v=Kjxs_pXFOb4 game music
// works in radiansssss and not degreessss
// function radianConverter(radian, distance){
// console.log(degree)
// let posx = distance * Math.cos(degree);
// let posy = distance * Math.sin(degree);
// console.log('posx',posx,'posy',posy)
// }
// radianConverter(0,1)
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
let posy = -200;
let base_image = new Image();
base_image.src = '../assets/developer.svg';
let base_image2 = new Image();
base_image2.src = '../assets/404.svg';
let base_image3 = new Image();
base_image3.src = '../assets/typeError.svg';
let base_image4 = new Image();
base_image4.src = '../assets/bear.svg';
let base_image5 = new Image();
base_image5.src = '../assets/sheep.svg';
let base_image6 = new Image();
base_image6.src = '../assets/javascript.svg';
let base_image7 = new Image();
base_image7.src = '../assets/inicial.svg';
let base_image8 = new Image();
base_image8.src = '../assets/desk.svg';
let base_image9 = new Image();
base_image9.src = '../assets/flag1.svg';
let base_image10 = new Image();
base_image10.src = '../assets/flag2.svg';
let base_image11 = new Image();
base_image11.src = '../assets/flag3.svg';
let base_image12 = new Image();
base_image12.src = '../assets/flag4.svg';
let shoot1_sound = new Audio("../assets/shoot1.mp3", {
volume: 1
});
let map_sound = new Audio("../assets/tes.mp3", {
volume: 1
});
let level1_sound = new Audio("../assets/west.mp3", {
volume: 1
});
let globalScope = this;
let globalMousePosition = {
x: 900,
y: 900
}
window.onload = function () {
//---------------------- mouse logic ------------------------------------------
function getMousePos(evt) {
var rect = globalScope.canvas.getBoundingClientRect();
globalMousePosition.x = evt.clientX - rect.left;
globalMousePosition.y = evt.clientY - rect.top;
console.log(globalMousePosition)
}
function onCanvasClickGetMousePosition() {
globalScope.canvas.addEventListener('click', function (evt) {
getMousePos(evt);
shoot1_sound.play();
})
}
function resetMouseState() {
globalMousePosition.x = 50000;
globalMousePosition.y = 50000;
}
onCanvasClickGetMousePosition();
//------------------------- Classes -------------------
//----------------------------- game class --------------------------------
class game {
constructor() {
this.level = 0;
this.levelCompleted = {
level_1: false,
level_2: false,
level_3: false
}
}
teste() {
console.log('teste game passou')
}
main_function() {
switch (this.level) {
case 0: // intro level
console.log('intro')
ctx.drawImage(base_image7, 0, 0, width, height);
if (globalMousePosition.y >= 568 && globalMousePosition.y <= 616) {
this.level = 1;
resetMouseState()
}
break;
case 1: // map level
console.log('map')
map_sound.play();
ctx.drawImage(base_image8, 0, 0, width, height);
ctx.drawImage(base_image9, 193, 385, width/6, height/6);
map_sound.play();
if (globalMousePosition.y >= 468 && globalMousePosition.y <= 506) {
this.level = 2;
resetMouseState()
}
break;
case 2: // first level boot camp
level1_sound.play();
map_sound.pause();
enemy_404_1.posy += 0.9;
enemy_typeError_1.posy += 0.9;
enemy_bear_1.posx += 0.8;
enemy_sheep_1.posx -= 0.5;
enemy_sheep_1.posy -= 0.5;
ctx.clearRect(0, 0, width, height)
dev1.paint();
enemy_404_1.paint();
enemy_typeError_1.paint();
enemy_bear_1.paint();
enemy_sheep_1.paint();
enemy_js_1.paint();
enemy_js_2.paint();
resetMouseState()
break;
case 3: // second level junior developer
console.log('second level junior developer')
break;
case 4: // third level senior developer
console.log('third level senior developer')
break;
case 5: // final level last level
console.log('final level last level')
break;
case 6: // show enemies on the map menu
console.log('show enemies on the map menu')
break;
default:
console.log('default')
break;
}
}
}
//--------------------------- class dev ---------------------------------
class dev {
constructor() {
this.health = 5
}
teste() {
console.log('teste passou')
}
paint() {
ctx.drawImage(base_image, width / 3, height / 3, width / 4, height / 4);
}
}
//--------------------------- class enemy 404 ----------------------------------
class enemy_404 {
constructor(posx, posy, offset_left, offset_right, offset_top, offset_bottom) {
this.health = 5
this.posx = 0;
this.posy = -200;
this.offset_left = 0;
this.offset_right = 0;
this.offset_top = this.posy + 31;
this.offset_bottom = this.posy + 131;
this.isAlive = true;
}
teste() {
console.log('teste passou')
}
getShoot() {
if (this.isAlive === false) {
this.offset_top = 900;
this.offset_bottom = 900;
} else {
this.offset_top = this.posy + 31;
this.offset_bottom = this.posy + 131;
// console.log('globalMousePosition2', globalMousePosition)
if (globalMousePosition.y >= this.offset_top && globalMousePosition.y <= this.offset_bottom) {
console.log('died')
this.isAlive = false;
} else {
ctx.drawImage(base_image2, width / 3, this.posy, width / 4, height / 4);
}
}
}
reachTheCenter(){
if(posx >= 300 && posx <= 400 ) {
// the game shows the death menu
}
}
paint() {
this.getShoot();
}
}
//-------------------------- enemy class type error -----------------------------------
class enemy_typeError {
constructor(posx, posy, offset_left, offset_right, offset_top, offset_bottom) {
this.health = 5
this.posx = 0;
this.posy = -550;
this.offset_left = 0;
this.offset_right = 0;
this.offset_top = this.posy + 31;
this.offset_bottom = this.posy + 131;
this.isAlive = true;
}
getShoot() {
if (this.isAlive === false) {
this.offset_top = 900;
this.offset_bottom = 900;
} else {
this.offset_top = this.posy + 31;
this.offset_bottom = this.posy + 131;
// console.log('globalMousePosition2', globalMousePosition)
if (globalMousePosition.y >= this.offset_top && globalMousePosition.y <= this.offset_bottom) {
console.log('died')
this.isAlive = false;
} else {
ctx.drawImage(base_image3, width / 3, this.posy, width / 4, height / 4);
}
}
}
paint() {
this.getShoot();
}
}
//---------------------------- class enemy bear -----------------------------------
class enemy_bear {
constructor(posx, posy, offset_left, offset_right, offset_top, offset_bottom) {
this.health = 5
this.posx = -330;
this.posy = 0;
this.offset_left = 0;
this.offset_right = 0;
this.offset_top = this.posy + 31;
this.offset_bottom = this.posy + 131;
this.isAlive = true;
}
teste() {
console.log('teste passou')
}
getShoot() {
if (this.isAlive === false) {
this.offset_top = 900;
this.offset_bottom = 900;
} else {
this.offset_top = this.posy + 300;
this.offset_bottom = this.posy + 370;
// console.log('globalMousePosition2', globalMousePosition)
// console.log('this.offset_top', this.offset_top,'this.offset_bottom',this.offset_bottom,'posx',this.posx,'posy',this.posy)
if (globalMousePosition.y >= this.offset_top && globalMousePosition.y <= this.offset_bottom) {
console.log('died')
this.isAlive = false;
} else {
ctx.drawImage(base_image4, this.posx, height/3 +20, width / 6, height / 6);
}
}
}
paint() {
this.getShoot();
}
}
//------------------------- class enemy sheep --------------------------------------
class enemy_sheep {
constructor(posx, posy, offset_left, offset_right, offset_top, offset_bottom) {
this.health = 5
this.posx = 800;
this.posy = 800;
this.offset_left = 0;
this.offset_right = 0;
this.offset_top = this.posy + 31;
this.offset_bottom = this.posy + 131;
this.isAlive = true;
}
teste() {
console.log('teste passou')
}
getShoot() {
if (this.isAlive === false) {
this.offset_top = 900;
this.offset_bottom = 900;
} else {
this.offset_top = this.posy + 0;
this.offset_bottom = this.posy + 70;
if (globalMousePosition.y >= this.offset_top && globalMousePosition.y <= this.offset_bottom) {
console.log('died')
this.isAlive = false;
} else {
ctx.drawImage(base_image5, this.posx, this.posy, width / 7, height / 7);
}
}
}
paint() {
this.getShoot();
}
}
//---------------------------------------------------------------
class enemy5 {
constructor() {
this.health = 5
}
teste() {
console.log('teste passou')
}
paint() {
ctx.drawImage(base_image6, 250, 150, width / 5, height / 5);
}
}
//--------------------------- enemy main class ------------------------------------
// this is the main enemy class
// enemy random class , random postion and then goes to center
// enemy(distance, speed, base_image) the inicial position is random
class enemy_main {
constructor(posx, posy) {
this.health = 5
this.posx = posx;
this.posy = posy;
this.offset_left = 0;
this.offset_right = 0;
this.offset_top = this.posy + 31;
this.offset_bottom = this.posy + 131;
this.isAlive = true;
}
teste() {
console.log('teste passou')
}
addingForAnimating(){
this.posx +=1.6;
this.posy +=1.6;
}
getShoot() {
if (this.isAlive === false) {
this.offset_top = 900;
this.offset_bottom = 900;
} else {
this.offset_top = this.posy + 0;
this.offset_bottom = this.posy + 70;
console.log('globalMousePosition2', globalMousePosition)
console.log('this.offset_top: ', this.offset_top,'this.offset_bottom: ',this.offset_bottom,'posx: ',this.posx,'posy: ',this.posy)
if (globalMousePosition.y >= this.offset_top && globalMousePosition.y <= this.offset_bottom) {
console.log('died')
this.isAlive = false;
} else {
ctx.drawImage(base_image6, this.posx, this.posy, width / 7, height / 7);
}
}
}
paint() {
this.addingForAnimating();
this.getShoot();
}
}
//---------------------------------------------------------------
let dev1 = new dev()
let enemy_404_1 = new enemy_404(posy)
let enemy_typeError_1 = new enemy_typeError()
let enemy_bear_1 = new enemy_bear()
let enemy_sheep_1 = new enemy_sheep()
let enemy_js_1 = new enemy_main(-600,-600)
let enemy_js_2 = new enemy_main(-1000,-1000)
let main_game_class = new game()
//level1_sound.play(); only after the user interacts with the page is that you can play music chrome 66
function animate() {
main_game_class.main_function()
requestAnimationFrame(animate)
}
animate();
};
|
import React from "react";
import Search from "./search";
import Results from "../results";
import { BASE_API_URL } from "../../const";
import Controls from "../controls";
const scrappingResponse = {
};
export default class SearchContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
searchQuery: null,
results: null,
type: 'all',
isLucene: false,
scrapping: false
};
this.setSearchQuery = this.setSearchQuery.bind(this);
this.search = this.search.bind(this);
this.onEnterPress = this.onEnterPress.bind(this);
this.onChange = this.onChange.bind(this);
this.toggleIsLucene = this.toggleIsLucene.bind(this);
this.toggleScrapping = this.toggleScrapping.bind(this);
}
setSearchQuery(e) {
this.setState({ searchQuery: e.target.value });
}
search() {
const { searchQuery, type, isLucene, scrapping } = this.state;
if (!searchQuery)
return;
const options = {
crossDomain: true,
method: 'GET'
};
const route = scrapping ? 'getMovie' : isLucene ? 'lucene/search' : 'search';
const url = `${BASE_API_URL}/${route}?q=${searchQuery}&type=${type}&id=${searchQuery}`;
fetch(url, options)
.then(responce => responce.json())
.then(results => this.setState({ results }))
.catch(e => console.log(e));
}
onEnterPress(e) {
if (e.key === 'Enter') {
e.preventDefault();
e.stopPropagation();
this.search();
}
}
toggleIsLucene() {
this.setState({
isLucene: !this.state.isLucene
})
}
onChange(e) {
this.setState({type: e.target.value });
}
toggleScrapping() {
this.setState({
scrapping: !this.state.scrapping
});
}
render() {
return this.state.scrapping ?
<div>
<button onClick={this.toggleScrapping}>
Search
</button>
<Search
setSearchQuery={this.setSearchQuery}
search={this.search}
onEnterPress={this.onEnterPress}
/>
{this.state.results ? (
<div className='scrapping-results'>
{this.state.results.title ?
<p>{this.state.results.title}</p> : null}
{this.state.results.year ?
<p>{this.state.results.year}</p> : null}
{this.state.results.premierData ?
<p>{this.state.results.premierData}</p> : null}
{this.state.results.genresList ?
<p>{this.state.results.genresList}</p> : null}
{this.state.results.director ?
<p>{this.state.results.director}</p> : null}
{this.state.results.filmStars ?
<p>{this.state.results.filmStars}</p> : null}
{this.state.results.annotation ?
<p>{this.state.results.annotation}</p> : null}
{this.state.results.synopsis ?
<p>{this.state.results.synopsis}</p> : null}
</div>
) : null}
</div> : (
<div>
<button onClick={this.toggleScrapping}>
Scrapping
</button>
<Search
setSearchQuery={this.setSearchQuery}
search={this.search}
onEnterPress={this.onEnterPress}
/>
<Controls
type={this.state.type}
onChange={this.onChange}
isLucene={this.state.isLucene}
toggleIsLucene={this.toggleIsLucene}
/>
<Results results={this.state.results} />
</div>
);
}
}
|
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { Session } from 'meteor/session';
import { Products } from '../Collections/Products.js';
import { Carts } from '../Collections/Carts.js';
import { FlowRouter } from 'meteor/kadira:flow-router';
import './SearchPageBuyer.html';
import './SearchPageSeller.html';
import './DisplaySearchPage.html';
Template.DisplaySearchPage.onCreated(function(){
var self = this;
self.autorun(function() {
self.subscribe('products');
})
});
Template.DisplaySearchPage.helpers({
searchproducts() {
var tagsvar = FlowRouter.getQueryParam("tagsvar");
console.log(tagsvar);
var tagsvarres = tagsvar.toLowerCase();
tagsvarres = tagsvarres.split(',');
var Productslist;
Productslist = Products.find({tags: {$in: tagsvarres}});
return Productslist;
},
});
|
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;
const UserSchema = mongoose.Schema(
{
email: { type: String, required: false, unique: true },
passwordHash: { type: String, required: true },
parent: { type: Schema.Types.ObjectId, ref: 'User' },
children: [{ type: Schema.Types.ObjectId, ref: 'User' }],
points: { type: Number, default: 0 },
depth: { type: Number, default: 0 }
},
{ timestamps: true }
);
UserSchema.plugin(uniqueValidator);
UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.passwordHash);
};
UserSchema.virtual('password')
.get(function() {
return this._password;
})
.set(function(value) {
this._password = value;
this.passwordHash = bcrypt.hashSync(value, 8);
});
UserSchema.methods.setPoints = async function() {
let countHash = {
1: 40,
2: 20,
3: 10,
4: 5,
5: 2
};
let count = 0;
let depthGetter = async function(user) {
if (user.parent) {
let parent = await User.findById(user.parent);
count += 1;
countHash[count]
? (parent.points += countHash[count])
: (parent.points += 1);
await parent.save();
return depthGetter(parent);
}
return;
};
return depthGetter(this);
};
const autoPopulateChildren = function(next) {
this.populate('children');
next();
};
UserSchema.pre('findOne', autoPopulateChildren).pre(
'find',
autoPopulateChildren
);
const User = mongoose.model('User', UserSchema);
module.exports = User;
|
/* eslint global-require: 0 import/no-dynamic-require: 0 */
/* istanbul ignore file */
const internalLoaders = require('./domain/bootloaders');
const startApp = async () => {
await internalLoaders.boot();
global.app = {
...internalLoaders
};
const port = process.env.APP_PORT || 8080;
app.server.listen(port, () => {
// eslint-disable-next-line no-console
console.info(
`La Manicurista Backend listening at http://127.0.0.1:${port}`
);
});
};
startApp().then();
|
import React, { useState } from "react";
import Card from "../Card/Card";
import AuthForm from "../AuthForm/AuthForm";
import PurchaseForm from "../PurchaseForm/PurchaseForm";
import InfoForm from "../InfoForm/InfoForm";
import "../../App.css";
import "./style.css";
const GalleryItem = props => {
const [openAuth, setOpenAuth] = useState(false);
const [openPurchase, setOpenPurchase] = useState(false);
const [openInfo, setOpenInfo] = useState(false);
// открываем модальное окно покупки или авторизации, если пользователь не авторизован;
// при открытии модальных окон останавливаем проигрывание мелодии
const openPurchaseForm = () => {
props.stopPrevAudio(null, null);
if (!props.login) {
setOpenAuth(true);
} else {
setOpenPurchase(true);
}
};
const handleOpenInfo = () => {
setOpenInfo(true);
props.stopPrevAudio(null, null);
};
const handleCloseAuth = () => {
setOpenAuth(false);
};
const handleClosePurchase = () => {
setOpenPurchase(false);
};
const handleCloseInfo = () => {
setOpenInfo(false);
};
return (
<div className="gallery-item">
<Card
elem={props.elem}
stopPrevAudio={props.stopPrevAudio}
isPlayed={props.isPlayed}
/>
<div className="gallery-item-footer">
<span>${props.elem.priceModelNo}</span>
<div className="btn-block">
<div className="btn" onClick={openPurchaseForm}>
<i className="fa fa-shopping-basket"></i>
</div>
<div className="btn">
<i className="fa fa-gift"></i>
</div>
<div className="btn" onClick={handleOpenInfo}>
<i className="fa fa-info"></i>
</div>
</div>
</div>
<AuthForm
open={openAuth}
handleClose={handleCloseAuth}
authorize={props.authorize}
/>
<PurchaseForm
open={openPurchase}
handleClose={handleClosePurchase}
purchase={props.purchase}
authorize={props.authorize}
elem={props.elem}
login={props.login}
passw={props.passw}
/>
<InfoForm
open={openInfo}
handleClose={handleCloseInfo}
elem={props.elem}
/>
</div>
);
};
export default GalleryItem;
|
const express = require("express");
const morgan = require("morgan");
const app = express();
const es6Renderer = require("express-es6-template-engine");
const session = require("express-session");
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.use(morgan("dev"));
// app.use(
// session({
// secret: process.env.SECRET_KEY || "dev",
// resave: true,
// saveUninitialized: false,
// cookie: { maxAge: 60000 },
// })
// );
app.engine("html", es6Renderer);
app.set("views", "templates");
app.set("view engine", "html");
var threads = [
{
id: 1,
title: "Test Thread 1",
name: "John",
content: "This is a test forum post with id 1",
likes: 0,
comments: [
{
id: 1,
name: "Vera",
content: "very cool!",
},
{
id: 2,
name: "Felix",
content: "what vera said!",
},
],
},
{
id: 2,
title: "Test Thread 2",
name: "Sarah",
content: "this is a test forum post with id 2.",
likes: 0,
comments: [
{
id: 1,
name: "Jake",
content: "a finished project is a good project",
},
],
},
];
let idCount = 2;
let commentCount = 3;
// GET home page
app.get("/", (req, res) => {
res.render("home", {
partials: {
head: "/partials/head",
nav: "/partials/nav"
},
});
});
// GET api/threads/
app.get("/threads", (req, res) => {
res.render("threadList", {
locals: {
threads,
},
partials: {
head: "/partials/head",
nav: "/partials/nav"
},
});
});
// GET threads/:id -- Render a Single Post
app.get("/threads/:id", (req, res) => {
const id = req.params.id;
const thread = threads.find((thread) => thread.id === parseInt(id));
if (thread) {
res.render("thread", {
locals: {
thread,
},
partials: {
head: "/partials/head",
nav: "/partials/nav"
},
});
} else {
// res.status(404).send(`no thread with id ${id}`);
const error = new Error("Not found");
error.status = 404;
console.log(error.status);
res.render("error", {
locals: {
thread,
error,
},
partials: {
head: "/partials/head",
nav: "/partials/nav"
},
});
}
});
// POST /threads -- making a new thread
app.post("/threads", (req, res) => {
console.log(req.body);
// error method below will force a content key
if (!req.body.content || req.body.content == "") {
res.status(400).send("Forum Thread Empty. Please include content key");
return;
}
// push new thread w/ new id.
threads.push({ ...req.body, comments: [],likes: 0, id: ++idCount });
res.render("threadList", {
locals: {
threads,
},
partials: {
head: "/partials/head",
nav: "/partials/nav"
},
});
});
// PUT /threads/:id -- Add a Like
app.put("/threads/:id", (req, res) => {
console.log(req.body);
let id = req.params.id;
// if (!req.body.content || req.body.content == "") {
// res.status(400).send("bad request it needs content key.");
// return;
// }
let thread = threads.find((thread) => thread.id === parseInt(id));
thread.likes++ ;
res.json(thread.likes);
});
// POST /threads/:id/comments -- testing using POST method to add comments.
app.post("/threads/:id/comments", (req, res) => {
console.log(req.body);
let id = req.params.id;
if (!req.body.content || req.body.content == "") {
res.status(400).send("bad request it needs content key.");
return;
}
let thread = threads.find((thread) => thread.id === parseInt(id));
thread.comments.push({ ...req.body, id: ++commentCount });
res.render("thread", {
locals: {
thread,
},
partials: {
head: "/partials/head",
nav: "/partials/nav"
},
});
});
// DELETE /threads/:id -- Delete a thread
app.delete("/threads/:id", (req, res) => {
threads = threads.filter((element) => element.id !== parseInt(req.params.id));
res.json(threads);
});
// PUT /threads/:id/comments/:commentId -- edit a comment
// DELETE /threads/:id/comments/:commentId -- delete a comment
// Routes to catch all routing/server errors not caught inside route declarations
// -- goes right before app.listen
app.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});
app.use((error, req, res, next) => {
// res.status(error.status || 500).send({
// error: {
// status: error.status || 500,
// message: error.message || "Internal Server Error",
// },
// });
error.status = error.status || 500;
error.message = error.message || "internal server error";
res.render("error", {
locals: {
error,
},
partials: {
head: "/partials/head",
nav: "/partials/nav"
},
});
});
app.listen(port, function () {
console.log("Forum API is now listening on port " + port + "...");
});
|
export default class Rank {
};
|
var util = require("util");
var underscore = require("underscore");
var Adapter = require("./adapter");
var Commit = require("../commit");
function WebSQLAdapter(options, callback) {
var defaultOptions = {
name: "trailmix",
description: "TrailMix Database"
}
var options = underscore.defaults(options || {}, defaultOptions);
var db = openDatabase(options.name, '1.0', options.description, 2 * 1024 * 1024);
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS commits ( \
id TEXT PRIMARY KEY, \
parentIds TEXT, \
name TEXT, \
properties TEXT, \
changes TEXT, \
head INT \
)")
callback()
})
this.db = db;
}
util.inherits(WebSQLAdapter, Adapter);
WebSQLAdapter.prototype.root = function(callback) {
this.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM commits WHERE parentIds IS NULL", [], function (tx, results) {
var row = results.rows.item(0)
callback(convertRowToCommit(row))
});
})
}
WebSQLAdapter.prototype.delete = function(callback) {
this.db.transaction(function(tx) {
tx.executeSql("DELETE FROM commits", [], function() {
callback();
});
})
}
WebSQLAdapter.prototype.branches = function(callback) {
this.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM commits WHERE head = 1", [], function (tx, results) {
var branches = [];
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
branches.push(convertRowToCommit(row))
}
callback(branches);
});
})
}
WebSQLAdapter.prototype.commit = function(commitId, callback) {
this.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM commits WHERE id = ?", [commitId], function (tx, results) {
var row = results.rows.item(0)
callback(convertRowToCommit(row))
});
})
}
WebSQLAdapter.prototype.commits = function(options, callback) {
var defaults = {
head: null,
base: null
}
if(arguments.length == 1) {
callback = arguments[0];
options = {};
}
options = underscore.defaults(options, defaults);
if(options.head == null && options.base == null) {
this.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM commits", [], function (tx, results) {
var commits = [];
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
commits.push(convertRowToCommit(row))
}
callback(commits);
});
})
} else {
// TODO
}
}
WebSQLAdapter.prototype.saveCommit = function(commit, callback) {
this.db.transaction(function(tx) {
console.log("Save Commit!")
if(commit.parentIds) {
commit.parentIds.forEach(function(parentId) {
console.log(parentId)
tx.executeSql("UPDATE commits SET head = 0 WHERE id = ?", [parentId])
})
}
tx.executeSql("INSERT INTO commits VALUES (?, ?, ?, ?, ?, ?)",
convertCommitToRow(commit),
function() {
callback();
}
)
})
}
WebSQLAdapter.prototype.snapshots = function() {
// TODO
}
WebSQLAdapter.prototype.saveSnapshot = function(commit) {
// TODO
}
function convertRowToCommit(row) {
var commit = new Commit();
commit.id = row.id;
commit.parentIds = JSON.parse(row.parentIds);
commit.name = row.name;
commit.properties = JSON.parse(row.properties);
commit.changes = JSON.parse(row.changes);
return commit;
}
function convertCommitToRow(commit) {
var row = [
commit.id,
JSON.stringify(commit.parentIds),
commit.name,
JSON.stringify(commit.properties),
JSON.stringify(commit.changes),
1
]
return row;
}
module.exports = WebSQLAdapter;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Typography from 'material-ui/Typography';
import Grid from 'material-ui/Grid';
import { withStyles, createStyleSheet } from 'material-ui/styles';
import {Image} from 'cloudinary-react';
const styleSheet = createStyleSheet('ImageMessage', theme => ({
gridContainerBack: {
backgroundColor: '#F7F7F7',
width: '100%',
},
gridContainer: {
margin: 0,
maxWidth: '100%'
},
gridItem: {
right: 20,
padding: '0 !important',
position: 'absolute',
fontSize: '20px !important',
maxWidth: window.screen.width < 900 ? '160px' : 'default',
},
massageImage: {
marginLeft: window.screen.width < 900 ? '-40px' : '',
objectFit: 'cover',
height: window.screen.width < 900 ? '190px' : '400px',
}
}));
class ImageMessage extends Component
{
render() {
const { classes, text } = this.props;
return (
<div className={classes.gridContainerBack}>
<div className="container">
<Grid container align="center" className={classes.gridContainer}>
<Image
cloudName="vivala"
publicId="home_2.png"
width={window.screen.width > 800 ? 700 : 320}
//height={window.screen.width > 800 ? 500 : 250}
crop="scale" alt="Transforme sua vida"
className={classes.massageImage}
/>
<Grid item xs={4} className={classes.gridItem}>
<Typography type="subheading" color="inherit">{text}</Typography>
</Grid>
</Grid>
</div>
</div>
);
}
}
ImageMessage.propTypes = {
classes: PropTypes.object.isRequired,
text: PropTypes.string.isRequired
};
export default withStyles(styleSheet)(ImageMessage);
|
import React, { Component } from "react";
class ProfileCard extends Component {
render() {
return (
<div className="profile-card">
<h1>HEYYYYY</h1>
</div>
);
}
}
export default ProfileCard;
|
"use strict";
//Constantes de VIP.
const Attributes = require('../Classes/Attributes');
const Libraries = require('../Base/Libraries');
class UtilsVIP {
/**
* Función getRepromptText: Retorna el reprompt de Alexa de forma dinámica.
* @returns {String} RepropmtSpeakText
*/
static getRepromptText() {
let randomPositionHeader = Libraries.Utils.getRandomIndexOfArray(Libraries.TextConstants.RepromptHeaderSpeakText);
let randomPosition = Libraries.Utils.getRandomIndexOfArray(Libraries.TextConstants.RepropmtSpeakText);
return Libraries.TextConstants.RepromptHeaderSpeakText[randomPositionHeader] + Libraries.TextConstants.RepropmtSpeakText[randomPosition];
}
/**
* Función getSpeakText: Retorna el speak text de Alexa de forma automática.
* @param {Attributes} attributes
* @param {} speakText
* @param {} repromptText
* @param {} speakTextScreen
* @param {} repromptTextScreen
* @returns {Attributes} attributes
*/
static async getSpeakText(attributes = new Attributes().init(attributes), speakText, repromptText, speakTextScreen, repromptTextScreen) {
attributes.voiceResponse.speakTextScreen = speakTextScreen == undefined ? '' : speakTextScreen;
attributes.voiceResponse.repromptTextScreen = repromptTextScreen == undefined ? this.getRepromptText() : repromptTextScreen;
attributes.voiceResponse.speakText = speakText == undefined ? '' : speakText;
attributes.voiceResponse.repromptText = repromptText == undefined ? this.getRepromptText() : repromptText;
return Promise.resolve(attributes);
}
/**
* Función getErrorText: Retorna el error de la arquitectura VIP.
* @param {Attributes} attributes
* @returns {Attributes} attributes
*/
static async getErrorText(attributes = new Attributes().init(attributes)) {
switch (attributes.errorVIP.errorType) {
case '':
attributes.voiceResponse.speakTextScreen = Libraries.TextConstants.ErrorSpeakText;
attributes.voiceResponse.repromptTextScreen = Libraries.UtilsVIP.getRepromptText();
attributes.voiceResponse.speakText = Libraries.TextConstants.ErrorSpeakText;
attributes.voiceResponse.repromptText = Libraries.UtilsVIP.getRepromptText();
break;
default:
attributes.voiceResponse.speakTextScreen = Libraries.TextConstants.ErrorSpeakText;
attributes.voiceResponse.repromptTextScreen = Libraries.UtilsVIP.getRepromptText();
attributes.voiceResponse.speakText = Libraries.TextConstants.ErrorSpeakText;
attributes.voiceResponse.repromptText = Libraries.UtilsVIP.getRepromptText();
break;
}
return Promise.resolve(attributes);
}
}
module.exports = UtilsVIP;
|
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import './../styles/styles.css';
import logo from './../images/logo.svg';
import location from './../images/location.svg';
import jd from './../images/jd.png';
import MenuLink from './../components/MenuLink';
import data from './../data/person.json';
import ActiveUser from './../components/ActiveUser';
import GridView from './../components/GridView';
import ListView from './../components/ListView';
import FilterOptions from './../components/FilterOptions';
import settings from './../images/settings.svg';
import signOut from './../images/signOut.svg';
import gridView from './../images/gridView_blue.svg';
import listView from './../images/listView_blue.svg';
import { successPeople } from './../actions/action';
export class MainView extends React.Component {
constructor(props) {
super(props)
this.state = {
data: data,
active: 0,
activeButton: 'GridView',
searchValue: '',
selectValue: '',
menuOpen: true,
};
this.handleChange = this.handleChange.bind(this);
this.handleLivesChange = this.handleLivesChange.bind(this);
this.toggleDropdown = this.toggleDropdown.bind(this);
}
componentWillMount() {
this.props.successPeople();
}
handleChange(e) {
this.setState({ activeButton: e.target.value });
}
handleUserName(e) {
this.setState({ searchValue: e.target.value });
}
handleLivesChange(val) {
this.setState({ selectValue: val });
}
toggleDropdown() {
this.setState({ menuOpen: !this.state.menuOpen });
}
closeDropdown() {
this.setState({ menuOpen: true });
}
render() {
const filteredUsersArray = this.props.people.filter((people) => {
// const filteredUsersArray = this.state.data.person.filter((people) => {
return (
people.firstName.toLowerCase().includes(this.state.searchValue)
&& (!this.state.selectValue || people.city === this.state.selectValue)
);
});
let menuPage;
switch (this.props.match.params[0]) {
case 'home':
menuPage = filteredUsersArray;
break;
case 'contacts':
menuPage = filteredUsersArray.filter(people => people.friend === true);
break;
case 'favourites':
menuPage = filteredUsersArray.filter(people => people.favourite === true);
break;
case 'people':
menuPage = filteredUsersArray;
break;
case 'companies':
menuPage = filteredUsersArray.filter(people => people.position === 'CEO');
break;
default:
menuPage = [];
}
let pageView;
if (this.state.activeButton === 'GridView') {
pageView = (
<GridView menuPage={menuPage} />
);
} else if (this.state.activeButton === 'ListView') {
pageView = (
<ListView menuPage={menuPage} />
);
} else pageView = 'oops smth went wrong!';
const optionsArray = this.props.people.map((people) => {
return (people.city);
});
const citiesList = [...new Set(optionsArray)];
citiesList.unshift('');
return (
<div className="container">
<div id="menu" onClick={this.toggleDropdown} className={(this.state.menuOpen)? "open" : ""}>
<div id="nav-icon" onClick={this.toggleDropdown} className={(this.state.menuOpen)? "open" : ""}>
<span ></span>
<span ></span>
<span ></span>
<span ></span>
<span ></span>
<span ></span>
</div>
<div id="links" onClick={this.closeDropdown.bind(this)} className={(this.state.menuOpen)? "active" : ""} >
<section>
<ActiveUser data={this.state.data} active={this.state.active} />
<MenuLink />
<div className="settingsBlock">
<div className="settings">
<a href="/" >
<img src={settings} className="settingImg" alt="settings" />
<span>SETTINGS</span>
</a>
</div>
<div className="settings">
<a href="/" >
<img src={signOut} className="settingImg" alt="signOut" />
<span>SIGN OUT</span>
</a>
</div>
</div>
</section>
</div>
</div>
<div className="container_page">
<header>
<div className="header">
<div className="search_input">
<input
type="text"
className="form-control"
placeholder="Search..."
onChange={this.handleUserName.bind(this)}
/>
</div>
<div className="rightHeader">
<div className="welcomeUser">
<div className="welcome">
<span>Welcome,</span>
</div>
<div className="welcomeJD">
<img src={jd} className="JD" alt="JD" />
<span>John Doe</span>
</div>
</div>
<div className="header_logo">
<img src={logo} className="App-logo" alt="logo" />
</div>
</div>
</div>
<div className="pageView">
<div className="headerView">
<div className="pageName">
<h2>{this.props.match.params[0]}</h2>
</div>
<div
className="view"
onSubmit={this.handleSubmit}>
<label>
<input
className="radio radioGridView"
type="radio"
value="GridView"
checked={this.state.activeButton === 'GridView'}
onChange={this.handleChange}
/>
<img src={gridView} alt="gridView" />
</label>
<label>
<input
className="radio radioListView"
type="radio"
value="ListView"
checked={this.state.activeButton === 'ListView'}
onChange={this.handleChange}
/>
<img src={listView} alt="listView" />
</label>
</div>
</div>
<div className="location">
<img src={location} alt="location" />
<FilterOptions options={citiesList} changeOption={this.handleLivesChange} />
</div>
</div>
</header>
<main>
{pageView}
</main>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
people: state.people.people,
};
}
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({
successPeople,
}, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(MainView);
|
import React from 'react';
import { connect } from 'react-redux';
import { updateReview} from '../../actions/reviews_actions';
// TODO from tony // get the review
import { requestEvent} from '../../actions/business_actions';
import ReviewForm from './review_form';
class EditReviewForm extends React.Component {
componentDidMount(){
this.props.requestEvent(this.props.match.params.eventId);
}
render () {
const { event, formType, submitEvent } = this.props;
if (!event) return null;
return (
<ReviewForm
event={event}
formType={formType}
submitEvent={submitEvent} />
);
}
}
const mSTP = (state, ownProps) => ({
review: state.reviews[ownProps.match.params.eventId],
formType: 'Update Review'
});
const mDTP = (dispatch) => ({
requestReview: reviewId => dispatch(requestReview(reviewId)),
submitEvent : review => dispatch(updateReview(review))
});
export default connect(mSTP, mDTP)(EditReviewForm);
|
const intCard = (int) => {
return `<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${int.empFirstName}</h5>
<h6 class="card-subtitle mb-2 text-muted">${int.role}</h6>
<p class="card-text">ID: ${int.empID}</p>
<p class="card-text">Email: ${int.empEmail}</p>
<p class="card-text">GitHub Username: ${int.github}</p>
</div>
</div>
`;
};
// for(let i = 0; i < teamArray.length; i++) {
// if
// }
module.exports = intCard;
|
//main.js contents
//Pass a config object to require
require.config({
"packages": ["cart", "store"]
});
require(["cart", "store", "store/util"],
function (cart, store, util) {
//use the modules as usual.
});
|
import axios from "axios";
import { weatherMapAPIKey } from "./apiKeys/keys";
// Type imports
import {
GET_CITY,
GET_CITY_WEATHER,
LOADING_CITY,
LOADING_CITY_WEATHER,
CLEAR_CITY,
CITY_ERRORS
} from "./types";
// Fetches city data using the provided city id
export let fetchCityById = cityId => dispatch => {
setLoadingCity();
axios
.get(`/api/cityView/city/${cityId}`)
.then(res => {
dispatch({
type: GET_CITY,
payload: res.data
});
let cityName = res.data.name
.trim()
.slice(0, res.data.name.trim().indexOf(","))
.toLowerCase()
.replace(/ /g, "+");
dispatch(fetchCityWeather(cityName));
})
.catch(err => {
dispatch({
type: CITY_ERRORS,
payload: err.data
});
});
};
// Fetches weather data for the city using the provided city information
let fetchCityWeather = cityName => dispatch => {
setCityWeatherLoading();
axios
.get(
`https://cors-anywhere.herokuapp.com/https://api.openweathermap.org/data/2.5/forecast?q=${cityName},US&APPID=${weatherMapAPIKey}&units=imperial`
)
.then(res => {
dispatch({
type: GET_CITY_WEATHER,
payload: res.data
});
})
.catch(err => {
dispatch({
type: CITY_ERRORS,
payload: err.data
});
});
};
// Set city loading to be true while fetching city data
let setLoadingCity = () => dispatch => {
dispatch({
type: LOADING_CITY
});
};
// Set fetchingWeather to true while fetching city weather data
let setCityWeatherLoading = () => dispatch => {
dispatch({
type: LOADING_CITY_WEATHER
});
};
// Clears the city reducer
export let clearCityReducer = () => dispatch => {
dispatch({
type: CLEAR_CITY
});
};
|
// Importar los módulos requeridos
const mongoose = require("mongoose");
const Usuario = mongoose.model("Usuarios");
const { validationResult } = require("express-validator");
const year = new Date().getFullYear();
// Cargar el formulario de la creación de una cuenta de usuario
exports.formularioCrearCuenta = (req, res, next) => {
res.render("registrarse", {
layout: "auth",
typePage: "register-page",
signButtonValue: "/iniciar-sesion",
signButtonText: "Iniciar sesión",
year,
});
};
// Procesar el formulario de creación de cuenta
exports.crearCuenta = async (req, res, next) => {
// Verificar que no existan errores de validación
const errores = validationResult(req);
const messages = [];
// Obtener las variables desde el cuerpo de la petición
const { nombre, email, password ,direccion,
telefono,
ciudad} = req.body;
// Si hay errores
if (!errores.isEmpty()) {
// Utilizar la función map para navegar dentro de un arreglo
errores
.array()
.map((error) =>
messages.push({ message: error.msg, alertType: "danger" })
);
// Agregar los errores a nuestro mensajes flash
req.flash("messages", messages);
res.redirect("/crear-cuenta");
} else {
// Intentar almacenar los datos del usuario
try {
// Crear el usuario
// https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise
// https://developer.mozilla.org/es/docs/Learn/JavaScript/Asynchronous/Async_await
await Usuario.create({
email,
password,
nombre,
direccion,
ciudad
,telefono,
admin: false
});
// Mostrar un mensaje
messages.push({
message: "!Usuario creado satisfactoriamente!",
alertType: "success",
});
req.flash("messages", messages);
res.redirect("/iniciar-sesion");
} catch (error) {
messages.push({
message: error,
alertType: "danger",
});
req.flash("messages", messages);
res.redirect("/crear-cuenta");
}
}
};
// Cargar el formulario de inicio de sesión
exports.formularioIniciarSesion = (req, res, next) => {
res.render("iniciarSesion", {
layout: "auth",
typePage: "login-page",
signButtonValue: "/crear-cuenta",
signButtonText: "Regístrate",
year,
});
};
exports.modificarUsuario = async (req, res, next) => {
const {nombre, telefono, ciudad,direccion } = req.body;
try {
const email = req.user.email;
const usuario = await Usuario.findOne({email});
usuario.telefono = telefono;
usuario.direccion = direccion;
usuario.nombre=nombre;
usuario.ciudad = ciudad;
console.log(usuario);
await usuario.save();
res.redirect("/perfil");
} catch (error) {
res.redirect("/perfil");
}
}
exports.perfil = (req, res, next) => {
res.locals.role = req.user.admin;
const usuarios = req.user.nombre;
nombre = req.user.nombre;
direccion=req.user.direccion;
ciudad=req.user.ciudad;
telefono=req.user.telefono;
res.render("perfil", {
usuarios,
email: req.user.email,
telefono,
ciudad,
direccion,
});
}
exports.usuariomain = (req, res, next) => {
const usuarios = req.user.nombre;
nombre = req.user.nombre;
res.render("/layouts/main", {
usuarios,
email: req.user.email,
nombre
});
}
|
const validateEntityMiddleware = require("./validation.middleware")
const validUUIDMiddleware = require("./uuid-validation.middleware")
module.exports = {
validateEntityMiddleware,
validUUIDMiddleware
}
|
(function(){
Route.getinlanddiscount(function(data){
var str = template('tpl',data);
$('main .info').html(str);
})
})();
|
import React from 'react'
import './backTop.css'
let indexWrap = document.getElementsByClassName("indexWrap")[0]
class BackTop extends React.Component {
state = {
scHeight: 100,
flag: false
}
goToBack(){
let pos = indexWrap.scrollTop;
if(pos > 0){
indexWrap.scrollTop = (pos - 28)
}else{
clearInterval(this.goToBackIt)
}
}
componentWillUnmount(){
clearInterval(this.goToBackIt)
indexWrap.onscroll = null
}
componentDidMount(){
this.onScoll()
}
// 监听定位, 超出显示回到顶部按钮
onScoll(){
indexWrap.onscroll = ()=>{
if(indexWrap.scrollTop > this.state.scHeight){
this.setState({
flag: true
})
}else{
this.setState({
flag: false
})
}
}
}
// 回到顶部
backTop() {
this.goToBackIt = setInterval(()=>{this.goToBack()}, 16)
}
render() {
return (
<span style={{transition: "0.5s"}} className={ this.state.flag ? 'other-backTop' : 'other-backTop-none'} onClick={() => { this.backTop() }}>
<span className="other-backTop-bg"></span>
</span>
)
}
}
export default BackTop
|
// let authentication = require('./controllers/authentication');
// const passportService = require('./services/passport');
// const passport = require('passport');
// const requireAuth = passport.authenticate('jwt', { session: false });
// const requireSignIn = passport.authenticate('local', { session: false });
// const images = require('./controllers/images');
const traffic = require('./controllers/traffic');
const health = require('./controllers/health');
const dashboard = require('./controllers/dashboard');
// const infoburst = require('./controllers/infoburst');
const OktaJwtVerifier = require('@okta/jwt-verifier');
const oktaJwtVerifier = new OktaJwtVerifier({
issuer: 'https://dev-456721.oktapreview.com/oauth2/default',
clientId: '0oairuqk2i2gqj7mZ0h7',
assertClaims: {
aud: 'api://default',
},
});
/**
* A simple middleware that asserts valid access tokens and sends 401 responses
* if the token is not present or fails validation. If the token is valid its
* contents are attached to req.jwt
*/
function authenticationRequired(req, res, next) {
const authHeader = req.headers.authorization || '';
const match = authHeader.match(/Bearer (.+)/);
if (!match) {
return res.status(401).end();
}
const accessToken = match[1];
const expectedAudience = 'api://default';
return oktaJwtVerifier.verifyAccessToken(accessToken, expectedAudience)
.then((jwt) => {
req.jwt = jwt;
next();
})
.catch((err) => {
res.status(401).send(err.message);
});
}
module.exports = function (app) {
app.get('/', health.health);
app.get('/secured', health.secured);
app.get('/heartbeat', health.heartbeat);
app.post('/traffic',traffic.getAllTrafficCams);
app.post('/payments', traffic.getPaymentsForCam);
app.get('/siteids', traffic.getAllSiteIds);
app.post('/streets', traffic.getDistinctStreets);
app.post('/compare', traffic.getComparissonTable);
app.get('/statistics', traffic.getAllStats);
app.post('/allcamsbyid', traffic.getAllTrafficCamsByIDs);
app.post('/viewdetails/revenue', traffic.getViewDetailsRevenue);
app.get('/statistics/yearfilters', traffic.getAllyearsFilters);
app.post('/statistics/statsfiltered', traffic.getAllStatsFiltered);
// app.get('/infoburst/test', infoburst.getInfoburstStats);
app.post('/dashboard/totals', dashboard.getDashboardTotals);
app.post('/dashboard/charts/bymonth', dashboard.getBreakDownByMonth);
app.post('/dashboard/charts/bymonthbreakdown', dashboard.getBreakDownByMonthWithDetails);
app.post('/dashboard/table', dashboard.getTableData);
}
|
module.exports = {
apps : [
{
name: "server",
script : "../server/server.js",
watch: true,
instances: 2,
exec_mode: "cluster",
ignore_watch: ["node_modules"],
watch: true,
},
{
name: "websocket",
script: "../server/websocket.js",
watch: true,
instances: 2,
exec_mode: "cluster",
ignore_watch: ["node_modules"],
watch: true,
},
{
name: "fileServer",
script: "../server/fileServer.js",
watch: true,
},
{
name: "gateway",
script: "./gateway.js",
watch: true,
ignore_watch: ["node_modules"],
watch: true,
},
]
}
|
import React, { useState } from "react";
import { Grid, Button } from "@material-ui/core";
import { connect } from "react-redux";
import ShareIcon from '@material-ui/icons/Share'
function Insights(props) {
return (
<div className="home-insights">
<div className="title border pb-sm-10">OUR LATEST INSIGHTS</div>
<Grid container spacing={3} className="card-container">
<Grid item lg={3} md={3} xs={12} className="card-wrapper">
<div className="card-content">
<img src="/assets/images/insights/card-1.png" alt="card" />
<div className="card-wrapper">
<div className="primary-title">How wealthy individuals can contribute to the overall economic growth Cycle.</div>
<div className="card-title pb-24">Redesigned Account Planning Transforms an IT Company’s Performance</div>
<div className="description">Redesigned Account Planning Transforms an IT Company’s Performance</div>
<div className="card-read-more">
<span>read more</span>
<ShareIcon className="share" />
</div>
</div>
</div>
</Grid>
<Grid item lg={3} md={3} xs={12} className="card-wrapper">
<div className="card-content">
<img src="/assets/images/insights/card-2.png" alt="card" />
<div className="card-wrapper">
<div className="primary-title">How wealthy individuals can contribute to the overall economic growth Cycle.</div>
<div className="card-title pb-24">Redesigned Account Planning Transforms an IT Company’s Performance</div>
<div className="description">New tools and strategies boost year-on-year growth and reenergize the company’s sales pipeline</div>
<div className="card-read-more">
<span>read more</span>
<ShareIcon className="share" />
</div>
</div>
</div>
</Grid>
<Grid item lg={3} md={3} xs={12} className="card-wrapper">
<div className="card-content">
<img src="/assets/images/insights/card-3.png" alt="card" />
<div className="card-wrapper">
<div className="primary-title">Key drivers for finding quality Talent for your business</div>
<div className="card-title pb-24">Redesigned Account Planning Transforms an IT Company’s Performance</div>
<div className="description">New tools and strategies boost year-on-year growth and reenergize the company’s sales pipeline</div>
<div className="card-read-more">
<span>read more</span>
<ShareIcon className="share" />
</div>
</div>
</div>
</Grid>
<Grid item lg={3} md={3} xs={12} className="card-wrapper">
<div className="card-content">
<img src="/assets/images/insights/card-4.png" alt="card" />
<div className="card-wrapper">
<div className="primary-title">How industries can increase job Opportunities with automation</div>
<div className="card-title pb-24">Redesigned Account Planning Transforms an IT Company’s Performance</div>
<div className="description">New tools and strategies boost year-on-year growth and reenergize the company’s sales pipeline</div>
<div className="card-read-more">
<span>read more</span>
<ShareIcon className="share" />
</div>
</div>
</div>
</Grid>
</Grid>
</div>
);
}
const mapStateToProps = state => ({
});
export default connect(
mapStateToProps,
{ }
)(Insights);
|
import React from 'react'
import './Cards.css'
function Cards({ cardset }) {
const renderCardsets = (cardset) => {
const wrappedCardsets = []
for (let i = 0; i < cardset.length; i++) {
let cardrow = cardset[i]
wrappedCardsets.push(<ul className="cards__items" key={i}>{cardrow}</ul>)
}
return wrappedCardsets
}
return (
<div className="cards">
<div className="cards__container">
<div className="cards__wrapper">
{renderCardsets(cardset)}
</div>
</div>
</div>
)
}
export default Cards
|
import mongoose from 'mongoose';
import logger from './logger';
mongoose.Promise = global.Promise;
const uri =
process.env.NODE_ENV === 'test'
? `mongodb://${process.env.TEST_DB_USER}:${process.env.TEST_DB_PASS}@${process.env.TEST_DB_SERVER}/${process.env.TEST_DB_NAME}`
: `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_SERVER}/${process.env.DB_NAME}`;
const env = process.env.NODE_ENV ? process.env.NODE_ENV : 'production';
const connection = mongoose.connect(uri, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true
});
connection
.then((db) => {
logger.info(`Successfully connected to ${uri} MongoDB cluster in ${env} mode.`);
return db;
})
.catch((err) => {
if (err.message.code === 'ETIMEDOUT') {
logger.info('Attempting to re-establish database connection.');
mongoose.connect(uri);
} else {
logger.error('Error while attempting to connect to database:');
logger.error(err);
}
});
export default connection;
|
import _start from "../sounds/start.mp3";
import _pause from "../sounds/pause.mp3";
import _reset from "../sounds/stop.mp3";
import _end from "../sounds/alarm-buzzer.mp3";
export const start = new Audio(_start);
export const pause = new Audio(_pause);
export const reset = new Audio(_reset);
export const end = new Audio(_end);
|
/**
* @param {number} n
* @return {string}
*/
var countAndSay = function (n) {
if (n === 1) return "1";
let answer = "1";
// iterate it n-1 times
for (let i = 1; i < n; i++) {
let iteration = "";
let count = 0;
let int = "";
for (let number of answer) {
if (number !== int && count > 0) {
iteration += count + int;
count = 1;
} else {
count++;
}
int = number;
}
answer = iteration + count + int;
}
return answer;
};
console.log(countAndSay(3))
|
define([
'angular',
'lodash',
'config'
],
function (angular, _, config) {
'use strict';
var module = angular.module('kibana.services');
module.service('fields', function(dashboard, $rootScope, $http, esVersion, alertSrv, ejsResource) {
// Save a reference to this
var self = this;
var ejs = ejsResource(config.elasticsearch);
this.list = ['_type'];
this.indices = [];
// Stop tracking the full mapping, too expensive, instead we only remember the index names
// we've already seen.
//
$rootScope.$watch(function(){return dashboard.indices;},function(n) {
if(!_.isUndefined(n) && n.length && dashboard.current.index.warm_fields) {
// Only get the mapping for indices we don't know it for
var indices = _.difference(n,_.keys(self.indices));
// Only get the mapping if there are new indices
if(indices.length > 0) {
self.map(indices).then(function(result) {
self.indices = _.union(self.indices,_.keys(result));
self.list = mapFields(result);
});
}
}
});
var mapFields = function (m) {
var fields = [];
_.each(m, function(types) {
_.each(types, function(type) {
fields = _.difference(_.union(fields,_.keys(type)),
['_parent','_routing','_size','_ttl','_all','_uid','_version','_boost','_source']);
});
});
return fields;
};
this.map = function(indices) {
var request = ejs.client.get('/' + indices.join(',') + "/_mapping",
undefined, undefined, function(data, status) {
if(status === 0) {
alertSrv.set('Error',"Could not contact Elasticsearch at "+ejs.config.server+
". Please ensure that Elasticsearch is reachable from your system." ,'error');
} else {
alertSrv.set('Error',"No index found at "+ejs.config.server+"/" +
indices.join(',')+"/_mapping. Please create at least one index." +
"If you're using a proxy ensure it is configured correctly.",'error');
}
});
// Flatten the mapping of each index into dot notated keys.
return request.then(function(p) {
var mapping = {};
return esVersion.gte('1.0.0.RC1').then(function(version) {
_.each(p, function(indexMap,index) {
mapping[index] = {};
_.each((version ? indexMap.mappings : indexMap), function (typeMap,type) {
mapping[index][type] = flatten(typeMap);
});
});
return mapping;
});
});
};
// This should understand both the 1.0 format and the 0.90 format for mappings. Ugly.
var flatten = function(obj,prefix) {
var propName = (prefix) ? prefix : '',
dot = (prefix) ? '.':'',
ret = {};
for(var attr in obj){
if(attr === 'dynamic_templates' || attr === '_default_') {
continue;
}
// For now only support multi field on the top level
// and if there is a default field set.
if(obj[attr]['type'] === 'multi_field') {
ret[attr] = obj[attr]['fields'][attr] || obj[attr];
var keys = _.without(_.keys(obj[attr]['fields']),attr);
for(var key in keys) {
ret[attr+'.'+keys[key]] = obj[attr]['fields'][keys[key]];
}
} else if (attr === 'properties' || attr ==='fields') {
_.extend(ret,flatten(obj[attr], propName));
} else if(typeof obj[attr] === 'object' &&
(!_.isUndefined(obj[attr].type) || !_.isUndefined(obj[attr].properties))){
_.extend(ret,flatten(obj[attr], propName + dot + attr));
} else {
if(propName !== '') {
ret[propName] = obj;
}
}
}
return ret;
};
});
});
|
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
define(function(require) {
require('spice-main');
var host = null, port = null;
var sc;
function spice_set_cookie(name, value, days) {
var date, expires;
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
};
function spice_query_var(name, defvalue) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: defvalue;
}
function spice_error(e) {
disconnect();
}
function connect() {
var host, port, password, scheme = "ws://", uri;
// By default, use the host and port of server that served this file
host = spice_query_var('host', window.location.hostname);
// Note that using the web server port only makes sense
// if your web server has a reverse proxy to relay the WebSocket
// traffic to the correct destination port.
var default_port = window.location.port;
if (!default_port) {
if (window.location.protocol == 'http:') {
default_port = 80;
} else if (window.location.protocol == 'https:') {
default_port = 443;
}
}
port = spice_query_var('port', default_port);
if (window.location.protocol == 'https:') {
scheme = "wss://";
}
// If a token variable is passed in, set the parameter in a cookie.
// This is used by nova-spiceproxy.
token = spice_query_var('token', null);
if (token) {
spice_set_cookie('token', token, 1)
}
password = spice_query_var('password', '');
path = spice_query_var('path', 'websockify');
if ((!host) || (!port)) {
console.log("must specify host and port in URL");
return;
}
if (sc) {
sc.stop();
}
uri = scheme + host + ":" + port + "?token=" + token;
try {
sc = new SpiceMainConn({uri: uri, screen_id: "spice-screen", dump_id: "debug-div",
message_id: "message-div", password: password, onerror: spice_error, onagent: agent_connected});
}
catch (e) {
alert(e.toString());
disconnect();
}
}
function disconnect() {
console.log(">> disconnect");
if (sc) {
sc.stop();
}
if (window.File && window.FileReader && window.FileList && window.Blob) {
var spice_xfer_area = document.getElementById('spice-xfer-area');
document.getElementById('spice-area').removeChild(spice_xfer_area);
document.getElementById('spice-area').removeEventListener('dragover', handle_file_dragover, false);
document.getElementById('spice-area').removeEventListener('drop', handle_file_drop, false);
}
console.log("<< disconnect");
}
function agent_connected(sc) {
window.addEventListener('resize', handle_resize);
window.spice_connection = this;
resize_helper(this);
if (window.File && window.FileReader && window.FileList && window.Blob) {
var spice_xfer_area = document.createElement("div");
spice_xfer_area.setAttribute('id', 'spice-xfer-area');
document.getElementById('spice-area').addEventListener('dragover', handle_file_dragover, false);
document.getElementById('spice-area').addEventListener('drop', handle_file_drop, false);
} else {
console.log("File API is not supported");
}
}
connect();
});
|
import React from 'react'
import { View, Text, StyleSheet, Button } from 'react-native'
export default function Store({history}) {
return (
<View style={styles.container}>
<Button title="Go Back" color="red" onPress={() => history.goBack()} />
</View>
)
}
const styles = StyleSheet.create({
container : {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
text: {
fontSize: 30
}
})
|
/*
* Copyright 2011-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var vertx = vertx || {};
if (!vertx.createHttpServer) {
(function() {
function convertMap(j_map) {
var map = {};
var j_iter = j_map.entrySet().iterator();
while (j_iter.hasNext()) {
var entry = j_iter.next();
map[entry.getKey()] = entry.getValue();
}
return map;
}
function wrappedRequestHandler(handler) {
return function(j_req) {
//We need to add some functions to the request and the response
var reqHeaders = null;
var reqParams = null;
var req = {
headers: function() {
if (!reqHeaders) {
reqHeaders = convertMap(j_req.headers());
}
return reqHeaders;
},
params: function() {
if (!reqParams) {
reqParams = convertMap(j_req.params());
}
return reqParams;
}
};
var j_resp = j_req.response;
var respHeaders = null;
var headersWritten = false;
function writeHeaders() {
if (respHeaders && !headersWritten) {
var j_hdrs = j_resp.headers();
for (var k in respHeaders) {
j_hdrs.put(k, respHeaders[k])
}
headersWritten = true;
}
}
var respTrailers = null;
var trailersWritten = false;
function writeTrailers() {
if (respTrailers && !trailersWritten) {
var j_trailers = j_resp.trailers();
for (var k in respTrailers) {
j_trailers.put(k, respTrailers[k])
}
trailersWritten = true;
}
}
var resp = {
headers: function() {
if (!respHeaders) {
respHeaders = {};
}
return respHeaders;
},
putAllHeaders: function(other) {
var hdrs = resp.headers();
for (var k in other) {
hdrs[k] = other[k];
}
},
trailers: function() {
if (!respTrailers) {
respTrailers = {};
}
return respTrailers;
},
putAllTrailers: function(other) {
var trlrs = resp.trailers();
for (var k in other) {
trlrs[k] = other[k];
}
},
write: function(arg0, arg1, arg2) {
writeHeaders();
if (arg1) {
if (arg2) {
j_resp.write(arg0, arg1, arg2);
} else {
j_resp.write(arg0, arg1);
}
} else {
j_resp.write(arg0);
}
return resp;
},
writeBuffer: function(buffer) {
writeHeaders();
j_resp.writeBuffer(buffer);
},
continueHandler: function(handler) {
j_resp.continueHandler(handler);
},
sendHead: function() {
writeHeaders();
j_resp.sendHead();
return resp;
},
end: function(arg0, arg1) {
writeHeaders();
writeTrailers();
if (arg0) {
if (arg1) {
j_resp.end(arg0, arg1);
} else {
j_resp.end(arg0);
}
} else {
j_resp.end();
}
}
}
req.response = resp;
req.__proto__ = j_req;
resp.__proto__ = j_req.response;
handler(req);
}
}
vertx.createHttpServer = function() {
var j_server = org.vertx.java.platform.impl.RhinoVerticleFactory.vertx.createHttpServer();
var that = {};
that.requestHandler = function(handler) {
if (handler) {
if (typeof handler === 'function') {
handler = wrappedRequestHandler(handler);
} else {
// It's a route matcher
handler = handler._to_java_handler();
}
j_server.requestHandler(handler);
}
return that;
};
that.websocketHandler = function(handler) {
if (handler) {
j_server.websocketHandler(handler);
}
return that;
};
that.close = function(handler) {
if (handler) {
j_server.close(handler);
} else {
j_server.close();
}
};
that.listen = function(port, host) {
if (host) {
j_server.listen(port, host);
} else {
j_server.listen(port);
}
return that;
}
that.setSSL = function(ssl) {
j_server.setSSL(ssl);
return that;
}
that.setKeyStorePath = function(path) {
j_server.setKeyStorePath(path);
return that;
}
that.setKeyStorePassword = function(password) {
j_server.setKeyStorePassword(password);
return that;
}
that.setTrustStorePath = function(path) {
j_server.setTrustStorePath(path);
return that;
}
that.setTrustStorePassword = function(password) {
j_server.setTrustStorePassword(password);
return that;
}
that.setClientAuthRequired = function(required) {
j_server.setClientAuthRequired(required);
return that;
}
that.setTCPNoDelay = function(tcpNoDelay) {
j_server.setTCPNoDelay(tcpNoDelay);
return that;
}
that.setSendBufferSize = function(size) {
j_server.setSendBufferSize(size);
return that;
}
that.setReceiveBufferSize = function(size) {
j_server.setReceiveBufferSize(size);
return that;
}
that.setTCPKeepAlive = function(keepAlive) {
j_server.setTCPKeepAlive(keepAlive);
return that;
}
that.setReuseAddress = function(reuse) {
j_server.setReuseAddress(reuse);
return that;
}
that.setSoLinger = function(linger) {
j_server.setSoLinger(linger);
return that;
}
that.setTrafficClass = function(klazz) {
j_server.setTrafficClass(klazz);
return that;
}
that.setClientAuthRequired = function(required) {
j_server.setClientAuthRequired(required);
return that;
}
that.isTCPNoDelay = function() {
return j_server.isTCPNoDelay();
}
that.getSendBufferSize = function() {
return j_server.getSendBufferSize();
}
that.getReceiveBufferSize = function() {
return j_server.getReceiveBufferSize();
}
that.isSoLinger = function() {
return j_server.isSoLinger();
}
that.getTrafficClass = function() {
return j_server.getTrafficClass();
}
that.isSSL = function() {
return j_server.isSSL();
}
that._to_java_server = function() {
return j_server;
}
return that;
}
vertx.createHttpClient = function() {
var j_client = org.vertx.java.platform.impl.RhinoVerticleFactory.vertx.createHttpClient();
function wrapResponseHandler(handler) {
var wrapperHandler = function(j_resp) {
var respHeaders = null;
var respTrailers = null;
var resp = {
headers: function() {
if (!respHeaders) {
respHeaders = convertMap(j_resp.headers());
}
return respHeaders;
},
trailers: function() {
if (!respTrailers) {
respTrailers = convertMap(j_resp.trailers());
}
return respTrailers;
}
};
resp.__proto__ = j_resp;
handler(resp);
}
return wrapperHandler;
}
function wrapRequest(j_req) {
var reqHeaders = null;
var headersWritten = false;
function writeHeaders() {
if (reqHeaders && !headersWritten) {
var j_hdrs = j_req.headers();
for (var k in reqHeaders) {
j_hdrs.put(k, reqHeaders[k])
}
headersWritten = true;
}
}
var wrapped = {
headers: function() {
if (!reqHeaders) {
reqHeaders = convertMap(j_req.headers());
}
return reqHeaders;
},
putAllHeaders: function(other) {
var hdrs = wrapped.headers();
for (var k in other) {
hdrs[k] = other[k];
}
},
write: function(arg0, arg1, arg2) {
writeHeaders();
if (arg1) {
if (arg2) {
j_req.write(arg0, arg1, arg2);
} else {
j_req.write(arg0, arg1);
}
} else {
j_req.write(arg0);
}
return wrapped;
},
writeBuffer: function(buff) {
writeHeaders();
j_req.writeBuffer(buff);
},
continueHandler: function(handler) {
j_req.continueHandler(handler);
},
sendHead: function() {
writeHeaders();
j_req.sendHead();
return wrapped;
},
end: function(arg0, arg1) {
writeHeaders();
if (arg0) {
if (arg1) {
j_req.end(arg0, arg1);
} else {
j_req.end(arg0);
}
} else {
j_req.end();
}
}
};
wrapped.__proto__ = j_req;
return wrapped;
}
var that = {};
that.exceptionHandler = function(handler) {
j_client.exceptionHandler(handler);
return that;
}
that.setMaxPoolSize = function(size) {
j_client.setMaxPoolSize(size);
return that;
}
that.getMaxPoolSize = function() {
return j_client.getMaxPoolSize();
}
that.setKeepAlive = function(keepAlive) {
j_client.setKeepAlive(keepAlive);
return that;
}
that.setSSL = function(ssl) {
j_client.setSSL(ssl);
return that;
}
that.setKeyStorePath = function(path) {
j_client.setKeyStorePath(path);
return that;
}
that.setKeyStorePassword = function(password) {
j_client.setKeyStorePassword(password);
return that;
}
that.setTrustStorePath = function(path) {
j_client.setTrustStorePath(path);
return that;
}
that.setTrustStorePassword = function(password) {
j_client.setTrustStorePassword(password);
return that;
}
that.setTrustAll = function(trustAll) {
j_client.setTrustAll(trustAll);
return that;
}
that.setPort = function(port) {
j_client.setPort(port);
return that;
}
that.setHost = function(host) {
j_client.setHost(host);
return that;
}
that.connectWebsocket = function(uri, handler) {
j_client.connectWebsocket(uri, handler);
}
that.getNow = function(uri, handler) {
return wrapRequest(j_client.getNow(uri, wrapResponseHandler(handler)));
}
that.options = function(uri, handler) {
return wrapRequest(j_client.options(uri, wrapResponseHandler(handler)));
}
that.get = function(uri, handler) {
return wrapRequest(j_client.get(uri, wrapResponseHandler(handler)));
}
that.head = function(uri, handler) {
return wrapRequest(j_client.head(uri, wrapResponseHandler(handler)));
}
that.post = function(uri, handler) {
return wrapRequest(j_client.post(uri, wrapResponseHandler(handler)));
}
that.put = function(uri, handler) {
return wrapRequest(j_client.put(uri, wrapResponseHandler(handler)));
}
that.delete = function(uri, handler) {
return wrapRequest(j_client.delete(uri, wrapResponseHandler(handler)));
}
that.trace = function(uri, handler) {
return wrapRequest(j_client.trace(uri, wrapResponseHandler(handler)));
}
that.connect = function(uri, handler) {
return wrapRequest(j_client.connect(uri, wrapResponseHandler(handler)));
}
that.patch = function(uri, handler) {
return wrapRequest(j_client.patch(uri, wrapResponseHandler(handler)));
}
that.request = function(method, uri, handler) {
return wrapRequest(j_client.request(method, uri, wrapResponseHandler(handler)));
}
that.close = function() {
j_client.close();
}
that.setTCPNoDelay = function(tcpNoDelay) {
j_client.setTCPNoDelay(tcpNoDelay);
return that;
}
that.setSendBufferSize = function(size) {
j_client.setSendBufferSize(size);
return that;
}
that.setReceiveBufferSize = function(size) {
j_client.setReceiveBufferSize(size);
return that;
}
that.setTCPKeepAlive = function(keepAlive) {
j_client.setTCPKeepAlive(keepAlive);
return that;
}
that.setReuseAddress = function(reuse) {
j_client.setReuseAddress(reuse);
return that;
}
that.setSoLinger = function(linger) {
j_client.setSoLinger(linger);
return that;
}
that.setTrafficClass = function(klazz) {
j_client.setTrafficClass(klazz);
return that;
}
that.isTCPNoDelay = function() {
return j_client.isTCPNoDelay();
}
that.getSendBufferSize = function() {
return j_client.getSendBufferSize();
}
that.getReceiveBufferSize = function() {
return j_client.getReceiveBufferSize();
}
that.isSoLinger = function() {
return j_client.isSoLinger();
}
that.getTrafficClass = function() {
return j_client.getTrafficClass();
}
that.isSSL = function() {
return j_client.isSSL();
}
return that;
}
vertx.RouteMatcher = function() {
var j_rm = new org.vertx.java.core.http.RouteMatcher();
this.get = function(pattern, handler) {
j_rm.get(pattern, wrappedRequestHandler(handler));
}
this.put = function(pattern, handler) {
j_rm.put(pattern, wrappedRequestHandler(handler));
}
this.post = function(pattern, handler) {
j_rm.post(pattern, wrappedRequestHandler(handler));
}
this.delete = function(pattern, handler) {
j_rm.delete(pattern, wrappedRequestHandler(handler));
}
this.options = function(pattern, handler) {
j_rm.options(pattern, wrappedRequestHandler(handler));
}
this.head = function(pattern, handler) {
j_rm.head(pattern, wrappedRequestHandler(handler));
}
this.trace = function(pattern, handler) {
j_rm.trace(pattern, wrappedRequestHandler(handler));
}
this.connect = function(pattern, handler) {
j_rm.connect(pattern, wrappedRequestHandler(handler));
}
this.patch = function(pattern, handler) {
j_rm.patch(pattern, wrappedRequestHandler(handler));
}
this.all = function(pattern, handler) {
j_rm.all(pattern, wrappedRequestHandler(handler));
}
this.getWithRegEx = function(pattern, handler) {
j_rm.getWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.putWithRegEx = function(pattern, handler) {
j_rm.putWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.postWithRegEx = function(pattern, handler) {
j_rm.postWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.deleteWithRegEx = function(pattern, handler) {
j_rm.deleteWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.optionsWithRegEx = function(pattern, handler) {
j_rm.optionsWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.headWithRegEx = function(pattern, handler) {
j_rm.headWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.traceWithRegEx = function(pattern, handler) {
j_rm.traceWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.connectWithRegEx = function(pattern, handler) {
j_rm.connectWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.patchWithRegEx = function(pattern, handler) {
j_rm.patchWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.allWithRegEx = function(pattern, handler) {
j_rm.allWithRegEx(pattern, wrappedRequestHandler(handler));
}
this.noMatch = function(handler) {
j_rm.noMatch(wrappedRequestHandler(handler));
}
this._to_java_handler = function() {
return j_rm;
}
}
})();
}
|
import axios from 'axios';
export function loginHandler(data) {
return dispatch => {
dispatch({
type: 'LOGIN_PENDING',
});
axios
.post("http://192.168.1.100:8000/users/api/auth/login", data)
.then(res => {
dispatch({type: 'LOGIN_SUCCESS', payload: res.data});
})
.catch(err => {
dispatch({
type: 'LOGIN_REJECTED',
payload: err,
});
});
};
}
export function logoutHandler() {
return dispatch => {
dispatch({type: 'LOGOUT'});
};
}
|
import {Color} from 'spritejs';
export function parseColor(colors) {
if(Array.isArray(colors)) {
return colors.map((c) => {
if(typeof c === 'string') {
return new Color(c);
}
return c;
});
}
return typeof colors === 'string' ? new Color(colors) : colors;
}
|
/**
* @author lxl
* @version v1.0.12
* 等于类型 符号: 等于(==) 不等于(!=)
* 范围 符号: 大于(>) 小于(<) 不小于(>=) 不大于(<=)
* 模糊 符号: 像(~=)
* eg:
* let qs = 'at>123456789,tid==00895485acb,tid>=null,at<233456789,hid~=A01**1223++300\\03+++,at!=200,hid!=B01122330003,pid==,cid!=00,ppd>,value==138,,mail==abc_1554+da==ddkl@163.com';
* return: {
at:{
$gt: 123456789,
$lt: 233456789,
$ne: 200
},
tid:{
$eq: '00895485acb'
},
hid:{
$regex: '/A01\\*\\*1223\\+\\+300\\\\03\\+\\+\\+/gi'
}
}
*/
/**
* @param {String} queryString 以透号分割的key, value字符串
* @param {<Object> | <boolean>} options 默认为boolean值为true, 为Object时则指定key的字符型数字强制转为数值型数字, 如{ at: true }, 则会对key为at的值能转为数值型强制转换
* @return {JSON} conditions
*/
function parseQstring(queryString, options = true) {
if(!queryString) return {};
/** 暂时只支持的mongo支持的逻辑计算符号集 */
const mongoObj = {
'==': '$eq',
'!=': '$ne',
'>=': '$gte',
'<=': '$lte',
'>': '$gt',
'<': '$lt',
'~=':'$regex'
};
const conditions = {};
const queryStringArr = queryString.split(','); //[ 'tid==00895485acb', 'at>123456789', 'at<233456789', 'at!=200', 'hid~=A01122330003', 'hid!=B01122330003' ]
let key = ''; //变量名
let temObj = {}; //铺助对象, 用于构造参数对象, 如{ "tid":{"$eq":"00895485acb"} }
for (let qs of queryStringArr) {
if (!qs) continue;
const logiclOperator = (/[==|!=|>=|<=|>|<|~=]{1,2}/).exec(qs)[0]; // 此处用正则取出逻辑操作符号
if (!logiclOperator) continue;
let logiclOperatorIndex = qs.indexOf(logiclOperator);
key = qs.substring(0, logiclOperatorIndex);
let value = qs.substring(logiclOperatorIndex + logiclOperator.length);
if(!key || key.toLowerCase() === 'undefined' || key.toLowerCase() === 'null') continue;
if (!value || value.toLowerCase() === 'undefined' || value.toLowerCase() === 'null') continue;
if (logiclOperator === '~=') { // 针对模糊查找时对value作转义字符处理
value = new RegExp(makeQueryStringAllRegExp(value), 'gi');
}
if (typeof options === 'boolean' && options) { // 此处决定是否将字符型数字转为数值型数字
value = isNaN(Number(value)) ? value : Number(value);
} else if (typeof options === 'object') {
if (options[key]) value = isNaN(Number(value)) ? value : Number(value);
}
if (conditions[key]) {
conditions[key][mongoObj[logiclOperator]] = value; //conditions存在属性时,追加属性
} else {
temObj[mongoObj[logiclOperator]] = value; //conditions不存在属性时,直接给str赋属性
conditions[key] = temObj;
temObj = {}; //conditions不存在属性时,赋空对象给str以重新赋属性
}
}
return conditions; //{"tid":{"$eq":"00895485acb"},"at":{"$gt":"123456789","$lt":"233456789","$ne":"200"},"hid":{"$regex":"/A01\\*\\*1223\\+\\+300\\\\03\\+\\+\\+/gi","$ne":"B01122330003"}}
};
/**
* 将字符串中的特殊作转义处理
* @param {String} str
*/
function makeQueryStringAllRegExp(str) {
const fbsArr = ['\\\\', '\\$', '\\(', '\\)', '\\*', '\\+', '\\.', '\\[', '\\]', '\\?', '\\^', '\\{', '\\}', '\\|'];
for (let item of fbsArr) {
const instead = RegExp(item, 'g');
str = str.replace(instead, item);
}
return str;
};
module.exports = parseQstring;
|
$(document).ready(function() {
var $window = $(window);
checkHeight($window);
$window.resize(function () { checkHeight($window); });
});
function checkHeight($window) {
var windowsHeight = $window.height();
var headerHeight = $('.header').height();
var borderBottomHeight = $('.border.hor.bot').height();
var borderTopHeight = $('.border.hor.top').height();
var footerHeight = $('.footer').height();
var innerHeight = windowsHeight - (headerHeight + (borderBottomHeight + borderTopHeight));
var contentHeight = windowsHeight - (headerHeight + borderBottomHeight + borderTopHeight + footerHeight) - 20;
$('.frontpage .banner').css("height", innerHeight + "px");
$('.content').css("min-height", contentHeight + "px");
}
function contactformCompleted(data) {
var errorCode = data.statusText;
var errorMessage = data.ErrorMessage;
if (errorCode === "OK") {
$(".contactform").slideUp(function () {
$(".thanks").slideDown();
});
}
else if (errorCode === "Error") {
alert(errorMessage);
}
}
function formCompleted(data) {
var errorCode = data.ErrorCode;
var errorMessage = data.ErrorMessage;
alert(errorCode + " - " + errorMessage);
}
function test(result) {
if (result) {
alert("Authentication succesful. Redirecting to main intranet page.");
}
else {
alert("Authentication failed. Please check your username and password.");
}
}
|
// <--- LISTENERS --->
// Listener for the landing page button. Launches the game, refreshes the screen.
$('.landing-pageContent #startButton').on('click',(e) => {
$userInput = $('#petName')
game.checkName($userInput);
})
// listener to decide if cat or dog
$('.catOrDog').on('click',(e) => {
$petType = $(e.target)
game.start($('#petName'),$petType);
})
// listeners for action buttons during the game
$('#action-buttons').on('click',(e) => {
$button = $(e.target)
game.action($button)
})
// <-- GAME ENGINE AND DATA -->
// Tamagotchi class. All data regarding tamagotchi is stored here.
class Tamagotchi {
constructor(petName,petType){
this.name = petName;
this.age = 1;
this.sleepiness = 1;
this.hunger = 1;
this.boredom = 1;
this.maxStatValue = 10;
this.minStatValue = 1;
this.isSleeping = false;
this.isAlive = true;
this.isAwake = true;
this.currentSprite = 1;
this.totalSprites = 10;
this.sleepinessSquares = [];
this.hungerSquares = [];
this.boredomSquares = [];
this.pickedSprite = petType;
this.difficultyIndex = 1;
this.latestMorph = 1;
};
// creates the array with colors of boxes used for stats animation.
// can be changes to display higher or lower maxStatValue
createSquares(maxStatValue){
for (let i = 1; i <= this.maxStatValue; i++){
let color = this.returnColor(i);
this.sleepinessSquares.push(color);
this.hungerSquares.push(color);
this.boredomSquares.push(color);
}
};
// color coding for the squares created in createSquares
returnColor(squareIndex){
let color = ''
switch (squareIndex){
case 1:
case 2:
case 3:
case 4: {color = 'darkgreen'; break;}
case 5:
case 6:
case 7: {color = 'orange'; break;}
case 8:
case 9:
case 10: {color = 'red'; break;}
default: {console.log('error in createSquares function')}
}
return color;
};
// based on time, updates stats of the pet.
// increase in stats depends on difficulty. Difficulty based on age and morph level.
// if pet needs to morph, return a true value to calling function to morph.
updateStas(time, dayLength){
if(time % dayLength === 0) this.age++;
if(time % Math.ceil(dayLength/12) === 0) this.sleepiness+= this.difficultyIndex;
if(time % 45 === 0) this.hunger += this.difficultyIndex;
if(time % 15 === 0) this.boredom += this.difficultyIndex;
this.checkAlive();
if(this.age % 5 === 0 && this.latestMorph !== this.age) {
this.difficultyIndex++
this.latestMorph = this.age
return true;
} else return false;
};
// sleep, feed, play functions reset value of stats to minimum value
sleep(){
this.sleepiness = this.minStatValue;
this.isAwake = false;
};
feed(){
this.hunger = this.minStatValue
};
play(){
this.boredom = this.minStatValue;
};
// kills your pet... it's life I guess..
kill(){
this.isAlive = false;
};
// sets value in Tamagotchi object to false if pet is dead.
checkAlive(){
if (this.sleepiness >= 10 || this.hunger >=10 || this.boredom >=10){
this.isAlive = false;
}
};
}
// game object. game timer and animations are all here
const game = {
pet : {},
// dayLength - please consider cycle length of setInterval prior to change.
// influences speed of again and other stats speed of increase
dayLength: 300,
time: 1,
// user cannot start a game if a valid input is not provided.
// hides modal box sitting on top of game.
checkName($userInput){
const petName = $userInput.val();
if (petName !== '') {
$('#petName').fadeOut(1000);
$('#startButton').fadeOut(1000);
this.catOrDog();
} else alert ('Pet name cannot be empty!')
},
catOrDog(){
$('.catOrDog').delay(1000).fadeIn(1000);
// this.start(petName,'cat')
// $('.landing-page').fadeOut(1500);
},
// starts the game. creates the pet objects, initiate time, set up stats
start($petName,$petType){
const petName = $petName.val()
const petType = $petType.text().toLowerCase()
$('.landing-page').fadeOut(1500);
$('.catOrDog').fadeOut(1500);
$('.landing-pageContent > h3').remove();
this.pet = new Tamagotchi(petName,petType)
this.pet.createSquares(this.pet.maxStatValue)
$('#petNameBio').text(petName)
$('#petAgeBio').text(`${this.pet.age} days`)
this.printStats();
this.startTimer();
},
// update of stats bar of the game.
printStats(){
$('#sleepinessSquares').empty();
$('#hungerSquares').empty();
$('#boredomSquares').empty();
for (let i = 0; (i < this.pet.sleepiness && i < this.pet.maxStatValue); i++){
const $square = $('<div>').val(i).css('background-color', this.pet.sleepinessSquares[i])
$('#sleepinessSquares').append($square)
}
for (let i = 0; (i < this.pet.boredom && i < this.pet.maxStatValue); i++){
const $square = $('<div>').val(i).css('background-color', this.pet.boredomSquares[i])
$('#boredomSquares').append($square)
}
for (let i = 0; (i < this.pet.hunger && i < this.pet.maxStatValue); i++){
const $square = $('<div>').val(i).css('background-color', this.pet.hungerSquares[i])
$('#hungerSquares').append($square)
}
$('#petAgeBio').text(`${this.pet.age} days`)
},
// start timer of the game. In charge of ending the game if pet is dead.
// responsible for kicking off the pet morph animation
startTimer(){
this.pet.currentSprite = 1;
const intervalId = setInterval(() => {
if(this.pet.isAlive === false) {
clearInterval(intervalId);
this.gameOver()
} else if (this.pet.isAwake && this.pet.isAlive){
const runMorphAnimation = this.pet.updateStas(this.time, this.dayLength);
this.printStats();
this.animatePet();
this.time++;
if(runMorphAnimation) this.animateMorph()
} else if (this.pet.isAwake === false && this.pet.isAlive){
clearInterval(intervalId)
this.animateIdle();
}
},100)
},
// Depending on button clicked, triggers different function
action($button){
const action = $button.text();
switch(action){
case 'FEED': {this.pet.feed(); break;}
case 'SLEEP': {this.pet.sleep(); break;}
case 'PLAY': {this.pet.play(); break;}
case 'KILL': {this.pet.kill(); break;}
default: console.log('ERROR in action switch code')
}
},
// Launches game over screen. Allow user to restart game.
// animates death of the pet
gameOver(){
this.pet.currentSprite = 1;
const intervalId = setInterval(() => {
if (this.pet.currentSprite <= this.pet.totalSprites) {
$nextSprite = $(`<img id='petSprite' src=${this.pet.pickedSprite}/Dead${this.pet.currentSprite}.png>`)
$('#petSprite').replaceWith($nextSprite)
this.pet.currentSprite++
} else {
clearInterval(intervalId);
$('#petName').val('');
const $deadPet = $('<h3>').text(`${this.pet.name} is dead..`)
$($deadPet).insertBefore('#petName')
$('.landing-pageContent > button').text ('Restart game')
$('.landing-page').fadeIn(1500);
$('.landing-pageContent').fadeIn(1500);
$('#petName').fadeIn(1500);
$('#startButton').fadeIn(1500);
}
},100)
},
// in charge of animating the pet
animatePet(){
if(this.pet.currentSprite > this.pet.totalSprites) this.pet.currentSprite = 1
$nextSprite = $(`<img id='petSprite' src=${this.pet.pickedSprite}/walk${this.pet.currentSprite}.png>`)
$('#petSprite').replaceWith($nextSprite)
this.pet.currentSprite++;
},
// manages morphing animation on left bar. Morph animation replaces LHS stats with sentence " your pet is morphing!"
animateMorph(){
$('#petNameBio').fadeOut(1000).delay(5500).fadeIn(1000)
$('#petAgeBio').fadeOut(1000).delay(5500).fadeIn(1000)
$('#morphAlarm').delay(1500).fadeIn(1000).delay(3000).fadeOut(1000)
},
animateIdle(){
$nextSprite = $(`<img id='petSprite' src=${this.pet.pickedSprite}/idle${this.pet.currentSprite}.png>`)
$('#pet-home').css('background-color','darkgrey')
$('#action-buttons > *').fadeOut(1500);
this.currentSprite = 1;
const intervalId = setInterval(() => {
if (this.pet.currentSprite <= this.pet.totalSprites) {
$nextSprite = $(`<img id='petSprite' src=${this.pet.pickedSprite}/idle${this.pet.currentSprite}.png>`)
$('#petSprite').replaceWith($nextSprite)
this.pet.currentSprite++;
} else {
clearInterval(intervalId)
this.currentSprite = 1;
this.pet.isAwake = true;
$('#pet-home').css('background-color','white')
$('#action-buttons > *').fadeIn(1500);
this.startTimer();
}
}, 1000)
}
}
|
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
require('./userPhoto');
require('./showCircle');
require('./showMeeting');
require('./map');
$('.modal').on('shown.bs.modal', function() {
$(this).find('[autofocus]').focus();
});
if($('.modal .is-invalid').length) {
$('.modal').has('.is-invalid').modal('show');
}
$(document).mouseup(function (e) {
var container = $(".popover");
if (!container.is(e.target)
&& container.has(e.target).length === 0) {
container.popover("hide");
}
});
$(function () {
initNewTooltips();
});
window.initNewTooltips = () => {
$('[data-toggle="tooltip"]:not([data-original-title])').tooltip();
};
|
let Vue = require("vue");
let VueRouter = require("vue-router");
let VueResource = require("vue-resource");
let page = {};
let Snackbar = require("snackbarlightjs");
Vue.use(VueRouter);
Vue.use(VueResource);
Vue.use(Snackbar);
// Router
let router = new VueRouter({
//history: true,
saveScrollPosition: true
});
const LOGIN_URL = "/api/login";
const SIGNUP_URL = "/api/users";
const LOGOUT_URL = "/api/logout"
Auth = {
install() {
Vue.prototype.$auth = new Authenticate();
}
}
class Authenticate {
constructor() {
this.authenticated = this.check();
}
login(context, input, redirect = false) {
context.$http.post(LOGIN_URL, input).then((response) => {
this.setToken(response.data.token);
this.authenticated = true;
if (redirect !== false) {
context.$router.go(redirect);
}
}, (errors) => {
this.snackbarErrors(context, errors);
});
}
register(context, input, redirect = false, login = true) {
context.$http.post(SIGNUP_URL, input).then((response) => {
if (login) {
this.setToken(response.data.token);
this.authenticated = true;
}
if (redirect !== false) {
context.$router.go(redirect);
}
}, (errors) => {
this.snackbarErrors(context, errors);
});
}
logout(context, redirect = false) {
context.$http.get(LOGOUT_URL).then((response) => {
this.removeToken();
this.authenticated = false;
if (redirect !== false) {
context.$router.go(redirect);
}
});
}
check() {
let token = this.getToken();
if (typeof(token) != "undefined" && token != null) {
return true;
}
return false;
}
snackbarErrors(context, errors) {
let fields = errors.data.errors;
for (let field in fields) {
let errorsField = fields[field];
for (let i = errorsField.length - 1; i >= 0; i--) {
context.$snackbar.create(errorsField[i]);
}
}
}
getToken() {
return localStorage.getItem("token")
}
setToken(token) {
localStorage.setItem("token", token);
}
removeToken() {
localStorage.removeItem("token")
}
}
Vue.http.interceptors.push({
request: function(request) {
var headers = request.headers;
if (!headers.hasOwnProperty('Authorization')) {
headers['Authorization'] = localStorage.getItem("token");
}
return request;
}
});
Vue.use(Auth);
Vue.http.headers.common["Authorization"] = "Bearer " + localStorage.getItem("token");
page.landing = require("./Pages/landing.vue");
page.productsIndex = require("./Pages/Products/index.vue");
page.productsShow = require("./Pages/Products/show.vue");
page.login = require("./Pages/Auth/login.vue");
page.register = require("./Pages/Auth/register.vue");
page.usersShow = require("./Pages/Users/show.vue");
page.notFound = require("./Pages/notFound.vue");
navBar = require("./Components/navBar.vue");
product = require("./Components/productCard.vue");
router.map({
"":{
component: page.productsIndex,
name: "home",
},
"login":{
component: page.login,
name: "login",
},
"register":{
component: page.register,
name: "register",
},
"profile/:id":{
component: page.usersShow,
name: "profile",
},
"*":{
component: page.notFound,
name: "notFound",
}
});
Vue.config.debug = true;
Vue.component('nav-bar', navBar);
Vue.component('product', product);
let App = Vue.extend({});
router.start(App, "#app");
|
import { combineReducers } from 'redux';
import pdv from './pdv';
export const rootReducer = combineReducers({ pdv });
|
const helpers = require("../helpers");
const elements = {
emailInput: element(by.css("input[type='email']")),
passwordInput: element(by.css("input[type='password']")),
signInButton: element(by.css("button[type='submit']"))
};
async function waitUntilReady() {
await helpers.waitUntilClickable(elements.emailInput);
}
async function logIn(email, password) {
await waitUntilReady();
await elements.emailInput.click();
await elements.emailInput.sendKeys(email);
await elements.passwordInput.sendKeys(password);
await elements.signInButton.click();
}
module.exports = {
waitUntilReady,
logIn
};
|
/**
* This file is part of Sesatheque.
* Copyright 2014-2015, Association Sésamath
*
* Sesatheque is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation.
*
* Sesatheque is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Sesatheque (LICENCE.txt).
* @see http://www.gnu.org/licenses/agpl.txt
*
*
* Ce fichier fait partie de lapplication Sésathèque, créée par lassociation Sésamath.
*
* Sésathèque est un logiciel libre ; vous pouvez le redistribuer ou le modifier suivant
* les termes de la GNU Affero General Public License version 3 telle que publiée par la
* Free Software Foundation.
* Sésathèque est distribué dans lespoir quil sera utile, mais SANS AUCUNE GARANTIE ;
* sans même la garantie tacite de QUALITÉ MARCHANDE ou dADÉQUATION à UN BUT PARTICULIER.
* Consultez la GNU Affero General Public License pour plus de détails.
* Vous devez avoir reçu une copie de la GNU General Public License en même temps que Sésathèque
* (cf LICENCE.txt et http://vvlibri.org/fr/Analyse/gnu-affero-general-public-license-v3-analyse
* pour une explication en français)
*/
'use strict';
/**
* Pour utiliser le chargement de jquery & jstree à la demande avec du jsonP,
* compiler ce fichier par webpack depuis une appli quelconque (qui mettra son publicPath)
* Cf README
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = asyncBuild;
var _ = _interopRequireDefault(require("."));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncBuild(elt, arbre, options) {
require.ensure(['jquery', 'jstree'], function (require) {
// on laisse l'appli appelante charger son jquery si elle a une version de prédilection
if (typeof window.jQuery === 'undefined') window.jQuery = require('jquery'); // et son jstree (qui devra être compatible avec notre code…)
if (!window.jQuery.jstree) window.jQuery.jstree = require('jstree'); // juste pour déclencher la compilation de nos css, qui seront mergées avec celles de l'appli
require('jstree/dist/themes/default/style.css');
require('./jstree.css');
(0, _.default)(elt, arbre, options);
});
}
|
function aspectResize () {
var w = $('.boardMinWidth').width();
$('.boardMinWidth').css('height',w + 'px');
$('.numbers').css('line-height', w/8 + 'px');
$('.letters').css('line-height', w*6/88 + 'px');
var sqsize = $('#square0').width();
$( '.piece').draggable( 'option', 'cursorAt', {left: sqsize/2, top: sqsize/2} );
$('#right-container').css('height',$('#boardContainer').height());
// $('.pgn').css('margin-top',0.06*$('#boardContainer').width());
$('.comment').css('margin-bottom',0.06*$('#boardContainer').width());
//$('#boardContainer').hide();
}
$(function () {
aspectResize();
for (var j = 0; j < 8; j++) {
$('.l' + j).data('col',j).click(function () {underlineColumn($(this).data('col'));});
$('.n' + j).data('row',j).click(function () {underlineRow($(this).data('row'));});
for (var i = 0; i < 8; i++) {
$('#square' + (16*j+i)).data('coor',16*j+i).bind("contextmenu", function (e) {
var coor = $(this).data('coor');
var i = coor%16;
var j = (coor-i)/16;
$(this).toggleClass('underline-bad-'+(i+j)%2);
return false;
}).click(function () {
var coor = $(this).data('coor');
var i = coor%16;
var j = (coor-i)/16;
$(this).toggleClass('underline-good-'+(i+j)%2);
});
}
}
var underlinedColumns = [];
var underlinedRows = [];
function underlineColumn(col) {
var index = underlinedColumns.indexOf(col);
if (index == -1) {
underlinedColumns.push(col);
}
else {
underlinedColumns.splice(index,1);
}
for (var k = 0; k < 8; k++) {
if (underlinedRows.indexOf(k) != -1) continue;
$('#square' + (16*k+col)).toggleClass('underline_'+((col+k)%2));
}
}
function underlineRow(row) {
var index = underlinedRows.indexOf(row);
if (index == -1) {
underlinedRows.push(row);
}
else {
underlinedRows.splice(index,1);
}
for (var k = 0; k < 8; k++) {
if (underlinedColumns.indexOf(k) != -1) continue;
$('#square' + (16*row+k)).toggleClass('underline_'+((row+k)%2));
}
}
$('#square0').click(function () {
var color = ['blue','orange','grey','green'][Math.floor(4*Math.random())];
$('#boardDiv').removeClass().addClass(color + '-schema');
});
var cui = new chessUI();
cui.start('rnbqkbnr\/pppppppp\/8\/8\/8\/8\/PPPPPPPP\/RNBQKBNR w KQkq - 0 1');
if (_GAME) cui.viewGame(_GAME);
});
|
$(document).ready(function(){
// Now access it with that path
var path_to_the_webservice = "lorem.json";
$('#runner').runner({
countdown: true,
startAt: 59000,
milliseconds: false,
stopAt: 0
}).on('runnerFinish', function(eventObject, info) {
$('.bodyLower .toggleBtn').click();
$('.navbar-inverse').toggleClass('on');
});;
$('.toggle-time').click(function(e) {
e.preventDefault();
$(this).toggleClass('on');
$('#runner').runner('toggle');
});
$('.navbar-brand').click(function(){
$('.navbar-inverse').toggleClass('on');
if( $('.navbar-inverse').hasClass('on') == true ) {
// Start the timer
$('#runner').runner('start');
// Get JSON and randomly display stuff
$.getJSON(path_to_the_webservice, function(data){
var randomnumber=Math.floor(Math.random()*data.length);
$('#text1').text(data[randomnumber].text1);
$('#person').attr('src', data[randomnumber].picture);
});
$.getJSON(path_to_the_webservice, function(data){
var randomnumber=Math.floor(Math.random()*data.length);
$('#text2').text(data[randomnumber].text2);
});
$.getJSON(path_to_the_webservice, function(data){
var randomnumber=Math.floor(Math.random()*data.length);
$('#text3').text(data[randomnumber].text3);
});
$.getJSON(path_to_the_webservice, function(data){
var randomnumber=Math.floor(Math.random()*data.length);
$('#text4').text(data[randomnumber].text4);
});
} else {
// Start the timer
$('#runner').runner('reset', true);
}
// Play or Stop Metronome
$('.bodyLower .toggleBtn').click();
});
});
|
/*
* @Author: anchen
* @Date: 2016-03-17 17:18:18
* @Last Modified by: anchen
* @Last Modified time: 2016-03-21 17:25:56
*/
var assertEqual = function(val1, val2, msg) {
if (val1 !== val2){
console.log(msg || (val1 + " does not equal " + val2));
}else if(val1 === val2){
console.log('val1 is equal with val2');
}
};
Math.guid = function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
}).toUpperCase();
};
var Model = {
inherited : function(){},
created : function(){},
prototype : {
init : function(){}
},
create : function(){
var object = Object.create(this);
object.parent = this;
object.fn = object.prototype = Object.create(this.prototype);
object.created();
this.inherited(object);
return object;
},
init : function(){
var instance = Object.create(this.prototype);
instance.parent = this;
instance.init.apply(instance, arguments);
return instance;
},
extend : function(o){
$.extend(this, o);
typeof o.extended == 'function' && o.extended(this);
},
include : function(o){
$.extend(this.prototype, o);
typeof o.included == 'function' && o.included(this);
}
}
jQuery.extend(Model.prototype,{
init : function(obj){
if(obj){
this.load(obj);
}
},
load : function(obj){
for(var attr in obj){
this[attr] = obj[attr];
}
}
})
Model.records = {};
Model.include({
newRecord : true,
create : function(){
if(!this.id){
this.id = Math.guid();
}
this.newRecord = false;
this.parent.records[this.id] = this;
},
destroy : function(){
delete this.parent.records[this.id];
}
})
Model.include({
update : function(){
this.parent.records[this.id] = this;
}
})
Model.include({
save : function(){
this.newRecord ? this.create() : this.update();
}
})
Model.extend({
find : function(id){
return this.records[id] || ('Unkown record');
}
})
Model.extend({
created : function(){
this.records = {};
this.attributes = [];
}
})
Model.extend({
populate : function(values){
this.records = {};
for(var i=0,len=values.length;i<len;i++){
var record = values[i];
record.newRecord = false;
this.records[record.id] = record;
}
}
})
Model.include({
attributes : function(){
var result = {};
for(var i in this.parent.attributes){
var attr = this.parent.attributes[i];
result[attr] = this[attr];
}
result.id = this.id;
return result;
}
})
var Model.LocalStorage = {
saveLocal : function(name){
var results = [];
for(var i in this.records){
results.push(this.records[i]);
}
localStorage[name] = JSON.stringify(results);
},
loadLocal : function(name){
var result = JSON.parse(localStorage[name]);
this.populate(result);
}
}
var Asset = Model.create();
Asset.extend({
find : function(id){
return this.records[id].dup() || 'Unkown record';
}
})
Asset.include({
create : function(){
this.newRecord = false;
this.parent.records[this.id] = this.dup();
},
update : function(){
this.parent.records[this.id] = this.dup();
},
dup : function(){
return jQuery.extend(true, {}, this);
}
})
var Model.LocalStorage = {
saveLocal : function(name){
var results = [];
for(var i in this.records){
results.push(this.records[i]);
}
localStorage[name] = JSON.stringify(results);
},
loadLocal : function(name){
var result = JSON.parse(localStorage[name]);
this.populate(result);
}
}
Asset.extend(Model.LocalStorage);
Model.include({
createRemote : function(url, callback){
$.$.post(url, this.attributes(), function(data, textStatus, xhr) {
/*optional stuff to do after success */
});
},
updateRemote : function(url, callback){
$.$.ajax({
url: url,
type: 'PUT',
data: this.attributes(),
success : callback(){
}
})
}
})
Asset.init({'name':'json.txt'}).createRemote('/asset');
var asset = Asset.init();
// test
asset.name = "same, same";
asset.id = 1
asset.save();
var asset2 = Asset.init();
asset2.name = "but different";
asset2.id = 2;
asset2.save();
assertEqual( Asset.find(1).name, "same, same" );
asset2.destroy();
|
const parseClassconstant = require('./parseClassconstant');
const classconstants = JSON.parse(require('fs').readFileSync(require('path').join(__dirname, '/../../tests/data/kinds/classconstant.json'), 'utf-8'));
const table = [
[0, {constants: {CONSTANT1: 123}, visibility: 'protected'}],
[1, {constants: {CONSTANT2: 456, CONSTANT3: 789}, visibility: 'public', lines: [91, 91]}],
[2],
[3],
];
test.each(table)('%s',
(i, expected = classconstants[i]) => {
expect(parseClassconstant(classconstants[i])).toStrictEqual(expected);
},
);
|
import React from 'react'
import './footer.styles.scss'
export const Footer = () => (
< div className='footer'>
<div className='options'>
<a className="btn btn-social-icon btn-google" href="http://google.com/+"><i className="fa fa-google-plus"></i></a>
<a className="btn btn-social-icon btn-facebook" href="http://www.facebook.com/profile.php?id="><i className="fa fa-facebook"></i></a>
<a className="btn btn-social-icon btn-linkedin" href="http://www.linkedin.com/in/"><i className="fa fa-linkedin"></i></a>
<a className="btn btn-social-icon btn-twitter" href="http://twitter.com/"><i className="fa fa-twitter"></i></a>
<a className="btn btn-social-icon btn-google" href="http://youtube.com/"><i className="fa fa-youtube"></i></a>
<a className="btn btn-social-icon" href="mailto:"><i className="fa fa-envelope-o"></i></a>
</div>
<div className="copyright">
<div className="col-auto ">
<p><b>© Copyright 2020 IgnitePlus</b></p>
</div>
</div>
</div>
)
|
/**
* This is a function that adding 1 to your numbers
*/
function incArray(...myArray) {
for (let i = 0; i < myArray.length; i++) {
myArray[i] += 1
}
console.log(myArray)
}
incArray(1, 2, 3, 4)
|
'use strict';
angular.module('FEF-Angular-UI.openingTimes', [])
.directive('openingTimes', [function() {
return {
restrict: 'AE',
replace: true,
templateUrl: 'templates/opening-times.html',
scope: {
times: '='
}
}
}]);
|
// database/firebaseDb.js
import * as firebase from 'firebase';
import firestore from 'firebase/firestore'
const firebaseConfig = {
apiKey: "AIzaSyBYcJZEroIUBLA_yOGPCzXS9-qEZWTNz28",
authDomain: "empapp-56e97.firebaseapp.com",
databaseURL: "https://empapp-56e97.firebaseio.com",
projectId: "empapp-56e97",
storageBucket: "empapp-56e97.appspot.com",
messagingSenderId: "851926992524",
appId: "1:851926992524:web:1062511eade3b6bd3a1da9",
measurementId: "G-WLYQJWF53C"
};
firebase.initializeApp(firebaseConfig);
firebase.firestore();
export default firebase;
|
/* flow */
import configure from 'redux-idle-monitor'
import { IDLE_STATUSES } from './constants'
import { idleStatusDelay, activeStatusAction, idleStatusAction } from './actions'
const opts = { appName: 'example-ui',
IDLE_STATUSES,
idleStatusDelay,
activeStatusAction,
idleStatusAction
}
const { middleware, reducer, actions } = configure(opts)
export { middleware, reducer, actions }
|
// banmi.js - 1.0
// A simple module for rate-limited lockouts
// (c) 2019 Charlton Trezevant
// MIT License
var Banmi = {};
// Initial ban length, which is used to calculate the scaling ban length per
// the total number of failed attempts
Banmi.initialBanLength = 120;
// Maximum failure threshold that login attempts cannot exceed.
Banmi.maxFailThreshold = 2;
Banmi.bans = {};
Banmi.createBanRecord = function(user){
logger.info("Banmi: Creating new ban record for " + user);
this.bans[user] = {
numFailuresRecorded: 0,
initialBanTime: new Date(),
lastFailTime: new Date()
};
};
Banmi.deleteBanRecord = function(user){
logger.info("Banmi: deleting ban record for " + user);
delete this.bans[user];
};
Banmi.banRecordExists = function(user){
if(this.bans[user]){
logger.info("Banmi: recordExists: Found a ban on file for " + user);
return true;
} else {
logger.info("Banmi: recordExists: No bans on file for " + user);
return null;
}
};
Banmi.numFailuresRecorded = function(user){
if(!this.banRecordExists(user))
return 0;
logger.info("Banmi: numFailuresRecorded: " + this.bans[user].numFailuresRecorded + " failures recorded for user " + user);
return this.bans[user].numFailuresRecorded;
};
Banmi.banTimeRemaining = function(user){
if(!this.banRecordExists(user))
return 0;
currentTime = new Date();
logger.info("Banmi: banTimeRemaining: Time remaining for user " + user + " is " + (this.bans[user].expireTime - currentTime));
return this.bans[user].expireTime - currentTime;
};
Banmi.recordFailure = function(user){
if(!this.banRecordExists(user))
this.createBanRecord(user);
currentTime = new Date();
this.bans[user].lastFailTime = new Date();
this.bans[user].numFailuresRecorded++;
scaledBanLength = this.initialBanLength;
if(this.numFailuresRecorded(user) >= this.maxFailThreshold)
scaledBanLength = (Math.floor(this.bans[user].numFailuresRecorded / this.maxFailThreshold) * this.initialBanLength);
this.bans[user].expireTime = currentTime.setSeconds(currentTime.getSeconds() + scaledBanLength);
logger.info("Banmi: recordFailure: Ban state updated for " + user + ": " + JSON.stringify(this.bans[user]));
};
Banmi.isBanned = function(user){
if(!this.banRecordExists(user))
return false;
if(this.banTimeRemaining(user) < 0){
logger.info("Banmi: banTimeRemaining: Ban time for user " + user + " has completed, will now garbage collect: " + this.banTimeRemaining(user));
this.deleteBanRecord(user);
return false;
}
logger.info("Banmi: banTimeRemaining: Time remaining for user " + user + " is " + this.banTimeRemaining(user) + ", and ban state is: "+ this.numFailuresRecorded(user) >= this.maxFailThreshold);
return this.numFailuresRecorded(user) >= this.maxFailThreshold;
};
module.exports = Banmi;
|
function tripleFive() {
for (i = 0; i < 3; i++) {
console.log("Five!");
}
}
tripleFive();
function lastLetter(s) {
return s.charAt(s.length-1);
}
console.log(lastLetter("hello"));
function square(num) {
return num * num;
}
console.log(square(4));
function negate(num) {
num -= num * 2;
return num;
}
console.log(negate(3));
function toArray(x, y, z) {
var myArr = [x, y, z];
return myArr;
}
console.log(toArray(1,2,3));
function startsWithA(s) {
if (s.charAt(0).toLowerCase() === 'a')
return true;
else
return false;
}
console.log(startsWithA('far'));
console.log(startsWithA('Advil'));
function excite(s) {
return (s + "!!!");
}
console.log(excite("hi"));
function sun(s) {
if (s.indexOf('sun') > 0)
return true;
else
return false;
}
console.log(sun('asunder'));
console.log(sun('rubbish'));
function tiny(n) {
if (n > 0 && n < 1)
return true;
else
return false;
}
console.log(tiny(.4));
console.log(tiny(1.1));
function getSeconds(s) {
var times = [];
times = s.split(":");
var minutes = Number(times[0]);
var seconds = Number(times[1]);
return minutes * 60 + seconds;
}
console.log(getSeconds("4:30"));
|
/*
* @lc app=leetcode.cn id=235 lang=javascript
*
* [235] 二叉搜索树的最近公共祖先
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
let ancestor = root;
while (true) {
if (p.val > ancestor.val && q.val > ancestor.val) {
ancestor = ancestor.right;
} else if (p.val < ancestor.val && q.val < ancestor.val) {
ancestor = ancestor.left;
} else {
break;
}
}
return ancestor;
};
// @lc code=end
|
$(document).ready(function(){
var time1 = 0
var time2 = 0
var difference = 0
$("#q2").hide();
$("#diff").hide();
$("#yourName").change(function(){
time1 = new Date().getTime();
//alert("The first name was changed at " + time1);
$("#q2").show();
});
$("#q2").change(function(){
time2 = new Date().getTime();
//alert("The last name was changed at " + time2);
difference = (time2-time1)/1000;
$("#diff").show();
$("#diff:text").val(difference);
});
});
|
import React from "react";
import { render, cleanup, fireEvent } from "@testing-library/react";
import ListItem from "./ListItem";
const setup = (text, checked, onCheck, url) => {
return render(
<ListItem
checked={checked}
text={text}
onCheckChange={onCheck}
url={url}
/>
);
};
describe("List Item", () =>{
afterEach(cleanup);
it("calls onCheck when checkbox clicked", () => {
const onCheck = jest.fn();
const text = "test text";
const { getByLabelText } = setup(text, false, onCheck, "http://www.google.com");
const checkbox = getByLabelText(text + " checkbox");
fireEvent.click(checkbox);
expect(onCheck).toBeCalled();
});
it("renders correct href for specified url on link component", () => {
const onCheck = jest.fn();
const text = "test text";
const link = "http://www.google.com"
const { getByText } = setup(text, false, onCheck, link);
const itemDescription = getByText(text);
expect(itemDescription.getAttribute("href").includes(link)).toBe(true);
})
});
|
import React from "react";
import "react-accessible-accordion/dist/fancy-example.css";
import "bootstrap/dist/css/bootstrap.min.css";
import {
Accordion,
AccordionItem,
AccordionItemHeading,
AccordionItemButton,
AccordionItemPanel,
} from "react-accessible-accordion";
const CardListView = (props) => {
return (
<AccordionItem>
<AccordionItemHeading>
<AccordionItemButton>
<h4>Title: {props.title}</h4>
</AccordionItemButton>
</AccordionItemHeading>
<AccordionItemPanel>
<ul>
<li>Shipping Date: {props.shippingDate}</li>
<li>Responsibility: {props.responsibility}</li>
</ul>
</AccordionItemPanel>
</AccordionItem>
);
};
export default CardListView;
|
'use strict';
const moment = require('moment');
const debug = require('./debug');
function next(context, curr) {
if (context.workflows.indexOf(curr) < -1) {
debug.stack(`Unsupported workflow : ${curr}`);
}
const index = context.workflows.indexOf(curr);
if (index + 1 >= context.workflows.length) {
return null;
}
return context.workflows[index + 1];
}
class Workflow {
constructor(workflow_operator) {
if (!workflow_operator) {
debug.stack('Invalid parameter: workflow_operator cannot be null.');
}
this.operator = workflow_operator;
}
async wrong(context, e) {
context.success = false;
context.curr = {
workflow: 'error',
error_step: context.curr.workflow,
start: moment().valueOf(),
end: null,
error: e
};
try {
await this.error_handler(context, 12);
} catch (e) {
context.curr.error = e;
}
context.curr.end = moment().valueOf();
}
async dispatch(context, curr) {
const operator = this.operator;
if (typeof operator[curr] === 'undefined') {
debug.stack(`Unimplemented ${curr}() method in operator.`);
}
context.curr = {
workflow: curr,
start: moment().valueOf(),
end: null,
success: null
};
let res = null;
try {
res = await operator[curr].call(this, context);
context.curr.success = true;
} catch (e) {
context.curr.success = false;
context.curr.error = e;
}
context.curr.end = moment().valueOf();
context.step_data[curr] = context.curr;
if (!context.curr.success) {
await this.wrong(context, context.curr.error);
} else if (typeof res === 'string' && context.workflows.indexOf(res) > -1) {
await this.dispatch(context, res);
} else {
curr = next(context, curr);
if (curr) {
await this.dispatch(context, curr);
}
}
}
async start(context) {
return new Promise((resolve, reject) => {
if (!context) {
debug.stack('Invalid context.');
}
if (!Array.isArray(context.workflows)) {
debug.stack('context.workflows should be Array.');
}
if (!context.workflows.length) {
debug.stack('context.workflows cannot be empty.');
}
this.error_handler = reject;
context.success = null;
context.curr = {};
context.step_data = {};
this.dispatch(context, context.workflows[0]).then(() => {
context.curr = {};
context.success = true;
resolve(context);
}).catch((e) => {
context.curr = {};
this.wrong(context, e);
});
});
}
}
module.exports = Workflow;
|
import React from 'react';
import { NavLink } from 'react-router-dom';
const NavLinks = () => {
const navigationlistLinks = ['portfolio', 'about', 'contact'];
const renderList = navigationlistLinks.map((link, i) => (
<li className="link-item" key={i}>
<NavLink activeClassName="hoverColor" to={`/${link}`}>
{i === 1 ? link + ` Us` : link}
</NavLink>
</li>
));
return <ul className="link-items">{renderList}</ul>;
};
export default NavLinks;
|
/*
* C.Utils.Intersection //TODO description
*/
'use strict';
C.Utils.Intersection.Test = function (a, b, p) {
if ((a.Y > p.Y) !== (b.Y > p.Y) && (p.X < (b.X - a.X) * (p.Y - a.Y) / (b.Y - a.Y) + a.X)) {
return (true);
}
return (false);
};
C.Utils.Intersection.IsPointInsideRectangle = function (a, b, c, d, p) {
if (C.Utils.Intersection.Test(a, b, p) ||
C.Utils.Intersection.Test(b, c, p) ||
C.Utils.Intersection.Test(c, d, p) ||
C.Utils.Intersection.Test(d, a, p)) {
return (true);
}
return (false);
};
|
var results = ["hello", "world"];
var i = -1;
exports.obj1 = {
toString: function () {
i = i+1;
return results[i];
}
};
var counter = 0
exports.obj2 = {
valueOf: function () {
counter++;
return counter;
}
};
|
exports.invoiceFooter = (doc) => {
doc
.fontSize(9).font("Helvetica").text("Thank you for your business!", 40, 530)
.fontSize(9).font("Helvetica").text("Any question? Please contact us anytime at support@ppcwiz.com", 40, 550)
}
|
/**
* @fileoverview General-purpose key frame animation
* @author Tony Parisi
*/
goog.provide('SB.MeshAnimator');
goog.require('SB.Component');
// MeshAnimator class
// Construction/initialization
SB.MeshAnimator = function(param)
{
SB.Component.call(this, param);
param = param || {};
this.skins = param.skins || [];
this.running = false;
this.frame = 0;
this.duration = param.duration ? param.duration : SB.MeshAnimator.default_duration;
this.frameRate = SB.MeshAnimator.default_frame_rate;
this.loop = param.loop ? param.loop : false;
}
goog.inherits(SB.MeshAnimator, SB.Component);
// Start/stop
SB.MeshAnimator.prototype.start = function()
{
if (this.running)
return;
this.startTime = Date.now();
this.running = true;
}
SB.MeshAnimator.prototype.stop = function()
{
this.running = false;
this.publish("complete");
}
// Update - drive key frame evaluation
SB.MeshAnimator.prototype.update = function()
{
if (!this.running)
return;
var skin = this.skins[0];
if ( skin )
{
var now = Date.now();
var deltat = (now - this.startTime) / 1000;
var fract = deltat - Math.floor(deltat);
this.frame = fract * this.frameRate;
for ( var i = 0; i < skin.morphTargetInfluences.length; i++ )
{
skin.morphTargetInfluences[ i ] = 0;
}
skin.morphTargetInfluences[ Math.floor( this.frame ) ] = 1;
}
}
// Statics
SB.MeshAnimator.default_duration = 1000;
SB.MeshAnimator.default_frame_rate = 30;
|
import Product from '../components/product/product';
import {shallow} from 'enzyme';
import apiService from '../services/apiService';
import store from '../redux/store';
// TODO, broken after adding state,
describe('Testing product component', () => {
let component;
beforeEach(() => {
component = shallow(<Product store={store} {...{match: {params: {id: 'HI334'}}}}/>,
{disableLifecycleMethods: true}).shallow();
})
afterEach(() => {
component.unmount();
})
test('Snapshot test', () => {
expect(component).toMatchSnapshot();
})
test('SHOULD render a spinner before api call has been made', () => {
expect(component.find('Spinner').exists()).toBeTruthy();
})
test('SHOULD render h1 with error WHEN getProduct returns error value', (done) => {
const spyDidMount = jest.spyOn(component.instance(), 'componentDidMount');
const spyApiServiceProduct = jest.spyOn(apiService, 'getProduct').mockResolvedValue({
error: true,
message: 'some err'
});
const spyApiServiceReview = jest.spyOn(apiService, 'getReviews').mockResolvedValue({
error: true,
message: 'some err'
});
const didMount = component.instance().componentDidMount();
expect(spyDidMount).toHaveBeenCalled();
expect(spyApiServiceProduct).toHaveBeenCalledWith('HI334');
didMount.then(() => {
component.update();
expect(component.find('h1').text()).toContain('Error happened please try again later');
spyDidMount.mockRestore();
spyApiServiceProduct.mockRestore();
spyApiServiceReview.mockRestore();
done();
})
})
test('SHOULD render product container with reviews WHEN getProduct returns product data', (done) => {
const spyDidMount = jest.spyOn(component.instance(), 'componentDidMount');
const product = {
currency: '$',
price: 39,
id: 'HI334',
name: 'product',
description: 'description',
imgUrl: 'https://assets.adidas.com/images/w_320,h_320,f_auto,q_auto:sensitive,fl_lossy/c93fa315d2f64775ac1fab96016f09d1_9366/Dame_6_Shoes_Black_FV8624_01_standard.jpg'
};
const reviews =
[{
productId: 'HI334',
locale: 'en-US,en;q=0.9,ru;q=0.8,en-GB;q=0.7,nl;q=0.6,lt;q=0.5',
rating: 0,
text: 'string'
}]
const spyApiServiceProduct = jest.spyOn(apiService, 'getProduct').mockResolvedValue(product);
const spyApiServiceReview = jest.spyOn(apiService, 'getReviews').mockResolvedValue(reviews);
const didMount = component.instance().componentDidMount();
expect(spyDidMount).toHaveBeenCalled();
expect(spyApiServiceProduct).toHaveBeenCalledWith('HI334');
didMount.then(() => {
component.update();
expect(component.find('div.item-container').exists()).toBeTruthy();
expect(component.find('div.customer-reviews').exists()).toBeTruthy();
spyDidMount.mockRestore();
spyApiServiceProduct.mockRestore();
spyApiServiceReview.mockRestore();
done();
})
})
})
|
// # Ghost Server
// Handles the creation of an HTTP Server for Ghost
const debug = require('ghost-ignition').debug('server');
const Promise = require('bluebird');
const fs = require('fs-extra');
const path = require('path');
const _ = require('lodash');
const config = require('../shared/config');
const urlUtils = require('./../shared/url-utils');
const errors = require('@tryghost/errors');
const {events, i18n} = require('./lib/common');
const logging = require('../shared/logging');
const moment = require('moment');
/**
* ## GhostServer
* @constructor
* @param {Object} rootApp - parent express instance
*/
function GhostServer(rootApp) {
this.rootApp = rootApp;
this.httpServer = null;
this.connections = {};
this.connectionId = 0;
// Expose config module for use externally.
this.config = config;
}
const debugInfo = {
versions: process.versions,
platform: process.platform,
arch: process.arch,
release: process.release
};
/**
* ## Public API methods
*
* ### Start
* Starts the ghost server listening on the configured port.
* Alternatively you can pass in your own express instance and let Ghost
* start listening for you.
* @param {Object} externalApp - Optional express app instance.
* @return {Promise} Resolves once Ghost has started
*/
GhostServer.prototype.start = function (externalApp) {
debug('Starting...');
const self = this;
const rootApp = externalApp ? externalApp : self.rootApp;
let socketConfig;
const socketValues = {
path: path.join(config.get('paths').contentPath, config.get('env') + '.socket'),
permissions: '660'
};
return new Promise(function (resolve, reject) {
if (Object.prototype.hasOwnProperty.call(config.get('server'), 'socket')) {
socketConfig = config.get('server').socket;
if (_.isString(socketConfig)) {
socketValues.path = socketConfig;
} else if (_.isObject(socketConfig)) {
socketValues.path = socketConfig.path || socketValues.path;
socketValues.permissions = socketConfig.permissions || socketValues.permissions;
}
// Make sure the socket is gone before trying to create another
try {
fs.unlinkSync(socketValues.path);
} catch (e) {
// We can ignore this.
}
self.httpServer = rootApp.listen(socketValues.path);
fs.chmod(socketValues.path, socketValues.permissions);
config.set('server:socket', socketValues);
} else {
self.httpServer = rootApp.listen(
config.get('server').port,
config.get('server').host
);
}
self.httpServer.on('error', function (error) {
let ghostError;
if (error.errno === 'EADDRINUSE') {
ghostError = new errors.GhostError({
message: i18n.t('errors.httpServer.addressInUse.error'),
context: i18n.t('errors.httpServer.addressInUse.context', {port: config.get('server').port}),
help: i18n.t('errors.httpServer.addressInUse.help')
});
} else {
ghostError = new errors.GhostError({
message: i18n.t('errors.httpServer.otherError.error', {errorNumber: error.errno}),
context: i18n.t('errors.httpServer.otherError.context'),
help: i18n.t('errors.httpServer.otherError.help')
});
}
reject(ghostError);
});
self.httpServer.on('connection', self.connection.bind(self));
self.httpServer.on('listening', function () {
debug('...Started');
self.logStartMessages();
return GhostServer.announceServerStart()
.finally(() => {
resolve(self);
});
});
});
};
/**
* ### Stop
* Returns a promise that will be fulfilled when the server stops. If the server has not been started,
* the promise will be fulfilled immediately
* @returns {Promise} Resolves once Ghost has stopped
*/
GhostServer.prototype.stop = function () {
const self = this;
return new Promise(function (resolve) {
if (self.httpServer === null) {
resolve(self);
} else {
self.httpServer.close(function () {
events.emit('server.stop');
self.httpServer = null;
self.logShutdownMessages();
resolve(self);
});
self.closeConnections();
}
});
};
/**
* ### Restart
* Restarts the ghost application
* @returns {Promise} Resolves once Ghost has restarted
*/
GhostServer.prototype.restart = function () {
return this.stop().then(function (ghostServer) {
return ghostServer.start();
});
};
/**
* ### Hammertime
* To be called after `stop`
*/
GhostServer.prototype.hammertime = function () {
logging.info(i18n.t('notices.httpServer.cantTouchThis'));
return Promise.resolve(this);
};
/**
* ## Private (internal) methods
*
* ### Connection
* @param {Object} socket
*/
GhostServer.prototype.connection = function (socket) {
const self = this;
self.connectionId += 1;
socket._ghostId = self.connectionId;
socket.on('close', function () {
delete self.connections[this._ghostId];
});
self.connections[socket._ghostId] = socket;
};
/**
* ### Close Connections
* Most browsers keep a persistent connection open to the server, which prevents the close callback of
* httpServer from returning. We need to destroy all connections manually.
*/
GhostServer.prototype.closeConnections = function () {
const self = this;
Object.keys(self.connections).forEach(function (socketId) {
const socket = self.connections[socketId];
if (socket) {
socket.destroy();
}
});
};
/**
* ### Log Start Messages
*/
GhostServer.prototype.logStartMessages = function () {
// Startup & Shutdown messages
if (config.get('env') === 'production') {
logging.info(i18n.t('notices.httpServer.ghostIsRunningIn', {env: config.get('env')}));
logging.info(i18n.t('notices.httpServer.yourBlogIsAvailableOn', {url: urlUtils.urlFor('home', true)}));
logging.info(i18n.t('notices.httpServer.ctrlCToShutDown'));
} else {
logging.info(i18n.t('notices.httpServer.ghostIsRunningIn', {env: config.get('env')}));
logging.info(i18n.t('notices.httpServer.listeningOn', {
host: config.get('server').socket || config.get('server').host,
port: config.get('server').port
}));
logging.info(i18n.t('notices.httpServer.urlConfiguredAs', {url: urlUtils.urlFor('home', true)}));
logging.info(i18n.t('notices.httpServer.ctrlCToShutDown'));
}
function shutdown() {
logging.warn(i18n.t('notices.httpServer.ghostHasShutdown'));
if (config.get('env') === 'production') {
logging.warn(i18n.t('notices.httpServer.yourBlogIsNowOffline'));
} else {
logging.warn(
i18n.t('notices.httpServer.ghostWasRunningFor'),
moment.duration(process.uptime(), 'seconds').humanize()
);
}
process.exit(0);
}
// ensure that Ghost exits correctly on Ctrl+C and SIGTERM
process.removeAllListeners('SIGINT').on('SIGINT', shutdown).removeAllListeners('SIGTERM').on('SIGTERM', shutdown);
};
/**
* ### Log Shutdown Messages
*/
GhostServer.prototype.logShutdownMessages = function () {
logging.warn(i18n.t('notices.httpServer.ghostIsClosingConnections'));
};
module.exports = GhostServer;
const connectToBootstrapSocket = (message) => {
const socketAddress = config.get('bootstrap-socket');
const net = require('net');
const client = new net.Socket();
return new Promise((resolve) => {
const connect = (options = {}) => {
let wasResolved = false;
const waitTimeout = setTimeout(() => {
logging.info('Bootstrap socket timed out.');
if (!client.destroyed) {
client.destroy();
}
if (wasResolved) {
return;
}
wasResolved = true;
resolve();
}, 1000 * 5);
client.connect(socketAddress.port, socketAddress.host, () => {
if (waitTimeout) {
clearTimeout(waitTimeout);
}
client.write(JSON.stringify(message));
if (wasResolved) {
return;
}
wasResolved = true;
resolve();
});
client.on('close', () => {
logging.info('Bootstrap client was closed.');
if (waitTimeout) {
clearTimeout(waitTimeout);
}
});
client.on('error', (err) => {
logging.warn(`Can't connect to the bootstrap socket (${socketAddress.host} ${socketAddress.port}) ${err.code}`);
client.removeAllListeners();
if (waitTimeout) {
clearTimeout(waitTimeout);
}
if (options.tries < 3) {
logging.warn(`Tries: ${options.tries}`);
// retry
logging.warn('Retrying...');
options.tries = options.tries + 1;
const retryTimeout = setTimeout(() => {
clearTimeout(retryTimeout);
connect(options);
}, 150);
} else {
if (wasResolved) {
return;
}
wasResolved = true;
resolve();
}
});
};
connect({tries: 0});
});
};
/**
* @NOTE announceServerStartCalled:
*
* - backwards compatible logic, because people complained that not all themes were loaded when using Ghost as NPM module
* - we told them to call `announceServerStart`, which is not required anymore, because we restructured the code
*/
let announceServerStartCalled = false;
module.exports.announceServerStart = function announceServerStart() {
if (announceServerStartCalled || config.get('maintenance:enabled')) {
return Promise.resolve();
}
announceServerStartCalled = true;
events.emit('server.start');
// CASE: IPC communication to the CLI via child process.
if (process.send) {
process.send({
started: true,
debug: debugInfo
});
}
// CASE: Ghost extension - bootstrap sockets
if (config.get('bootstrap-socket')) {
return connectToBootstrapSocket({
started: true
});
}
return Promise.resolve();
};
/**
* @NOTE announceServerStopCalled:
*
* - backwards compatible logic, because people complained that not all themes were loaded when using Ghost as NPM module
* - we told them to call `announceServerStart`, which is not required anymore, because we restructured code
*/
let announceServerStopCalled = false;
module.exports.announceServerStopped = function announceServerStopped(error) {
if (announceServerStopCalled) {
return Promise.resolve();
}
announceServerStopCalled = true;
// CASE: IPC communication to the CLI via child process.
if (process.send) {
process.send({
started: false,
error: error,
debug: debugInfo
});
}
// CASE: Ghost extension - bootstrap sockets
if (config.get('bootstrap-socket')) {
return connectToBootstrapSocket({
started: false,
error: error,
debug: debugInfo
});
}
return Promise.resolve();
};
|
import React from 'react'
import PropTypes from 'prop-types'
import { NavLink } from 'react-router-dom'
import { Icon } from 'semantic-ui-react'
import classes from './ToolbarSub_1.module.scss'
import SubMenu from './ToolbarSub_2'
const toolbarSub_1 = props => {
const { navigations, showup, activateHandler, actives, childPusher } = props
const subClassName = showup ? [classes.SubOne, classes.Active].join(' ') : classes.SubOne
const menuClassname = nested => nested ? [classes.Menu, classes.Nest].join(' ') : classes.Menu
return (
<ul className={subClassName}>
{navigations.map((nav, key) => (
<li className={menuClassname(nav.nested)} key={key} >
<NavLink activeClassName={classes.Active} to={nav.route} onClick={() => activateHandler(nav.route, nav.nested)}>
<Icon className={classes.MenuIcon} name={nav.icon} size='large' />
<span className={classes.MenuText}>
<b>{nav.text}</b>
</span>
{ nav.nested ? childPusher(actives.includes(nav.route)) : null }
</NavLink>
{ nav.nested ? <SubMenu actives={actives} showup={actives.includes(nav.route)} activateHandler={activateHandler} navigations={nav.childs} childPusher={childPusher} /> : null }
</li>
))}
</ul>
)
}
toolbarSub_1.propTypes = {
navigations: PropTypes.array,
childPusher: PropTypes.func,
showup: PropTypes.bool,
activateHandler: PropTypes.func,
actives: PropTypes.array
}
export default toolbarSub_1
|
const express = require("express");
const router = express.Router();
const deleteEnvPeak = require("../library/deleteEnvPeak");
const sendFailureMess = require("../library/sendFailureMess");
const submitTask = require("../library/submitTask");
const updateEnvStatusSync = require("../library/updateEnvStatusSync");
const formidable = require('formidable');
const fs = require("fs");
/**
* Express router for /msalign
*
* Handle request to upload msalign file, save files to project directory,
* then delete current envelope peaks and submit process msalign file task to
* task scheduler
*/
let msalign = router.post('/msalign', function (req, res) {
let form = new formidable.IncomingForm();
form.maxFileSize = 5000 * 1024 * 1024; // 5gb file size limit
form.encoding = 'utf-8';
form.uploadDir = "tmp";
form.keepExtensions = true;
form.parse(req, function (err, fields, files) {
let ms1 = files.ms1file;
let ms2 = files.ms2file;
let dbDir = fields.projectDir;
let projectName = fields.projectName;
let projectCode = fields.projectCode;
deleteEnvPeak(dbDir, projectCode);
console.log('Deleted previous Envelope Peaks!');
let email = fields.email;
dbDir = dbDir.substr(0, dbDir.lastIndexOf(".")) + '.db';
let des_ms1 = dbDir.substr(0, dbDir.lastIndexOf("/")) + '/' + ms1.name;
let des_ms2 = dbDir.substr(0, dbDir.lastIndexOf("/")) + '/' + ms2.name;
if (ms1 === undefined || ms2 === undefined) {
console.log("Upload files failed!");
sendFailureMess(projectName, projectCode, email);
return;
}
fs.rename(ms1.path, des_ms1, function (err) {
if (err) {
console.log(err);
return res.send({"error": 403, "message": "Error on saving file!"});
}
fs.rename(ms2.path, des_ms2, function (err) {
if (err) {
console.log(err);
return res.send({"error": 403, "message": "Error on saving file!"});
}
res.end();
let parameterTask1 = __dirname + '/../utilities/convertMS1Msalign.js '+ dbDir + ' ' + des_ms1;
submitTask(projectCode, 'node', parameterTask1, 1);
let parameterTask2 = __dirname + '/../utilities/convertMS2Msalign.js '+ dbDir + ' ' + des_ms2;
submitTask(projectCode, 'node', parameterTask2, 1);
updateEnvStatusSync(1, projectCode);
})
})
})
});
module.exports = msalign;
|
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "statsPosted",
execute(client) {
const embed = new MessageEmbed()
.setTitle("Bot stats posted!")
.setDescription("stats listed below")
.addField("Guilds", client.utils.formatNumber(client.guilds.cache.size));
},
};
|
import React from "react";
import All from "./components/all";
import Home from "./pages/home";
import Tel from "./pages/tel";
import { useParams } from "react-router-dom";
import Settings from "./pages/settings";
import Dashboards from "./pages/dashboards";
import Error from "./components/error";
const Dpages = () => {
const { pages } = useParams();
const Pages = (pages) => {
switch (pages) {
case "home":
return <Home />;
case "settings":
return <Settings />;
case "dashboards":
return <Dashboards />;
case "tel":
return <Tel />;
default:
return <Error />;
}
};
console.log(pages);
return <All>{Pages(pages)}</All>;
};
export default Dpages;
|
class controller{
constructor(model,view){
this.model=model;
this.view=view;
this.model.ListConnection(this.UpdateListConnection);
this.view.FilterButtonsEventer(this.FilterConnection);
this.view.SubmitTodo(this.SubmitConnection);
this.view.RemoveTodo(this.RemoveConnection);
this.view.EditTodo(this.EditConnection);
this.view.DoneTodo(this.DoneConnection);
this.UpdateListConnection(this.model.todos);
}
UpdateListConnection = todos => {
this.view.ShowTodos(todos);
}
FilterConnection = type => {
this.model.FilterChanger(type);
}
SubmitConnection = Title => {
this.model.AddTodo(Title);
}
EditConnection = (ID, NewTitle) => {
this.model.EditTodo(ID,NewTitle);
}
RemoveConnection = ID => {
this.model.RemoveTodo(ID);
}
DoneConnection = ID => {
this.model.DoneToDo(ID);
}
}
|
import React, { useState,useEffect, useLayoutEffect } from 'react';
import { useOktaAuth } from '@okta/okta-react';
import {Card} from 'primereact/card'
import { InputText } from 'primereact/inputtext';
import { ProgressSpinner } from 'primereact/progressspinner';
const SignInForm = () => {
const { oktaAuth } = useOktaAuth();
const [sessionToken, setSessionToken] = useState();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [Loader,setLoader] = useState(false)
const [failed,setFailed] = useState('')
var LoaderElement = () => {
useEffect(() => {
},[])
if(Loader) {
return (<React.Fragment><ProgressSpinner style={{width: '50px', height: '50px'}} strokeWidth="8" fill="#EEEEEE" animationDuration=".5s"/></React.Fragment>)
} else return(<React.Fragment></React.Fragment>)
}
var FailMsg = () => {
if(failed.length > 0) {
return (<React.Fragment><div className="bg-red-300 text-left p-4 rounded">{failed}</div></React.Fragment>)
} else {
return <React.Fragment></React.Fragment>
}
}
const handleSubmit = (e) => {
e.preventDefault();
setLoader(true)
oktaAuth.signInWithRedirect({ username, password })
.then(res => {
setLoader(false)
const sessionToken = res.sessionToken;
setSessionToken(res.sessionToken);
// sessionToken is a one-use token, so make sure this is only called once
oktaAuth.signIn({ sessionToken });
})
.catch(err => {console.log('Found an error', err); setLoader(false); setFailed(err.toString())});
};
const handleUsernameChange = (e) => {
setUsername(e.target.value);
};
const handlePasswordChange = (e) => {
setPassword(e.target.value);
};
if (sessionToken) {
// Hide form while sessionToken is converted into id/access tokens
return null;
}
return (
<div className="w-full h-screen flex">
{/* <Card className="w-2/5 m-auto h-2/5">
<form onSubmit={handleSubmit} className="space-y-4 text-center">
<label className="block space-y-4">
<div className="block"> Username</div>
<div className="block">
<InputText
id="username" type="text"
value={username}
onChange={handleUsernameChange} />
</div>
</label>
<label className="block space-y-4">
<div className="block"> Password</div>
<div className="block">
<InputText
id="password" type="password"
value={password}
onChange={handlePasswordChange} />
</div>
</label>
<div className="block">
<input className="focus:outline-none outline-none h-12 w-48 hover:bg-blue-100" id="submit" type="submit" value="Submit" />
</div>
<LoaderElement />
<FailMsg />
</form>
</Card> */}
</div>
);
};
export default SignInForm;
|
/**
* init
*/
$(document).bind('pageshow', function(){
if($('.search_result_container:visible').length == 0) return;
// menu
//$('#menu:visible').children().removeClass('selected');
//$('.menu_search:visible').addClass('selected');
// introduction
var resultContainer = $('.search_result_container .intro:visible');
if(resultContainer.html() == ''){
resultContainer.html(getMessages().searchIntro);
$('.keyword:visible').attr('value', getMessages().searchHelpText);
}
// search setup
$('.search_form:visible').submit(function() { $('.selected:visible').get(0).focus(); itunesSearch(); return false; }); // submitでフォーカスを外して検索
//$('#search_form').blur(itunesSearch); // blurイベントに検索アクションを割り当て…たかったが、なぜか効かないのでHTMLのonblur属性に直に設定した
});
function focusHandler() {
var keywordField = $('.keyword:visible');
if(keywordField.hasClass('not_focused')) {
keywordField.removeClass('not_focused');
keywordField.attr('value', '');
}
}
/**
* jump to album page
*/
function jump2Album(albumId) {
$.mobile.changePage({
url: 'album',
type: 'get',
data: 'cId=' + albumId
}, "slide", false, true, false);
}
/**
* jump to bookmarks page
*/
function jump2Bookmarks() {
$.mobile.changePage({
url: "bookmark",
type: "get",
data: ""
}, "slide", false, true, false);
}
|
//const { options } = require('yargs');
const { crearArchivo } = require('./helpers/multiplicar')
const argv = require('./config/yargs')
console.clear();
//console.log(process.argv);
//console.log(argv);
//console.log('base:yargs', argv.base);
//const [, , arg3 = 'base=5'] = process.argv;
//const[, base] = arg3.split('=');
//const base = 7;
crearArchivo(argv.b, argv.h, argv.l)
.then(nombreArchivo => console.log(nombreArchivo, 'creado'))
.catch(err => console.log(err));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.