text
stringlengths 7
3.69M
|
|---|
import React from 'react';
const AppHeader = ({toDo, done}) => {
return (
<div className="app-header d-flex">
<h1>Easy Todo</h1>
<div className="flex-column">
{/*<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitch1" checked="true" />
<label class="custom-control-label" for="darkSwitch">Dark switch</label>
</div>*/}
{(toDo === 0 && done === 0)
? 'List is empty now'
: <span className="badge badge-dark">{toDo} more to do, {done} done</span>}
</div>
</div>
);
};
export default AppHeader;
|
/**
* @param {string} s
* @param {string} p
* @return {boolean}
*/
var isMatch = function(s, p) {
// I added empty space to move index of letter to equal matrix index
s = ' ' + s;
p = ' ' + p;
const sLength = s.length;
const pLength = p.length;
// console.log(s.length)
// console.log(p.length)
// console.log({s, p})
// matrix of s Height and p length all false except [0][0] which is true as no pattern with no string matches
const matrix = Array(sLength).fill().map(() => Array(pLength).fill(false))
matrix[0][0] = true;
for (let z=1; z<pLength; z++) {
if (p[z] === '*' && matrix[0][z-2] == true) matrix[0][z] = true;
}
for (let i=1; i<sLength; i++) {
for (let j=1; j<pLength; j++) {
if (p[j] === '*') {
// 0 match
if (matrix[i][j-2] === true) matrix[i][j] = true;
// n match
if (s[i] === p[j-1] || p[j-1] === '.') {
if ( matrix[i-1][j] === true ) matrix[i][j] = true;
}
} else {
if (p[j] === s[i] || p[j] === '.') {
if (matrix[i-1][j-1] === true) matrix[i][j] = true;
}
}
}
}
// console.log(matrix)
return matrix[sLength-1][pLength-1];
};
|
function runTest()
{
FBTest.openNewTab(basePath + "console/4322/issue4322.html", function(win)
{
FBTest.openFirebug(function () {
FBTest.enableConsolePanel(function(win)
{
var config = {tagName: "div", classes: "logRow logRow-errorMessage"};
FBTest.waitForDisplayedElement("console", config, function(row)
{
var title = row.querySelector(".errorTitle");
FBTest.compare(/getSession is not defined/, title.textContent,
"The error title must match.");
var link = row.querySelector(".objectLink.objectLink-sourceLink");
FBTest.compare(FW.FBL.$STRF("Line", ["issue4322.html", 10]), link.textContent,
"The source link must match.");
FBTest.testDone();
});
FBTest.clearConsole();
FBTest.click(win.document.getElementById("testButton"));
});
});
});
}
|
/*********************房源日志***************************/
import {onPost,onGet} from "../main";
//房源平台【添加操作】记录日志
export const houseAddLog = params =>{
return onPost('sso/main/houseAddLog',params);
}
// 房源平台修改操作】记录日志
export const houseUpdateLog = params =>{
return onPost('sso/main/houseUpdateLog',params);
}
// 房源平台【查询操作】记录日志
export const houseQueryLog = params =>{
return onPost('sso/main/houseQueryLog',params);
}
// 房源平台【删除操作】记录日志
export const houseDelLog = params =>{
return onPost('sso/main/houseDelLog',params);
}
// 房源日志-----查询房源日志
export const queryHouseActionLogPageList = params=>{
return onPost('house/houseLogQuery/queryHouseActionLogPageList',params)
}
// 房源日志-----根据房源编号查询房源日志
export const queryHouseActionLogByHouseId = params=>{
return onPost('house/houseLogQuery/queryHouseActionLogByHouseId',params)
}
// 房源日志-----根据房源类型查询房源日志
export const queryHouseActionLogByHouseType = params=>{
return onPost('house/houseLogQuery/queryHouseActionLogByHouseType',params)
}
// 房源日志-----根据房源类型查询一手房源日志
export const auxOneHandHouseActionLogPageList = params=>{
return onPost('house/houseLogQuery/auxOneHandHouseActionLogPageList',params)
}
// 查看电话日志
export const auxTelephoneViewLogPageList = params=>{
return onPost('house/houseLogQuery/auxTelephoneViewLogPageList',params)
}
// 房源日志-----根据房源类型查询房源操作枚举对象
export const returnOperatorTypeObj = params=>{
return onPost('house/houseLogQuery/returnOperatorTypeObj',params)
}
// 获取资源类型枚举对象
export const returnSourceTypeObj = params=>{
return onPost('house/houseLogQuery/returnSourceTypeObj',params)
}
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');//HTTP request logger middleware
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('client-sessions');//session management
var config =require('./config');
var knox = require('knox');//AWS API
var routes = require('./routes/index');//index.js
var users = require('./routes/users').router;//users.js
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
//Sessions
app.use(session({
cookieName: 'session_notesource',
secret: 'hello_its_me',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000
}));//millisec
app.use(function(req, res, next) {
if (req.session_notesource.seenyou) {
res.setHeader('X-Seen-You', 'true');
} else {
// setting a property will automatically cause a Set-Cookie response
// to be sent
req.session_notesource.seenyou = true;
res.setHeader('X-Seen-You', 'false');
}
next();
});
//API
app.use('/', routes);
app.use('/users', users);
//AWS
// var knoxClient = knox.createClient({
// key:config.S3AccessKey,
// secret:config.S3Secret,
// bucket:config.S3Bucket
// });
// exports.knoxClient = knoxClient;
//Download part (test)
app.use('/download/test',function(req,res,next){
res.download('./note_assets/cu/gened/PhilosLogic/Heray.pdf');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.sendFile('error.html',{"root":'views'});
//res.redirect('/');
});
module.exports = app;
|
var count = 0;
document.getElementById('result').innerHTML = '已投人数:' + count;
var data = []
data[0] = {
name: '1号',
num: 0
}
data[1] = {
name: '2号',
num: 0
}
data[2] = {
name: '3号',
num: 0
}
data[3] = {
name: '4号',
num: 0
}
data[4] = {
name: '5号',
num: 0
}
data[5] = {
name: '6号',
num: 0
}
data[6] = {
name: '7号',
num: 0
}
data[7] = {
name: '8号',
num: 0
}
var ul = document.getElementById('ph_ol')
//排序
function px(data) {
for (var index = 0; index < data.length - 1; index++) {
for (var j = index; j < data.length; j++) {
if (data[index].num < data[j].num) {
var t = data[index];
data[index] = data[j];
data[j] = t;
}
}
}
return data;
}
function add(n) {
count += 1;
var childs = ul.childNodes;
document.getElementById('result').innerHTML = '已投人数:' + count;
for (var key in data) {
if ((n + '号') == data[key].name) {
data[key].num += 1;
}
}
//删除ul下的所有子节点
// for (var i = childs.length - 1; i >= 0; i--) {
// ul.removeChild(childs.item(i));
// }
ul.innerHTML ='';
px(data);
//动态添加ul下子节点
for (var key in data) {
var li = document.createElement("li");
li.innerHTML = "第"+(parseInt(key)+1)+"名:" + data[key].name + '票数:' + data[key].num;
ul.appendChild(li);
}
}
|
// Page module
define(["app", "controllers/base/page"],
function (app, BasePage) {
var Page = {};
Page.View = BasePage.View.extend({
carouselLinks : [],
gallery : null,
beforeRender: function () {
var done = this.async();
done();
console.log("beforeRender: " + this.$el.attr("module"));
},
afterRender: function () {
console.log("afterRender: " + this.$el.attr("module"));
var context = this;
context.$('.container-fluid a').each(function() {
context.carouselLinks.push({
href: $(this).attr("href"),
title: $(this).data("name"),
id: $(this).data("id"),
image: $(this).data("image"),
thumb: $(this).data("thumb"),
description: $(this).data("description"),
width: $(this).data("width"),
height: $(this).data("height"),
name: $(this).data("name"),
datetime: $(this).data("datetime"),
})
});
context.$('.container-fluid a').on("click", function(e) {
e.preventDefault();
context.gallery = blueimp.Gallery(
context.$('.container-fluid a'),
{
container: context.$('.gallery'),
carousel: true,
startSlideshow: false,
index: $(this).data("index"),
onslide: function (index, slide) {
var data = context.carouselLinks[index];
context.$('.select, .edit').data('id', data.id);
context.$('.select, .edit').data('image', data.image);
context.$('.select, .edit').data('thumb', data.thumb);
context.$('.select, .edit').data('description', data.description);
context.$('.select, .edit').data('name', data.name);
context.$('.select, .edit').data('width', data.width);
context.$('.select, .edit').data('height', data.height);
context.$('.gallery .size').html(data.width + "x" + data.height + " (" + data.datetime + ")");
},
}
);
});
this.$('.select-sm, .select').on("click", function(e) {
e.preventDefault();
var arr = window.name.split("_");
var ts = "";
if (arr.length > 1) {
ts = arr[1];
}
var selectBtn = $(".photo-widget-select[data-timestamp=" + ts + "]", window.opener.document);
if (selectBtn.size() > 0) {
var formGroup = selectBtn.parent();
var id = $(this).data('id');
var image = $(this).data('image');
var thumb = $(this).data('thumb');
var description = $(this).data('description');
formGroup.attr("data-image", image);
formGroup.find("input").val(id);
var previewWidth = formGroup.find(".thumb-preview").attr("data-previewWidth");
var previewThumb = formGroup.find(".thumb-preview").attr("data-previewThumb");
var src = (previewThumb == "true") ? thumb : image;
var width = (previewWidth == "") ? "" : 'width="'+previewWidth+'"';
formGroup.find(".thumb-preview").html('<a href="'+$(this).data('image')+'" class="plugin-box" title="'+description+'" rel="easyii-photos"><img '+width+' src="'+src+'"></a>');
}
window.close();
});
this.$('.edit').on("click", function() {
if (context.gallery) {
context.gallery.close();
}
var editors = app.layoutManager.getWidgets("module-photolibrary-widget-editor");
if (editors.length == 0) {
alert("Please add the widget module-photolibrary-widget-editor");
return;
}
//editors[0].uploadImage(context.data.width, context.data.height, context.data.folderSlug, context);
editors[0].editImage($(this).data("id"), $(this).data("image"), $(this).data("name"), context.data.width, context.data.height, context.data.folderSlug, $(this).data("description"), $.proxy(context.callback, context));
/*
var context = this;
setTimeout(function() {
editImage($(context).data("image"), $(context).data("name"), 200, 200);
}, 1000);
*/
});
this.$('.upload').on("click", function(e) {
e.preventDefault();
var editors = app.layoutManager.getWidgets("module-photolibrary-widget-editor");
if (editors.length == 0) {
alert("Please add the widget module-photolibrary-widget-editor");
return;
}
//editors[0].uploadImage(context.data.width, context.data.height, context.data.folderSlug, context);
editors[0].uploadImage(0, 0, context.data.folderSlug, $.proxy(context.callback, context));
});
},
callback : function() {
//window.location = window.location.href + "&page=1";
location.href = this.replaceUrlParam(location.href, 'page', 1);
},
replaceUrlParam : function(url, paramName, paramValue){
if(paramValue == null)
paramValue = '';
var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
if(url.search(pattern)>=0){
return url.replace(pattern,'$1' + paramValue + '$2');
}
var arr = url.split("#");
return arr[0] + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
},
afterAllRender: function () {
console.log("afterAllRender: " + this.$el.attr("module"));
},
resize: function (ww, wh) {
//console.log("resize: " + this.$el.attr("module") + " " + ww + "," + wh);
}
});
// Return the module for AMD compliance.
return Page;
});
|
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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.
*/
({
testResetTokenNormalCase : {
test: function(cmp) {
var actual;
var myToken = "myToken";
$A.clientService.resetToken(myToken);
var storage = $A.storageService.getStorage("actions");
$A.test.assertNotUndefinedOrNull(storage);
// Verify the token in storage gets updated
var key = "$AuraClientService.token$";
storage.adapter.getItems([key]).then(
function(items) {
if(items[key]) {
actual = items[key].value.token
}
}, function() {
$A.test.fail("Failed to get value from storage.");
});
$A.test.addWaitFor(true, function() {
return typeof actual !== "undefined";
}, function() {
$A.test.assertEquals(myToken, actual);
});
}
}
})
|
import "./index.css"
import StarYellow from "../Icons/starYellow"
import Star from "../Icons/star"
import ToDown from "../Icons/toDown"
import HeartRed from "../Icons/heartRed"
import Compar from "../Icons/compar"
function DetailsPage({ info }) {
return (
<div className="DetailsPage">
<h2>Carrots from Tomissy Farm</h2>
<div className="icons">
<StarYellow />
<StarYellow />
<StarYellow />
<StarYellow />
<Star />
<p>(1 customer review)</p>
</div>
<p className="text">
Carrots from Tomissy Farm are one of the best on the market.
Tomisso and his family are giving a full love to his Bio products.
Tomisso’s carrots are growing on the fields naturally.
</p>
<div className="flex">
<div className="flex">
<div className="category">
<p>SKU:</p>
<p>Category:</p>
<p>Stock:</p>
<p>Farm</p>
</div>
<div className="sku">
<p className="skuP">{info.sku}</p>
<p className="categoryP">{info.category}</p>
<p className="stock">{info.stock}</p>
<p className="farm">{info.farm}</p>
</div>
</div>
<div className="flex">
<div className="category categoryTwo">
<p>Freshness:</p>
<p>Buy by:</p>
<p>Delivery:</p>
<p>Delivery area</p>
</div>
<div className="freshness">
<p>{info.freshness}</p>
<p>{info.buyBy}</p>
<p>{info.delivery}</p>
<p>{info.deliveryArea}</p>
</div>
</div>
</div>
<div className="CarrotsPrise">
<div className="prise">
<p className="newPrise">{info.discount}</p>
<p className="oldPrise">{info.oldPrise}</p>
</div>
<div className="PcsDiv">
<p className="number">1</p>
<div className="height"></div>
<p className="Pcs">Pcs</p>
<ToDown />
</div>
<div className="AddToCart">
<button className="button">
<p className="plus">+</p>
Add to cart
</button>
</div>
</div>
<div className="AddList">
<HeartRed /><p className="addListP">Add to my wish list</p>
<Compar /><p className="compareP">Compare</p>
</div>
<div className="Cook">
<p className="p first">Description</p>
<p className="p">Reviews</p>
<p className="infoNum three">{info.reviewsNum}</p>
<p className="p">Questions</p>
<p className="infoNum">{info.questionsNum}</p>
</div>
<div className="lineDiv">
<div className="lineGreen"></div>
<div className="lineGray"></div>
</div>
<div className="cookInfo">
<h4>Origins</h4>
<p>{info.origins}</p>
<h4 className="title">How to cook</h4>
<p>{info.howToCook}</p>
</div>
<h4 className="fullofVitamins">Full of Vitamins!</h4>
<div className="lineWidth"></div>
<table>
<tr>
<th> Vitamins </th>
<th> Quantity </th>
<th> % DV </th>
</tr>
{
info.vitamins.map(item => {
return (
<tr>
<td>{item.vitaminsName}</td>
<td>{item.quantity}</td>
<td>{item.dv}</td>
</tr>
)
})
}
</table>
</div>
)
}
export default DetailsPage
|
/*
* Copyright (C) 2009-2014 SAP SE or an SAP affiliate company. All rights reserved
*/
jQuery.sap.require("sap.ca.ui.utils.resourcebundle");
sap.ui.controller("sap.ca.ui.dialog.SelectItem", {
_SELECTITEM_DIALOG_ID: "DLG_SLTITEM",
_SELECTITEM_LIST_ID: "LST_ITEMS",
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* @memberOf About
*/
// onInit: function() {
//
// },
onBeforeOpenDialog: function() {
//set default selection
var oDlgModel = this.getView().byId(this._SELECTITEM_DIALOG_ID).getModel();
if (oDlgModel) {
var iDefaultIndex = oDlgModel.getProperty("/defaultIndex");
//set the default selection
var lstItems = this.getView().byId(this._SELECTITEM_LIST_ID);
var arrItems = lstItems.getItems();
if (arrItems && iDefaultIndex >= 0 && iDefaultIndex < arrItems.length) {
lstItems.setSelectedItem(arrItems[iDefaultIndex], true); //mark the selection on UI
}
}
},
onSelectionChange: function(oEvent) {
var oSelectedItem = oEvent.getParameters().listItem;
if (oSelectedItem && oSelectedItem.getBindingContext()) {
//1. close the current dialog at first
this.getView().byId(this._SELECTITEM_DIALOG_ID).close();
//2. open the confirmation dialog
var oSelectedObject = oSelectedItem.getBindingContext().getObject();
var oResult = {
selectedIndex: oEvent.getParameters().listItem.getParent().indexOfItem(oSelectedItem),
selectedItem: oSelectedObject
};
sap.ca.ui.dialog.factory.closeDialog(this._SELECTITEM_DIALOG_ID, oResult);
}
},
onCancelDialog: function() {
var oResult = {
selectedIndex: -1,
selectedItem: null
};
sap.ca.ui.dialog.factory.closeDialog(this._SELECTITEM_DIALOG_ID, oResult);
}
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* @memberOf About
*/
// onBeforeRendering: function() {
//
// },
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* @memberOf About
*/
// onAfterRendering: function() {
//
// },
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* @memberOf About
*/
// onExit: function() {
//
// }
});
|
import React from "react";
import clsx from "clsx";
import { ReactComponent as Logo } from "../icons/logo.svg";
import { makeStyles, useTheme } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import IconButton from "@material-ui/core/IconButton";
import { ReactComponent as BellSVG } from "../icons/bell.svg";
import { ReactComponent as MailSVG } from "../icons/mail.svg";
import { ReactComponent as SettingsSVG } from "../icons/settings.svg";
import { ReactComponent as HelpSVG } from "../icons/help.svg";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import SideBar from "../components/SideBar.js";
import Main from "./Main";
import CssBaseline from "@material-ui/core/CssBaseline";
import { BrowserRouter, Link } from "react-router-dom";
import { SnackbarProvider } from "notistack";
import Box from "@material-ui/core/Box";
const drawerWidth = 240;
const useStyles = makeStyles(theme => ({
root: {
display: "flex"
},
appBar: {
position: "fixed",
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(["margin", "width"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
background: "off-white",
// "#0288d1"
color: "white"
},
appBarShift: {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(["margin", "width"], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen
})
},
menuButton: {
marginRight: 10,
color: "black",
align: "center"
},
hide: {
display: "none"
},
drawer: {
width: drawerWidth,
flexShrink: 0,
whiteSpace: "nowrap"
},
drawerPaper: {
width: drawerWidth
},
drawerOpen: {
width: drawerWidth,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
drawerClose: {
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
overflowX: "hidden",
width: theme.spacing(9) + 1,
[theme.breakpoints.up("sm")]: {
width: theme.spacing(10) + 1
}
},
toolbar: {
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
padding: "0 8px"
// ...theme.mixins.toolbar,
},
content: {
flexGrow: 1,
padding: theme.spacing(3)
},
inputRoot: {
color: "black"
},
inputInput: {
padding: theme.spacing(1, 1, 1, 7),
transition: theme.transitions.create("width"),
width: "100%",
[theme.breakpoints.up("md")]: {
width: 800
}
},
grow: {
flexGrow: 1
},
sectionDesktop: {
display: "none",
[theme.breakpoints.up("md")]: {
display: "flex"
}
}
}));
function App(props) {
const classes = useStyles();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
function handleDrawerOpen() {
setOpen(true);
}
function handleDrawerClose() {
setOpen(false);
}
return (
<BrowserRouter>
<div className={classes.root}>
<CssBaseline />
<AppBar
elevation={0}
color="inherit"
position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open
})}
>
<Toolbar>
<IconButton
size="medium"
data-sidebar-test-open
color="inherit"
aria-label="Open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, { [classes.hide]: open })}
>
<Logo width={45} />
</IconButton>
<div className={classes.grow} />
<div className={classes.sectionDesktop}>
<IconButton>
<BellSVG />
</IconButton>
<IconButton component={Link} to={"/inbox"}>
<MailSVG />
</IconButton>
<IconButton component={Link} to={"/settings"}>
<SettingsSVG />
</IconButton>
<IconButton>
<HelpSVG />
</IconButton>
</div>
</Toolbar>
</AppBar>
<Drawer
PaperProps={{ width: 50 }}
variant="permanent"
className={clsx(classes.drawer, {
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})}
classes={{
paper: clsx({
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})
}}
open={open}
>
<div className={classes.toolbar}>
<IconButton data-sidebar-test-close onClick={handleDrawerClose}>
{theme.direction === "rtl" ? (
<ChevronRightIcon />
) : (
<ChevronLeftIcon />
)}
</IconButton>
</div>
<SideBar profile={props.profile} />
</Drawer>
<div style={{ width: "100%", marginTop: 100 }}>
<SnackbarProvider
anchorOrigin={{
vertical: "bottom",
horizontal: "right"
}}
maxSnack={3}
autoHideDuration={4000}
preventDuplicate={true}
>
<Main profile={props.profile} location={props.location} />
</SnackbarProvider>
</div>
</div>
</BrowserRouter>
);
}
export default App;
|
const express = require('express')
const { unfollowUser } = require('../controllers/userController')
const router = express.Router()
router.post('/:id', async(req, res) => {
let userId = req.params.id
let response = await unfollowUser(req._username, userId)
if (response.status) {
res.status(200).json({ message: response.message })
} else {
res.status(400).json({ message: response.message })
}
})
module.exports = router
|
const projectValidator = require('./project-validator');
const projectCombiner = ({
baseChallengeProject, competitors, projectNames, warnings,
}) => {
const combinedProject = JSON.parse(JSON.stringify(baseChallengeProject));
// for the target that is the stage
// change the variable of the spriteName to the value of the playerName
const stageIndex = baseChallengeProject.targets.findIndex(sprite => sprite.name === 'Stage' && sprite.isStage);
combinedProject.meta.ruleWarnings = [...warnings];
combinedProject.meta.blockCounts = [];
// add each competitor to the game
for (let i = 0; i < competitors.length; i += 1) {
const playerNumber = i + 1;
const spriteName = `Player ${playerNumber}`;
const projectName = projectNames && projectNames[i];
const playerIndex = combinedProject.targets.findIndex(sprite => sprite.name === 'Player 1');
const validatedProject = projectValidator({
playerProject: competitors[i],
baseChallengeProject,
spriteName,
projectName,
});
const playerBot = validatedProject.targets[playerIndex];
const spriteIndex = combinedProject.targets.findIndex(sprite => sprite.name === spriteName);
const currentSprite = combinedProject.targets[spriteIndex];
if (playerIndex === -1) {
// detect if player project is missing a player 1
combinedProject.meta.ruleWarnings.push(`The ${spriteName} project is missing a Player 1`);
} else if (!currentSprite) {
// detect if base project can handle this many competitors
combinedProject.meta.ruleWarnings.push(`Too many competitors for this challenge. Game can handle ${i} competitors, but received ${competitors.length} competitors.`);
} else {
currentSprite.blocks = playerBot.blocks;
currentSprite.variables = playerBot.variables;
combinedProject.meta.ruleWarnings = [
...combinedProject.meta.ruleWarnings,
...validatedProject.ruleWarnings.map(warning => `${warning} for ${spriteName}`),
];
combinedProject.meta.blockCounts = [
...combinedProject.meta.blockCounts,
{
playerName: projectName || spriteName,
blockCount: validatedProject.blockCount,
},
];
// Update project to display playerName in variable spot on load
const spriteNameVariableKey = Object
.entries(baseChallengeProject.targets[stageIndex].variables)
.reduce((aggregator, [key, value]) => {
if (!aggregator && Array.isArray(value) && value[0] === `${spriteName} Name` && projectName) {
return key;
}
return aggregator;
}, null);
if (spriteNameVariableKey) {
combinedProject.targets[stageIndex].variables[spriteNameVariableKey][1] = projectName;
}
}
}
return combinedProject;
};
module.exports = projectCombiner;
|
let vertexShader = `
attribute vec2 a_position;
attribute vec2 a_texcoord;
uniform mat3 u_matrix;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(u_matrix * vec3(a_position, 1), 1);
v_texcoord = a_texcoord;
}
`
let fragmentShader = `
precision highp float;
varying vec2 v_texcoord;
uniform sampler2D u_texture;
uniform vec4 u_light;
void main() {
gl_FragColor = texture2D(u_texture, v_texcoord) * u_light;
}
`
|
const Validator = require('validator');
const isEmpty = require('./is-empty');
const validateLoginInput = data => {
const errors = {};
data.message = !isEmpty(data.message) ? data.message : '';
data.subject = !isEmpty(data.subject) ? data.subject : '';
data.email = !isEmpty(data.email) ? data.email : '';
if (!Validator.isEmail(data.email)) {
errors.email = 'Email is invalid';
}
if (Validator.isEmpty(data.email)) {
errors.email = 'Field is required';
}
if (!Validator.isLength(data.subject, { min: 5 })) {
errors.subject = 'Subject is too short (min: 5 characters)';
}
if (Validator.isEmpty(data.subject)) {
errors.subject = 'Subject field is required';
}
if (!Validator.isLength(data.message, { min: 20 })) {
errors.message = 'Message is too short (min: 20 characters)';
}
if (Validator.isEmpty(data.message)) {
errors.message = 'Message field is required';
}
return {
errors,
isValid: isEmpty(errors)
};
};
module.exports = validateLoginInput;
|
const sqlite3 = require('sqlite3').verbose();
/**
* Get scan level by given scan. Async mode.
* @param {string} dir - Project directory
* @param {number} scanID - Scan number
* @param {function} callback - Callback function that handles query results
* @returns {function} Callback function
* @async
*/
function getScanLevel(dir, scanID, callback) {
let sql = `SELECT SCANLEVEL AS scanLevel
FROM SPECTRA
WHERE SCAN = ?`;
let dbDir = dir.substr(0, dir.lastIndexOf(".")) + ".db";
let resultDb = new sqlite3.Database(dbDir, (err) => {
if (err) {
console.error(err.message);
}
//console.log('Connected to the result database.');
});
resultDb.get(sql, [scanID], (err, row) => {
if (err) {
throw err;
}
return callback(null, row);
});
resultDb.close();
}
module.exports = getScanLevel;
|
var rules = require('../../public/js/validation/rules');
exports.validatePassword = function(v){
return test(v,'password');
};
exports.validateUsername = function(v){
return test(v,"username");
};
exports.validateEmail = function(v){
return test(v,'email');
};
exports.rules = rules;
var test = function(v,patternName){
var pattern = new RegExp(rules[patternName].pattern,'i');
if (pattern){
console.log("Test "+v+" against pattern "+pattern+":"+pattern.test(v));
return pattern.test(v);
}
else{
return false;
}
};
|
import path from 'path'
import express from 'express'
import bunyan from 'bunyan'
import config from 'config'
import proxy from 'http-proxy-middleware'
import socket from './socket'
import { get as getModel } from './db/install'
import db, { prime, update } from './db'
const logger = bunyan.createLogger({ name: 'webgl-pano-server' })
const app = express()
app.set('view engine', 'ejs')
app.set('views', path.resolve(__dirname, '../client/html'))
const server = socket(app)
const indexHtml = (function() {
if (
process.env.NODE_ENV === 'production' &&
process.env.MORPHEUS_ENVIRONMENT === 'staging'
) {
return 'index-staging.html'
}
if (process.env.NODE_ENV === 'production') {
return 'index-production.html'
}
return 'index.html'
})()
const gameDbPath = path.resolve(config.gameDbPath)
logger.info('static game dir', { gameDbPath })
const rootPath = config.rootPath ? config.rootPath : ''
app.use('/__', proxy({ target: 'http://localhost:4040' }))
app.use(
'/api',
proxy({
target: 'http://localhost:4041/soapbubble/us-central1',
pathRewrite: function(path) {
return path.replace('/api', '')
},
}),
)
app.use(`${rootPath}/GameDB`, express.static(gameDbPath))
app.get(`${rootPath}/($|index.html)`, (req, res) => {
res.sendFile(path.join(__dirname, `../public/${indexHtml}`))
})
app.use(rootPath, express.static('public'))
server.listen(config.port, () => {
logger.info('server up and running on 8050')
})
|
/////////////////////////////////////////////////////////////////////
///////////////////VARIABLES INITIALIZATION /////////////////////////
/////////////////////////////////////////////////////////////////////
//Do not change these values unless you know what you are doing
//They change the frequency shown on screen, what can dessync it with
//the time/div shown.
const SINC_FILTER_SAMPLES = 100;
const RESAMPLE_MULTIPLIER = 5;
var reductor_index = 0;
const REDUCTOR = [1198, 602, 364 , 460 , 230, 138, 46];
//REDUCTOR is a vector that decreases window points to get smallers time/div.
/* define 500 and 300us/div was difficult using timer trigger of 50 and 30.
For this reason, we choose to use reductor. Despite using all samples, we use
602 for 500us/div and 364 for 300us/div. It was adjusted by regra de 3.
Bellow that, we put ADC in free running mode, what give us a period of 13us.
Every div in without REDUCTOR uses 20 samples per div.
So, by regra de 3, we use REDUCTOR vector to decrease quantity of samples linearly.
So, we can get smaller time/div.
*/
var mid_screen=511;
const HALF_SCREEN = 409;//size from mid to top or bottom
var trigger_status = 0; //trigger varies 0~2, 0 - off, 1 - rising, 2 - falling
var trigger_lvl = mid_screen;
var v_ref = mid_screen; //mid value or y axes times 10. it is the dc value
//added to the input to set signal to mid adc range.
var adjust_v_ref = 0;
const VERTICAL_STEP = 8; //step for trigger and dc lvl line movement.
//a gain that multiplies all acquired data. It works as a compensation
//for wrong resistor gains and ADC gain error
var adjust_gain = 1;
var acquisition_period = 0.00005; //start of acquisition period (reset point)
var gain = 1; //start of gain (reset point)
let buffer_aquisition = []; //store data acquisition when received from serial
let flag_pause = false; //store pause status if paused, do not acquire (it only stops after ending
//acquisition array)
let flag_button_pause = false;
let flag_button_save_data = false;
const CONFIG_FILE = 'config.csv'; //config file path
const INITIAL_CONFIG = "adjust_v_ref=0\n"+"adjust_gain=1\n"; //config default values
const SAVE_DATA_FILE = 'save_data';
|
import React from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Dashboard from './components/dashboard/dashboard';
import ProductDetails from './components/productDetail';
import PageNotFound from './components/404';
const Routers = () => {
return (
<Switch>
<Route exact path="/dashboard" component={Dashboard} />
<Route exact path="/">
<Redirect to="/dashboard" />
</Route>
<Route path="/productDetail/:prodId" component={ProductDetails} />
<Route component={PageNotFound} />
</Switch>
)
}
export default Routers;
|
function setup() {
createCanvas(500, 500);
for(let i=0; i<500; i+=100){
rect(i, 0, 100, 100);
rect(i, 100, 100, 100);
rect(i, 200, 100, 100);
rect(i, 300, 100, 100);
rect(i, 400, 100, 100);
}
}
function draw() {
}
|
Class("User", {
has : {
app : { is : 'rw' },
target : { is : 'rw' },
profile : { is : 'rw' },
},
methods : {
init : function () {
var self = this;
$(document).ready(function () {
self.setTarget( $( '.accesskeys>.show' ) );
self.target.click( function ( ev ) {
self.show_credentials();
} );
});
},
show_credentials : function () {
var self = this;
$.ajax({
url : '/v1/user/profile',
cache : false,
async : true,
success : function ( profile ) {
self.setProfile( profile.result );
self.show();
},
contentType : 'application/json',
dataType : 'json',
type : 'GET'
});
},
show : function () {
var self = this;
var tpl = "\
<table>\
<tr>\
<td>Firstname</td>\
<td>{{firstname}}</td>\
</tr>\
<tr>\
<td>Lastname</td>\
<td>{{lastname}}</td>\
</tr>\
<tr>\
<td>Email</td>\
<td>{{email}}</td>\
</tr>\
<tr>\
<td>Created</td>\
<td>{{created}}</td>\
</tr>\
<tr>\
<td>username</td>\
<td>{{username}}</td>\
</tr>\
<tr>\
<td>Password</td>\
<td>{{password}}</td>\
</tr>\
</table>\
";
var content = $('.accesskeys .content').html('');
var markup = $( Mustache.render( tpl, self.profile ) )
.appendTo( content );
markup.click( function ( ev ) { $( ev.currentTarget ).remove() } )
},
},
// after : {
// }
})
|
const Users = require("./users")
module.exports = {
async findByUsername (username) {
const user = await Users.findOne({
username
})
return user
},
async findBySocketId (socketId) {
const user = await Users.findOne({
socketId
})
return user
},
async findOnlineUsers(){
const users = await Users.find({
socketId: {
$ne : null
}
})
return users.map(user => ({
username : user.username,
emoji : user.emoji
}))
}
}
|
// pages/personalpage/personalpage.js
Page({
data: {
},
onLoad: function (options) {
},
informationContent: function (e) {
var id = e.currentTarget.dataset.id;
wx.navigateTo({
url: '/pages/informationContent/informationContent?id='+id,
})
}
})
|
const Chance = require('chance');
const addWinnerToMatchUp = require('./add-winner-to-match-up');
const roundRobinGenerator = async (pools, eventId) => {
const matchUpPromises = [];
const columnsArray = Object.values(pools);
for (let i = 0; i < columnsArray.length; i += 1) {
const column = columnsArray[i];
for (let j = 0; j < column.length; j += 1) {
const player = column[j];
for (let k = j + 1; k < column.length; k += 1) {
const opponent = column[k];
const matchUpNumber = matchUpPromises.length + 1;
const matchUpDetails = {
gameType: 'Pool',
eventId,
matchUpNumber,
player,
opponent,
};
matchUpPromises.push(addWinnerToMatchUp(matchUpDetails));
}
}
}
const matchUps = await Promise.all(matchUpPromises);
// shuffle the same way every time
const chance = new Chance(123);
const shuffledMatchUps = chance.shuffle(matchUps);
return { matchUps, shuffledMatchUps };
};
module.exports = roundRobinGenerator;
|
import React, { useContext } from 'react'
import { GlobalContext } from '../useReducer'
import { FaLocationArrow } from 'react-icons/fa'
import { format } from 'date-fns'
import { WeatherInFiveDaysStyles, HilightsStyles } from './WeatherInFiveDaysStyles'
export default function Weather() {
const { state } = useContext(GlobalContext)
let futureWeather = state.weatherInFiveDays.consolidated_weather
console.log(state.weatherInFiveDays);
const weatherFromTomorow = futureWeather?.splice(1)
console.log(state);
const futureWeatherElem = (weatherFromTomorow) => {
return weatherFromTomorow
? <WeatherInFiveDaysStyles> {weatherFromTomorow.map((weather, index) =>
<div
key={index}
>
<div>
{
index === 0 ?<div> <span className="date">Tomorrow</span></div> :
<div>
<span className="date">{ format(new Date(weather.applicable_date), 'EEE') }</span>
<span className="date">{ format(new Date(weather.applicable_date), 'i') }</span>
<span className="date">{ format(new Date(weather.applicable_date), 'LLL') }</span>
</div>
}
</div>
<img src={`https://www.metaweather.com//static/img/weather/${weather.weather_state_abbr}.svg`} alt={`${weather.weather_state_name}`} />
<div className="max-min-temp">
<span className="max-temp"> {Math.round(weather.max_temp)} °C </span>
<span className="min-temp"> {Math.round(weather.min_temp)} °C </span>
</div>
</div>
)
}
</WeatherInFiveDaysStyles>
: <div>Loading...</div>
}
const celciusSymb = <span>℃</span>
const fahrenheitSmb = <span>℉</span>
function changeDegree(degree) {
return <span
onClick={() => {console.log("Hello world")}}
style={{
padding: "0.6rem",
backgroundColor : "#585676",
borderRadius : "50%",
marginInline : "0.5rem",
cursor : 'pointer'
}}>{ degree } </span>
}
return (
<div style={{margin : "1rem"}}>
<div style={{ textAlign: "end", paddingInline: "1.5rem", paddingBlock: "2rem" }}>
{changeDegree(celciusSymb)}
{changeDegree(fahrenheitSmb)}
</div>
{futureWeatherElem(weatherFromTomorow)}
{futureWeather && <div className="heilight">
<h3 style={{ maxWidth: 850, marginLeft : "0", marginRight : "auto", paddingBlock: "1rem"}}>
Today's Highlight
</h3>
<HilightsStyles className="hilight-container">
<div>
<h4 className="headlines">wind status</h4>
<p className="number">
{futureWeather && Number(futureWeather[0].wind_direction).toFixed(2)} <span>mph</span>
</p>
<div>
<FaLocationArrow className="arrow-location"/> {futureWeather && futureWeather[0].wind_direction_compass}
</div>
</div>
<div>
<h4 className="headlines">Humidity</h4>
<p className="number">
{futureWeather && futureWeather[0].humidity} <span>%</span>
</p>
<progress max="100" value={futureWeather && futureWeather[0].humidity}></progress>
</div>
<div>
<h4 className="headlines">Visibility</h4>
<p className="number">
{futureWeather && Number(futureWeather[0].visibility).toFixed(2)} <span>miles</span>
</p>
</div>
<div>
<h4 className="headlines">Air Presure</h4>
<p className="number">
{futureWeather && futureWeather[0].air_pressure} <span>mb</span>
</p>
</div>
</HilightsStyles>
</div>}
</div>
)
}
|
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
user: {
ansSex: '',
ansBirthYear: '',
ansBirthMonth: '',
ansBirthDay: '',
ansInstruction: '',
ansHospitalization: '',
ansHospitalizationHistory: '',
ansConsultation: ''
}
},
mutations: {
setUser(state, data) {
Object.assign(state.user, data);
}
},
getters: {
getUser: state => state.user
}
})
|
// eslint-disable-next-line
import React from 'react';
class ShowProfile extends React.Component {
url ="https://api.github.com/users/vatsank"
constructor(props) {
super(props);
this.state = {
profile:{},
loaded:false
}
}
componentDidMount(){
fetch(this.url)
.then(resp => resp.json())
.then(profile => this.setState({profile, loaded:true}))
}
render() {
if(!this.state.loaded){
return(
<div>
<h1>loading...</h1>
</div>
);
} else {
return (
<div>
<p>{this.state.profile.name}</p>
<img src={this.state.profile.avatar_url} alt="Profile Picture"></img>
</div>
);
}
}
}
export default ShowProfile;
|
import React from 'react';
import { connect } from 'react-redux';
import Todos from './components/Todos'
import AddTodo from './components/AddTodo'
import RouterTest from './components/RouterTest';
import { actionAddTodo } from './actions/AddTodoAction'
class App extends React.Component {
render() {
const {dispatch, todos, location } = this.props;
return (
<div>
<AddTodo onClick={text => dispatch(actionAddTodo(text))}/>
<Todos todos={todos}/>
<RouterTest location={location} />
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return {
location : ownProps.match.params.filter,
todos : state.todos
};
}
export default connect(mapStateToProps)(App)
|
const shareData = {
title: 'MDN',
text: 'Learn web development on MDN!',
url: 'https://developer.mozilla.org',
};
const btn = document.querySelector('#share-button');
btn.addEventListener('click', async () => {
await navigator.share(shareData);
});
|
var searchBtn = document.getElementsByClassName('searchButton');
var searchBar = document.getElementsByClassName('searchBar');
var pesquisa = document.getElementsByClassName('pesquisa');
function searchDropdown() {
for (var i = 0; i < searchBar.length; i++) {
searchBar[i].classList.toggle("searchBarShow");
}
for (var j = 0; j < pesquisa.length; j++) {
pesquisa[j].classList.toggle("activeSearchBar");
}
}
var footerSearchBtn = document.getElementsByClassName('footerSearchButton');
var footerSearchBar = document.getElementsByClassName('footerSearchBar');
var pesquisaFooter = document.getElementsByClassName('pesquisaFooter');
function footerSearchDropdown() {
for (var i = 0; i < footerSearchBar.length; i++) {
footerSearchBar[i].classList.toggle("searchBarShow");
}
for (var j = 0; j < pesquisa.length; j++) {
pesquisaFooter[j].classList.toggle("activeSearchBar");
}
}
|
const {ipcRenderer} = require('electron');
const products = document.querySelector('#products');
ipcRenderer.on('product:new', (e, newProduct) => {
console.log(newProduct);
const newTemplate = `
<div class="col-md-6 col-lg-4 p-2 p-2">
<div class="card text-center">
<div class="card-header">
<h2 class="title text-info">${newProduct.name}</h2>
</div>
<div class="card-body">
<h4 class="price text-warning">$ ${newProduct.price}</h4>
<hr>
<h3 class="description">${newProduct.description}</h3>
</div>
<div class="card-footer">
<button class="btn btn-danger btn-sm">
Eliminar
</button>
</div>
</div>
</div>
`;
products.innerHTML += newTemplate;
const btns = document.querySelectorAll('.btn-danger');
btns.forEach(btn => {
btn.addEventListener('click', e => {
e.target.parentElement.parentElement.parentElement.remove();
})
})
});
ipcRenderer.on('products:removeAll', (e) => {
products.innerHTML = "";
})
|
import { GeoService } from './providers'
export const state = () => ({
geoList: []
})
export const actions = {
async getGeoList ({ commit }, text) {
const data = await GeoService.getGeoList(text)
commit('SET_GEO_LIST', data)
}
}
export const mutations = {
SET_GEO_LIST (state, data) {
state.geoList = data.features
}
}
|
import React from 'react';
import { withHooks, useState, useMemo } from '../hooks-diy';
const UseMemo = withHooks(() => {
const [count, setCount] = useState(3);
const [number, setNumber] = useState(3);
const expensive = useMemo(() => {
let sum = 0;
for(let i = 0; i <= count; i++){
sum += i;
}
return sum;
}, [count])
return(
<React.Fragment>
<p>{ count }</p>
<button onClick = {() => setCount(count+1)}>setCount(每次加1)</button>
<Child expensive = { expensive }/>
<p>{ number }</p>
<button onClick = {() => setNumber(number+1)}>setNumber(每次加1)</button>
</React.Fragment>
)
});
const Child = withHooks(({ expensive }) => (<p>expensive: { expensive }</p>))
export { UseMemo }
|
const router = require('express').Router();
const { Patient, Payment } = require('../models/Patient');
const Admin = require('../models/Admin');
router.get('/', (req, res)=>{
res.render('home')
})
router.post('/signin', (req, res)=>{
});
module.exports = router;
|
export const muiStyles = theme => ({
link: {
textDecoration: 'none'
},
buttonRoot: {
marginRight: 15,
marginBottom: 12,
[theme.breakpoints.down("xs")]: {
fontSize: '0.75rem',
lineHeight: 1.5,
marginBottom: 8,
marginRight: 8,
},
},
buttonRootMR0: {
[theme.breakpoints.down("xs")]: {
fontSize: '0.75rem',
lineHeight: 1.5,
marginBottom: 8,
marginRight: 0,
},
},
})
|
import axios from 'axios';
import * as Constants from '../constants/Constants';
const ProfileActionCreators = {
register: function (profile) {
return {
type: Constants.REGISTER(),
payload: axios.post('/api/v0/profile', {profile})
}
},
getProfile: function (id) {
return {
type: Constants.GET_MY_PROFILE(),
payload: axios.get('/api/v0/profile', {
params: {
id
}
})
}
},
getMyProfile: function (facebookId) {
return {
type: Constants.GET_MY_PROFILE(),
payload: axios.get('/api/v0/profile', {
params: {
facebookId
}
})
}
},
getAll: function (type, gender, ageMin, ageMax) {
return {
type: Constants.GET_ALL_PROFILE(),
payload: axios.get('/api/v0/profiles', {
params: {
type,
gender,
ageMin,
ageMax
}
})
}
},
getSingle: function (singleId) {
return {
type: Constants.GET_SINGLE_PROFILE(),
payload: axios.get('/api/v0/profile', {
params: {
singleId
}
}),
meta: {
fetchingId: singleId
}
}
},
getFriends: function (singleId) {
return {
type: Constants.GET_FRIENDS(),
payload: axios.get('/api/v0/friends', {
params: {
singleId
}
})
}
},
linkFriend: function (singleId, friendId) {
return {
type: Constants.LINK_FRIEND(),
payload: axios.post('/api/v0/ishelpedby', {
singleId,
friendId
})
}
}
};
export default ProfileActionCreators;
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import ClothingSection from './ClothingSection';
class MainPage extends Component {
componentDidMount() {
if (this.props.loggedIn === false) {
this.props.logIn()
}
}
selectAll = () => {
this.props.selectAll()
this.props.SelectAllHats(this.props.hats)
this.props.SelectAllTops(this.props.tops)
this.props.SelectAllJackets(this.props.jackets)
this.props.SelectAllBottoms(this.props.bottoms)
this.props.SelectAllShoes(this.props.shoes)
console.log(this.props.hats)
}
render() {
return (
<div className='main-page'>
<button onClick={this.selectAll}>Select All</button>
<ClothingSection hats={this.props.hats}
category='Hats'
/>
<ClothingSection tops={this.props.tops}
category='Tops'
/>
<ClothingSection jackets={this.props.jackets}
category='Jackets'
/>
<ClothingSection bottoms={this.props.bottoms}
category='Bottoms'
/>
<ClothingSection shoes={this.props.shoes}
category='Shoes'
/>
</div>
);
}
}
function mapStateToProps(state) {
return {
loggedIn: state.loggedIn,
hats: state.hats,
tops: state.tops,
jackets: state.jackets,
bottoms: state.bottoms,
shoes: state.shoes
}
}
function mapDispatchToProps(dispatch) {
return {
logIn: () => dispatch({type: 'LOG_IN', payload: true}),
selectAll: () => dispatch({type: 'SELECT_ALL', payload: true}),
SelectAllHats: (data) => dispatch({type: 'SELECT_ALL_HATS', payload: data}),
SelectAllTops: (data) => dispatch({type: 'SELECT_ALL_TOPS', payload: data}),
SelectAllJackets: (data) => dispatch({type: 'SELECT_ALL_JACKETS', payload: data}),
SelectAllBottoms: (data) => dispatch({type: 'SELECT_ALL_BOTTOMS', payload: data}),
SelectAllShoes: (data) => dispatch({type: 'SELECT_ALL_SHOES', payload: data})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
|
(function() {
class Umbrella {
constructor(config) {
this.context = config.context;
this.scene = config.scene;
this.radius = 100;
this.position = { x: WIDTH / 2, y: HEIGHT / 2 };
}
update() {
this.position.x = this.scene.mouse.x;
this.position.y = this.scene.mouse.y;
}
render() {
let ctx = this.context;
ctx.beginPath();
ctx.strokeStyle = 'white';
ctx.fillStyle = "gray";
ctx.arc(this.position.x, this.position.y, this.radius, Math.PI, 0);
ctx.fill();
ctx.moveTo(this.position.x - this.radius, this.position.y);
ctx.lineTo(this.position.x + this.radius, this.position.y);
ctx.moveTo(this.position.x, this.position.y);
ctx.lineTo(this.position.x, this.position.y + this.radius);
ctx.stroke();
ctx.beginPath();
ctx.arc(this.position.x + 15, this.position.y + this.radius, 15, Math.PI, 0, true);
ctx.stroke();
}
};
window.RainingNamespace = window.RainingNamespace || {};
RainingNamespace.Umbrella = Umbrella;
const
WIDTH = 600,
HEIGHT = 600,
MAX_LENGTH = 20;
})();
|
const express = require("express");
const bodyParser = require("body-parser");
const { MongoClient, ObjectID } = require("mongodb");
const assert = require("assert");
const app = express();
app.use(bodyParser.json());
const MongoUrl = "mongodb://localhost:27017";
const dataBase = "MovieList";
app.get("/home", (req, res) => {
res.send("hello");
});
MongoClient.connect(MongoUrl,{ useNewUrlParser: true }, (err, client) => {
assert.equal(err, null, "dataBase connection failed");
const db = client.db(dataBase);
app.post('/add-movie', (req, res) => {
let newMovie = req.body
db.collection('movies').insertOne(newMovie, (err, data) => {
if(err) res.send("can't add new movie")
res.send("new movie added")
})
})
app.get('/movies', (req, res) => {
db.collection('movies').find().toArray((err, data) => {
if(err) res.send("can't show movie list")
res.send(data)
})
})
app.put('/modify_movie/:id', (req, res) => {
let id = ObjectID(req.params.id)
db.collection('movies').findOneAndUpdate({_id: id},{$set: {...req.body}}, (err, data) => {
if(err) res.send("can't delete movie")
res.send(data)
})
})
app.delete('/delete_movie/:id', (req, res) => {
let id = ObjectID(req.params.id)
db.collection('movies').findOneAndDelete({_id: id}, (err, data) => {
if(err) res.send("can't delete movie")
res.send(data)
})
})
}
);
app.listen(4000, err => {
if (err) console.log("there is an error");
console.log("server is running on port 4000");
});
|
(function() {
var Background = window.Background = function(obj) {
this.image = obj.img.background;
this.render = function() {
obj.ctx.drawImage(this.image, 0, 0);
}
}
})()
|
import React from "react";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemSecondaryAction from "@material-ui/core/ListItemSecondaryAction";
import ListItemText from "@material-ui/core/ListItemText";
import Checkbox from "@material-ui/core/Checkbox";
import IconButton from "@material-ui/core/IconButton";
import DeleteIcon from "@material-ui/icons/Delete";
const TodoList = ({ todos, deleteTodo, enterTodo, current, setCurrent }) => {
return (
<List>
{todos.map(({ todoText: todo, taskDone }, index) => {
const isSelected = current === null ? false : index === current;
return (
<ListItem
key={index.toString()}
dense
button
selected={isSelected}
onClick={() => setCurrent(index)}
>
<Checkbox
tabIndex={-1}
disableRipple
onClick={() => enterTodo(index)}
value="taskDone"
checked={taskDone}
/>
<ListItemText primary={todo} />
<ListItemSecondaryAction>
<IconButton
aria-label="Delete"
onClick={() => {
deleteTodo(index);
}}
>
<DeleteIcon />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
);
})}
</List>
);
};
export default TodoList;
|
import React from "react"
const spinners = ()=>
(<div className="spinnertable">
<div className="rect1"></div>
<div className="rect2"></div>
<div className="rect3"></div>
<div className="rect4"></div>
<div className="rect5"></div>
<div className="rect6"></div>
</div>)
export default spinners
|
define(function(require, exports, module){
var global = require('../global/global');
var fenye = require('../global/fenye');
var url = '/index.php?g=Wap&m=Act&a=getindex&token=' + token + '&wecha_id=' + wid;
fenye(url, 'data_list', '5');
});
|
export { propTypes, defaultProps } from "./article-list-prop-types-base";
|
/**
* Created by Aymen on 2016-10-16.
*/
import React, {Component} from 'react';
export default class LoggedOutNavBar extends Component {
render(){
return(
<nav className="teal lighten-2">
<ul className="nav nav-pills">
<li><a>Login</a></li>
<li><a>Join Laborprize</a></li>
</ul>
</nav>
)
}
}
|
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
let element = new Set();
for(let i in A){
if(!element.has(A[i])){
element.add(A[i]);
}
else{
element.delete(A[i]);
}
}
const result = [...element];
return result[0];
}
|
const mongoose = require('mongoose');
const Validator = require('validator');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({
fullname: {
type: String,
required: [true, 'Full name is required'],
},
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
trim: true,
validate: [Validator.isEmail, 'Please enter valid email'],
},
password: {
type: String,
required: [true, 'Password is required'],
minlength: [5, 'Minimum 6 characters'],
},
});
userSchema.pre('save', async function (next) {
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 12);
next();
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;
|
import React from 'react';
import { Button, Image, Space } from 'antd';
import { NavLink } from 'react-router-dom';
import { Header, ListMenu, HeaderText, styles } from './style';
// Component
const Navbar = ({ title, backgroundColor, textColor }) => {
// render
return (
<>
<Header backgroundColor={backgroundColor} textColor={textColor}>
<HeaderText>
<Image
height={"40"}
preview={false}
src={require("../../../assets/img/BANK_BRI_logo.svg").default}
/>
</HeaderText>
<Space size={"small"}>
<ListMenu>
<NavLink
style={styles.link}
activeStyle={styles.linkActive}
exact
to={"/"}
>
Home
</NavLink>
</ListMenu>
<ListMenu>
<NavLink
style={styles.link}
activeStyle={styles.linkActive}
exact
to={"/course"}
>
Course
</NavLink>
</ListMenu>
<ListMenu>
<NavLink
style={styles.link}
activeStyle={styles.linkActive}
exact
to={"/blog"}
>
Blog
</NavLink>
</ListMenu>
<NavLink to={"/user/login"} style={{ marginLeft: 20 }}>
<Button type={"primary"} shape={"round"}>Sign In</Button>
</NavLink>
</Space>
</Header>
</>
)
}
export default Navbar
|
const request = require("supertest");
const expect = require("expect");
const app = require("./app.js");
process.on("unhandledRejection", err => { throw err })
describe("koa within express", () => {
it("serves express requests", () => {
return request(app)
.get("/express/hello")
.expect(200)
.then(({body}) => {
expect(body).toEqual({ hello: "express" })
})
})
it("serves koa requests", () => {
return request(app)
.get("/koa/hello")
.expect(200)
.then(({body}) => {
expect(body).toEqual({ hello: "koa" })
})
})
it("koa can send explicit 404 requests", () => {
return request(app)
.get("/koa/not_found")
.expect(404)
.then(({body}) => {
expect(body).toEqual({ error: "not found" })
})
})
it("catches errors from koa and routes them to express", () => {
return request(app)
.get("/koa/throw_error")
.expect(500)
.then(({body}) => {
expect(body).toEqual({
message: "Express error handler: Kaboom!",
error: {},
})
})
});
it("yields control back to express", () => {
return request(app)
.get("/express/hello_again")
.expect(200)
.then(({body}) => {
expect(body).toEqual({ hello_again: "express" })
})
})
it("express fall-through handling works", () => {
return request(app)
.get("/no_such_route")
.expect(404)
.then(({body}) => {
expect(body).toEqual({
message: "Express error handler: Express says: Not Found!",
error: { status: 404 },
})
})
})
})
|
(function() {
console.log('ala');
}).call(this);
|
module.exports = {
a: 1,
b: 'Anh',
c: [1, 'Em', true, false, {}, 0, function () { }],
sum: (x, y) => x + y,
obj: { a: 'a', b: 'b', c: 'c' }
};
|
import { PROPERTY_ID_PLACEHOLDER } from '../../constants';
import { PATHNAME_TEMPLATE } from '../constants';
/**
* @param {number} propertyId
* @return {string}
*/
export const getPathname = propertyId =>
PATHNAME_TEMPLATE.replace(PROPERTY_ID_PLACEHOLDER, propertyId);
|
// This is the actual program. First, there must be a manager,
// then the user may add as many interns and engineers as they want.
const Manager = require("./lib/Manager");
const Engineer = require("./lib/Engineer");
const Intern = require("./lib/Intern");
const inquirer = require("inquirer");
const path = require("path");
const fs = require("fs");
// The two lines below explain the need for the output folder, and the team.html file.
// team.html is where the answers to the questions are displayed.
const OUTPUT_DIR = path.resolve(__dirname, "output")
const outputPath = path.join(OUTPUT_DIR, "team.html");
//The line below connects this to the htmlRenderer.js file.
const render = require("./lib/htmlRenderer");
// Function prompts the user to ask what type of employee you are.
// (Manager is seperate, it is assumed there is one manager.)
function getEmployeeType(){
return inquirer.prompt([
{
type:'list',
message:`Enter the Employee's role : `,
choices:['Engineer','Intern'],
name:'role'
}
]);
}
// Each employee type (manager, engineer, or intern) has different information required. (See tests)
function getStandardQuestions(role){
// Standard questions to ask all employees. See Employee.js/Employee.test.js
const standardQuestions = [
{
type:'input',
message:`Name of ${role}: `,
name:'name'
},
{
type:'input',
message:`ID# of ${role}: `,
name:'id'
},
{
type:'input',
message:`Email for ${role}: `,
name:'email'
},
];
let questions;
// Specialized questions for each of the three positions.
// See 10-OOP activities 20 and 21 for examples of subclasses.
if (role=="Engineer"){
questions = [...standardQuestions,
{
type:'input',
message:`GitHub for ${role}: `,
name:'github'
}]
}
else if (role=="Intern"){
questions = [...standardQuestions,
{
type:'input',
message:`School for ${role}: `,
name:'school'
}]
}
else if (role=="Manager"){
questions = [...standardQuestions,
{
type:'input',
message:`Office Number for ${role}: `,
name:'officeNumber'
}]
}
return inquirer.prompt(questions);
}
// Prompt provides "yes or No" question to restart questions to add another employee.
function addMorePrompt(){
return inquirer.prompt([
{
type:'list',
message:`Add more users? : `,
choices:['Yes',"No"],
name:'confirm'
}
]);
}
async function run(){
const employees = [];
let firstRun = true;
// loop through the employee creation untill the user says do not add more
do{
// Write code to use inquirer to gather information about the development team members,
// The first run must be the Manager, and there can only be one Manager.
if(!firstRun){
type = await getEmployeeType();
}
else{
firstRun = false;
type = {role:"Manager"}
}
let data = await getStandardQuestions(type.role);
// and to create objects for each team member (using the correct classes as blueprints!)
switch(type.role){
case 'Engineer':
employees.push( new Engineer(data.name, data.id, data.email, data.github));
break;
case 'Intern':
employees.push( new Intern(data.name, data.id, data.email, data.school));
break;
case 'Manager':
employees.push( new Manager(data.name, data.id, data.email, data.officeNumber));
break;
}
// If the addMorePrompt function is answered "no", the loop ends.
var getMore = await addMorePrompt();
} while (getMore.confirm!= "No");
//console.log( employees );
// After the user has input all employees desired, call the `render` function (required
// above) and pass in an array containing all employee objects; the `render` function will
// generate and return a block of HTML including templated divs for each employee!
const html = render(employees);
//console.log(html);
// After you have your html, you're now ready to create an HTML file using the HTML
// returned from the `render` function. Now write it to a file named `team.html` in the
// `output` folder. You can use the variable `outputPath` above target this location.
// try and catch serve to report errors. See 09-NodeJS activities 38 and 40 for examples.
try{
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR);
}
}
catch(err){
return console.log(err);
}
fs.writeFile(outputPath, html, function(err){
if (err){return console.log(err)}
console.log("Successfully wrote team.html.");
})
}
// Line below causes code to actually run, by triggering the above async function. (IMPORTANT)
run();
// Write code to use inquirer to gather information about the development team members,
// and to create objects for each team member (using the correct classes as blueprints!)
// After the user has input all employees desired, call the `render` function (required
// above) and pass in an array containing all employee objects; the `render` function will
// generate and return a block of HTML including templated divs for each employee!
// After you have your html, you're now ready to create an HTML file using the HTML
// returned from the `render` function. Now write it to a file named `team.html` in the
// `output` folder. You can use the variable `outputPath` above target this location.
// Hint: you may need to check if the `output` folder exists and create it if it
// does not.
// HINT: each employee type (manager, engineer, or intern) has slightly different
// information; write your code to ask different questions via inquirer depending on
// employee type.
// HINT: make sure to build out your classes first! Remember that your Manager, Engineer,
// and Intern classes should all extend from a class named Employee; see the directions
// for further information. Be sure to test out each class and verify it generates an
// object with the correct structure and methods. This structure will be crucial in order
// for the provided `render` function to work! ```
|
import _ from 'lodash';
import { relay, resolver, attributeFields } from 'graphql-sequelize';
import { sequelize, User, Social } from '../../db';
const sequelizeNodeInterface = relay.sequelizeNodeInterface;
const sequelizeConnection = relay.sequelizeConnection;
import {
// nodeDefinitions,
fromGlobalId,
globalIdField,
} from 'graphql-relay';
import {
GraphQLEnumType,
GraphQLSchema,
GraphQLObjectType,
GraphQLList,
GraphQLString,
GraphQLInt,
GraphQLNonNull,
GraphQLID,
GraphQLBoolean,
} from 'graphql';
import connections from './connections';
// automatically define a models attributes as fields for a GraphQL object type
const defaultFields = attributeFields(User, {
// ... options
// exclude: [], // array of model attributes to ignore - default: []
// only: Array, // only generate definitions for these model attributes - default: null
globalId: true, // return an relay global id field - default: false
// map: Object, // rename fields - default: {}
// allowNull: Boolean, // disable wrapping mandatory fields in `GraphQLNonNull` - default: false
// commentToDescription: Boolean, // convert model comment to GraphQL description - default: false
// cache: Object, // Cache enum types to prevent duplicate type name error - default: {}
});
const customFields = { socials: {
type: connections.social.connectionType,
args: connections.social.connectionArgs,
resolve: connections.social.resolve,
} };
const userType = new GraphQLObjectType({
name: User.name,
fields: _.assign(defaultFields, customFields),
});
export default userType;
|
$().ready(function () {
var extract = function (data) {
var entities = [];
if (data.length) {
for (var i = 0; i < data.length; i++) {
entities[i] = data[i]['propertyMap'];
entities[i]['id'] = data[i]['key']['id'];
}
}
return entities;
};
var displayPlans = function (plans) {
if (!plans.length) {
$("#plans").append('<strong>No training plan found...</strong>');
return;
}
$.each(plans, function (index, plan) {
$("#plans").append('<li><a href="/ha-result-detail-screen.html?idKey=' + plan['strKey'] + '">' + plan['pTitle'] + '</a></li>');
});
};
var displayExercises = function (exercises) {
if (!exercises.length) {
$("#exercises").append('<strong>No exercise found...</strong>');
return;
}
$.each(exercises, function (index, exercise) {
$("#exercises").append('<li><a href="/details?idKey=' + exercise['strKey'] + '">' + exercise['title'] + '</a></li>');
});
};
$.get("/search", {action: "getAllDomains"})
.success(function (data) {
var html = '<div class="row">';
for (var i = 0; i < data.length; i++) {
html += '<div class="col-md-3">' +
'<button type="submit" class="btn btn-default btn-lg">' +
'<span class="glyphicon glyphicon-tree-deciduous"></span>' +
'</button>' +
' <a href="#" class="domain">' + data[i] + '</a>' +
'</div>';
}
html += '</div>';
$("#content .row:last-child").html(html);
$(".domain").click(function () {
var domain = $(this).text();
$.get("/search", {action: "getAllByDomain", pSport: domain})
.success(function (data) {
var searchHtmlTemplate =
'<div class="row"> ' +
'<h3>Training Plans for ' + domain + '</h3>' +
'<hr> ' +
'<ul id="plans"> ' +
'</ul> ' +
'</div> ' +
'<div class="row"> ' +
'<h3>Exercises for ' + domain + '</h3>' +
'<hr>' +
'<ul id="exercises">' +
'</ul>' +
'</div>';
$("#content").html(searchHtmlTemplate);
plans = extract(data);
displayPlans(plans);
displayExercises([]);
});
});
});
$("#searchForm").submit(function (e) {
var q = $("#search").val();
var searchHtmlTemplate =
'<div class="row"> ' +
'<h3>Training Plans</h3> ' +
'<hr> ' +
'<ul id="plans"> ' +
'</ul> ' +
'</div> ' +
'<div class="row"> ' +
'<h3>Exercises</h3> ' +
'<hr>' +
'<ul id="exercises">' +
'</ul>' +
'</div>';
$("#content").html(searchHtmlTemplate);
if (q.length) {
$.get("/search", {pTitle: q, action: "search"})
.success(function (data) {
var plans = extract(data['plans']),
exercises = extract(data['exercises']);
displayPlans(plans);
displayExercises(exercises);
});
$.get("/rss")
.done(function (data) {
content = $("#content");
content.append('<div class="row">' +
'<h3>News</h3>' +
'<hr>' +
'<ul id="news">');
$.each(data['rss'], function (index, rss) {
$("#news").append('<li><a href="' + rss['url'] + '">' + rss['title'] + '</a></li>');
});
content.append('</ul></div>');
});
}
e.preventDefault();
});
});
|
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import HomePage from "./pages/home/HomePage";
import "./App.css";
function App() {
return (
<Router>
<HomePage />
</Router>
);
}
export default App;
|
/**
* Main module, should be used in the ng-app.
* @ngdoc module
* @name FitFacebook
*/
var ngModule = angular.module('FitFacebook', [
'ngAnimate', 'ngRoute', 'ngMessages',
'ngCookies', 'ngSanitize',
'ngResource', 'underscore',
'angularMoment',
'ff.dashboardModule',
'ff.newsModule',
'ff.friendModule',
'ff.coreModule'
])
require('./components/ng-underscore/ng-underscore.js');
/**
* INJECT the module in the FitFacebook Module, AS IT IS ABOVE.
* LOAD the module, SO IT IS BELLOW.
*/
require('./modules/ff-core/ff.core.app.js');
require('./modules/ff-friend/ff.friend.app.js');
require('./modules/ff-news/ff.news.app.js');
require('./modules/ff-dashboard/ff.dashboard.app.js');
|
/* eslint-disable */
import React from 'react'
import { connect } from 'react-redux'
import {Accordion, Panel,Button, FormControl, FormGroup, InputGroup, Label } from 'react-bootstrap'
import Yaml from 'js-yaml';
import { readContext } from '../lib/helpers'
import { Marked } from './Ui'
//import Holdable from 'react-holdable'
import UnsupportedField from '../../node_modules/react-jsonschema-form/lib/components/fields/UnsupportedField';
import uuid from 'uuid';
import dotProp from 'dot-prop';
const parseTrait=(label,text)=>{
let trait={}
if (typeof text === 'string') {
trait.description=text
} else {
trait=Object.assign({},text)
}
trait.cost=trait.cost || 0
if (!trait.name) trait.name=label
return trait;
}
class TraitSelect extends React.Component {
constructor(props){
super(props)
this.handleClick=this.handleClick.bind(this)
this.state={
data: {},
value:null
}
this.placeholder="Select item to add"
}
handleClick(e){
if (!this.state.value) return;
let formData=this.props.widget.formData;
this.props.widget.onChange([...formData,this.state.value],{ validate: false })
}
groupFilter(i){
return true;
}
traitFilter(i){
return true;
}
render(){
return <FormGroup>
<InputGroup><FormControl componentClass="select" placeholder={this.placeholder} defaultValue="" onChange={e=>{this.setState(Object.assign(this.state,{value:JSON.parse(e.target.value)}))}}>
<option>{this.placeholder}</option>
{Object.entries(this.state.data).filter(this.groupFilter.bind(this)).map((entry,i)=>{
let [group,item]=entry;
return <optgroup key={i} label={group}>{Object.entries(item).filter(this.traitFilter.bind(this)).map((sfx_entry,j)=>{
let [label,value]=sfx_entry;
return <option key={j} value={JSON.stringify(parseTrait(label, value))}>{label}</option>
})}</optgroup>
})}
</FormControl><InputGroup.Button><Button bsStyle="success" onClick={e=>{this.handleClick(e)}}>Add</Button></InputGroup.Button></InputGroup></FormGroup>
}
}
export class SFXSelect extends TraitSelect {
componentDidMount()
{
this.placeholder="Select SFX to add"
fetch(require('../data/sfx.yaml')).then((response)=>{
response.text().then(function(txt){this.setState({data:Yaml.safeLoad(txt)})}.bind(this))
})
}
}
SFXSelect=connect((state)=>({currentCharacter: state.currentCharacter}))(SFXSelect)
export class SQSelect extends TraitSelect {
componentDidMount()
{
this.placeholder="Select Star quality to add"
fetch(require('../data/sfx-sq.yaml')).then((response)=>{
response.text().then(function(txt){this.setState({data:Yaml.safeLoad(txt)})}.bind(this))
})
}
}
SQSelect=connect((state)=>({currentCharacter: state.currentCharacter}))(SQSelect)
export class ModSelect extends TraitSelect {
componentDidMount()
{
this.placeholder="Select Mod to add"
fetch(require('../data/mods.yaml')).then((response)=>{
response.text().then(function(txt){this.setState({data:Yaml.safeLoad(txt)||{}})}.bind(this))
})
}
groupFilter(i) {
let type=null
if (type=dotProp.get(this.props.widget.formContext,"type",null)){
type=Object.keys(type)[0];
return i[0].search(new RegExp("^"+type,"gi"))>-1;
}
return true;
}
}
ModSelect=connect((state)=>({currentCharacter: state.currentCharacter }))(ModSelect)
export const PROFILES=readContext(require.context('../data/casts', true))
export class ProfileSelector extends React.Component {
constructor(props){
super(props)
this.state={
casting:{},
selected: null,
character:null
}
}
componentDidMount()
{
Object.entries(PROFILES).forEach(([file,path])=>{
fetch(path).then((response)=>{
response.text().then(function(txt){
let data={}
Yaml.safeLoadAll(txt).forEach(item=>{
data[item.name]=item;
})
this.setState({...this.state, casting: {...this.state.casting,[file.replace(/(^\.\/)|(\.yaml$)/gi,'').replace(/_/gi," ")]:data}})
}.bind(this))
})
})
}
/* */
render(){
let cast;
let select = (item)=>{
let [selected, character] = item;
if (this.state.selected && (selected==this.state.selected)){
selected=null;
character=null;
}
this.setState(Object.assign(this.state,{selected,character}))
}
let create = (item) =>{
let [selected, character] = item;
fromTemplate(character)
}
if (this.state.casting){
cast=(<Accordion>{Object.entries(this.state.casting).map((entry, i)=>{
let [key, chr] = entry;
return <Panel header={key} eventKey={i} key={i}><div className="listing">
{Object.entries(chr).map(
(item,j)=>{
let [name,char] = item;
return <MiniCard character={item} key={j} selected={this.state.selected && (this.state.selected===name)} onClick={e=>{select(item)}} />
}
)}
</div></Panel>
})}</Accordion>)
}
const fromTemplate=(item=null)=>{
if (!item)
item=this.state.character
this.props.dispatch({
type:'CHARACTER_NEW',
payload: Object.assign({},item,{name: item.name, profile: item.name})
});
}
return <div className="profileSelector">
<h4>Select a character or Create new</h4>
{cast}
<Button onClick={e=>fromTemplate()} bsStyle="primary" block disabled={!this.state.selected}>New from template</Button>
</div>
}
}
ProfileSelector=connect()(ProfileSelector)
export class MiniCard extends React.Component {
render(){
let [name, item] = this.props.character;
return <dl className={"miniCard "+((this.props.selected)?'selected':'')} onClick={this.props.onClick}>
<dt>{name} {item.ratings? `(${item.ratings})`:''} {item.__card? '':<Label>Incomplete</Label>}</dt>
<dd><Marked md={item.description}/></dd>
</dl>
}
}
|
import React from "react";
import "./Vacancies.css";
import { BaseComponent } from "../components/BaseComponent";
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom'
class VacanciesView extends BaseComponent {
constructor(props) {
super(props);
this.state = {
profile: null,
}
}
render() {
return (
<ul>
<li><NavLink exact to="/vacancies/frontend">Frontend-разработчик (ReactJS)</NavLink></li>
</ul>
);
}
}
export default connect(state => (state))(VacanciesView)
|
let mongoose = require('mongoose');
let IncomeSchema = require('../schemas/IncomeSchema');
let Income = mongoose.model('income', IncomeSchema);
module.exports = Income;
|
// pages/register/register.js
var util = require('../../utils/util.js')
var common = require('../../service/common.js')
var SHA_256 = require('../../utils/SHA256.js')
import {
RegisterData,
resgister
} from '../../service/user.js'
Page({
data: {
register: {},
animationData1: {},
animationData2: {},
hidden1: false,
hidden2: true,
isDisplay1: 'none',
isDisplay2: 'none',
isDisplay3: 'none',
isDisplay4: 'none',
isDisplay5: 'none',
isDisplay6: 'none',
warnMsg: '',
isError: false,
genderIndex: 0,
gender: ['男', '女'],
date: '2017-09-01', //创建时间
buildingId: 0,
buildingName: '',
roomId: 0,
roomNum: '',
password: '',
next_btn: '下一步',
hidden: false
},
// 检验姓名
testName(e) {
const name = e.detail.value
if (util.checkName(name)) {
this.setData({
isDisplay1: ''
})
} else {
this.setData({
warnMsg: '输入姓名格式不正确',
isError: true,
isDisplay1: 'none'
})
}
},
// 检验身份证
testIDcard(e) {
const IDcard = e.detail.value
if (util.checkIDcard(IDcard)) {
this.setData({
isDisplay2: ''
})
} else {
this.setData({
warnMsg: '输入身份证格式不正确',
isError: true,
isDisplay2: 'none'
})
}
},
// 检验年龄
testAge(e) {
const age = e.detail.value
if (util.checkAge(age)) {
this.setData({
isDisplay3: ''
})
} else {
this.setData({
warnMsg: '输入年龄不正确',
isError: true,
isDisplay3: 'none'
})
}
},
// 检验联系电话
testTel(e) {
const phone = e.detail.value
if (!util.checkPhone(phone)) {
this.setData({
warnMsg: '联系电话格式不正确',
isError: true,
isDisplay4: 'none'
})
} else {
this.setData({
isDisplay4: ''
})
}
},
// 监听日期
bindDateChange: function (e) {
this.setData({
date: e.detail.value
})
},
// 监听性别
bindGenderChange: function (e) {
this.setData({
genderIndex: e.detail.value
})
},
// 检测密码
testPwd(e) {
const pwd = e.detail.value
const effort = util.checkPwd(pwd)
if (effort == 0) {
this.setData({
warnMsg: '请输入密码',
isError: true,
isDisplay5: 'none'
})
}
else if (effort == -1) {
this.setData({
warnMsg: '输入密码仅限6位字符',
isDisplay5: 'none',
isError: true
})
}
else {
this.setData({
warnMsg: '',
isError: false,
isDisplay5: '',
password: pwd
})
}
},
// 确认密码
testAgain(e) {
const inputPwd = e.detail.value
if (this.data.password == '') {
this.setData({
warnMsg: '请输入密码',
isDisplay6: 'none',
isError: true
})
}else if(inputPwd != this.data.password) {
this.setData({
warnMsg: '前后输入密码不一致',
isDisplay6: 'none',
isError: true
})
}else {
this.setData({
warnMsg: '',
isDisplay6: '',
isError: false
})
}
},
next() {
const FLAG = (this.data.isDisplay1 == '') &&
(this.data.isDisplay2 == '') &&
(this.data.isDisplay3 == '') &&
(this.data.isDisplay4 == '')
if (!FLAG) {
this.setData({
warnMsg: '请先将信息填写完整',
isError: true
})
}
else {
// 动画效果
if (this.data.hidden1 == false) {
var animation1 = wx.createAnimation({
duration: 400,
timingFunction: 'ease',
})
animation1.opacity(0).step()
this.setData({
animationData1: animation1.export(),
})
var animation2 = wx.createAnimation({
duration: 400,
timingFunction: 'ease',
})
animation2.opacity(1).step()
this.setData({
animationData2: animation2.export(),
})
setTimeout(function () {
this.setData({
hidden1: true,
hidden2: false,
next_btn: '返回上一级'
})
}.bind(this), 400)
}
else {
var animation1 = wx.createAnimation({
duration: 400,
timingFunction: 'ease',
})
animation1.opacity(0).step()
this.setData({
animationData2: animation1.export(),
})
var animation2 = wx.createAnimation({
duration: 400,
timingFunction: 'ease',
})
animation2.opacity(1).step()
this.setData({
animationData1: animation2.export(),
})
setTimeout(function () {
this.setData({
hidden1: false,
hidden2: true,
next_btn: '下一步'
})
}.bind(this), 400)
}
}
},
// 提交表单
submitRegister(e) {
const FLAG = (this.data.isDisplay1 == "" && this.data.isDisplay2 == "") &&
(this.data.isDisplay3 == "" && this.data.isDisplay4 == "") &&
(this.data.isDisplay5 == "" && this.data.isDisplay6 == "")
if (!FLAG) {
wx.showModal({
title: '出错啦',
content: '请确认输入信息是否正确',
showCancel: false
})
} else {
const data = e.detail.value
// 封装数据
const register = new RegisterData(data)
register.gender = this.data.gender[this.data.genderIndex]
register.buildingId = this.data.buildingId
register.roomId = this.data.roomId
register.account = register.telephone
// 密码加密
register.password = SHA_256.sha256_digest(register.password)
this.setData({
register
})
// 提交表单并跳转登录页
resgister(register).then(res => {
const result = res.data
if (result.status == 200) {
wx.showToast({
title: '注册成功',
duration: 2000,
success: function () {
setTimeout(function () {
wx.redirectTo({
url: '../login/login'
})
}, 1000)
}
})
} else {
common.errorStatus(result)
}
})
}
},
onLoad: function (options) {
// 获取query参数
this.setData({
buildingId: options.buildingId,
buildingName: options.buildingName,
roomNum: options.roomNum,
roomId: options.roomId
})
}
})
|
import Vue from 'vue'
import Cookies from 'js-cookie'
import 'normalize.css/normalize.css' // a modern alternative to CSS resets
import Element from 'element-ui'
import './assets/styles/element-variables.scss'
import '@/assets/styles/index.scss' // global css
import '@/assets/styles/ruoyi.scss' // ruoyi css
import App from './App'
import store from './store'
import router from './router'
import permission from './directive/permission'
import './assets/icons' // icon
import './permission' // permission control
import { getDicts } from "@/api/system/dict/data";
import { getConfigKey } from "@/api/system/config";
import { parseTime, resetForm, addDateRange, selectDictLabel, download, handleTree, getObjFromArray } from "@/utils/ruoyi";
import Pagination from "@/components/Pagination";
// 全局方法挂载
Vue.prototype.getDicts = getDicts
Vue.prototype.getConfigKey = getConfigKey
Vue.prototype.parseTime = parseTime
Vue.prototype.resetForm = resetForm
Vue.prototype.addDateRange = addDateRange
Vue.prototype.selectDictLabel = selectDictLabel
Vue.prototype.download = download
Vue.prototype.handleTree = handleTree
Vue.prototype.getObjFromArray = getObjFromArray
Vue.prototype.msgSuccess = function (msg) {
this.$message({ showClose: true, message: msg, type: "success" });
}
Vue.prototype.msgError = function (msg) {
this.$message({ showClose: true, message: msg, type: "error" });
}
Vue.prototype.msgInfo = function (msg) {
this.$message.info(msg);
}
import base from "./utils/base.js"
Vue.use(base);
// 全局组件挂载
Vue.component('Pagination', Pagination)
Vue.use(permission)
/**
* If you don't want to use mock-server
* you want to use MockJs for mock api
* you can execute: mockXHR()
*
* Currently MockJs will be used in the production environment,
* please remove it before going online! ! !
*/
Vue.use(Element, {
size: Cookies.get('size') || 'medium' // set element-ui default size
})
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
import moment from "moment";
Vue.filter("dateFormat", function(dataStr, pattern) {
if (!!!dataStr) {
return '';
}
if (!!!pattern) {
pattern = "YYYY-MM-DD HH:mm:ss";
}
return moment(dataStr).format(pattern);
});
/*
Vue.filter('formatTime',function(time){
if(time){
var date=new Date(time);
var difftime = Math.abs(new Date() - date)
// 获取当前时间的年月
var nowyear = date.getFullYear();
var nowmonth = date.getMonth+1;
var yearAllday = 0;
var monthAllday = 0;
// 判断是否为闰年
if((nowyear%4===0&& nowyear%100!==0) || nowyear%400===0){
yearAllday = 366
}else{
yearAllday = 365
}
// 每个月的天数
if(yearAllday === 366 && nowmonth === 2){
monthAllday = 29
}else if(yearAllday === 365 && nowmonth === 2){
monthAllday = 28
}
if(nowmonth === 4 || nowmonth === 6 || nowmonth === 9 || nowmonth === 11){
monthAllday = 30
}else {
monthAllday = 31
}
if(difftime > yearAllday*24*3600*1000){
var yearNum = Math.floor(difftime/ (yearAllday*24*3600*1000))
return yearNum + "年前"
}else if(difftime > monthAllday * 24 * 3600 * 1000 && difftime< yearAllday*24*3600*1000){
var monthNum = Math.floor(difftime/(monthAllday*24*60*60*1000))
// 拼接
return monthNum + "月前";
}else if(difftime>7*24*60*60*1000 && difftime && difftime < monthAllday*24*60*60*1000){
var weekNum = Math.floor(difftime/(7*24*3600*1000))
return weekNum+"周前";
}else if(difftime < 7 * 24 * 3600 * 1000 && difftime > 24 * 3600 * 1000){
// //注释("一周之内");
// var time = newData - diffTime;
var dayNum = Math.floor(difftime / (24 * 60 * 60 * 1000));
return dayNum + "天前";
} else if (difftime < 24 * 3600 * 1000 && difftime > 3600 * 1000) {
// //注释("一天之内");
// var time = newData - diffTime;
var dayNum = Math.floor(difftime / (60 * 60 * 1000));
return dayNum + "小时前";
} else if (difftime < 3600 * 1000 && difftime > 0) {
// //注释("一小时之内");
// var time = newData - diffTime;
var dayNum = Math.floor(difftime / (60 * 1000));
return dayNum + "分钟前";
}
}
})*/
|
import $ from '$';
import _ from 'underscore';
import Quillify from './Quillify';
// Extend JS built-ins
Object.defineProperty(Object.prototype, 'rename_property', {
value(old_name, new_name){
try{
this[new_name] = this[old_name];
delete this[old_name];
} catch(f){
console.log('prop not found');
}
},
});
_.extend(Date.prototype, {
toString(){
var pad = function(x){return ((x<10) ? '0' : '') + x;};
if(this.getTime()){
var d = pad(this.getDate());
var m = pad(this.getMonth()+1);
var y = this.getFullYear();
var hr = pad(this.getHours());
var min = pad(this.getMinutes());
return [y, m, d].join('/') + ' ' + hr + ':' + min;
}
return null;
},
});
_.extend(String, {
hex_to_rgb(hex){
// http://stackoverflow.com/questions/5623838/
hex = hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b){
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}:null;
},
contrasting_color(hex){
// http://stackoverflow.com/questions/1855884/
var rgb = String.hex_to_rgb(hex),
a = 1 - (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b)/255;
return (a<0.5)?'#000':'#fff';
},
random_string(){
return 'xxxxxxxxxxxxxxx'.replace(/x/g, function(c){
return String.fromCharCode(97+parseInt(26*Math.random()));
});
},
});
_.extend(String.prototype, {
printf(){
//http://stackoverflow.com/questions/610406/
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number){
return typeof args[number] !== 'undefined' ? args[number] : match;
});
},
});
_.extend(Array.prototype, {
splice_object(obj){
if (this.length === 0) return this;
for (var i = this.length-1; i>=0; i-=1){
if(this[i] === obj){this.splice(i, 1);}
}
},
});
_.extend(Math, {
GammaCDF(x,a){
// adapted from http://www.math.ucla.edu/~tom/distributions/gamma.html
var gcf = function(X, A){
// Good for X>A+1
var A0=0,
B0=1,
A1=1,
B1=X,
AOLD=0,
N=0;
while (Math.abs((A1-AOLD)/A1)>0.00001){
AOLD=A1;
N=N+1;
A0=A1+(N-A)*A0;
B0=B1+(N-A)*B0;
A1=X*A0+N*A1;
B1=X*B0+N*B1;
A0=A0/B1;
B0=B0/B1;
A1=A1/B1;
B1=1;
}
var Prob=Math.exp(A*Math.log(X)-X-logGamma(A))*A1;
return 1-Prob;
},
gser = function(X, A){
// Good for X<A+1
var T9=1/A,
G=T9,
I=1;
while (T9>G*0.00001){
T9=T9*X/(A+I);
G=G+T9;
I=I+1;
}
G = G*Math.exp(A*Math.log(X)-X-logGamma(A));
return G;
},
logGamma = function(Z){
var S = 1 + 76.18009173/Z-
86.50532033/(Z+1)+
24.01409822/(Z+2)-
1.231739516/(Z+3)+
0.00120858003/(Z+4)-
0.00000536382/(Z+5),
LG= (Z-0.5)*Math.log(Z+4.5)-(Z+4.5)+Math.log(S*2.50662827465);
return LG;
},
GI;
if (x<=0){
GI=0;
} else if(a>200){
var z=(x-a)/Math.sqrt(a);
var y=Math.normalcdf(z);
var b1=2/Math.sqrt(a);
var phiz=0.39894228*Math.exp(-z*z/2);
var w=y-b1*(z*z-1)*phiz/6; //Edgeworth1
var b2=6/a;
var u=3*b2*(z*z-3)+b1*b1*(z^4-10*z*z+15);
GI=w-phiz*z*u/72; //Edgeworth2
}else if(x<a+1){
GI=gser(x,a);
}else{
GI=gcf(x,a);
}
return GI;
},
normalcdf(X){
// cumulative density function (CDF) for the standard normal distribution
// HASTINGS. MAX ERROR = .000001
var T = 1 / (1 + 0.2316419 * Math.abs(X)),
D = 0.3989423 * Math.exp(-X * X / 2),
p = D * T * (0.3193815 + T * (-0.3565638 + T * (1.781478 + T * (-1.821256 + T * 1.330274))));
return (X > 0)? 1 - p: p;
},
inv_tdist_05(df){
// Calculates the inverse t-distribution using a piecewise linear form for
// the degrees of freedom specified. Assumes a two-tailed distribution with
// an alpha of 0.05. Based on curve-fitting using Excel's T.INV.2T function
// with a maximum absolute error of 0.00924 and percent error of 0.33%.
//
// Roughly equivalent to scipy.stats.t.ppf(0.975, df)
var b;
if (df < 1){
return NaN;
}else if(df == 1){
return 12.7062047361747;
}else if(df < 12){
b = [7.9703237683E-05,-3.5145890027E-03, 0.063259191874,
-0.59637230750, 3.1294134410, -8.8538894383, 13.358101926];
}else if(df < 62){
b = [1.1184055716E-10, -2.7885328039E-08, 2.8618499662E-06,
-1.5585120701E-04, 4.8300645273E-03, -0.084316656676,
2.7109288893];
}else{
b = [5.1474329765E-16, -7.2622263880E-13, 4.2142967681E-10,
-1.2973354626E-07, 2.2753080520E-05, -2.2594979441E-03,
2.0766977669E+00];
if (df > 350){
console.log('Warning, extrapolating beyond range for which regression was designed.');
}
}
return b[0]*Math.pow(df,6) + b[1]*Math.pow(df,5) + b[2]*Math.pow(df,4) +
b[3]*Math.pow(df,3) + b[4]*Math.pow(df,2) + b[5]*Math.pow(df,1) +
b[6];
},
log10(val){
// required for IE
return Math.log(val) / Math.LN10;
},
mean(array){
switch(array.length){
case 0:
return null;
case 1:
return array[0];
default:
var sum=0, err=false;
array.forEach(function(v){if(typeof(v)!=='number'){err = true;} sum += v;});
}
if((err===false) && (isFinite(sum))){
return sum/array.length;
}else{
return null;
}
},
});
_.extend(Number.prototype, {
toHawcString(){
return (this > 0.001)?
this.toLocaleString():
this.toString();
},
});
$.fn.quillify = Quillify;
// Django AJAX with CSRF protection.
var getCookie = function(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = $.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
csrftoken = getCookie('csrftoken'),
sessionid = getCookie('sessionid'),
csrfSafeMethod = function(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
crossDomain: false,
beforeSend(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader('X-CSRFToken', csrftoken);
xhr.setRequestHeader('sessionid', sessionid);
}
},
});
|
(function(shoptet) {
function get() {
var content = shoptet.cookie.get(shoptet.config.cookiesConsentName);
if (!content) {
return false;
}
return JSON.parse(content);
}
function set(agreements) {
var consentValidity = 6 * 30; /* 6 months */
var consentAgreements = Object.create(agreements);
if (consentAgreements.length == 0) {
consentAgreements.push(shoptet.config.cookiesConsentOptNone);
consentValidity = shoptet.config.cookiesConsentRefuseDuration;
}
var cookieId = '';
for (i = 0; i < 8; i++) {
cookieId += Math.random().toString(32).substr(2, 4);
}
var cookieData = {
consent: consentAgreements.join(','),
cookieId: cookieId
};
if (!shoptet.cookie.create(shoptet.config.cookiesConsentName, JSON.stringify(cookieData), {days: consentValidity})) {
return false;
}
$.ajax({
type: 'POST',
headers: {
'X-Shoptet-XHR': 'Shoptet_Coo7ai'
},
url: shoptet.config.cookiesConsentUrl,
data: cookieData,
success: function(data) {
if (data.code == 200) {
console.debug('ajax db saving ok');
}
}
});
if (shoptet.consent.acceptEvents.length > 0) {
shoptet.consent.acceptEvents.forEach(function(fn) {
fn(agreements);
});
}
return true;
}
function onAccept(event) {
if (typeof event === 'function') {
shoptet.consent.acceptEvents.push(event);
}
}
function isSet() {
var cookie = shoptet.consent.get();
return (cookie !== false) ? true : false;
}
function isAccepted(agreementType) {
if (shoptet.config.cookiesConsentIsActive !== 1) {
return true;
}
var cookie = shoptet.consent.get();
if (!cookie.consent) {
return false;
}
var allowed = cookie.consent.split(',');
return allowed.includes(agreementType);
}
function openCookiesSettingModal() {
$('html').addClass('cookies-visible');
showSpinner();
var successCallback = function (response) {
var requestedDocument = shoptet.common.createDocumentFromString(response.getPayload());
var content = $(requestedDocument).find('.js-cookiesSetting');
content.find('.js-cookiesConsentOption').each(function () {
if(shoptet.consent.isAccepted(this.value)) {
$(this).attr('checked','checked');
}
});
content = content.html();
hideSpinner();
shoptet.modal.open({
scrolling: true,
opacity: '.95',
html: shoptet.content.colorboxHeader + content + shoptet.content.colorboxFooter,
className: shoptet.modal.config.classMd,
width: shoptet.modal.config.widthMd,
height: shoptet.modal.config.initialHeight,
onComplete: function() {
$('#cboxContent').addClass('cookiesDialog');
shoptet.modal.shoptetResize();
},
onClosed: function() {
$('html').removeClass('cookies-visible');
$('#cboxContent').removeClass('cookiesDialog');
}
});
shoptet.scripts.signalDomLoad('ShoptetDOMContentLoaded');
};
shoptet.ajax.makeAjaxRequest(
shoptet.config.cookiesConsentSettingsUrl,
shoptet.ajax.requestTypes.get,
'',
{
'success': successCallback
},
{
'X-Shoptet-XHR': 'Shoptet_Coo7ai'
}
);
}
function cookiesConsentSubmit(value) {
var possibleAgreements = [
shoptet.config.cookiesConsentOptAnalytics,
shoptet.config.cookiesConsentOptPersonalisation
];
var agreements = [];
switch(value) {
case 'all':
agreements = possibleAgreements;
break;
case 'reject':
value = 'none'
break;
case 'selection':
$('.js-cookiesConsentOption').each(function () {
if (this.checked == true && possibleAgreements.includes(this.value)) {
agreements.push(this.value);
}
});
break;
default:
if (value != 'none') {
console.debug('unknown consent action');
return;
}
}
if (!shoptet.consent.set(agreements)) {
console.debug('error setting consent cookie');
return;
}
$('.js-siteCookies').remove();
shoptet.modal.close();
}
document.addEventListener('DOMContentLoaded', function () {
(function() {
'use strict';
var CookieConsent = function(root) {
var script_selector = 'data-cookiecategory';
var _cookieconsent = {};
_cookieconsent.run = function() {
if (shoptet.consent.isSet()) {
var consent = shoptet.consent.get();
if (consent) {
var accepted_categories = consent.consent.split(',');
var scripts = document.querySelectorAll('script[' + script_selector + ']');
var _loadScripts = function(scripts, index) {
if(index < scripts.length){
var curr_script = scripts[index];
var curr_script_category = curr_script.getAttribute(script_selector);
if(_inArray(accepted_categories, curr_script_category) > -1){
curr_script.type = 'text/javascript';
curr_script.removeAttribute(script_selector);
var src = curr_script.getAttribute('data-src');
var fresh_script = _createNode('script');
fresh_script.textContent = curr_script.innerHTML;
(function(destination, source){
var attr, attributes = source.attributes;
var len = attributes.length;
for(var i=0; i<len; i++){
attr = attributes[i];
destination.setAttribute(attr.nodeName, attr.nodeValue);
}
})(fresh_script, curr_script);
src ? (fresh_script.src = src) : (src = curr_script.src);
if(src){
if(fresh_script.readyState) {
fresh_script.onreadystatechange = function() {
if (fresh_script.readyState === "loaded" || fresh_script.readyState === "complete" ) {
fresh_script.onreadystatechange = null;
_loadScripts(scripts, ++index);
}
};
} else {
fresh_script.onload = function(){
fresh_script.onload = null;
_loadScripts(scripts, ++index);
};
}
}
curr_script.parentNode.replaceChild(fresh_script, curr_script);
if(src) return;
}
_loadScripts(scripts, ++index);
}
}
_loadScripts(scripts, 0);
}
}
}
var _inArray = function(arr, value) {
var len = arr.length;
for(var i=0; i<len; i++){
if(arr[i] === value)
return i;
}
return -1;
}
var _createNode = function(type){
var el = document.createElement(type);
if(type === 'button'){
el.setAttribute('type', type);
}
return el;
}
return _cookieconsent;
}
var init = 'initCookieConsent';
if(typeof window[init] !== 'function'){
window[init] = CookieConsent
}
})();
var cc = initCookieConsent();
cc.run();
shoptet.consent.onAccept(function(agreements) {
cc.run();
});
});
shoptet.consent = shoptet.consent || {};
shoptet.scripts.libs.consent.forEach(function(fnName) {
var fn = eval(fnName);
shoptet.scripts.registerFunction(fn, 'consent');
});
shoptet.consent.acceptEvents = [];
})(shoptet);
|
import React from 'react';
import './style.css';
import InstagramLogo from './glyph-logo_May2016.png';
import GmailLogo from './gmailLogo.png';
function SideBarSocialNetworks(){
return(
<div id="sidebarContainer">
<a target="_blank" rel="noopener" href="https://www.instagram.com/zxltrn/"><img src={InstagramLogo} alt="Instagram logo" className="instagram"/></a>
<a target="_blank" rel="noopener" href="mailto:zaltron.julian@gmail.com"><img src={GmailLogo} alt="Gmail logo" className="gmail"/></a>
<div className="socialSidebarLine"/>
</div>
);
}
export default SideBarSocialNetworks;
|
const connection = require('./connection');
const coll = 'products';
const getAllProducts = async () => {
const [products] = await connection.execute(`SELECT * FROM Trybeer.${coll};`);
return products;
};
module.exports = {
getAllProducts,
};
|
module.exports = function (ast, indent) {
// deafult to 2
indent = indent || 2;
let indentStr = getIndentStr(indent),
styles = ""
if(ast.type == "stylesheet"){
styles=getRulesStr(ast.stylesheet.rules, indentStr)
}
return styles
}
function getIndentStr ( indent ) {
let indentStr
for(let i=0; i<indent; i++){
indentStr += " "
}
return indentStr
}
function getRulesStr ( rules, indentStr ) {
let styles = ""
rules.forEach((rule)=>{
if ( rule.type == "rule") {
styles += getRuleStr(rule, indentStr) + "\n"
}
})
return styles
}
function getRuleStr ( rule, indentStr ) {
let RuleStr = ""
RuleStr += rule.selectors + " {" + getDeclarationsStr(rule.declarations, indentStr) + "\n" + "}";
return RuleStr
}
function getDeclarationsStr( declarations, indentStr ) {
let declarationsStr = ""
declarations.forEach((declaration)=>{
declarationsStr += "\n" + indentStr + getDeclarationStr(declaration)
})
return declarationsStr
}
function getDeclarationStr ( declaration ) {
let declarationStr = ""
if(declaration.type == "declaration"){
declarationStr += declaration.property+ ": " + declaration.value + ";"
}
return declarationStr
}
|
(g => {
g.globalfreespace = g.globalfreespace || {};
g.fnc = g.fnc || {};
const f = g.fnc.f;
const datas = g.val;
const hsla = g.fnc.hsla;
const checkary = g.fnc.checkary;
g.addEventListener('load', () => {
(async () => {
g.fnc.maindraw({
name: "",
metric: [9],
weight: [1]
})
/*document.getElementById("subtitle").innerHTML = "平均人数";
let d = [0, 0, 0, 0, 0, 0, 0, 0, 0],
dd = datas.data3;
await g.fnc.f(() => {
for (let i = 0; i < d.length; i++) {
d[i] = dd["エリア" + (i + 1)]
}
});
await g.fnc.draw2(d, "人")
await g.fnc.draw1("chart2", [
["日時", datas.data3.timestamps],
["エリア1", datas.data3["エリア1"]],
[],
["エリア3", datas.data3["エリア3"]],
[],
["エリア9", datas.data3["エリア9"]]
]);*/
})();
});
})(this)
|
import React, { useEffect, useState } from 'react'
import {
View,
Image,
FlatList,
TouchableHighlight,
Dimensions,
} from 'react-native';
export default function PictureList(props) {
const [list, setList] = useState([]);
const keyExtractor = item => item.id;
function onClick() {
}
useEffect(() => {
if (props.list) {
setList(props.list)
console.log(props.list)
} else {
console.log('lista passada para o comp PictureList VAZIA')
}
}, [props.list])
return (
<View style={{ flex: 1 }}>
<FlatList
numColumns={3}
data={list || []}
keyExtractor={keyExtractor}
renderItem={({ item }) => <PictureListItem onClick={props.onClick} item={item} />}
/>
</View>
);
}
function PictureListItem(props) {
const { item } = props
const { width } = Dimensions.get('window'); //windows retorna objeto que terá width e heigth, como queremos só a largura, pegamos o width
return (
<TouchableHighlight onPress={() => { props.onClick(item) }}>
<Image
source={{ uri: item.url }}
style={{
width: width / 3 - 8,
height: width / 3 - 8,
margin: 2
}}
/>
</TouchableHighlight>
);
}
|
const titles = {
DASHBOARD: 'Dashboard',
TRADING_PLATFORM: 'Trading platform app',
LOGIN: 'Login',
REGISTER: 'Sign up',
VERIFY_EMAIL: 'Verify Email',
SETTINGS: 'Settings',
DEPOSIT: 'Deposit',
WITHDRAW: 'Withdraw',
RESET_PASSWORD: 'Password reset',
FORGET_PASSWORD: 'Forget password',
STARTUP_INFO: 'Startup info',
PRIVACY_POLICY: 'Privacy policy',
TERMS_AND_CONDITIONS: 'Terms and conditions',
};
export default titles;
|
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n
// validateNumber(1) --> true
// validateNumber('hello') --> false
|
/**
* 财务账户/晓可币充值
*/
import React, { Component, PureComponent } from 'react';
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
Image,
ScrollView,
Platform,
TouchableOpacity
} from 'react-native';
import { connect } from 'rn-dva';
import * as nativeApi from "../../config/nativeApi";
import Header from '../../components/Header';
import CommonStyles from '../../common/Styles';
import ImageView from '../../components/ImageView';
import TextInputView from '../../components/TextInputView';
import Content from "../../components/ContentItem";
import * as requestApi from '../../config/requestApi';
import * as customPay from '../../config/customPay';
import CommonButton from '../../components/CommonButton';
import { getProtocolUrl } from '../../config/utils'
import Line from '../../components/Line';
const payChannels={
xkq:'账户余额',
xkb:'晓可币',
swq:'实物券',
xfq:'消费券',
xfqs :'店铺消费券',
alipay:'支付宝',
wxpay:'微信',
tfAlipay:'天府银行-支付宝',
tfWxpay :'天府银行-微信'
}
const { width, height } = Dimensions.get('window');
export default class FinanceChargeScreen extends PureComponent {
static navigationOptions = {
header: null,
}
constructor(props) {
super(props)
let currency = this.props.navigation.getParam('currency', '');
let title = this.props.navigation.getParam('title', '晓可币充值');
this.state = {
number: '',
payModalVis: false,
payTypeList: [],
selectMoneyIndex:0,
moneyList: [],
payChannelIndex:0,
currency,
title,
getMoneys:false,
agreementUri: ''
}
}
componentDidMount () {
// this.getPayTypeList()
this.getList()
this.handleGetProtocolUrl()
let payTypeList=[
{name:'微信支付',key:'wxpay',icon:require('../../images/mall/wechat_pay.png')},
{name:'支付宝支付',key:'alipay',icon:require('../../images/user/alipay.png')},
]
Platform.OS=='ios'?
payTypeList=[{name:'Apple Pay',key:'applePay',icon:require('../../images/account/apple_payicon.png')}]:null
this.setState({payTypeList})
}
componentWillUnmount() {
this.chagneState('payModalVis',false)
}
// 获取协议
handleGetProtocolUrl = () => {
getProtocolUrl('MAM_XKB_RECHARGE_RULE').then(res => {
this.setState({
agreementUri: res.url
})
}).catch(err => {
console.log(err)
// Toast.show("协议请求失败")
})
}
// 获取支付方式列表,获取后需要过滤出支付宝,和微信,如果是内部支付,需要做密码验证
getPayTypeList = () => {
let temp = []
requestApi.xkbPayChannel().then(res => {
if (res) {
res.map((item,index) => {
if(item.payChannel!='applePay' || (item.payChannel=='applePay' && Platform.OS=='ios')){
temp.push({
// icon:require('../../images/mall/wechat_pay.png'),
title:payChannels[item.payChannel] || 'apple支付',
...item
})
}
})
}
console.log('支付方式列表',res)
this.chagneState('payTypeList',temp)
}).catch(err => {
console.log(err)
})
}
getList=()=>{ //获取充值列表
Loading.show()
requestApi.xkbDenominationQList().then(res => {
this.setState({
moneyList:res.denominations,
getMoneys:true
})
}).catch(err => {
console.log(err)
})
}
// 选择支付
handleSelectPay = (payType) => {
if(this.state.moneyList.length>0){
Loading.show()
const { number,moneyList,selectMoneyIndex, currency } = this.state
let param = {
// amount: moneyList[selectMoneyIndex].amount,
// amount: 1, // 测试
payChannel: payType,
currency,
xkbId:moneyList[selectMoneyIndex].id
}
requestApi.uniPaymentXkbCharge(param).then(res => {
this.setState({payModalVis:false})
switch(payType){
case 'alipay':this.handleAliPay(res);break;// 支付宝支付
case 'wxpay':this.handleWeChatPay(res);break;// 微信支付
case 'applePay':this.handleApplePay(res);break;// ios内购
}
}).catch(err => {
console.log(err)
});
}else{
Toast.show(this.state.getMoneys?'面额充值列表为空':'获取面额充值列表失败')
}
}
// ios内购
handleApplePay=(res)=>{
console.log('apple支付',res)
const {moneyList,selectMoneyIndex}=this.state
nativeApi.applePay({
...res.otherParams,
productId: moneyList[selectMoneyIndex].iosId
}).then((res)=>{
console.log('成功',res)
if(res.status==0){//是真正的成功
this.props.navigation.replace('TransferSuccess', { payFailed: false,type:'充值' });
}else if(res.status==1 || res.status==3){ //内购扣了钱,由于网络问题服务器还未进行验证,一般是成功的
Toast.show('支付成功,请稍后查看验证结果')
this.props.navigation.replace('TransferSuccess', { payFailed: false ,type:'充值'});
}else{
Toast.show(res.msg)
}
}).catch((res)=>{
console.log('失败',res)
// this.props.navigation.replace('TransferSuccess', { payFailed: true,type:'充值' });
})
}
// 微信支付
handleWeChatPay = (res) => {
Loading.show()
const { navigation } = this.props
let wx_param = {
partnerId: res.next.channelPrams.partnerId,
prepayId: res.next.channelPrams.prepayId,
nonceStr: res.next.channelPrams.nonceStr,
timeStamp: res.next.channelPrams.timestamp,
package: res.next.channelPrams.pack,
sign: res.next.channelPrams.sign,
}
customPay.wechatPay({
param: wx_param,
successCallBack: () => {
navigation.replace('TransferSuccess', { payFailed: false ,type:'充值'});
},
faildCallBack: () => {
navigation.replace('TransferSuccess', { payFailed: true,type:'充值' });
}
})
}
// 支付宝支付
handleAliPay = (res) => {
const { navigation } = this.props
customPay.alipay({
param: res.next.channelPrams.aliPayStr,
successCallBack: () => {
navigation.replace('TransferSuccess', { payFailed: false,type:'充值' });
},
faildCallBack: () => {
navigation.replace('TransferSuccess', { payFailed: true ,type:'充值'});
}
})
}
chagneState = (key = '', value='') => {
this.setState({
[key]: value
})
}
render() {
const { navigation } = this.props;
const { payModalVis, number,selectMoneyIndex,moneyList,payTypeList,payChannelIndex, title, currency } = this.state
let unit = currency === "xkr" ? "元" : "晓可币";
console.log(payTypeList)
return (
<View style={styles.container}>
<Header
title={title}
navigation={navigation}
goBack={true}
/>
<ScrollView>
<Content>
<Line title='支付方式' point={null}/>
<View style={styles.lineView}>
{
moneyList.map((item,index)=>{
return(
<TouchableOpacity
onPress={()=>this.setState({selectMoneyIndex:index})}
key={index}
style={[styles.item,{
backgroundColor:selectMoneyIndex==index?CommonStyles.globalHeaderColor:'#fff',
borderWidth:selectMoneyIndex==index?0:1,
marginTop:index>2?10:0
}]}
>
<Text style={[styles.commonText,{color:selectMoneyIndex==index?'#fff':'#222'}]}>{item.denomination/100}{unit}</Text>
<Text style={[{color:selectMoneyIndex==index?'#fff':'#999999',marginTop:3,fontSize:12}]}>¥{item.amount/100}</Text>
</TouchableOpacity>
)
})
}
</View>
</Content>
<Content>
{
payTypeList.map((item,index)=>{
return(
<TouchableOpacity
onPress={() => {this.setState({payChannelIndex:index})}}
key={index}
style={[styles.actionLine, { justifyContent: 'space-between', width: width - 20, paddingHorizontal: 15 }]}
>
<View style={styles.line}>
<ImageView
source={Platform.OS=='ios'?require('../../images/logo.jpg'):item.icon}
sourceWidth={20}
sourceHeight={20}
style={{ marginRight: 8 }}
/>
{
Platform.OS=='ios'?
<View>
<Text>晓可联盟</Text>
<Text style={{fontSize:10,color:'#999',marginTop:3}}>app内购项目</Text>
</View>:
<Text>{item.name}</Text>
}
</View>
<ImageView
source={payChannelIndex===index? require("../../images/mall/checked.png"):require("../../images/mall/unchecked.png")}
sourceWidth={14}
sourceHeight={14}
/>
</TouchableOpacity>
)
})
}
</Content>
<TouchableOpacity onPress={()=>navigation.navigate('AgreementDeal',{title:'充值服务协议',uri:this.state.agreementUri})}>
<Text style={styles.read}>阅读并同意<Text style={{color:CommonStyles.globalHeaderColor}}>《充值服务协议》</Text></Text>
</TouchableOpacity>
<CommonButton
title='立即充值'
onPress={() => {
payTypeList[payChannelIndex]?this.handleSelectPay(payTypeList[payChannelIndex].key):Toast.show('获取支付方式失败')
}}
/>
</ScrollView>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
backgroundColor: CommonStyles.globalBgColor,
alignItems: 'center',
position: 'relative'
},
content: {
alignItems: 'center',
paddingBottom: 10
},
line: {
flexDirection: 'row',
alignItems: 'center'
},
title: {
fontSize: 17,
color: '#222222',
marginTop: 37,
marginBottom: 13,
textAlign: 'center'
},
inputView: {
width: width - 50,
height: 53,
borderRadius: 10,
overflow: 'hidden',
paddingHorizontal: 15,
backgroundColor: 'white'
},
bottomContent: {
backgroundColor: '#fff',
width: width
},
actionLine: {
height: 50,
textAlign: 'center',
justifyContent: 'center',
borderTopWidth: 1,
borderColor: '#F1F1F1',
flexDirection: 'row',
alignItems: 'center'
},
actionTitle: {
fontSize: 17,
color: '#000000',
textAlign: 'center'
},
container_modal: {
flex: 1,
justifyContent: 'center',
backgroundColor:'rgba(0, 0, 0, 0.5)'
},
innerContainer: {
backgroundColor: '#fff',
position: 'absolute',
bottom: 0,
left: 0,
width,
},
rechargeBtn: {
backgroundColor: CommonStyles.globalHeaderColor,
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center',
paddingVertical: 10,
marginTop: 45,
},
commonText:{
fontSize:14,
},
lineView:{
flexDirection:'row',
alignItems:'center',
paddingVertical:15,
justifyContent:'space-between',
flexWrap:'wrap',
width:width-50,
marginLeft:15,
},
item:{
width:(width-50-30)/3,
height:50,
alignItems:'center',
justifyContent:'center',
borderRadius:6,
borderColor:'#DCDCDC'
},
read:{
fontSize:14,
color:'#999',
marginTop:10,
width:width-20
}
});
|
import React, {useState, useEffect, createRef} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Button,
Image,
} from 'react-native';
import {ImgNotProduct} from '../../assets/images/no-product-found.png';
import {FlatGrid} from 'react-native-super-grid';
import axios from 'axios';
import {API_URL} from '@env';
import {Rating} from 'react-native-ratings';
const actionSheetRef = createRef();
const MainCatalogScreen = ({navigation, route}) => {
let {card, pickColor, pickCategory, pickSize} = route.params;
const [isProducts, setIsProducts] = useState([]);
const [isFilter, setIsFilter] = useState([]);
const [isNotFound, setIsNotFound] = useState(false);
console.log('ini products', isProducts);
console.log('ini isFilter', isFilter);
const handleFilter = () => {
axios
.get(
`${API_URL}/products/filter?category=${pickCategory}&size=${pickSize}&color=${pickColor}`,
)
.then((res) => {
const filter = res.data.data;
if (filter.length == 0) {
setIsNotFound(true);
} else {
setIsFilter(filter);
}
})
.catch((err) => {
console.log(err);
});
};
const getNew = async () => {
await axios
.get(`${API_URL}/products?keyword=created_at DESC&limit=100`)
.then((res) => {
const products = res.data.data.products;
setIsProducts(products);
})
.catch((err) => {
console.log(err);
});
};
// const getPopular = async () => {
// await axios
// .get(`${API_URL}/products?keyword=rating DESC&limit=100`)
// .then((res) => {
// const cardTwo = res.data.data.products;
// // console.log('DataPopular', cardTwo);
// setCardTwo(cardTwo);
// })
// .catch((err) => {
// setIsNotFound(true);
// console.log(err);
// });
// };
// const getProduct = () => {
// setIsProducts(card);
// }
useEffect(() => {
handleFilter(pickCategory, pickColor, pickSize);
}, [pickCategory, pickColor, pickSize]);
useEffect(() => {
getNew();
}, []);
// useEffect(() => {
// getPopular();
// }, []);
return (
<>
{isNotFound === true &&
pickColor !== undefined &&
pickCategory !== undefined &&
pickSize !== undefined ? (
<View
style={{
width: '100%',
height: '100%',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}>
<Image
source={require('../../assets/images/no-product-found.png')}
style={{width: 150, height: 150}}
/>
<Text style={{fontSize: 20}}>Oops, your product not found!</Text>
</View>
) : isNotFound === false &&
pickColor !== undefined &&
pickCategory !== undefined &&
pickSize !== undefined ? (
<FlatGrid
itemDimension={130}
data={isFilter}
style={styles.gridView}
spacing={10}
renderItem={({item}) => (
<TouchableOpacity
onPress={() =>
navigation.navigate('DetailProduct', {
itemId: item.id,
categories: item.category_name,
})
}>
<View
style={[styles.itemContainer, {backgroundColor: '#ffffff'}]}>
<Image
source={{
uri: `${API_URL}${JSON.parse(item.product_photo).shift()}`,
}}
style={{borderRadius: 10, width: '100%', height: 100}}
resizeMode="contain"
/>
<View style={styles.rating}>
<Rating
ratingCount={5}
startingValue={item.rating}
readonly={true}
imageSize={15}
style={{paddingRight: 5}}
/>
<Text children={item.rating} />
</View>
<Text style={styles.itemName}>{item.product_name}</Text>
<Text style={styles.itemCode}>{item.product_price}</Text>
</View>
</TouchableOpacity>
)}
/>
) : pickCategory === undefined &&
pickSize === undefined &&
pickColor === undefined &&
isNotFound === false ? null : (
<FlatGrid
itemDimension={130}
data={isProducts}
style={styles.gridView}
spacing={10}
renderItem={({item}) => (
<TouchableOpacity
onPress={() =>
navigation.navigate('DetailProduct', {
itemId: item.id,
categories: item.category_name,
})
}>
<View
style={[styles.itemContainer, {backgroundColor: '#ffffff'}]}>
<Image
source={{
uri: `${API_URL}${JSON.parse(item.product_photo).shift()}`,
}}
style={{borderRadius: 10, width: '100%', height: 100}}
resizeMode="contain"
/>
<View style={styles.rating}>
<Rating
ratingCount={5}
startingValue={item.rating}
readonly={true}
imageSize={15}
style={{paddingRight: 5}}
/>
<Text children={item.rating} />
</View>
<Text style={styles.itemName}>{item.product_name}</Text>
<Text style={styles.itemCode}>{item.product_price}</Text>
</View>
</TouchableOpacity>
)}
/>
)}
</>
);
};
const styles = StyleSheet.create({
gridView: {
marginTop: 10,
flex: 1,
},
itemContainer: {
justifyContent: 'flex-end',
borderRadius: 5,
padding: 10,
height: 190,
},
itemName: {
fontSize: 16,
color: '#000000',
fontWeight: '600',
},
itemCode: {
fontWeight: '600',
fontSize: 12,
color: '#000000',
},
rating: {
flexDirection: 'row',
marginTop: 5,
alignItems: 'center',
},
});
export default MainCatalogScreen;
|
import React, { useState } from "react";
import { makeStyles, Grid, Button, BottomNavigation, BottomNavigationAction } from "@material-ui/core";
import { connect } from "react-redux";
import { EgretTextField, EgretDropDown } from '../../egret'
import { COLORS } from '../../app/config'
const SELECT_DATA = [
{ id: 1, name: 'Commercial Real Estate' },
{ id: 2, name: 'Cannabis Application Support' },
{ id: 3, name: 'Consumer Product & services' },
{ id: 4, name: 'Clean Tech, Fitness' },
{ id: 5, name: 'Financial Services' },
{ id: 6, name: 'Medical Technology, Biotech, Healthcare' },
{ id: 7, name: 'Education & E-Learning' },
];
const useStyles = makeStyles({
root: {
width: '100%',
height: 60,
background: 'transparent',
textAlign: 'center',
'& .MuiBottomNavigationAction-root': {
maxWidth: 'unset',
color: '#353535',
fontWeight: '600',
margin: '0 50px',
padding: '20px 0 25px',
'&:hover': {
color: COLORS.PRIMARY
},
'&.Mui-selected': {
borderBottom: `3px solid ${COLORS.PRIMARY}`
},
'& .MuiBottomNavigationAction-label': {
fontSize: '1em',
}
}
},
});
function ContactHeader(props) {
const classes = useStyles();
const [value, setValue] = useState('los-angeles');
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<div className="contact-header">
<div className="plan-investor">
<div>Drive change in how your </div>
<div>company operates Contact US</div>
</div>
<Grid container spacing={2} style={{ zIndex: 20 }}>
<Grid item lg={6} md={7} xs={12} className="plan-container">
<EgretDropDown
data={SELECT_DATA}
placeholder={'Reason for inquiry'}
/>
</Grid>
<Grid item lg={6} md={5} xs={12} className="info-container">
<EgretTextField
placeholder="Full Name"
className="full-name"
bordercolor={'transparent'}
/>
<EgretTextField
placeholder="Phone Number"
className="phone-number"
bordercolor={'transparent'}
/>
<EgretTextField
placeholder="Your Email Address"
className="email"
bordercolor={'transparent'}
/>
<Button variant="contained" color="primary" className="btnSubmit">
Submit
</Button>
</Grid>
</Grid>
<div className="navigation">
<BottomNavigation value={value} showLabels onChange={handleChange} className={classes.root}>
<BottomNavigationAction label="Los Angeles" value="los-angeles" />
<BottomNavigationAction label="San Francisco" value="san-francisco" />
<BottomNavigationAction label="New York" value="new-york" />
<BottomNavigationAction label="Seattle" value="seattle" />
<BottomNavigationAction label="Chicago" value="chicago" />
<BottomNavigationAction label="Boston" value="boston" />
</BottomNavigation>
</div>
<div className="contact-header-bottom"></div>
</div>
);
}
const mapStateToProps = state => ({
});
export default connect(
mapStateToProps,
{ }
)(ContactHeader);
|
/* eslint-disable import/first, global-require */
if (process.env.NODE_ENV === 'development') {
require('preact/debug');
}
import { h, Component, render } from 'preact';
import Router, { route } from 'preact-router';
import { CreatePage, EditPage, ListPage } from 'pages';
import { createHashHistory } from 'history';
import { uuid, logger } from 'options/utils';
import 'styles/app.scss';
class App extends Component {
constructor() {
super();
this.state = {
// Information about all shortcuts
commandShortcuts: [],
// Are all required data received
initialized: false,
// Synchronized storage
storage: {
commands: [],
},
};
this.onCreateCommand = this.onCreateCommand.bind(this);
this.onRemoveCommand = this.onRemoveCommand.bind(this);
this.onEditCommand = this.onEditCommand.bind(this);
this.onUserComeBack = this.onUserComeBack.bind(this);
}
async componentDidMount() {
const commandShortcuts = await this.getCommandShortcuts();
const storage = await this.initStorage();
this.setState({
initialized: true,
commandShortcuts,
storage,
});
const extName = chrome.i18n.getMessage('extName');
const optionsPageTitle = chrome.i18n.getMessage('optionsPageTitle');
document.title = `${extName} - ${optionsPageTitle}`;
window.addEventListener('focus', this.onUserComeBack);
}
async onCreateCommand(value) {
await this.setState(({ storage }) => ({
storage: {
...storage,
commands: storage.commands.concat({
id: uuid(),
...value,
}),
},
}));
await this.saveToStorageAndReturnToList();
}
async onEditCommand(id, value) {
await this.setState(({ storage }) => {
const editCommand = storage.commands.findIndex((command) => command.id === id);
const commands = [...storage.commands];
commands[editCommand] = {
...value,
id,
};
return {
storage: {
...storage,
commands,
},
};
});
await this.saveToStorageAndReturnToList();
}
async onRemoveCommand(id) {
await this.setState(({ storage }) => ({
storage: {
...storage,
commands: storage.commands.filter((command) => command.id !== id),
},
}));
try {
await this.saveStorage();
} catch (error) {
logger.error(error);
}
}
async onUserComeBack() {
// Update the value of the shortcuts
// as the user could change them on another tab
await this.updateCommandShortcuts();
}
getCommandShortcuts() {
return new Promise((resolve) => {
chrome.commands.getAll((commandShortcuts) => {
resolve(this.commandShortcutsPreparation(commandShortcuts));
});
});
}
setState(newState) {
return new Promise((resolve) => {
super.setState(newState, resolve);
});
}
componentWilUnmount() {
window.removeEventListener('focus', this.onUserComeBack);
}
commandShortcutsPreparation(commandShortcuts) {
return commandShortcuts
.map(({ name, description, shortcut }) => ({
id: name,
name,
description,
shortcut,
}))
.sort(this.sortCommandShortcutsById);
}
sortCommandShortcutsById(a, b) {
return a.id - b.id;
}
async initStorage() {
let data;
const initValue = {
commands: [],
};
const Storage = await import(/* webpackChunkName: "storage" */ 'utils/storage');
this.storage = new Storage.default();
try {
data = await this.storage.fetch();
} catch (error) {
logger.error(error);
}
return {
...initValue,
...data,
};
}
async saveToStorageAndReturnToList() {
try {
await this.saveStorage();
route('/');
} catch (error) {
logger.error(error);
}
}
async saveStorage() {
const { storage } = this.state;
await this.storage.set(storage);
}
async updateCommandShortcuts() {
const commandShortcuts = await this.getCommandShortcuts();
this.setState({
commandShortcuts,
});
}
render() {
const {
initialized,
storage,
commandShortcuts,
} = this.state;
if (initialized !== true) {
return (
<div>
{chrome.i18n.getMessage('initialization')}
</div>
);
}
return (
<Router history={createHashHistory()}>
<CreatePage
path="/create"
commands={storage.commands}
commandShortcuts={commandShortcuts}
onCreateCommand={this.onCreateCommand}
/>
<EditPage
path="/edit/:id"
commands={storage.commands}
commandShortcuts={commandShortcuts}
onEditCommand={this.onEditCommand}
/>
<ListPage
commands={storage.commands}
commandShortcuts={commandShortcuts}
onRemoveCommand={this.onRemoveCommand}
default
/>
</Router>
);
}
}
render(<App />, document.body);
|
import { combineReducers } from 'redux';
import load from './components/Loader/reducer';
const reducers = combineReducers({
load
});
export default reducers;
|
const fs = require('fs')
describe('Screenshot differences', () => {
test('Diff directory does not exist', async () => {
expect(fs.existsSync('screenshots/diff/')).toBe(false)
})
})
|
import React, { Component } from 'react';
class SocialLinks extends Component {
render() {
return(
<div className="d-flex justify-content-around">
<a href="https://www.instagram.com/a.d.jacks/" target="_blank" rel="noopener noreferrer"><i class="fab fa-instagram"></i></a>
<a href="https://www.linkedin.com/in/alexander-jacks/" target="_blank" rel="noopener noreferrer"><i class="fab fa-linkedin-in"></i></a>
<a href="https://github.com/alexanderjacks" target="_blank" rel="noopener noreferrer"><i class="fab fa-github"></i></a>
</div>
);
}
}
export default SocialLinks;
|
nextIcon.addEventListener("click", function (e){
let orderedItems=document.getElementById("order-row").querySelectorAll(".order-list");
for(let i=0;i<orderedItems.length;i++){
if(orderedItems[i].textContent.indexOf("kava") !== -1){
let coffeeIcons=document.querySelectorAll("#coffee-counter li");
let j=0;
while(coffeeIcons[j].classList.contains("selected")){
j++;
}
coffeeIcons[j].classList.add("selected");
document.getElementById("coffee-current-counter").innerHTML = j+1+"/"+ '9';
}
}
});
|
({
handleUpdateExpense: function(component, event, helper) {
var updatedExp = event.getParam("expense");
helper.updateExpense(component, updatedExp);
},
handleCreateExpense: function(component, event, helper) {
var newExpense = event.getParam("expense");
helper.createExpense(component, newExpense);
},
/**
* here’s the outline of what this code does:
* 1. Create a remote method call.
* 2. Set up what should happen when the remote method call returns.
* 3. Queue up the remote method call.
* c.xxxx in Controller Code context represents Server-side controller
* step is 1 --> 3 --> 2
* Load expenses from Salesforce
*/
doInit: function(component, event, helper) {
// Create the action
// component.get("c.whatever") returns a reference to an action available in the controller.
// In this case, it returns a remote method call to our Apex controller.
// This is how you create a call to an @AuraEnabled method.
var action = component.get("c.getExpenses");
// Add callback behavior for when response is received
// 'this' is the scope in which the callback will execute;
// here 'this' is the action handler function itself.
// Think of it as an address, or...maybe a number.
// The function is what gets called when the server response is returned. So:
// action.setCallback(scope, callbackFunction);
// Callback functions, function(response), take a single parameter, response,
// which is an opaque object that provides the returned data,
// if any, and various details about the status of the request.
// In this specific callback function, we do the following.
// 1. Get the state of the response.
// 2. If the state is SUCCESS, that is, our request completed as planned, then:
// 3. Set the component’s expenses attribute to the value of the response data.
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.expenses", response.getReturnValue());
}
else {
console.log("Failed with state: " + state);
}
});
// Send action off to be executed
// The next line that actually runs is this one.
// We saw $A briefly before.
// It’s a framework global variable that provides a number of important functions and services.
// $A.enqueueAction(action) adds the server call
// that we’ve just configured to the Lightning Components framework request queue.
// It, along with other pending server requests,
// will be sent to the server in the next request cycle.
// It queues up the server request.
// As far as your controller action is concerned, that’s the end of it.
// You’re not guaranteed when, or if, you’ll hear back.
$A.enqueueAction(action);
},
})
|
'use strict';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as _ from 'underscore';
import * as EventManager from 'modules/events';
import * as config from 'config';
import * as settings from 'modules/settings';
import * as request from 'modules/request';
import Item from 'components/settings/item/code';
import './style';
class Settings extends React.Component {
handlerListSelect = (options) => {
var opts = options || {};
var wrapper = ReactDOM.findDOMNode(this),
cl = 'some_sgi_opened';
if (_.contains(opts.sgi.classList, 'sgi_opened')) {
wrapper.classList.add(cl);
} else {
wrapper.classList.remove(cl);
}
};
getCategoriesHandler = (callback) => {
var cb = callback || _.noop,
sData = settings.get();
if (!sData.category2.values.length) {
this.categoriesRequest = request.get({
url: config.UPWORK_jobs_categories
}, (err, response) => {
console.log(this.categoriesRequest);
if (err) {
cb(err);
//Raven.captureException(err);
} else if (!response) {
cb(null, null);
} else if (this.categoriesRequest) {
this.categoriesRequest = null;
var categories = _.pluck(response.categories, 'title');
categories.unshift('All');
_.each(categories, item => {
let category = {};
category[item] = item;
sData.category2.values.push(category);
this.tmpSettings.category2.values.push(category);
});
settings.set(sData);
cb(null, sData.category2.values);
}
});
}
};
tmpSettings = {};
handlerChange = (values) => {
_.each(values, item => {
this.tmpSettings[item.name].value = item.value;
});
};
componentDidMount = () => {
this.tmpSettings = settings.get();
EventManager.on('stngListSelected', this.handlerListSelect);
};
componentWillUnmount = () => {
this.categoriesRequest = null;
var cur_settings = settings.get(),
needToUpdateCache = false,
changed = false;
_.each(cur_settings, (item, key) => {
if (item.value !== this.tmpSettings[key].value) {
if (item.search) {
needToUpdateCache = true;
}
changed = true;
}
});
if (changed) {
settings.set(this.tmpSettings);
}
if (changed || needToUpdateCache) {
EventManager.trigger('settingsSaved', {
changed,
needToUpdateCache
});
}
this.tmpSettings = {};
EventManager.off('stngListSelected', this.handlerListSelect);
};
render() {
var sData = settings.get(),
budgetValueText = sData.budgetFrom.value + '$ - ' + sData.budgetTo.value + '$',
dndValueText = sData.dndFrom.value + ' - ' + sData.dndTo.value;
return (
<div id="settings">
<Item
handler={this.handlerChange}
title="Category"
type="list"
name="category2"
value={sData.category2.value}
values={sData.category2.values}
handlerOpen={this.getCategoriesHandler}
/>
<Item
handler={this.handlerChange}
title="Budget"
type="slider"
name="budget"
value={sData.budgetFrom.value}
values={sData.budgetFrom.values}
valueText={budgetValueText}
from={sData.budgetFrom.value}
to={sData.budgetTo.value}
/>
<Item
handler={this.handlerChange}
title="Job type"
type="list"
name="jobType"
value={sData.jobType.value}
values={sData.jobType.values}
/>
<Item
handler={this.handlerChange}
title="Duration"
type="list"
name="duration"
value={sData.duration.value}
values={sData.duration.values}
/>
<Item
handler={this.handlerChange}
title="Workload"
type="list"
name="workload"
value={sData.workload.value}
values={sData.workload.values}
/>
<Item
handler={this.handlerChange}
title="Allow notifications"
type="switcher"
relations="notifications"
name="notifyAllow"
checked={sData.notifyAllow.value}
/>
<Item
handler={this.handlerChange}
title="Notify every"
type="list"
relations="notifications"
name="notifyInterval"
value={sData.notifyInterval.value}
values={sData.notifyInterval.values}
disable={!sData.notifyAllow.value}
/>
<Item
handler={this.handlerChange}
title="Do not disturb"
type="time"
relations="notifications"
name="dnd"
value={sData.dndFrom.value}
values={sData.dndFrom.values}
from={sData.dndFrom.value}
to={sData.dndTo.value}
valueText={dndValueText}
disable={!sData.notifyAllow.value}
/>
<Item
handler={this.handlerChange}
title="Preview in extension"
type="switcher"
name="preview"
descr="See the job description directly in extension"
checked={sData.preview.value}
/>
</div>
);
}
}
export default Settings;
|
import React, { useState, useEffect } from 'react';
import MicrosoftLogin from "react-microsoft-login";
import Axios from 'axios';
import * as qs from 'querystring';
import { useHistory } from 'react-router-dom';
import { UserDetailsContext } from '../App';
const UserAuth = (props) => {
const searchQuery = window.location.hash;
const { UserNameContext, EdxTokenContext, MsAuthTokenContext } = React.useContext(UserDetailsContext);
let history = useHistory();
let path = props && props.location && props.location.state &&
(props.location.state.path !== undefined || props.location.state.path !== null) ?
props.location.state.path : '/baseform';
// DEMO purpose code
if (searchQuery.includes('assessment')) {
path = '/assessment';
}
else if (searchQuery.includes('course'))
path = '/CourseList';
else {
path = '/baseform';
}
const edxTokenGenerator = (account, accessToken) => {
// let userName = ""
// let password = ""
// if (account.userName === "Laxmi@vteamlabs.com") {
// userName ="Laxmi"
// UserNameContext.setUserName(userName);
// password = "Vteam1234"
// }
// else if (account.userName === "Cristina@vteamlabs.com" ) {
// userName = "CristinaStudent"
// UserNameContext.setUserName(userName);
// password = "Team@123"
// }
// else if(account.userName === "Jonas@vteamlabs.com"){
// userName = "Jonas"
// UserNameContext.setUserName(userName);
// password = "Team@123"
// } else {
// }
return Axios.post('https://edxvteam.com/oauth2/exchange_access_token/azuread-oauth2/',
qs.stringify({
// grant_type: "password",
// client_id: "eSIp6KMW0CIMEDrjwDSJ3IhL5zcujcNF0aFoE0YY",
// client_secret: "vTUI81eTQbD8Vt7ZM7fVNEgH1VL5r4sEVqy76cwXrdEaI49D8IMpRy4HgJhbJhQA2AbPRhwwvxHvsVWRfTJZnoIgacBp1870ZvdqSm5yqDD8eXb8JTuUfDoy3fh1AlK4",
// token_type: "Bearer",
// username: userName,
// password: password
client_id: "fJeK3hLJ93ldqFwyBZ2MhqXTTBO5dgNRwxLxN5T9",
access_token: accessToken
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then((response) => {
EdxTokenContext.setEdxToken(response.data.access_token)
userDetails(response.data.access_token)
// Axios.get('https://edxvteam.com/api/user/v1/accounts?email=' + account.userName,
// {
// headers: {
// Authorization: `Bearer ${response.data.access_token}`
// }
// })
// .then((response) => {
// let edxUser = response.data[0];
// UserNameContext.setUserName(edxUser.username);
// // if (account.userName === "Cristina@vteamlabs.com") {
// // UserNameContext.setUserName("Cristina");
// // }
// // else if (account.userName === "Jones@vteamlabs.com") {
// // UserNameContext.setUserName("Jones");
// // }
// // else {
// // UserNameContext.setUserName(edxUser.username);
// // }
// console.log(UserNameContext.userName)
// history.push(path)
// }, (error) => {
// console.log(error)
// })
}, (error) => {
console.log(error)
})
}
const authHandler = (err, data) => {
try {
const { accessToken, account } = data.authResponseWithAccessToken;
console.log(account.userName)
if (accessToken !== null) {
MsAuthTokenContext.setMsAuthToken(accessToken);
edxTokenGenerator(account, accessToken);
}
}
catch (error) {
console.log(error)
}
}
const userDetails = (access_token) => {
Axios.get('https://edxvteam.com/api/user/v1/me',
{
headers: {
Authorization: `Bearer ${access_token}`
}
}).then((response) => {
let edxUser = response.data;
UserNameContext.setUserName(edxUser.username);
history.push(path)
}, (error) => {
console.log(error)
})
}
return (<MicrosoftLogin
clientId={'c4e63d26-dcf1-4d0a-bac1-ae0bc5afca83'}
authCallback={authHandler} redirectUri={'https://ankagr289.github.io/#/login'}
graphScopes={['Calendars.ReadWrite', 'Group.ReadWrite.All', 'user.read']} />)
};
export default UserAuth
|
// 消息推送
var sio = require("socket.io");
var eventBuffer = [];
var socketBuffer = {};
/**
* 模块内容定义
* @public
*/
module.exports.define = {
id: "socket",
/** 模块名称 */
name: "Socket 通讯组件",
/** 模块版本 */
version: "1.0",
/** 模块依赖 */
dependencies: ["config", "webserver"]
};
/**
* 初始化socket服务端对象。
* @param {object} config 应用程序配置对象实例
* @param {Object} webserver 服务对象
*/
exports.run = function(config, webserver) {
if (!config || !webserver) {
throw new Error("config 或 webserver 不存在");
}
var numUsers = 0;
var io = sio(webserver);
io.on("connection", function(socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on("new message", function(data) {
// we tell the client to execute 'new message'
socket.broadcast.emit("new message", {
username: socket.username,
message: data
});
console.log("SOCKET.IO NEW MESSAGE:" + data);
});
// when the client emits 'add user', this listens and executes
socket.on("add user", function(username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit("login", {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit("user joined", {
username: socket.username,
numUsers: numUsers
});
console.log("SOCKET.IO NEW USER:" + username);
});
// when the client emits 'typing', we broadcast it to others
socket.on("typing", function() {
socket.broadcast.emit("typing", {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on("stop typing", function() {
socket.broadcast.emit("stop typing", {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on("disconnect", function() {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit("user left", {
username: socket.username,
numUsers: numUsers
});
console.log(
"SOCKET.IO USER LEFT:%s Count:%s",
socket.username,
numUsers
);
}
});
});
};
/** 连接SOCKET
* @param {string} user 连接SOCKET的人员编号
*/
exports.connect = user => {
io.on("connection", socket => {
if (socketBuffer[user]) {
}
socketBuffer[user] = socket;
});
};
/** 添加事件监听
* @param {string} event 监听的事件名称
* @param {function} func 监听执行时的回调函数
*/
exports.on = (event, func) => {
eventBuffer.push({ event: event, func: func });
};
/** 给指定客户端发送消息
* @param {string} user 消息接收人员编号
* @param {string} data 消息内容
*/
exports.send = (sender, message) => {
socketBuffer[sender].send(message);
};
/** 加入聊天室
* @param {string} user 加入聊天室的人员编号
*/
exports.join = user => {
if (socketBuffer[user]) {
return { success: false, message: "该用户已经加入聊天室!" };
} else {
}
};
exports.getlist = () => {};
|
import React, { useState } from 'react';
import PropTypes from 'prop-types';
export const NamespaceControllerContext = React.createContext({
currentPage: 0,
changePage: index => {},
isChooseColorOpen: false,
chosenNamespace: {},
setChosenNamespace: namespace => {}
});
const NamespaceControllerContextProvider = ({ children }) => {
const [currentPage, changePage] = useState(0);
const [chosenNamespace, setChosenNamespace] = useState({});
const [isChooseColorOpen, setChooseColorOpen] = useState(false);
const toggleColorChoose = () => {
setChooseColorOpen(!isChooseColorOpen);
};
return (
<NamespaceControllerContext.Provider
value={{ currentPage, changePage, isChooseColorOpen, toggleColorChoose, chosenNamespace, setChosenNamespace }}
>
{children}
</NamespaceControllerContext.Provider>
);
};
NamespaceControllerContextProvider.propTypes = {
children: PropTypes.node.isRequired
};
export default NamespaceControllerContextProvider;
|
let config = {};
config.APP_ID = "wx7daec4246ae67438";
config.CHANNEL = "CN_WEB_WECHAT";
config.DEBUG = true;
config.DEVICE_ID = "0000";
config.DOWNLOAD_NAME = "wxddz-test.qfun.com";
config.HORTOR_GAMEID = "external_qfddz_test";
config.HORTOR_SECRET = "e9a1c2baf83361b3d21dcd345bf7e1d1";
config.HORTOR_WALL_GAMEID = "qfddz";
config.HORTOR_WALL_KEY = "XtUNYLJnM9guiCpG";
config.HOST_HTTP = "http://";
config.HOST_NAME = "wxddz-test.qfun.com";
config.HOST_PAY_CALLBACK = "http://pay-test.qfun.com/wx/game/pay/cb";
config.HOST_PAY_NAME = "http://wxddz-test.qfun.com/webpay/wx/game/order/create";
config.HOST_RES_FORMAT = "%s%s/media/wxgame/%s/%s/static/";
config.HOST_WSS = "ws://";
config.LANG = "cn";
config.NICK = "test";
config.OS = "web";
config.RES_VERSION = 632004;
config.SOCKET_IP = "wxddz-test.qfun.com";
config.SOCKET_PORT = 29511;
config.UIN = 87;
config.UNITY_PAY_SECRET = "F0V-]060D~;v=64d8b9LBA0/x>1=I%+g";
config.UPLOAD_HORTOR_NAME = "wxlog-test.hortorgames.com/wxlog/api/v1/external/stats";
config.UPLOAD_STAT_NAME = "wxddz-test.qfun.com:8200/stat/event_track";
config.VERSION = 632;
export default config
|
/// MARK: 🤖 Main server for the Quizicle website - - - - - - - - - - - - - - -
var express = require('express')
var handlebars = require('handlebars')
var expressHandlebars = require('express-handlebars')
var bodyParser = require('body-parser')
var fs = require('fs')
var app = express()
app.engine('handlebars', expressHandlebars({defaultLayout: 'main'}))
app.set('view engine', 'handlebars')
var port = process.env.PORT || 3000
app.use(bodyParser.json())
app.use(express.static('public'))
///SECTION: Public functions
app.get('/', function(req, res) {
lookupRecentQuizzes(3, function(result) {
if (result) {
res.status(200).render('home', {
title: 'Quizicle',
recents: result,
scripts: [
{file_name: "/search.js"}
]
})
} else {
next()
}
})
})
app.get('/quiz/:quizID', function(req, res, next) {
var quizID = req.params.quizID
lookupQuiz(quizID, function(quiz) {
if (quiz) {
quiz.title = quiz.name + " - Quizicle"
quiz.creation_date = getMonthYear(quiz.creation_date)
res.status(200).render('quiz', {
quiz: quiz,
title: quiz.name + " - Quizicle",
scripts: [
{file_name: "/search.js"},
{file_name: "/practice.js"}
]
})
} else {
next()
}
})
})
app.get('/edit/:quizID', function(req, res, next) {
var quizID = req.params.quizID
// Look up quiz ID in DB
next()
})
app.get('/search/:searchTerm', function(req, res, next) {
var searchTerm = req.params.searchTerm;
searchTerm=searchTerm.replace(/\+/g, ' ')
var results={}
searchCollection(searchTerm, function(results){
if(results.length!=0){
results.forEach(function(item, index) {
item.creation_date = getMonthYear(item.creation_date)
})
res.status(200).render('results', {
title: 'Search Results',
search_results: results,
query: searchTerm,
scripts: [
{file_name: "/search.js"}
]
})
}
else{
res.status(404).render('results', {
title: "No Results",
no_result: 1,
query: searchTerm,
scripts: [
{file_name: "/search.js"},
]
});
}
})
})
app.get('/create', function(req, res, next) {
res.status(200).render('editQuiz', {
title: 'Create a Quiz — Quizicle',
scripts: [
{file_name: "/search.js"},
{file_name: "/create.js"},
{file_name: "/newCardTemplate.js"}
]
});
});
///SECTION: API Functions
app.post('/api/create', function(req, res, next) {
console.log(req.body);
var quiz = req.body
console.log(quiz);
// Check name and cards fields exist.
if (quiz && quiz.name && quiz.cards) {
// Check name non-empty cards length non-zero.
if (quiz.name.replace(/ /g, '').length !== 0 && quiz.cards.length > 0) {
// Check every card has prompt and answer.
for (index = 0; index < quiz.cards.length; index++) {
if (!quiz.cards[index].prompt || quiz.cards[index].prompt.replace(/ /g, '').length == 0 ||
!quiz.cards[index].answer || quiz.cards[index].answer.replace(/ /g, '').length == 0) {
res.status(400).send({
error: "Some cards missing prompts/answers."
})
}
}
// Add a blank description if none exists or if all spaces.
if (!quiz.description || quiz.description.replace(/ /g, '').length === 0) {
quiz.description = ""
}
// Add empty tags array if none exists or if all spaces.
if (!quiz.tags || quiz.tags.length === 0) {
quiz.tags = []
} else {
// Check every tag has text.
for (index = quiz.tags.length - 1; index > 0; index--) {
if (quiz.tags[index].replace(/ /g, '').length === 0) {
res.status(400).send({
error: "Some tags empty."
})
}
}
}
// Server handles meta-data and db information
quiz.creation_date = String(Math.round(+new Date()/1000))
quiz.card_count = String(quiz.cards.length)
getNextQuizID(function(err, newID) {
if (err) {
res.status(500).send({
error: "Failed to create id."
})
}
quiz._id = String(newID)
addQuiz(quiz, function(err, result) {
if (err) {
res.status(500).send({
error: "Failed to write to database."
})
}
res.status(200).send(JSON.stringify({
message: "Quiz successfully added",
newID: String(newID)
}))
listDatabaseEntries()
})
})
} else {
res.status(400).send({
error: "Required fields empty."
})
}
} else {
res.status(400).send({
error: "Request missing required fields."
})
}
})
app.get('*', function(req, res) {
res.status(404).render('404', {
title: 'Oops!',
scripts: [
{file_name: "/search.js"},
]
})
})
function startServer() {
app.listen(port, function() {
console.log("🤖 Server is listening on port", port, "...\n")
})
}
/// MARK: ☁️ Mongo Database for the Quizicle website - - - - - - - - - - - - -
var MongoClient = require('mongodb').MongoClient
var database
const quizCollection = 'quizzes'
const sequenceCollection = 'sequence'
const quizSequence = 'quiz_ID'
// Set up Mongo DB parameters
var mongoDBHost = process.env.MONGODB_HOST
// Check if a port is specified, else default to the standard port
var mongoDBPort = process.env.MONGODB_PORT || 27017
var mongoDBUser = process.env.MONGODB_USER
var mongoDBPass = process.env.MONGODB_PASS
var mongoDBName = process.env.MONGODB_NAME
var mongoDBURL = 'mongodb://' + mongoDBUser + ':' + mongoDBPass + '@' +
mongoDBHost + ':' + mongoDBPort + '/' + mongoDBName
MongoClient.connect(mongoDBURL, function(err, client) {
if (err) {
throw err
}
// Set a gloabl variable so it can be used by the whole middleware stack.
database = client.db(mongoDBName)
console.log("☁️ Connected to database.")
startServer()
database.collection(quizCollection).createIndex({
name: "text",
description: "text",
tags: "text"
})
// Change this to `true` to clear the db and seed fresh from json.
if (false) seedDatabaseFromJSON('./exampleQuizzes.json', function() {
listDatabaseEntries()
})
// Start database from scratch.
if (false) resetDatabase(function() {
listDatabaseEntries()
})
// Change this to backup db. Do not use nodemon.
if (false) backupDatabaseToJSON()
})
///SECTION: DB API functions
// Returns the json of the quiz with the given id.
async function lookupQuiz(quizID, completion) {
var query = { _id: quizID }
database.collection(quizCollection).find(query).toArray(function(err, result) {
if (err) throw err;
completion(result[0])
});
}
// Writes new quiz to db.
async function addQuiz(quiz, completion) {
database.collection(quizCollection).insertOne(quiz, function(err, result) {
if (completion) {
completion(err, result)
}
})
}
//description tags name
async function searchCollection(searchTerm, completion) {
var query = searchTerm.split('+').join(' ');
database.collection(quizCollection).find({$text: {$search: query}}).toArray(function(err, result) {
if (err) throw err;
completion(result);
});
}
// Returns an array of the <count> most recent quizzes.
// - count: Int, max number of quizzes to get.
async function lookupRecentQuizzes(count, completion) {
var numberOfResults = parseInt(count)
var sorting = { creation_date: -1 }
database.collection(quizCollection).find().sort(sorting).toArray(function(err, result) {
if (err) throw err
// Get readable dates
result.forEach(function(item, index) {
item.creation_date = getMonthYear(item.creation_date)
})
completion(result.slice(0, numberOfResults))
})
}
///SECTION: DB utility functions
// Backs up database to a JSON file with name backup<date>.json.
// ⚠️ Don't run in nodemon or it will cycle forever!
function backupDatabaseToJSON() {
console.log("💾 Backing up database...");
database.collection(quizCollection).find({}).toArray(function(err, allQuizzes) {
if (err) throw err
var today = new Date();
var date = today.toISOString().substring(0, 10);
var fileName = "./backup" + date + ".json"
var fileContents = JSON.stringify(allQuizzes, null, " ");
fs.writeFile(fileName, fileContents, (err) => {
if (err) throw err
console.log("💾 Back up complete.");
});
})
}
function seedDatabaseFromJSON(filePath, completion) {
console.log("⚠️ Seeding database from " + filePath);
var quizzes = require(filePath)
cleanUp(quizCollection, function() {
createCollection(quizCollection, function() {
database.collection(quizCollection).insertMany(quizzes)
// Start the quiz id counter at the last seed quiz
resetIDs(quizzes.length + 1, function() {
if (completion) {
completion()
}
})
})
})
}
function resetDatabase(completion) {
console.log("⚠️ Resetting database...");
cleanUp(quizCollection, function() {
createCollection(quizCollection, function() {
// Start the quiz id counter at 1
resetIDs(1, function() {
if (completion) {
completion()
}
})
})
})
}
function resetIDs(start, completion) {
cleanUp(sequenceCollection, function() {
createCollection(sequenceCollection, function() {
var sequenceBase = {
_id: quizSequence,
sequence_value: start
}
database.collection(sequenceCollection).insertOne(sequenceBase)
if (completion) {
completion()
}
})
})
}
function getNextQuizID(completion) {
database.collection(sequenceCollection).findOneAndUpdate(
{ _id: quizSequence },
{ $inc: { sequence_value: 1 }},
function (err, data) {
completion(err, data.value.sequence_value)
})
}
function listDatabaseEntries() {
console.log("Collections: - - - - - - - - - - - - - - - - - - - -");
listAllCollections()
database.collection(quizCollection).find({}).toArray(function(err, result) {
console.log("Quizzes: - - - - - - - - - - - - - - - - - - - -");
console.log(result)
})
database.collection(sequenceCollection).find({}).toArray(function(err, result) {
console.log("Sequence: - - - - - - - - - - - - - - - - - - - -");
console.log(result)
})
}
function listAllCollections(completion) {
database.listCollections().toArray(function(err, collInfos) {
if (err) throw err
console.log(collInfos)
if (completion) {
completion()
}
})
}
function createCollection(collectionName, completion) {
database.createCollection(collectionName, function(err, result) {
if (err) throw err
if (completion) {
completion()
}
})
}
// Drops collection table if it exists
function cleanUp(collectionName, completion) {
database.listCollections().toArray(function(err, result) {
if (err) throw err
var deleting = false
result.forEach(result => {
if (result.name == collectionName) {
deleting = true
deleteCollection(collectionName, function() {
completion()
})
}
})
if (!deleting) completion()
})
}
function deleteCollection(collectionName, completion) {
database.collection(collectionName).drop(function(err, delOK) {
if (err) throw err
if (completion) {
completion()
}
})
}
///MARK: General utility functions
function getMonthYear(timestamp) {
var months = ['January','February','March','April','May','June','July','August','September','October','November','December']
var date = new Date(timestamp * 1000)
var year = date.getFullYear()
var month = months[date.getMonth()]
return(month + " " + year)
}
|
import React, { Component, PropTypes } from 'react';
import cookie from 'react-cookie';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { reduxForm, Field } from 'redux-form'
import { TextField }from 'redux-form-material-ui';
import FlatButton from 'material-ui/FlatButton';
import Card from 'material-ui/Card';
import Chip from 'material-ui/Chip';
import injectTapEventPlugin from 'react-tap-event-plugin';
import * as actions from '../actions';
injectTapEventPlugin();
function mapStateToProps(state){
const { isAuth, message } = state.auth;
return {
isAuth,
message
}
}
export class Login extends Component{
static propTypes = {
handleSubmit: PropTypes.func
}
static contextTypes = {
router: React.PropTypes.object
}
componentWillMount() {
/*
if token already stored redirect to /list
*/
if(cookie.load('token')) {
this.context.router.push('/list');
}
}
constructor(props) {
super(props);
};
render(){
const { handleSubmit, message, onLog, fields: {email, password} } = this.props;
return(
<div className="login-content">
<Card className="login-form">
{
message ?
<Chip className="login-error-message">
{message.message}
</Chip> :
null
}
<form onSubmit={handleSubmit(onLog)}>
<Field {...email}
name="email"
component={TextField}
hintText=""
floatingLabelText="Email"
type="text"
/>
<br />
<Field {...password}
name="password"
component={TextField}
hintText=""
floatingLabelText="Password"
type="password"
/>
<br />
<FlatButton
backgroundColor="#009688"
hoverColor="#4DB6AC"
label="Login"
type="submit"
className="login-button"
/>
</form>
</Card>
</div>
)
}
}
function mapDispatchToProps(dispatch){
return{
onLog: bindActionCreators(actions.loginUser, dispatch)
}
}
Login = reduxForm({
form: 'LoginForm',
fields: ['email', 'password']
})(Login)
Login = connect(mapStateToProps, mapDispatchToProps)(Login)
export default Login
|
var students = [
{ id: 1, name: "bruce", age: 40 },
{ id: 2, name: "zoidberg", age: 22 },
{ id: 3, name: "alex", age: 22 },
{ id: 4, name: "alex", age: 30 },
{ id: 5, name: "alex", age: 15 }
];
function compareName(a,b) {
if (a.name < b.name) {
return 1;
} else if (a.name > b.name){
return -1;
} else {
if (a.age < b.age) {
return 1;
} else if (a.age > b.age){
return -1
} else {
return 0
}
}
}
function compareAge(a,b) {
if (a.age < b.age) {
return 1;
} else if (a.age > b.age){
return -1
} else {
return 0
}
}
// I put the contents of the compareAge function into
// the else portion of "if" of the first age function to
// preexisting compare age when name is the same
students.sort(compareName);
console.log(students);
|
import React from 'react';
import classnames from 'classnames/bind';
import styles from './text.scss';
const cx = classnames.bind(styles);
const Text = (props) => {
const {
bold, upper, theme, text, size,
} = props;
return (
<div className={cx('text', {
'text--bold': bold,
'text--upper': upper,
[`text--theme-${theme}`]: theme,
[`text--size-${size}`]: size,
})}
>
<span>{text}</span>
</div>
);
};
export default Text;
|
import axios from 'axios';
import Fingerprint from './Fingerprint';
import getCSRFToken from '../utils/getCSRFToken';
// Fingerprint can take up to 500ms to generate,
// you should start its computation as soon as possible.
const fingerprint = new Fingerprint();
export const API_BASE = '/api/v1';
const api = axios.create({
baseURL: API_BASE,
});
api.defaults.headers = {
accept: 'application/json',
};
export default class {
_auth() {
const headers = {
'X-CSRF-Token': getCSRFToken(),
'X-Fingerprint': fingerprint.result,
};
return { headers };
}
getReports() {
return api.get('/reports');
}
createReport(report) {
return api.post('/reports', { report }, this._auth());
}
updateReport(report) {
const data = new FormData();
data.append('photo', report.photo);
return api.patch(`/reports/${report.id}`, data, this._auth());
}
createSetting(setting) {
return api.post('/settings', { setting }, this._auth());
}
}
|
import Satelite from "./classes/Satelite.js";
import Galaxy from "./classes/Galaxy.js";
import Rocket from "./classes/Rocket.js";
import Platform from "./classes/Platform.js";
import Sky from "./classes/Sky.js";
{
let pointlight1,
pointlight2,
pointlight3,
pointlight4,
pointlight5,
pointlight6,
hemisphereLight,
shadowLight,
camera,
scene,
renderer,
satelite,
galaxy,
net,
posePoints,
rocket,
engineFire,
platform,
sky,
detectionSphere,
radius,
centerpointx,
centerpointz,
direction,
roundTempPosX = 0,
roundTempPosZ = 6;
let collidableMeshList = [];
let buttonPressedArray = [];
let equal = false;
let readyforLaunch = false;
let countdownCounter = 10,
jupiterPassed = false;
const video = document.querySelector(".video");
const container = document.querySelector(".world");
const buttonArray = ["5", "3", "1", "2", "4"];
const $buttons = document.querySelectorAll("button");
const $text = document.querySelector(".text");
const $input = document.querySelector(".input");
const $buttoncontainer = document.querySelector(".buttons");
const $audio = document.querySelector("audio");
const $countdown = document.querySelector(".countdown");
const init = () => {
video.width = 600;
video.height = 600;
launch();
// space();
container.appendChild(renderer.domElement);
window.addEventListener("resize", onWindowResize, false);
};
const onWindowResize = () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
};
const launch = () => {
const launchInit = () => {
createScene();
createCamera();
createLights();
//add elements
addCamera();
addWorld();
addRocket();
addPlatform();
createSky();
loop();
$buttons.forEach(button =>
button.addEventListener("click", () => {
buttonEventHandler(button.textContent);
})
);
};
const createLights = () => {
hemisphereLight = new THREE.HemisphereLight(0x000000, 0x4662f8, 0.9);
shadowLight = new THREE.DirectionalLight(0xffffff, 0.7);
shadowLight.position.set(3, 0.15, 3);
shadowLight.castShadow = true;
shadowLight.shadow.camera.left = -400;
shadowLight.shadow.camera.right = 400;
shadowLight.shadow.camera.top = 400;
shadowLight.shadow.camera.bottom = -400;
shadowLight.shadow.camera.near = 1;
shadowLight.shadow.camera.far = 1000;
shadowLight.shadow.mapSize.width = 2048;
shadowLight.shadow.mapSize.height = 2048;
hemisphereLight.position.set(0, -10, 0);
scene.add(hemisphereLight);
scene.add(shadowLight);
};
const createScene = () => {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.shadowMap.enabled = true;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
};
const createCamera = () => {
camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
1,
1000
);
};
const addCamera = () => {
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices
.getUserMedia({ video: true })
.then(stream => {
video.srcObject = stream;
})
.catch(err0r => {
console.log("Something went wrong!");
});
}
};
const addRocket = () => {
rocket = new Rocket();
rocket.mesh.position.z = -40;
rocket.mesh.position.y = -5;
rocket.mesh.rotation.y = 1;
rocket.mesh.castShadow = true;
rocket.mesh.receiveShadow = true;
scene.add(rocket.mesh);
};
const addPlatform = () => {
platform = new Platform();
platform.mesh.position.z = -39;
platform.mesh.position.y = -7;
platform.mesh.rotation.z = 0;
platform.mesh.castShadow = true;
platform.mesh.receiveShadow = true;
scene.add(platform.mesh);
};
const createSky = () => {
sky = new Sky();
sky.mesh.position.y = -600;
sky.mesh.position.z = -50;
scene.add(sky.mesh);
};
const addWorld = () => {
const geom = new THREE.SphereGeometry(600, 20, 20);
const mat = new THREE.MeshBasicMaterial({ color: 0x5acd4d });
const sphere = new THREE.Mesh(geom, mat);
sphere.receiveShadow = true;
sphere.position.set(0, -630, -200);
scene.add(sphere);
};
const buttonEventHandler = e => {
buttonPressedArray.push(e);
$input.innerHTML = buttonPressedArray;
checkIfRightOrder();
};
const checkIfRightOrder = () => {
equal = checkArrays(buttonPressedArray, buttonArray);
if (equal === true) {
//button combination is right
$audio.play();
$input.innerHTML = "ready to launch rocket";
//wait to launch untill countdown is complete
setTimeout(launchRocket, 10000);
$countdown.innerHTML = countdownCounter;
setInterval(countdown, 1000);
$text.classList.add("hide");
$buttons.forEach(button => button.classList.add("hide"));
} else {
if (buttonPressedArray.length < buttonArray.length) {
//if they haven't pressed enough buttons
$input.innerHTML = buttonPressedArray;
console.log("keep going");
} else {
//if the combination isn't right
console.log("try again");
$input.innerHTML = "try again";
buttonPressedArray = [];
}
console.log(buttonPressedArray);
// console.log("try again/keep going");
}
};
const launchRocket = () => {
readyforLaunch = true;
rocket.addFire();
$input.classList.add("hide");
};
const countdown = () => {
if (countdownCounter > 1) {
$countdown.classList.remove("hide");
countdownCounter = countdownCounter - 1;
$countdown.innerHTML = countdownCounter;
} else {
$countdown.classList.add("hide");
clearInterval(countdown);
}
};
const checkArrays = (a, b) => {
if (a.length === b.length) {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
};
const loop = () => {
requestAnimationFrame(loop);
render();
};
const render = () => {
rocket.animate();
// change to timer
if (readyforLaunch === true) {
rocket.mesh.position.y += 0.1;
rocket.animate();
}
camera.lookAt(
new THREE.Vector3(
rocket.mesh.position.x,
rocket.mesh.position.y + 13,
rocket.mesh.position.z
)
);
sky.mesh.rotation.z -= 0.0001;
renderer.render(scene, camera);
};
launchInit();
};
const space = () => {
const spaceInit = () => {
$buttoncontainer.innerHTML = "";
getPosenet();
createScene();
createCamera();
createLights();
//add elements
addCamera();
addGalaxy();
addSatelite();
loop();
};
const getPosenet = async () => {
net = await posenet.load();
setCoordinates();
};
const setCoordinates = async () => {
const pose = await net.estimateSinglePose(video, 0.5, true, 16);
requestAnimationFrame(setCoordinates);
if (pose.keypoints[0].position.x < 200) {
direction = "links";
} else if (pose.keypoints[0].position.x > 400) {
direction = "rechts";
} else {
direction = "midden";
}
};
const mapValue = (value, istart, istop, ostart, ostop) =>
ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
const addCamera = () => {
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices
.getUserMedia({ video: true })
.then(stream => {
video.srcObject = stream;
})
.catch(err0r => {
console.log("Something went wrong!");
});
}
};
const addSatelite = () => {
satelite = new Satelite();
satelite.mesh.castShadow = true;
satelite.mesh.receiveShadow = true;
const geom = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const mat = new THREE.MeshPhongMaterial({
color: 0xffffff,
transparent: true,
opacity: 0
});
detectionSphere = new THREE.Mesh(geom, mat);
scene.add(detectionSphere);
scene.add(satelite.mesh);
};
const addGalaxy = () => {
galaxy = new Galaxy();
galaxy.mesh.position.set(0, -30, -800);
collidableMeshList.push(galaxy.astreoids.mesh);
scene.add(galaxy.mesh);
};
const createLights = () => {
pointlight1 = new THREE.PointLight(0xf6c861);
pointlight2 = new THREE.PointLight(0xf6c861);
pointlight3 = new THREE.PointLight(0xf6c861);
pointlight4 = new THREE.PointLight(0xf6c861);
pointlight5 = new THREE.PointLight(0xf6c861);
pointlight6 = new THREE.PointLight(0xf6c861);
pointlight1.position.set(0, 0, -600);
pointlight2.position.set(0, 0, -800);
pointlight3.position.set(-150, -100, -700);
pointlight4.position.set(150, 100, -700);
pointlight5.position.set(-150, 100, -700);
pointlight6.position.set(150, -100, -700);
scene.add(pointlight1);
scene.add(pointlight2);
scene.add(pointlight3);
scene.add(pointlight4);
scene.add(pointlight5);
scene.add(pointlight6);
};
const createScene = () => {
scene = new THREE.Scene();
scene.background = new THREE.TextureLoader().load("./assets/img/bg.jpg");
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
};
const createCamera = () => {
camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
1,
5000
);
};
const loop = () => {
requestAnimationFrame(loop);
if (jupiterPassed === false) {
radius =
Math.sqrt(
Math.pow(
galaxy.jupiter.mesh.position.x - galaxy.earth.mesh.position.x,
2
) +
Math.pow(
galaxy.jupiter.mesh.position.z - galaxy.earth.mesh.position.z,
2
)
) / 2;
centerpointx =
(galaxy.earth.mesh.position.x + galaxy.jupiter.mesh.position.x) / 2;
centerpointz =
(galaxy.earth.mesh.position.z + galaxy.jupiter.mesh.position.z) / 2;
if (
Math.floor(satelite.mesh.position.x - 10) <
Math.floor(galaxy.jupiter.mesh.position.x + 5) &&
Math.floor(satelite.mesh.position.x - 10) >
Math.floor(galaxy.jupiter.mesh.position.x - 5) &&
Math.floor(satelite.mesh.position.z + 800) <
Math.floor(galaxy.jupiter.mesh.position.z + 5) &&
Math.floor(satelite.mesh.position.z + 800) >
Math.floor(galaxy.jupiter.mesh.position.z - 5)
) {
jupiterPassed = true;
}
} else {
radius =
Math.sqrt(
Math.pow(
galaxy.pluto.mesh.position.x - galaxy.jupiter.mesh.position.x,
2
) +
Math.pow(
galaxy.pluto.mesh.position.z - galaxy.jupiter.mesh.position.z,
2
)
) / 2;
centerpointx =
(galaxy.jupiter.mesh.position.x + galaxy.pluto.mesh.position.x) / 2;
centerpointz =
(galaxy.jupiter.mesh.position.z + galaxy.pluto.mesh.position.z) / 2;
}
let speed = Date.now() * -0.0001;
satelite.mesh.position.set(
Math.cos(speed) * radius + centerpointx + 10,
-30,
Math.sin(speed) * radius + centerpointz - 800
);
// for (
// let vertexIndex = 0;
// vertexIndex < detectionSphere.geometry.vertices.length;
// vertexIndex++
// ) {
// const localVertex = detectionSphere.geometry.vertices[
// vertexIndex
// ].clone();
// const globalVertex = detectionSphere.matrix.applyMatrix4(localVertex);
// const directionVector = globalVertex.sub(detectionSphere.position);
// const ray = new THREE.Raycaster(
// detectionSphere.position,
// directionVector.clone().normalize()
// );
// const collisionResults = ray.intersectObjects(collidableMeshList);
// console.log(collisionResults);
// if (
// collisionResults.length > 0 &&
// collisionResults[0].distance < directionVector.length()
// ) {
// console.log("collision");
// }
// }
render();
};
const render = () => {
satelite.moveSatellite();
switch (direction) {
case "links":
roundTempPosX = Math.cos(Date.now() * 0.0003) * 6;
roundTempPosZ = Math.sin(Date.now() * 0.0003) * 6;
camera.position.set(
satelite.mesh.position.x + roundTempPosX,
-30,
satelite.mesh.position.z + roundTempPosZ
);
break;
case "rechts":
roundTempPosX = Math.cos(Date.now() * -0.0003) * 6;
roundTempPosZ = Math.sin(Date.now() * -0.0003) * 6;
camera.position.set(
satelite.mesh.position.x + roundTempPosX,
-30,
satelite.mesh.position.z + roundTempPosZ
);
break;
case "midden":
camera.position.set(
satelite.mesh.position.x + roundTempPosX,
satelite.mesh.position.y,
satelite.mesh.position.z + roundTempPosZ
);
break;
}
camera.lookAt(
new THREE.Vector3(
satelite.mesh.position.x,
satelite.mesh.position.y,
satelite.mesh.position.z
)
);
galaxy.animate();
renderer.render(scene, camera);
};
spaceInit();
};
init();
}
|
var expect = require("chai").expect;
var library = {
tracks: {
t01: {
id: "t01",
name: "Code Monkey",
artist: "Jonathan Coulton",
album: "Thing a Week Three"
},
t02: {
id: "t02",
name: "Model View Controller",
artist: "James Dempsey",
album: "WWDC 2003"
},
t03: {
id: "t03",
name: "Four Thirty-Three",
artist: "John Cage",
album: "Woodstock 1952"
}
},
playlists: {
p01: { id: "p01", name: "Coding Music", tracks: ["t01", "t02"] },
p02: { id: "p02", name: "Other Playlist", tracks: ["t03"] }
}
};
const playListFormat = details => {
return `${details.id}: ${details.name} - ${details.tracks.length} tracks`;
};
const trackFormat = details => {
return `${details.id}: ${details.name} by ${details.artist} (${details.album})`;
};
// FUNCTIONS TO IMPLEMENT:
// prints a list of all playlists, in the form:
// p01: Coding Music - 2 tracks
// p02: Other Playlist - 1 tracks
var printPlaylists = function() {
const playlists = library.playlists;
for (key in playlists) {
const details = playlists[key];
console.log(playListFormat(details));
}
};
// prints a list of all tracks, in the form:
// t01: Code Monkey by Jonathan Coulton (Thing a Week Three)
// t02: Model View Controller by James Dempsey (WWDC 2003)
// t03: Four Thirty-Three by John Cage (Woodstock 1952)
var printTracks = function() {
const tracks = library.tracks;
for (key in tracks) {
const details = library.tracks[key];
console.log(trackFormat(details));
}
};
// prints a list of tracks for a given playlist, in the form:
// p01: Coding Music - 2 tracks
// t01: Code Monkey by Jonathan Coulton (Thing a Week Three)
// t02: Model View Controller by James Dempsey (WWDC 2003)
var printPlaylist = function(playlistId) {
const playlistDetails = library.playlists[playlistId];
console.log(playListFormat(playlistDetails));
const tracks = playlistDetails.tracks;
for (track of tracks) {
console.log(trackFormat(library.tracks[track]));
}
};
// adds an existing track to an existing playlist
var addTrackToPlaylist = function(trackId, playlistId) {
library.playlists[playlistId].tracks.push(trackId);
};
// generates a unique id
// (use this for addTrack and addPlaylist)
var uid = function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
};
// adds a track to the library
var addTrack = function(name, artist, album) {
const newId = uid();
library.tracks[newId] = {
id: newId,
name: name,
artist: artist,
album: album
};
};
// adds a playlist to the library
var addPlaylist = function(name) {
const newId = uid();
library.playlists[newId] = {
id: newId,
name: name,
tracks: []
};
};
// STRETCH:
// given a query string string, prints a list of tracks
// where the name, artist or album contains the query string (case insensitive)
// tip: use "string".search("tri")
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
var printSearchResults = function(query) {
const tracks = library.tracks;
let searchResults = [];
for (key in tracks) {
const candidates = [
tracks[key].name,
tracks[key].artist,
tracks[key].album
];
let filteredCandidates = candidates.filter(candidate =>
candidate.toLowerCase().includes(query)
);
if (filteredCandidates.length) searchResults.push(tracks[key]);
}
for (track of searchResults) {
console.log(trackFormat(track));
}
};
// console.log("TESTS");
// printPlaylists();
// console.log("");
// printTracks("p01");
// console.log("");
// printPlaylist("p01");
// console.log("");
// addTrackToPlaylist("t03", "p01");
// console.log(library.playlists["p01"]);
// console.log("");
// addTrack("Blah", "Jane Doe", "Blahblah");
// console.log(library.tracks);
// console.log("");
// addPlaylist("ladida");
// console.log(library.playlists);
// console.log("");
// console.log(library);
//printSearchResults("jo");
|
import GenreList from './Genre-list';
export default GenreList;
|
let assert=require('assert');
const Player=require('../player.js');
let test={};
const winningMoves=[[1,2,3], [4,5,6], [7,8,9],
[1,4,7], [2,5,8], [3,6,9],
[1,5,9], [3,6,7]
];
test['hasWon checks whether the player moves contain winning move combination']=function(){
let tom=new Player("Tom");
let playerMoves=[1,2,3];
tom.addMove(1);
tom.addMove(2);
tom.addMove(3);
assert.ok(tom.hasWon(winningMoves));
jerry=new Player("Jerry");
jerry.addMove(1);
jerry.addMove(2);
jerry.addMove(5);
jerry.addMove(6);
jerry.addMove(7);
assert.ok(!jerry.hasWon(winningMoves));
};
exports.test=test;
|
var tasks =[];
document.addEventListener("DOMContentLoaded",function(){
if(localStorage.getItem('tasks')!=null){
tasks=JSON.parse(localStorage.getItem('tasks'));
displayTasks();
}
//Date picker stuffs
var out= document.getElementById("output");
var picker = new MaterialDatetimePicker({})
.on('submit', function(d) {
console.log(d);
var date= d.toString().split(" ");
out.value = date[0]+" "+date[1]+" "+date[2]+" "+date[3];
});
var el = document.querySelector('.c-datepicker-btn');
el.addEventListener('click', function() {
picker.open();
}, false);
var createButton=document.getElementById("createTask");
createButton.addEventListener("click",function(){
createTask();
});
console.log(tasks);
})
function createTask(){
var taskName = document.getElementById("taskName");
var date = document.getElementById("output");
var id = guid();
var task={};
task["Name"]=taskName.value;
task["Date"]=date.value;
task["id"]=id;
task["status"]="U";
tasks.push(task);
localStorage.setItem('tasks', JSON.stringify(tasks));
displayTasks();
document.getElementById("taskName").value="";
document.getElementById("output").value="";
}
function displayTasks(){
var taskName = document.getElementById("taskName");
var date = document.getElementById("output");
var taskcontainer = document.getElementById("taskcontainer");
console.log(tasks);
taskcontainer.innerText="";
for(var i=0;i<tasks.length;i++){
console.log("i"+i);
var newTaskDiv =document.createElement("div");
newTaskDiv.setAttribute("class","newTask");
//HEADER
var header =document.createElement("div");
header.setAttribute("id","taskHeader");
var status= document.createTextNode("Status:");
header.appendChild(status);
var checkboxContainer = document.createElement("span");
checkboxContainer.setAttribute("class","checkbox");
var ielement = document.createElement("i");
ielement.setAttribute("id",i);
if(tasks[i]["status"]=="U"){
ielement.setAttribute("class", "far fa-square");
}else{
ielement.setAttribute("class", "far fa-check-square");
}
checkboxContainer.appendChild(ielement);
header.appendChild(checkboxContainer);
newTaskDiv.appendChild(header);
//BODY
var body =document.createElement("div");
body.setAttribute("id","content");
var h2 = document.createElement("h2");
var taskheading= document.createTextNode(tasks[i]["Name"]);
h2.appendChild(taskheading);
body.appendChild(h2);
var span = document.createElement("span");
var taskDeadline= document.createTextNode("Task Deadline :: ");
span.appendChild(taskDeadline);
body.appendChild(span);
var taskDeadlineDate= document.createTextNode(tasks[i]["Date"]);
body.appendChild(taskDeadlineDate);
newTaskDiv.appendChild(body);
//FOOTER
var footer =document.createElement("div");
footer.setAttribute("id","taskFooter");
var viewdiv =document.createElement("div");
viewdiv.setAttribute("id","viewDiv");
//<i class="fas fa-eye"></i>
var iElement2 = document.createElement("i");
iElement2.setAttribute("class","fas fa-eye");
viewdiv.appendChild(iElement2);
var viewText= document.createTextNode("View");
viewdiv.appendChild(viewText);
footer.appendChild(viewdiv);
var delDiv =document.createElement("div");
delDiv.setAttribute("class","delDiv");
delDiv.setAttribute("id",tasks[i]["id"]);
var iElement3 = document.createElement("i");
iElement3.setAttribute("class","fas fa-trash-alt");
delDiv.appendChild(iElement3);
var delText= document.createTextNode("Delete");
delDiv.appendChild(delText);
footer.appendChild(delDiv);
newTaskDiv.appendChild(footer);
taskcontainer.appendChild(newTaskDiv);
}
//After displaying task add evwnt to update status
if(tasks!=null){
console.log("tasks are not null");
var __=document.getElementsByClassName("checkbox");
for(var j=0;j<__.length;j++){
__[j].addEventListener("click",function(e){
updateStatus(e.target.getAttribute("id"));
});
}
var ___=document.getElementsByClassName("delDiv");
for(var k=0;k<___.length;k++){
___[k].addEventListener("click",function(e){
deleteTask();
})
}
}
}
//ID generation for task
function guid() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
function updateStatus(id){
console.log("updationg status for array "+id+" tasks[id][\"status\"]"+tasks[id]["status"]);
var ielement= document.getElementById(id);
if(tasks[id]["status"]==="U"){
ielement.setAttribute("class","far fa-check-square");
tasks[id]["status"]="C";
}else{
ielement.setAttribute("class","far fa-square");
tasks[id]["status"]="U";
}
localStorage.setItem('tasks', JSON.stringify(tasks));
}
function deleteTask(id){
//tasks.find(task => task.id ===id) will return the object conatining the id and the we are finding its index to
//remove from array
var taskPos =tasks.indexOf(tasks.find(task => task.id ===id));
//Delete the item
tasks.splice(taskPos,1);
//Update the locat store
localStorage.setItem('tasks', JSON.stringify(tasks));
//Display the tasks
displayTasks();
}
|
import React, { Component } from 'react';
import Column_content from './component/column_content';
// import './column_text.css';
class Column_1606 extends Component{
render(){
const column_1606_article = {
title:['2007級 謝沛倫(Ambidio Inc. 共同創辦人)'],
hashtags:['系友專訪', '謝沛倫', '2007級', 'B92', 'Ambidio', 'AdventuresInSound', 'LosAngelesStartup', '聲音革命', 'Bloomberg媒體報導', 'Billboard', '讓筆電喇叭變百萬音響', '80年來最偉大的聲音革命', '李嘉誠與黑眼豆豆搶投資', 'HorizonsVentures', 'ColumbiaUniversity', 'ComputerGraphics', 'MusicTech', '大腦和耳朵重新連結的Ambidio時代'],
sections:[
{
bigtitle:'一、Ambidio快問快答',
sections:[
{
title:'Ambidio有何神奇?',
section:'使用者只要一指按下電腦、手機等播放鍵,便可享有具空間感的聲音效果。有效音場寬度是目前市面上其他技術的至少三倍以上。'
},
{
title:'Ambidio的好處?',
section:'重視音效的人不必再買一堆設備,就可用最低成本,體驗沉浸式音效。'
},
{
title:'Ambidio運用方式?',
section:'有兩種,一是直接將Ambidio技術直接嵌入影音或聲音檔案中,另一是透過程式即時將技術加入正在播放的聲音中。'
},
{
title:'Ambidio運用管道?',
section:'可廣泛應用在任何有立體聲揚聲器或耳機的硬體設備,包括筆記型電腦、電視及部分手機和平板電腦等,已有美國電影採用。(資料來源:BUSINESSDREAM經營夢想, https://goo.gl/T32Zyt)'
}
]
},
{
bigtitle:'二、前言',
sections:
[
{
title:' 前言',
section:' 「想像一下,打開電腦或是手機觀看影片或玩電動,就能感受到360度逼真的立體音效,彷彿賽車就從身旁呼嘯而過、恐龍就從眼前磅礡踩過的震撼聲音。」創辦於2014年,四名來自台灣的年輕人在洛杉磯,把心力傾注在聲音科技公司Ambidio上,得到七屆葛來美獎得主歌手will.i.am及李嘉誠先生旗下維港投資挹注支持。結合大腦感知模式和聲音科技,重塑大腦對聲音的解碼功能,創造出高質的聽覺體驗,透過一般立體聲揚聲器的平板電腦和手機,也能享受更勝環繞音效的聲音饗宴,如同身歷其境。Ambidio透過兩種方式改變對聲音的體驗:一種是直接將Ambidio技術直接嵌入影音或聲音檔案中,另一種是透過程式即時將技術加入正在播放的聲音中。一旦配備Ambidio技術,只需按下播放鍵,便可享擁奇幻兼具空間感的聲音效果。Ambidio可廣泛應用在任何有立體聲揚聲器的硬體設備,包括筆電、電視及部分手機和平板等。系學會很榮幸能夠聯絡上學長,讓我們來聽聽Ambidio Inc. 的Co-founder 謝沛倫學長為我們帶來的分享~'
}
]
},
{
bigtitle:'三、Ambidio 創業甘苦談',
sections:
[
{
title:'您是如何與其他co-founders相識並有共同創業的idea?可以敘述一下這段歷史嗎?',
section:'Co-founders認識很久,在台灣就認識了。我們不是為了創業而想idea,而是有另外一個co-founder之前就在做這方面的研究,而且成果不錯,想讓更多人使用和體驗。我也有幫他debug和brainstorm,之後思考如何推廣並且問其他人的意見。每個人因為過去經驗不同,都有不同的想法,但這些人的意見的共同交集就是成立一個公司,再想辦法搞定專利,之後甚麼都好說。成立公司比較簡單,但專利就需要寫一堆繁瑣的文件。'
},
{
title:'做研究與創業有什麼不同?',
section:'做研究比較focus在跟專業領域有關的事情,但成立公司就會需要處理很多雜事,我們每個月都在處理不同的事情,每件都是新的,只要發生事情就要趕快學,每週都有不同的情況。'
},
{
title:'Ambidio跟別人做的環繞聲是差在哪裡呢?',
section:'我們的優點在於,有許多Artist在做創造聲音,他要作混音、幫電影配聲音,要花很多時間。我們能夠打破物理的限制,就像在自然的情況下聲音是從四面八方來的一樣。我們不會讓聲音失真,不管用耳機或喇叭都可以,但耳機本來就滿有環繞感。如果你看到兩個喇叭在前面,但發現聲音從不同方向來,感覺會很神奇。'
},
{
title:'目前還沒有看到Ambidio出產品,只有看到demo,請問大約何時會出呢?你們未來的策略是?',
section:'目前ambidio會跟製作content的公司合作,像是做電影或音樂,所以我們做的東西通常不會直接deliver到個體客戶的手上,但我們客戶的產品你們會看到,只是目前還沒有,希望可以讓你們趕快看到。'
},
{
title:'有沒有因為這樣的產業,認識音樂人?',
section:'認識黑眼豆豆的Will.I.Am,他是我們的投資人。在我們的投資顧問室skywalker sound,也就是做星際大戰的公司,可以看到很多人,像是侏儸紀的混音師、星際大戰的混音師,在交流的時候會認識到很多音樂的魔術師。他們或許大眾面前不有名,但在幕後混音界很厲害。'
},
{
title:'創業至今遇到最大的挫折?',
section:'創業至今覺得會的東西太少,因為新開的公司會有很多方面的事,像是法律和會計,哪有可能知道那麼多事情,或是在專業領域上,其實也是學不完的,所以要趕快學然後趕快趕上。另外就是花太多時間在等待,就像是你等學校申請也要等待,我們創業要等專利等等。'
}
]
},
{
bigtitle:'四、大學時期',
sections:
[
{
title:'談談電機系的歸屬感',
section:'我不太確定什麼是歸屬感,不過在國外留學會覺得很多人是從同一個地方來的,比方說從台灣、台大或是電機系,比較會相互照應。除了生活以外,在工作上也會因為做的領域比較接近,可以相互建議。可能台大電機出國的比例比其他學校或學系還高一點,所以在這邊會有比較多同學。不過在台灣應該也是這樣子吧,很容易跟大學同學hangout。'
},
{
title:'當年最喜歡的教授',
section:'資工系的莊永裕老師。我上過他兩門課,分別是數位視覺效果與數位影像生成。那時候就啟發了我對computer graphics這個領域的興趣,想深入瞭解做特效、動畫背後的原理是什麼。電機系的話,應該是李琳山吧!我沒有上過他的信號系統,我上的是數位語音處理。他不是只有傳授這個學科的知識,他對學生怎麼做研究或做事的方法比較注重。我印象中他的課程設計就是以這個為出發點,並不只是把數位語音處理的不同component教給你。'
},
{
title:'當年電機系系上的神人?',
section:'我也是想了一下。其實應該大家都是奇才啦,有點官方說法。不過我想到的是會一邊打太極拳一邊踢足球的同學。'
},
{
title:'大學時期特別的成就或經歷',
section:'呃...沒有成就(笑)我沒參加系學會,沒拿書卷獎也沒社團。我大部分時間都在打系籃啦!對未來的影響就是到現在還是只會交籃球場上認識的人當朋友而已,沒有什麼正面的影響。'
},
{
title:'系上 / 系外對你最有幫助的一門課',
section:'系外就是剛剛說的數位視覺效果,系上是線性代數。我覺得工程數學對之後的很多進階學科都很有幫助。後來在學其他的東西的時候都會發現:哦!原來是這樣!可是真的要用的時候才發現沒學好然後又要複習。我的教授應該是馮蟻剛。也是要看你之後做什麼啦!如果你要做電波的話,那可能就是微方比較重要。'
},
{
title:'關於專題選擇',
section:'我跟過兩位老師。一位是鄭士康,當時我做電腦音樂相關的專題。因為我之前彈吉他所以就研究效果器的原理,再用code寫出來。另外一位是簡韶逸,那時候是做image based rendering。比如說你在動畫裡面看到的東西都是你有一個model然後貼一些texture上去然後把他render出來。那image based就是他可以拍很多很多的照片,然後用一些數學進行處理。比如說某一個視角的時候是用某一張圖的某些東西。可能跟幾何比較有關吧!但是也是多少有點關係啦。不過我的專題就是把當時已存在的方法實做出來。'
}
]
},
{
bigtitle:'五、美國念研究所時期',
sections:
[
{
title:' 留學讀研究所',
section:'我覺得最大的差別大概就是在美國唸研究所比較多就是在美國工作,多數人的目的一開始也是想在美國工作才來念研究所。我們那屆出國的比例、我猜大概有三四十個人吧,沒有非常多,可是到今年都還有人出國,就是工作了一下,但還想再念一點書,就再申請出國唸書,所以不一定要一畢業就出國。'
},
{
title:'出國前準備',
section:'(從台大電機畢業到去哥倫比亞大學中間隔了三年,請問除了當兵跟準備出國考試資料等等,還有在做什麼嗎?)我當時去中研院做研究,中研院那時好像是快要出國之前的人的臨時棲息地,因為像剛剛說大學專題就是實作一些已存在的東西,好像沒有一些厲害的paper,所以想說去中研院做一下研究,除了要增加publication之外,也學習做研究。其實我也不太確定幫助有多少,因為那時候我原本要念computer graphics,但我大學念電機系,關聯不大,所以我申請國外的CS沒上而EE有上。所以不敢說那段時間對申請多有幫助,不過對自己的學習是很有幫助的。'
},
{
title:'中研院的研究內容',
section:'我那時候去中研院是去資訊所、做跟電腦圖學相關的東西。那時候是跟廖弘源老師做偏視覺的研究,他做比較多視覺多媒體方面的research。(所以學長還是心繫CS嗎?)對,最後博班還是去念cs了(笑)因為在columbia念EE master的時候,他們很鼓勵去修一些其他所的課。畢業標準是修30學分,我那時只修了10學分電機所的課,其他都跑去修資工所的。Columbia畢業標準不需要一些發表,其實滿多學校不用的,我自己認為美國滿多學校對master的定位只是修一些比較進階的課,並不需要有論文。台灣就比較不一樣,有點像phd之前的預備,而美國就比較像就業導向,沒有很注重論文。'
},
{
title:'在美國的RA經驗',
section:'我有待過兩個實驗室,比較有趣的是我有做一個physical simulation,就是電腦動畫模擬衣服。那個時候他們有一個現成的系統,可以real time design衣服,像是可以改肩線等等,改2d的design時可以即時轉換成3d的圖show出來。以前的作法可能就是真的找一個假人偶,然後把布料釘上去。那樣子很麻煩,有個模擬軟體就比較好。(聽到現在感覺學長的經歷都跟聲音方面的研究沒什麼相關?比較多影像耶)剛剛那個鄭士康老師的專題,他其實就是跟聲音相關的,而且我在columbia也有修些跟聲音相關的課,不過沒有這方面的研究就是了。'
},
{
title:'Gramercy Surgery Center 工作經驗',
section:'(看到學長有在Gramercy Surgery Center當軟體工程師。Gramercy Surgery Center 是個醫療急救單位,那軟體工程師的任務為何?)它就是手術中心,那裡跟台灣的醫療系統不太一樣。在美國,醫生判斷你要做手術,那個醫生可能會在那個醫院幫你做,或是病人自己去外面的手術中心找外科醫生幫你做。那這種手術中心可以提供器材、護理人員等等。因為有各種不同的醫生來request他要在什麼時間做什麼手術,可是他們現成的管理系統很不方便,比較偏像會議管理那種,我就幫他們重寫一個系統安排手術時間。(那學長在美國是看到有一個機會,就去做,還是說這些研究助理,幫手術中心寫系統都是計劃好的?)當然不是,如果有計畫就不會做這些了(笑)。這些是剛好有認識的人介紹,然後就去了。'
},
{
title:'Disney Research - Capture & Effect Internship',
section:'(學長有在disney research 的Capture and effect部門實習過,請問大概是在做什麼?)Disney下面很多不同公司,有做特效、電影或disney world的等等,而disney research就是做很多公司需要的東西,所以做的東西很雜。我加入的是capture and effect,他們有一個系統可以拍很多照,然後reconstruct被拍的東西的3D model,接下來就是我就不能講了。'
}
]
},
{
bigtitle:'六、創業時期與未來展望',
sections:
[
{
title:'電機系學生 v.s. 創業',
section:'(電機系的學生需要什麼特質,才適合創業?何時開始?又,怎樣的個性不適合創業?)要喜歡自己做的事,因為會把所有時間都花在上面。(平常如何分工呢?)沒有明確的分工模式,我們有辦公室,但我們沒有住在一起,還有一個人在台灣。(假設有學弟妹很早就決定要創業,怎麼學習創業?)我自己是沒有準備過創業。我是在過程中學習,但是我也不能說你不需要準備,現在不是有什麼創業學程嗎?不過我也沒有上過這個學程,所以我也沒辦法說什麼。'
},
{
title:'未來聲音科技的突破?',
section:'其實現在很多聲音的公司,趨勢都是希望可以用更方便的方式讓客戶體驗更immersive的東西,可能還要考量到大家都在mobile上面使用。對我們來說就是希望可以成為下一個大家體驗聲音的方式。我們認為單聲道(mono)發明了很久,過了二三十年之後變成stereo,照理說接下來大家會想要環繞聲(surround sound),然而卻沒有很普及。這個東西並不是每個人都會一直在使用,但我們希望能夠把體驗聲音的方式從stereo變成ambidio。'
},
{
title:'未來規劃',
section:'希望是可以繼續做自己喜歡的事,並沒有說幾年之後在變什麼,幾年之後要變什麼。Ambidio短期的計畫就是要讓大家都聽到。(像是現在這樣每天都聽ambidio的聲音出去外面聽會不會覺得怪怪的?)沒有啊,目標就是要讓聽的人回到原始聲音該有的方式,所以如果我的目標就是要讓你自然的聽聲音,那不就和你平常走在馬路上聽聲音一樣嗎?'
},
{
title:'在美國和台灣軟體工程師的差別',
section:'薪水是不一樣,但花費也不一樣。最主要還是看自己喜歡怎麼樣,並不是說你一定要去美國。最大的不同應該還是美國講英文吧。總之還是要做自己喜歡的事情,像是喜不喜歡在美國生活也很重要。(那學長你認為你會一直待在美國嗎)短期之內應該會吧。'
},
{
title:'多媒體產業',
section:'學弟妹想走這行的話,有需要特別增進哪方面的知識嗎?就是,假設想要做類似ambidio這種事情的話,除了顧本科之外,還要做什麼?)這很難講出來,我自己覺得你吸收的知識越廣越好,然後你可以很快的在不同的主題之間移動。(那應該問說,要怎麼吸收這些知識?就是在求學,大學的階段的時候,可能是有什麼雜誌嗎?網站,還是要看論文?)如果是要找新的研究,那就是看最新的論文,例如一個陌生的領域,你會去找這個領域大家最新都在做什麼。當然你很可能看不懂,看不懂的時候就會去找它引用的東西,慢慢一個一個往前找,其實李琳山老師教的課大概就是這個概念。這些知識就是一個金字塔,新的東西都在上面,那你可能會需要很多很多基礎知識才可以達到最上面的東西,但是你沒有辦法去準備把所有基礎知識都弄好。當然基礎知識是學越多越好,不過學最新的科技的方式,就是你要會去找最新的東西,然後慢慢的往回,找出一條路。'
},
{
title:'如果再讀一次大學?',
section:'我如果再讀一次大學,老實說我就不會念電機系,因為如果我知道之後的路,我就不會去念。不過我覺得還是要增加基礎能力,像我剛才講的,你需要有足夠的基礎能力,你會比較容易pick-up之後的東西,因為現在的科技變化很快,但是像數學物理或是邏輯等等是不會改變的,可能就是要更廣泛接觸吧。(所以你想要做computer graphics是大學之後才確定的嗎?)是的。(有考慮過轉去資工系嗎?)可是我那時候已經大三了,來不及了,只好研究所再轉。'
}
]
},
{
bigtitle:' 七、結語',
sections:
[
{
title:'往後5-20年有哪些產業是值得學弟妹投入?',
section:'我覺得這個有點難預測,如果你現在去看二十年前的預測就知道了,所以我也不想要二十年後回頭來看,才發現當初自己亂講話。'
},
{
title:'一句話談談電機系給您的感覺',
section:'我覺得同學都非常厲害,所以你可以從同學中學到很多。聽起來很勢利,但未來對你的生涯都有幫助。'
}
]
},
],
annotation:['特別感謝:謝沛倫','撰寫:鍾興寰 Paulsu Su 陳威成 孫凡耕'],
id:'column_1606'
}
return (
<div>
<Column_content content = {column_1606_article}/>
</div>
)
}
}
export default Column_1606;
|
import React from "react";
import Navbar from "../components/Navbar/Navbar";
import MisEdificios from '../components/MisEdificios/MisEdificios';
function MisEdificiosPage() {
return (
<div>
<Navbar />
<MisEdificios />
</div>
);
}
export default MisEdificiosPage;
|
export const GO_ROOMS = 'GO_ROOMS'
export const BACK_HOME = 'BACK_HOME'
export const Postions = {
HOME: 'HOME',
ROOMS: 'ROOMS',
}
export function goRooms(name) {
console.log("goROms")
console.log(name)
return {type: GO_ROOMS, name}
}
export function backHome() {
console.log("backgome")
return {type: BACK_HOME}
}
|
import { Button,Col, Row, Form, Input, Dropdown, Radio, Checkbox } from "antd"
import { DownOutlined,CloseOutlined } from '@ant-design/icons';
import React, { useState } from "react"
import idea from "../../../assets/images/Banners/great_idea.svg"
import consulting from "../../../assets/images/Banners/consulting.svg"
import { dummy } from "../../../assets/common/Utils/DummyHome"
const Quotation = () => {
const option = (
<div style={{display:"flex",flexDirection:'column',justifyContent:'center',backgroundColor:'#f9f6f6',height:'80px'}} >
{dummy.service.map(item => (
<a style={{margin:'5px 0'}} className="custom-select-link" key={item.id} href="/#">
{item.name}
</a>
))}
</div>
)
const [sectionVisible, setSectionVisible] = useState("quotation")
return (
<div className="quotation">
<div className="container">
{sectionVisible === 'quotation' &&
<>
<div className="animate__animated animate__fadeIn quotation__image">
<img alt={idea} src={idea} />
</div>
<div className="animate__animated animate__fadeIn quotation__main">
<h2 className="primary-title">¿Quieres una cotización de tu idea? </h2>
<p className="paragraphs">
Te ayudamos a seguir el mejor camino para
tu negocio. Solo necesitas continuar y asegurarte antes de empezar
</p>
<Button onClick={()=>setSectionVisible("quotationForm")} className="button--primary">Contáctanos</Button>
</div>
</>
}
{sectionVisible === 'quotationForm' &&
<Row className="animate__animated animate__fadeIn quotationForm">
<Col className="quotationForm__content" lg={12} xs={24}>
<CloseOutlined onClick={()=>setSectionVisible("quotation")} />
<h2 className="paragraphs">Soy</h2>
<Form>
<Radio.Group>
<Row justify="space-between">
<Col lg={12} xs={24}>
<Form.Item>
<Radio value={1}>Persona natural</Radio>
</Form.Item>
</Col>
<Col lg={12} xs={24}>
<Form.Item>
<Radio value={2}>Empresa</Radio>
</Form.Item>
</Col>
</Row>
</Radio.Group>
<Row>
<Col lg={12} xs={24}>
<Form.Item
label="Nombre"
name="name"
rules={[{ required: false, message: 'Tu Nombre es obligatorio!' }]}>
<Input placeholder="Ingrese su nombre" />
</Form.Item>
<Form.Item
label="Numero de documento"
name="document"
rules={[{ required: false, message: 'Tu contacto es obligatorio!', type: 'number' }]}>
<Input placeholder="Ingrese su número de documento" />
</Form.Item>
</Col>
<Col lg={12} xs={24}>
<Form.Item
label="Correo"
name="email"
rules={[{ required: false, message: 'Tu correo es obligatorio!', type: 'email' }]}>
<Input placeholder="Ingrese su número de Correo" />
</Form.Item>
<Form.Item
style={{display:'flex',flexDirection:'row'}}
label="¿Cómo te ayudamos?"
name="type"
rules={[{ required: false, message: 'Consulta obligatoría' }]}>
<Dropdown overlay={option} >
<a onClick={e => e.preventDefault()} className="ant-dropdown-link" >
Seleccionar servicio <DownOutlined />
</a>
</Dropdown>,
</Form.Item>
</Col>
<Row>
<Col lg={20}>
<Form.Item>
<Checkbox >Confirmo que conozco y acepto la Política de Tratamiento
de Datos, Terminos y Condiciones.</Checkbox>
</Form.Item>
</Col>
</Row>
<Col lg={24} className="content-submit">
<Form.Item >
<Button className="button--primary" htmlType="submit" >Enviar</Button>
</Form.Item>
</Col>
</Row>
</Form>
</Col>
<Col lg={12} xs={24} className="content-image">
<img alt={consulting} src={consulting}/>
</Col>
</Row>
}
</div>
</div>
)
}
export default Quotation
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.