text
stringlengths 7
3.69M
|
|---|
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Container, Row } from 'react-bootstrap';
import { Link } from "react-router-dom";
function Home(props){
return(
<Container className = 'm-3'>
<Row>
<h1 className = 'display-5'> The One Stop Shop for Great Recipes</h1>
</Row>
<Row className = 'mt-3'>
<h3>Click any of the links below for a delicious recipe!!</h3>
</Row>
<Row className = 'mt-3'>
<ul>
{props.rec.map(recipe => (
<li key = {recipe.title}>
<Link to={recipe.title}>{recipe.title}</Link>
</li>
))}
</ul>
</Row>
<Row className = 'mt-3'>
<img src="https://www.thecookierookie.com/wp-content/uploads/2020/01/crockpot-taco-meat-beef-tacos-6-of-8-1.jpg" alt = '' height='300' width = '300' className = 'mr-3'></img>
<img src="https://keyassets-p2.timeincuk.net/wp/prod/wp-content/uploads/sites/53/2019/06/Salsa.jpg" alt = '' height='300' width = '400' className = 'ml-3'></img>
</Row>
</Container>
)
}
export default Home;
|
const Answer = require('../models/Answer.js')
function isAnswerOwner(req,res,next){
console.log('masuk checkOwner answer')
let answerId = req.params.answerId
Answer.findById({_id: answerId})
.populate('userId')
.then( answer => {
if(answer.userId.email == req.current_user.email){
console.log('cannot vote yours')
res.status(400).json({message: 'cannot vote yours'})
} else {
next()
}
})
.catch( error => {
res.status(400).json({error, message: error.message})
})
}
module.exports = isAnswerOwner
|
//variable declarations
var express = require('express'),
mongoose = require('mongoose'),
request = require('request'),
User = require("../models/user"),
Channel = require("../models/channel"),
getSubscribersApi = require("../getSubscribersAPI.js");
refreshSubscriberChannels = require("../refreshSubscriberChannels.js");
router = new express.Router();
router.get("/", function(req, res){
//get users
User.find({}, function(err, allUsers) {
res.render('./users/allUsers', { users: allUsers });
})
});
router.get("/myaccount", function(req, res){
//get my account
res.redirect("/users/" + req.user.id);
});
//SHOW video
router.get("/:id", function(req, res){
User
.findById(req.params.id)
.populate('subscriptions')
.exec(function(err, foundUser) {
if(err){
console.log(err)
} else {
res.render("./users/userView", {user: foundUser});
}
})
});
router.get("/:id/subscribers", function(req, res){
refreshSubscriberChannels(req.user, function(err, complete) {
if(err) return err;
res.redirect("/users/" + req.user.id);
})
});
module.exports = router;
|
'use strict'
require('./json')
|
//详情页
//登录后状态页面渲染
html_login();
//页面跳转
html_location();
//商品详情主内容选项卡
$(".col .col_main>ul>li").click(function(e){
//获取下标
$index=$(this).index();
//清除样式
for(var i=0;i<$(".col .col_main .module>div").size();i++){
$(".col .col_main .module>div").eq(i).css("display","none");
$(".col .col_main>ul>li").eq(i).children().attr("class","")
}
//点击切换
$(".col .col_main .module>div").eq($index).css("display","block");
//li样式变化
$(".col .col_main>ul>li").eq($index).children().attr("class","check")
})
//初始化页面渲染
var goods_id=getCookie("list_class");
if(goods_id){
//将商品id插入节点上
$("#goods_info").attr("class",goods_id)
$.ajax({
type:"get",
url:"../api/goods.php",
async:true,
data:{
"mate":"goods_data",//匹配参数
"goods_id":goods_id
},success:function(str){
var data = JSON.parse(str);
data=data[0];
// console.log(data)
//左边图片部分
var goods_imgs=data.goods_img;
goods_imgs=goods_imgs.split("&");
//渲染大图
$(".imgdet .pic>img").attr("src","../"+goods_imgs[0])
$(".imgdet .bigpic>img").attr("src","../"+goods_imgs[0])
var len=goods_imgs.length;
if(len>5){
len=5;
}else{
len=goods_imgs.length
}
//渲染小图
for(var j=0;j<len;j++){
var html="<li><img/><span></span></li>"
$(".imgdet .imglist>ul").append(html);
$(".imgdet .imglist>ul>li").eq(j).children().eq(0).attr("src","../"+goods_imgs[j]);
}
//样式设置
$(".imgdet .imglist>ul>li").eq(0).attr('class',"active")
if(len=5){
$(".imgdet .imglist>ul>li").eq(4).attr('style',"margin-right: 0;")
}
//中间信息部分
//$("").
//标题
$(".info_box>h2").text(data.goods_name);
//原价
$(".info_box .price_cost >del").text("¥"+data.goods_cost_price);
//现价
$(".info_box .property .price").text("¥"+data.goods_price);
//评价
$(".info_box .property .property_extra .pingjia").text(data.goods_assess);
//销量
$(".info_box .property .property_extra .xiaoliang").text(data.goods_sales);
//颜色
var colorimg=data.goods_colorimg.split("&");
for(var i=0;i<colorimg.length-1;i++){
//创建节点
var html="<li><img src=''/></li>"
$(".info_box .goods_style>ul").append(html);
$(".info_box .goods_style>ul>li").eq(i).children().attr("src","../"+colorimg[i]);
}
//尺码
var goods_size=data.goods_size.split("&");
for(var i=0;i<goods_size.length;i++){
//创建节点
var html="<li></li>"
$(".info_box .goods_size>ul").append(html);
$(".info_box .goods_size>ul>li").eq(i).text(goods_size[i]);
}
//库存
$(".info_box .goods_num_box .stock_num").text(data.goods_num)
}
});
}
else{
alert("好像哪里出问题了 !");
window.location.href="list.html";
}
//点击数量加减
//加数量
$('#goods_num_add').on('click',function(){
//给每一个加号绑定事件(用事件委托的方式绑定)
var val=$(this).prev().val();//前一个兄弟元素
val++;//隐式转换
if(val>=10){
//库存量是10.限制最大值
val=10;
return false;
}
//设置内容
$(this).prev().val(val);
});
//减数量
$('.goods_nums').on('click','#goods_num_red',function(){
//给每一个加号绑定事件(用事件委托的方式绑定)
var val=$(this).next().val();
val--;//隐式转换
// console.log(val);
if(val<=1){
//库存量是100.限制最大值
val=1;
}
//设置内容
$(this).next().val(val);
});
//选中尺码
$(".info_box .goods_size>ul").on("click","li",function(){
for(var i=0;i<$(".info_box .goods_size>ul>li").length;i++){
$(".info_box .goods_size>ul>li").eq(i).css("box-shadow","")
$(".info_box .goods_size>ul>li").eq(i).attr('class',"")
}
$(this).css("box-shadow","0 0 10px red");
$(this).attr('class',"size_check")
// var s=$(".info_box .goods_size>ul .size_check").text()
// console.log(s)
})
//加入购物车功能
$(".info_box .tocart").click(function(){
//用户id
var user_id=getCookie("user_id");
//商品id
var goods_id=$("#goods_info").attr("class")
//商品数量
var goods_num=$(".info_box .goods_num_box #goods_num").val();
//尺码
var goods_size=$(".info_box .goods_size>ul .size_check").text();
//是否登录
if(user_id){
//判断是否选择尺码
if(goods_size){
$.ajax({
type:"get",
url:"../api/goods.php",
async:true,
data:{
"mate":"intocart",//匹配参数
"user_id":user_id,
"goods_id":goods_id,
"goods_num":goods_num,
"goods_size":goods_size
},success:function(str){
if(str=="yes"){
alert("添加购物车成功!")
}
}
});
}
else{
alert("请选择尺码!")
}
}else{
var l=confirm("您还未登录,是否要进行登录?")
if(l){
window.open("login.html");
}
}
});
|
import {
BANK_DETAILS_REQUEST,
BANK_DETAILS_SUCCESS,
BANK_DETAILS_FAILURE,
} from './manage-bank-constants';
const bankDetailsRequest = (publicId, getBankSuccessCallback) => ({
getBankSuccessCallback,
publicId,
type: BANK_DETAILS_REQUEST,
});
export const bankDetailsSuccess = (data) => ({
data,
type: BANK_DETAILS_SUCCESS,
});
export const bankDetailsFailure = () => ({
type: BANK_DETAILS_FAILURE,
});
export const getBankData = async (
publicId,
getBankSuccessCallback,
dispatch
) => {
dispatch(bankDetailsRequest(publicId, getBankSuccessCallback));
};
|
import React from 'react';
import FilterDefs from './FilterDefs';
/*
attribute - filter field name
values - selected values
label - header label
onFilter - callback for state change
*/
export default React.createClass({
getInitialState: function() {
let values = this.props.values || [];
let set = {};
FilterDefs[this.props.attribute].values.forEach((val) => {
set[val] = values.length > 0 ? values.indexOf(val) >= 0 : true;
});
return set;
},
handleChange: function(event) {
var state = {};
state[event.target.value] = event.target.checked;
this.setState(state, () => {
let selected = Object.keys(this.state).filter((key) => {
return this.state[key];
});
this.props.onFilter(this.props.attribute, selected);
});
},
render() {
let attr = this.props.attribute;
let filter = FilterDefs[attr].values.map((val) => {
let id = `${val}Checkbox`;
let iconClasses = `${attr} ${val} checkbox-icon`;
return (
<div className="filter-checkbox" key={val}>
<input type="checkbox" value={val} id={id} onChange={this.handleChange} checked={this.state[val]} className="valign"/>
<label htmlFor={id} className="checkbox-label">
<i className={iconClasses} />
<span className="checkbox-text">{FilterDefs[attr].labels[val]}</span>
</label>
</div>
);
});
return (
<div className="filter">
<div className="filter-name">{this.props.label}</div>
{filter}
</div>
);
}
});
|
import React from 'react';
import { TextInput, View } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { string, func } from 'prop-types';
import { colors } from '@config/style';
import styles from './style';
const Input = ({ icon, value, action, placeholder }) => {
return (
<View style={styles.container}>
{icon && <Icon name={icon} size={22} color={colors.DarkGray} />}
<TextInput
onChangeText={(typed) => action(typed)}
value={value}
placeholder={placeholder}
style={styles.input}
/>
</View>
);
};
Input.defaultProps = {
// icon: ''
};
Input.propTypes = {
icon: string,
value: string.isRequired,
action: func.isRequired,
placeholder: string.isRequired,
};
export default Input;
|
"use strict";
// Controller
function Homepage(app, req, res) {
// HTTP action
this.action = (params) => {
// Response data
const data = {
success: true,
title: 'Hello World',
logged: req.session.get('logged')
};
// Send response
app.render(res, data, 'homepage', 'layout');
};
};
module.exports = Homepage;
|
import {
request
} from './request';
// 匹配结果批次查询 /match/batchList
export function getBatchList(){
return request({
method:'GET',
url:'/match/batchList',
})
}
// 匹配记录查询 /match/recordList
export const getRecordList = data => {
return request({
url: `/match/recordList`,
method: 'GET',
params: data
})
}
// 添加匹配结果 /match/addResult
export const addppResult=data=>{
return request({
method:'POST',
url:'/match/addResult',
params:data
})
}
// 删除匹配结果 /match/delRecord
export const deleterecord=matchRecordIds=>{
// console.log(data);
return request({
method:'DELETE',
url:'/match/delRecord',
params:{
matchRecordIds
}
})
}
// 导出文件大下 /stage-api/match/export/excel excel导出
export const getRecordexcl = data => {
return request({
url: `/match/export/excel`,
method: 'POST',
params:data
})
}
// 导出/match/export/world world
export const getRecordworld = data => {
return request({
url: `/match/export/world`,
method: 'POST',
params:data
})
}
|
// Frequency Counters
// Write a function called same, which accepts two arrays.
// The function should return true if every value in the
// array has it's corresponding value squared in the second
// array. The frequency of values must be the same.
//**** Naive Solution */
// This is a naive solution because it is O(n^2) time because of the nested loop.
// function same(arr1, arr2) {
// if(arr1.length != arr2.length) { // first checks if the two arrays are the same length
// return false;
// }
// for(let i = 0; i < arr1.length; i++) {
// let correctIndex = arr2.indexOf(arr1[i] ** 2) // call indexOf where we pass in the square of each value-- what is the index of i^2 in the second array
// if(correctIndex === -1) { // if the corrected index is -1, meaning that it is not in the second array, return false
// return false;
// }
// arr2.splice(correctIndex, 1) // removes the indexOf i^2 from the second array
// }
// return true // iterate through the array, and if we never return false we return true
// }
//** Refactored **//
// Time Complexity = O(n)
const same = (arr1, arr2) => {
if(arr1.length != arr2.length) {
return false;
}
let frequencyCounter1 = {} // count frequency of individual values in the array-- compiling an object that tells us how many times a value is in that array
let frequencyCounter2 = {}
for(let val of arr1) {
frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1
}
for(let val of arr2) {
frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1
}
for(let key in frequencyCounter1) {
if(!(key ** 2 in frequencyCounter2)) { // if key value of frequencyCounter1[i] is not presented and squared in frequencyCounter2, return false
return false
}
if(frequencyCounter2[key ** 2] !== frequencyCounter1[key]){ // checking to see if frequency of the values is the same by measuring truthy values
return false
}
}
return true
}
// console.log(same([1,2,3], [4,4,9]))
/** Anagrams */
// Given two strings, write a function to determine if the
// second string is an anagram of the first. An anagram is
// a word, phrase, or name formed by rearranging the
// letters of another, such as cinema, formed iceman.
function validAnagram(first, second) {
if (first.length !== second.length) {
return false;
}
const lookup = {};
for (let i = 0; i < first.length; i++) {
let letter = first[i];
//if letter exists, increment, otherwise set to 1
lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;
}
for (let i = 0; i < second.length; i++) {
let letter = second[i];
// can't find letter or letter is zero then it's not an anagrams
if (!lookup[letter]) {
return false;
} else {
lookup[letter] -= 1;
}
}
return true;
}
console.log(validAnagram("aaron", "noraa"))
|
/*
Enunciado:
Bienvenidos.
Pedir por prompt el precio y el porcentaje de descuento, mostrar el precio final con descuento por id.
*/
function mostrar()
{
var precio;
var descuento;
var precioFinal;
precio = parseInt(prompt("Ingrese el precio: "));
while(precio < 0 || isNaN(precio)){
alert("PRECIO INVALIDO");
precio = parseInt(prompt("Reingrese el precio: "));
}
descuento = parseInt(prompt("Ingrese el porcentaje de descuento"));
while(descuento < 0 || descuento > 100 || isNaN(descuento)){
alert("DESCUENTO INVALIDO");
descuento = parseInt(prompt("Reingrese el porcentaje de descuento (0-100)"));
}
precioFinal = ((100 - descuento) * precio) / 100;
document.getElementById('elPrecioFinal').value = precioFinal;
}
|
/*
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.require('claat.ui.cards.Sorter');
window['CardSorter'] = claat.ui.cards.Sorter;
/** @export */
claat.ui.cards.Sorter.prototype.sort;
/** @export */
claat.ui.cards.Sorter.prototype.filter;
/** @export */
claat.ui.cards.Sorter.prototype.filterByCategory;
/** @export */
claat.ui.cards.Sorter.prototype.filterByText;
/** @export */
claat.ui.cards.Sorter.prototype.filterByTags;
/** @export */
claat.ui.cards.Sorter.prototype.clearFilters;
/** @type {claat.ui.cards.Filter} */
var f;
/** @export */
f.cat;
/** @export */
f.text;
/** @export */
f.tags;
/** @export */
f.kioskTags;
|
import login from './index';
describe('Controller: Login', function() {
var $rootScope, $controller, $q, $state, ctrl, auth;
beforeEach(angular.mock.module(login));
beforeEach(angular.mock.inject(function(_$controller_, _$q_, _$rootScope_, _$state_, _auth_) {
$rootScope = _$rootScope_;
$q = _$q_;
$state = _$state_;
auth = _auth_;
$controller = _$controller_;
ctrl = $controller('LoginController', {auth: auth});
}));
it('#login redirects home', function() {
spyOn(auth, 'login').and.returnValue($q.when());
spyOn($state, 'go');
ctrl.user = {
name: 'user',
pass: 'name'
};
ctrl.login();
$rootScope.$digest();
expect($state.go).toHaveBeenCalledWith('home');
});
});
|
/*var fname=prompt("What is your first name?");
var lname=prompt("What is your last name?");
var age=prompt("What is your age?");
alert("Welcome to our website "+fname+" "+lname);
alert("You are "+age+" years old brat.");
console.log("Welcome to our website "+fname+" "+lname+" \nYou are "+age+" years old brat.");
*/
/*
var t=prompt("What would you like to do with the list\n 1.new\n2.list\n3.quit\n");
var list=["yo"];
while(t!="quit")
{
if (t=="new")
{
var listed=prompt("Enter your todo");
list.push(listed);
}
else
if (t=="list")
{
console.log(list);
}
else if (t=="delete")
{
list.pop(listed);
}
t=prompt("What would you like to do with the list\n 1.new\n2.list\n3.quit\n");
}
console.log("It was good meeting you.");
*/
/*
var colors=["red","orange","yellow","green"];
colors.forEach(function(color){
console.log(color);
});
*/
//console.log("connected");
/*function isUniform(arr){
var first = arr[0];
var flag=0;
for(var i=1;i<arr.length;i++){
if(arr[i]!==first)
{
//console.log("false\n");
flag=1;
}
}
if(flag==0)
console.log("true\n");
else
console.log("false");
}
isUniform([1,2,2,3,1]);
isUniform([1,2,3,1]);
isUniform([1,1,1]);
*/
/*
function sA(arr)
{
var total=0;
for (var i = 0; i < arr.length; i++) {
total=total+arr[i];
}
console.log(total);
}
sA([1,2,2,3,1]);
sA([1,2,2,2,1]);
*/
/*
function max(arr)
{
var max=arr[0];
for (var i = 1; i < arr.length; i++) {
console.log(arr[i]);
if(arr[i]>max)
{
max=arr[i];
}
}
console.log(max);
}
var t=prompt("Enter the numbers of numeric data to be compared");
var arr=[0];
for (var i = 0; i < t; i++) {
var listed=prompt("Enter your data");
arr.push(listed);
}
max(arr);
*/
var movies=[
{
title:"interstellar",
done:true,
rating: 4.5
},
{
title:"gravity",
done:false,
rating: 4.2
}
]
var chunnilal;
movies.forEach(function(lol)
{
if(lol.done)
{
chunnilal="watched";
}
else
{
chunnilal="not watched";
}
console.log("You have: "+chunnilal+" "+lol.title);
})
//phoad(movies);
|
$(document).on("submit", "form", function (event) { // kada je submitovana forma za kreiranje novog zaposlenog
event.preventDefault();
var name = $("#name").val();
var address = $("#address").val();
var description = $("#description").val();
var newUserJSON = formToJSON(name,address,description);
$.ajax({
type: "POST",
url: "http://localhost:8081/systemadmins/signupPharmacy",
dataType: "json",
contentType: "application/json",
data: newUserJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function () {
alert("success");
window.location.href = "adminSystemHomePage.html";
},
error: function (error) {
alert(error);
}
});
});
function formToJSON(name,address,description) {
return JSON.stringify(
{
"name": name,
"address": address,
"description": description,
}
);
};
|
import React from 'react';
import Restaurant from './Restaurant';
import {
createFragmentContainer,
graphql
} from 'react-relay';
import {
Link
} from 'react-router-dom';
class Restaurants extends React.Component {
render() {
return (
<div className="App-content">
<Link to="restaurants/create" className="pt-button pt-icon-add">Create New</Link>
<table className="pt-table" style={{width:'100%'}}>
<thead>
<tr>
<th>Name</th>
<th>Cuisine</th>
<th></th>
</tr>
</thead>
<tbody>
{this.props.viewer.allRestaurants.edges.map(({node}) => {
return <Restaurant key={node.__id} restaurant={node} viewer={this.props.viewer} />;
})}
</tbody>
</table>
</div>
)
}
}
export default createFragmentContainer(Restaurants, graphql`
fragment Restaurants_viewer on Viewer {
allRestaurants(
first: 1000
) @connection(key: "Restaurants_allRestaurants") {
edges {
node {
...Restaurant_restaurant
}
}
}
id
}
`)
|
//load map and itinerary data
const resItin = await fetch("data/itin.json")
const resWorld = await fetch("data/world.json")
let itin = await resItin.json()
let borders = await resWorld.json()
//get size of container
let width = d3.select("#container").node().getBoundingClientRect().width
let height = d3.select("#container").node().getBoundingClientRect().height
//add svg to container
let svg = d3.select("#container")
.append("svg")
.attr("width", width)
.attr("height", height)
//initialize geo-orthographic projection
let projection = d3.geoOrthographic()
.scale(250)
.center([0, 0])
.rotate([0, -30])
.translate([width / 2, height / 2])
//store initial scale
const initialScale = projection.scale()
//initialize path generator for the projection
let path = d3.geoPath().projection(projection)
//create projection background (a circle)
let globe = svg.append("circle")
.attr("fill", "#000")
.attr("stroke", "#000")
.attr("stroke-width", "0.2")
.attr("cx", width/2)
.attr("cy", height/2)
.attr("r", initialScale)
//create svg group
let map = svg.append("g")
//add country borders
map.append("g")
.attr("class", "countries" )
.selectAll("path")
.data(borders.features)
.enter().append("path")
.attr("d", path)
.attr("fill", "white")
.style('stroke', 'black')
.style('stroke-width', 0.35)
//plot points
const pinRadius = 1.7
svg.selectAll(null)
.data(itin)
.enter()
.append("path")
.each(function(d){
d3.select(this).datum({type: 'Point', coordinates: [d.lon, d.lat]})
.attr("d", path.pointRadius(pinRadius))
.attr("fill", "red")
})
//rotate
const sensitivity = 75
const speed = 200
const t = d3.timer(function(elapsed) {
const rotate = projection.rotate()
const k = sensitivity / projection.scale()
projection.rotate([
rotate[0] - 1 * k,
rotate[1]
])
path = d3.geoPath().projection(projection)
svg.selectAll("path").attr("d", path.pointRadius(pinRadius))
}, speed)
//respond to drag
svg.call(d3.drag().on("drag", (event) => {
const rotate = projection.rotate()
const k = sensitivity / projection.scale()
projection.rotate([
rotate[0] + event.dx * k,
rotate[1] - event.dy * k
])
path = d3.geoPath().projection(projection)
svg.selectAll("path").attr("d", path.pointRadius(pinRadius))
}))
//respond to scale slider change
d3.select("#scaleSlider").on("change", function(d){
projection.scale(this.value)
globe.attr("r", this.value)
})
//respond to scale reset button click
d3.select("#scaleResetButton").on("click", function() {
projection.scale(initialScale)
globe.attr("r", initialScale)
d3.select("#scaleSlider").property("value", initialScale)
})
|
const INPUT = require('./input');
// SOLUTION: 3409710
const arr = INPUT.split(',').map(Number);
arr[1] = 12;
arr[2] = 2;
const applyOperations = arr => {
for (let i = 0; i < arr.length; i += 4) {
const opcode = arr[i];
const firstValue = arr[i + 1];
const secondValue = arr[i + 2];
const memoryAddress = arr[i + 3];
if (opcode === 99) {
return;
}
if (opcode === 1) {
arr[memoryAddress] = arr[firstValue] + arr[secondValue];
} else if (opcode === 2) {
arr[memoryAddress] = arr[firstValue] * arr[secondValue];
} else {
throw Error(`UNKNOWN OPERATION: ${opcode}`);
}
}
};
applyOperations(arr);
console.log(arr[0]);
|
/**
* @license
* Copyright 2016 Google 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.
*/
goog.provide('shaka.polyfill.Promise');
goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.polyfill.register');
/**
* @summary A polyfill to implement Promises, primarily for IE.
* Only partially supports thenables, but otherwise passes the A+ conformance
* tests.
* Note that Promise.all() and Promise.race() are not tested by that suite.
*
* @constructor
* @struct
* @param {function(function(*), function(*))=} opt_callback
* @template T
*/
shaka.polyfill.Promise = function(opt_callback) {
/** @private {!Array.<shaka.polyfill.Promise.Child>} */
this.thens_ = [];
/** @private {!Array.<shaka.polyfill.Promise.Child>} */
this.catches_ = [];
/** @private {shaka.polyfill.Promise.State} */
this.state_ = shaka.polyfill.Promise.State.PENDING;
/** @private {*} */
this.value_;
// External callers must supply the callback. Internally, we may construct
// child Promises without it, since we can directly access their resolve_ and
// reject_ methods when convenient.
if (opt_callback) {
try {
opt_callback(this.resolve_.bind(this), this.reject_.bind(this));
} catch (e) {
this.reject_(e);
}
}
};
/**
* @typedef {{
* promise: !shaka.polyfill.Promise,
* callback: (function(*)|undefined)
* }}
*
* @summary A child promise, used for chaining.
* @description
* Only exists in the context of a then or catch chain.
* @property {!shaka.polyfill.Promise} promise
* The child promise.
* @property {(function(*)|undefined)} callback
* The then or catch callback to be invoked as part of this chain.
*/
shaka.polyfill.Promise.Child;
/**
* @enum {number}
*/
shaka.polyfill.Promise.State = {
PENDING: 0,
RESOLVED: 1,
REJECTED: 2
};
/**
* Install the polyfill if needed.
* @param {boolean=} opt_force If true, force the polyfill to be installed.
* Used in some unit tests.
*/
shaka.polyfill.Promise.install = function(opt_force) {
// Decide on the best way to invoke a callback as soon as possible.
// Precompute the setImmediate/clearImmediate convenience methods to avoid the
// overhead of this switch every time a callback has to be invoked.
if (window.setImmediate) {
// For IE and node.js:
shaka.polyfill.Promise.setImmediate_ = function(callback) {
return window.setImmediate(callback);
};
shaka.polyfill.Promise.clearImmediate_ = function(id) {
return window.clearImmediate(id);
};
} else {
// For everyone else:
shaka.polyfill.Promise.setImmediate_ = function(callback) {
return window.setTimeout(callback, 0);
};
shaka.polyfill.Promise.clearImmediate_ = function(id) {
return window.clearTimeout(id);
};
}
if (window.Promise && !opt_force) {
shaka.log.info('Using native Promises.');
return;
}
shaka.log.info('Using Promises polyfill.');
// Quoted to work around type-checking, since our then() signature doesn't
// exactly match that of a native Promise.
window['Promise'] = shaka.polyfill.Promise;
// Explicitly installed because the compiler won't necessarily attach them
// to the compiled constructor. Exporting them will only attach them to
// their original namespace, which isn't the same as attaching them to the
// constructor unless you also export the constructor.
window['Promise'].resolve = shaka.polyfill.Promise.resolve;
window['Promise'].reject = shaka.polyfill.Promise.reject;
window['Promise'].all = shaka.polyfill.Promise.all;
window['Promise'].race = shaka.polyfill.Promise.race;
// These are manually exported as well, because allowing the compiler to
// export them for us will cause the polyfill to end up in our generated
// externs. Since nobody should be accessing this directly using the
// shaka.polyfill namespace, it is okay not to @export these methods.
window['Promise']['prototype']['then'] =
shaka.polyfill.Promise.prototype.then;
window['Promise']['prototype']['catch'] =
shaka.polyfill.Promise.prototype.catch;
};
/**
* Uninstall the polyfill. Used in some unit tests.
*/
shaka.polyfill.Promise.uninstall = function() {
// Do nothing if there is no native implementation.
if (shaka.polyfill.Promise.nativePromise_) {
shaka.log.info('Removing Promise polyfill.');
window['Promise'] = shaka.polyfill.Promise.nativePromise_;
shaka.polyfill.Promise.q_ = [];
}
};
/**
* @param {*} value
* @return {!shaka.polyfill.Promise}
*/
shaka.polyfill.Promise.resolve = function(value) {
var p = new shaka.polyfill.Promise();
p.resolve_(undefined);
return p.then(function() {
return value;
});
};
/**
* @param {*} reason
* @return {!shaka.polyfill.Promise}
*/
shaka.polyfill.Promise.reject = function(reason) {
var p = new shaka.polyfill.Promise();
p.reject_(reason);
return p;
};
/**
* @param {!Array.<!shaka.polyfill.Promise>} others
* @return {!shaka.polyfill.Promise}
*/
shaka.polyfill.Promise.all = function(others) {
var p = new shaka.polyfill.Promise();
if (!others.length) {
p.resolve_([]);
return p;
}
// The array of results must be in the same order as the array of Promises
// passed to all(). So we pre-allocate the array and keep a count of how
// many have resolved. Only when all have resolved is the returned Promise
// itself resolved.
var count = 0;
var values = new Array(others.length);
var resolve = function(p, i, newValue) {
goog.asserts.assert(p.state_ != shaka.polyfill.Promise.State.RESOLVED,
'Invalid Promise state in Promise.all');
// If one of the Promises in the array was rejected, this Promise was
// rejected and new values are ignored. In such a case, the values array
// and its contents continue to be alive in memory until all of the Promises
// in the array have completed.
if (p.state_ == shaka.polyfill.Promise.State.PENDING) {
values[i] = newValue;
count++;
if (count == values.length) {
p.resolve_(values);
}
}
};
var reject = p.reject_.bind(p);
for (var i = 0; i < others.length; ++i) {
if (others[i] && others[i].then) {
others[i].then(resolve.bind(null, p, i), reject);
} else {
resolve(p, i, others[i]);
}
}
return p;
};
/**
* @param {!Array.<!shaka.polyfill.Promise>} others
* @return {!shaka.polyfill.Promise}
*/
shaka.polyfill.Promise.race = function(others) {
var p = new shaka.polyfill.Promise();
// The returned Promise is resolved or rejected as soon as one of the others
// is.
var resolve = p.resolve_.bind(p);
var reject = p.reject_.bind(p);
for (var i = 0; i < others.length; ++i) {
if (others[i] && others[i].then) {
others[i].then(resolve, reject);
} else {
resolve(others[i]);
}
}
return p;
};
/**
* @param {function(*)=} opt_successCallback
* @param {function(*)=} opt_failCallback
* @return {!shaka.polyfill.Promise}
*/
shaka.polyfill.Promise.prototype.then = function(opt_successCallback,
opt_failCallback) {
// then() returns a child Promise which is chained onto this one.
var child = new shaka.polyfill.Promise();
switch (this.state_) {
case shaka.polyfill.Promise.State.RESOLVED:
// This is already resolved, so we can chain to the child ASAP.
this.schedule_(child, opt_successCallback);
break;
case shaka.polyfill.Promise.State.REJECTED:
// This is already rejected, so we can chain to the child ASAP.
this.schedule_(child, opt_failCallback);
break;
case shaka.polyfill.Promise.State.PENDING:
// This is pending, so we have to track both callbacks and the child
// in order to chain later.
this.thens_.push({ promise: child, callback: opt_successCallback});
this.catches_.push({ promise: child, callback: opt_failCallback});
break;
}
return child;
};
/**
* @param {function(*)=} opt_callback
* @return {!shaka.polyfill.Promise}
*/
shaka.polyfill.Promise.prototype.catch = function(opt_callback) {
// Devolves into a two-argument call to 'then'.
return this.then(undefined, opt_callback);
};
/**
* @param {*} value
* @private
*/
shaka.polyfill.Promise.prototype.resolve_ = function(value) {
// Ignore resolve calls if we aren't still pending.
if (this.state_ == shaka.polyfill.Promise.State.PENDING) {
this.value_ = value;
this.state_ = shaka.polyfill.Promise.State.RESOLVED;
// Schedule calls to all of the chained callbacks.
for (var i = 0; i < this.thens_.length; ++i) {
this.schedule_(this.thens_[i].promise, this.thens_[i].callback);
}
this.thens_ = [];
this.catches_ = [];
}
};
/**
* @param {*} reason
* @private
*/
shaka.polyfill.Promise.prototype.reject_ = function(reason) {
// Ignore reject calls if we aren't still pending.
if (this.state_ == shaka.polyfill.Promise.State.PENDING) {
this.value_ = reason;
this.state_ = shaka.polyfill.Promise.State.REJECTED;
// Schedule calls to all of the chained callbacks.
for (var i = 0; i < this.catches_.length; ++i) {
this.schedule_(this.catches_[i].promise, this.catches_[i].callback);
}
this.thens_ = [];
this.catches_ = [];
}
};
/**
* @param {!shaka.polyfill.Promise} child
* @param {function(*)|undefined} callback
* @private
*/
shaka.polyfill.Promise.prototype.schedule_ = function(child, callback) {
goog.asserts.assert(this.state_ != shaka.polyfill.Promise.State.PENDING,
'Invalid Promise state in Promise.schedule_');
var Promise = shaka.polyfill.Promise;
var wrapper = function() {
if (callback && typeof callback == 'function') {
// Wrap around the callback. Exceptions thrown by the callback are
// converted to failures.
try {
var value = callback(this.value_);
} catch (exception) {
child.reject_(exception);
return;
}
// According to the spec, 'then' in a thenable may only be accessed once
// and any thrown exceptions in the getter must cause the Promise chain
// to fail.
var then;
try {
then = value && value.then;
} catch (exception) {
child.reject_(exception);
return;
}
if (value instanceof Promise) {
// If the returned value is a Promise, we bind it's state to the child.
if (value == child) {
// Without this, a bad calling pattern can cause an infinite loop.
child.reject_(new TypeError('Chaining cycle detected'));
} else {
value.then(child.resolve_.bind(child), child.reject_.bind(child));
}
} else if (then) {
// If the returned value is thenable, chain it to the child.
Promise.handleThenable_(value, then, child);
} else {
// If the returned value is not a Promise, the child is resolved with
// that value.
child.resolve_(value);
}
} else if (this.state_ == Promise.State.RESOLVED) {
// No callback for this state, so just chain on down the line.
child.resolve_(this.value_);
} else {
// No callback for this state, so just chain on down the line.
child.reject_(this.value_);
}
};
// Enqueue a call to the wrapper.
Promise.q_.push(wrapper.bind(this));
if (Promise.flushTimer_ == null) {
Promise.flushTimer_ = Promise.setImmediate_(Promise.flush);
}
};
/**
* @param {!Object} thenable
* @param {Function} then
* @param {!shaka.polyfill.Promise} child
* @private
*/
shaka.polyfill.Promise.handleThenable_ = function(thenable, then, child) {
var Promise = shaka.polyfill.Promise;
try {
var sealed = false;
then.call(thenable, function(value) {
if (sealed) return;
sealed = true;
var nextThen;
try {
nextThen = value && value.then;
} catch (exception) {
child.reject_(exception);
return;
}
if (nextThen) {
Promise.handleThenable_(value, nextThen, child);
} else {
child.resolve_(value);
}
}, child.reject_.bind(child));
} catch (exception) {
child.reject_(exception);
}
};
/**
* Flush the queue of callbacks.
* Used directly by some unit tests.
*/
shaka.polyfill.Promise.flush = function() {
var Promise = shaka.polyfill.Promise;
// Flush as long as we have callbacks. This means we can finish a chain more
// quickly, since we avoid the overhead of multiple calls to setTimeout, each
// of which has a minimum resolution of as much as 15ms on IE11.
// This helps to fix the out-of-order task bug on IE:
// https://github.com/google/shaka-player/issues/251#issuecomment-178146242
while (Promise.q_.length) {
// Callbacks may enqueue other callbacks, so clear the timer ID and swap the
// queue before we do anything else.
if (Promise.flushTimer_ != null) {
Promise.clearImmediate_(Promise.flushTimer_);
Promise.flushTimer_ = null;
}
var q = Promise.q_;
Promise.q_ = [];
for (var i = 0; i < q.length; ++i) {
q[i]();
}
}
};
/**
* @param {function()} callback
* @return {number}
* Schedule a callback as soon as possible.
* Bound in shaka.polyfill.Promise.install() to a specific implementation.
* @private
*/
shaka.polyfill.Promise.setImmediate_ = function(callback) { return 0; };
/**
* @param {number} id
* Clear a scheduled callback.
* Bound in shaka.polyfill.Promise.install() to a specific implementation.
* @private
*/
shaka.polyfill.Promise.clearImmediate_ = function(id) {};
/**
* A timer ID to flush the queue.
* @private {?number}
*/
shaka.polyfill.Promise.flushTimer_ = null;
/**
* A queue of callbacks to be invoked ASAP in the next frame.
* @private {!Array.<function()>}
*/
shaka.polyfill.Promise.q_ = [];
/** @private {?} */
shaka.polyfill.Promise.nativePromise_ = window.Promise;
shaka.polyfill.register(shaka.polyfill.Promise.install);
|
/* global G7 */
$(function() {
'use strict';
(function($, window, undefined) {
/**
* @name Services
* @memberof G7.Pages
* @description Holds the developer defined Services Behavior Methods.
*/
G7.Pages.Services = (function() {
/**
* @scope G7.Pages.Services
* @description Exposed methods from the G7.Pages.Services Module.
*/
return {
/**
* @name init
* @description G7.Pages.Services Module Constructor.
*/
init: (function() {
})(),
/**
* @name highlightService
* @description add css class to a service selected from navigation.
*/
highlightService: function(service) {
var cssClass = 'highlight',
param;
if ( !service ) {
param = G7.Utils.getUrlParam('service');
} else {
param = service;
}
var $element = $('#' + param);
$('.' + cssClass).removeClass(cssClass); // Removes class from any previously selected element
if(param) {
$element.addClass(cssClass);
$('html,body').animate({
scrollTop: $element.offset().top - 120
}, 500);
}
}
};
}());
})(jQuery, window);
});
|
import React from "react";
import styled from "styled-components";
import { Collapse } from "react-collapse";
const Content = styled.div`
color: ${props => props.theme.tabordion.content.color};
background: ${props => props.theme.tabordion.active.background};
padding: ${props => props.theme.tabordion.padding}em
${props => props.theme.tabordion.padding / 2}em 0;
overflow: hidden;
`;
class AccordionContent extends React.Component {
render() {
const { children, ...rest } = this.props;
return (
<Collapse {...rest}>
<Content>{children}</Content>
</Collapse>
);
}
}
export default AccordionContent;
|
import React from "react";
import Register from "./components/Register/Register";
import Navigation from "./components/Navigation/Navigation";
import Login from "./components/Login/Login";
import Dashboard from "./components/Dashboard/Dashboard";
import "./App.css";
const initialState = {
signedIn: false,
route: "register",
user: {
faculty_id: "",
name: "",
email: "",
college: "",
classes: [],
},
};
class App extends React.Component {
constructor() {
super();
this.state = initialState;
}
loadUser = (user) => {
this.setState({ user });
};
routeChange = (route) => {
if (route === "dashboard") {
this.setState({ signedIn: true });
} else {
this.setState(initialState);
}
this.setState({ route });
};
render() {
console.log(this.state);
const { signedIn, route, user } = this.state;
let form;
if (route === "login") {
form = <Login loadUser={this.loadUser} routeChange={this.routeChange} />;
} else if (route === "register") {
form = (
<Register loadUser={this.loadUser} routeChange={this.routeChange} />
);
}
return (
<div className="App">
<Navigation signedIn={signedIn} routeChange={this.routeChange} />
{!signedIn ? form : <Dashboard user={user} loadUser={this.loadUser} />}
</div>
);
}
}
export default App;
|
var moduleSchema = require('../module');
var _ = require('lodash');
moduleSchema = _.cloneDeep(moduleSchema);
_.extend(moduleSchema.properties, {
'sort-order': {
type: 'string',
required: true,
enum: ['ascending', 'descending']
},
'sort-by': {
type: 'string',
required: true
}
});
module.exports = moduleSchema;
|
$(function(){
var bus_id = 0;
var bus_number;
var lat,lon;
var map,marker,currentCenter,currentPath;
var coord_array = new Array();
var msg_array = new Array();
var marker = new Array();
var buses_list = new Array();
var i=0;
var hidden = true;
$(".progress-ring").show();
/* PUSHER CODE */
// var pusher = new Pusher('38c410e14df2239c04ab');
// var channel = pusher.subscribe('track-channel');
// channel.bind('bus-moved', function(data) {
// //if(data.bus_id == bus_id)
// push_data(data); // Checks if the data is for the same bus route.
// });
/* PUSHER CODE END */
/* SOCKETBOX CODE */
var socket = new SocketBox('apikey');
socket.subscribe('track-channel');
socket.bind('bus-moved', function(data) {
push_data(data);
});
/* SOCKETBOX CODE END */
// Initialization Code for Google Maps
function initialize()
{
if(bus_id==0)
{
currentCenter = coord_array[i-1];
var mapProp = {
center: currentCenter,
zoom:11,
zoomControl: true,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
for(var ctr=0;ctr<i;ctr++) {
marker[ctr]=new google.maps.Marker({
position: coord_array[ctr],
title : msg_array[ctr],
icon:'/static/img/bus_position_marker.png',
});
marker[ctr].setMap(map);
}
}
else {
currentCenter = coord_array[i-1];
var mapProp = {
center: currentCenter,
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
marker=new google.maps.Marker({
position: currentCenter,
icon:'/static/img/bus_position_marker.png',
//animation:google.maps.Animation.BOUNCE
});
marker.setMap(map);
currentPath=new google.maps.Polyline({
path:coord_array,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2
});
currentPath.setMap(map);
}
done_loading();
}
function setMarker(pos) {
currentPath.setPath(coord_array);
map.setCenter(pos);
marker.setPosition(pos);
}
function get_some_default_values() {
// Fills the table during the first run.
// Gets around 50 last values from the table.
if(bus_id==0)
{
$(".page-header-all-stats").html("<h2>Current State Of All Buses </h2>");
$.ajax({
async: false,
dataType: "json",
url: "/ajax/buses_status",
success: function(data)
{
console.log("Status of all buses...");
console.log(data);
$(".stats-table-body").html("");
coord_array = [];
msg_array = [];
i=0;
$.each(data, function(key,value) {
lat = value.lat;
lon = value.lon;
speed = value.speed;
time = value.time;
address_json_string = value.address;
address_json = JSON.parse(address_json_string);
address = address_json.address;
current_bus_id = value.id;
current_bus_number = value.number;
buses_list.push( {
id: current_bus_id,
number: current_bus_number,
});
time = parse_time(time);
append_table(current_bus_id, current_bus_number, address, time);
var pos = new google.maps.LatLng(lat,lon);
msg_array[i] = "BUS "+value.number+" was last updated on "+time;
coord_array[i++] = pos;
});
console.log(coord_array);
}
});
}
else {
$.each(buses_list, function(key,val) {
if(val.id==bus_id) {
bus_number=val.number;
$(".page-header-stats").html("<h2>Current State - "+bus_number+" </h2>");
}
});
$.ajax({
async: false,
dataType: "json",
url: "/ajax/last_trip/"+bus_id,
success: function(data) {
console.log("Data from the Previous coordinates...");
data = data.reverse();
console.log(data);
coord_array = [];
i=0;
$.each(data, function(key,value) {
var pos = new google.maps.LatLng(value.lat,value.lon);
coord_array[i++] = pos;
var data=value;
lat = data.lat;
lon = data.lon;
speed = data.speed;
time = data.time;
});
time = parse_time(time);
update_table(lat,lon,time,"Last Trip",speed,'');
console.log(coord_array);
}
});
}
}
get_some_default_values();
console.log("after the synchronous ajax call...");
google.maps.event.addDomListener(window, 'load', initialize);
// Called after the maps is loaded...
// Shows the table, and hides the loading bar.
function done_loading() {
if(hidden) {
$(".bus-details").show();
$(".progress-ring").hide();
$(".progress-ring").addClass("hidden");
hidden = false;
}
$('.bus-route-selector').removeAttr('disabled');
}
// This is called whenever a new value enters the database.
function push_data(data) {
console.log(data);
var oldlat = lat;
var oldlon = lon;
lat = data.lat;
lon = data.lon;
speed = data.speed;
time = data.time;
time = parse_time(time);
current_bus_id = data.bus_id;
address_json_string = data.address;
address_json = JSON.parse(address_json_string);
address = address_json.address;
if(bus_id==0) {
update_all_buses_stats(current_bus_id, address, time);
if( lat != oldlat || lon != oldlon ) {
var newLatLng = new google.maps.LatLng(lat, lon);
marker[current_bus_id-1].setPosition(newLatLng);
}
}
else if(data.bus_id==bus_id) {
if( lat == oldlat && lon == oldlon )
update_table(lat,lon,time,"Not Moved",speed,address);
else {
var pos = new google.maps.LatLng(lat,lon);
coord_array[i] = pos;
setMarker(pos);
i++;
update_table(lat,lon,time,"Moved",speed,address);
}
}
}
window.update_route = function(new_id) {
$(".progress-ring").show();
hidden=true;
bus_id = new_id;
if(bus_id==0) {
$('.stats').hide();
$('.all-stats').show();
$('.all-stats-body').html("");
}
else {
$('.stats').show();
$('.all-stats').hide();
$(".stats-table-body").html("");
}
get_some_default_values();
//google.maps.event.addDomListener(window, 'load', initialize);
initialize();
}
$('.bus-route-selector').click(function(){
$(this).attr('disabled', 'disabled');
});
});
|
import React from 'react';
import Stacked from '../comps/StackedLogo';
export default {
title:'leashed/Stacked Logo',
component: Stacked
};
export const StackedLogoComp = () => <Stacked/>
|
import React, { Component } from 'react';
import {connect} from 'react-redux'
import Itemlisttodo from './itemtodo';
class Listtodo extends Component {
render() {
console.log(this.props.tabtodo)
const {tabtodo}=this.props
return (
<div className='listtodo-app'>
{
tabtodo.map((el,index)=>
<Itemlisttodo key={index} itemtodo={el} id={index}/>
)
}
</div>
);
}
}
const mapStateToProps=(state)=>
{
return {
tabtodo:state.reducer
}
}
export default connect(mapStateToProps)(Listtodo);
|
import color from './color';
export default {
name: 'theme',
vsfunction(json) {
for (const clave in json) {
if (Object.prototype.hasOwnProperty.call(json, clave)) {
let colorx;
if (/^[rgb(]/g.test(json[clave])) {
colorx = json[clave].replace(/[rgb()]/g, '');
} else if (/[#]/g.test(json[clave])) {
const rgbx = color.hexToRgb(json[clave]);
colorx = `${rgbx.r},${rgbx.g},${rgbx.b}`;
} else {
colorx = json[clave];
}
color.setCssVariable(`--vs-${clave}`, colorx);
}
}
}
};
|
var ServiceContract = artifacts.require("ServiceContract");
var ServiceContractFactory = artifacts.require("ServiceContractFactory");
contract('ServiceContract', function(accounts) {
it("should have zero balance initially", function() {
return ServiceContract.deployed().then(function(instance) {
assert.equal(web3.eth.getBalance(instance.address).toNumber(), 0, "Balance should intitially be zero");
});
});
it("should accept payments using the addEther function and distribute", function() {
var contractInstance;
var userID = "123456";
var weiToSend = web3.toWei(5, 'ether');
var accInitialBalance = web3.eth.getBalance(accounts[1]);
console.log("account initial balance "+accInitialBalance);
return ServiceContract
.new(
"name",
accounts[1],
web3.toWei(1, 'ether'),
0 //one-time-purchase contract
)
.then(function(instance) {
contractInstance = instance;
return contractInstance.addEther(userID, {from: accounts[0], value: weiToSend});
})
.then(function(result) {
var accFinalBalance = web3.eth.getBalance(accounts[1])
console.log("account final balance "+accFinalBalance);
assert.equal(web3.eth.getBalance(contractInstance.address).toNumber(), 0, "Transferred value should have been distributed");
assert.equal(accFinalBalance.toNumber(), accInitialBalance.add(weiToSend).toNumber(), "Account 0 should receive owners cut");
});
});
it("should correctly calculate if a user is enabled based on the billing period and date", function() {
var contractInstance;
var userID = "123456";
var price = web3.toWei(1, 'ether');
var paidAmount = price;
return ServiceContract
.new(
"name",
accounts[0],
price,
100000, // billing period. 1 *price* gets you a subscription for this many seconds
)
.then(function(instance) {
contractInstance = instance;
return contractInstance.isEnabled(userID);
})
.then(function(isEnabled) {
assert.equal(isEnabled, false, "The user should not be enabled as they have not paid");
})
.then(function() {
return contractInstance.addEther(userID, {from: accounts[2], value: paidAmount});
})
.then(function(result) {
return contractInstance.isEnabled(userID);
})
.then(function(isEnabled) {
assert.equal(isEnabled, true, "The user should be enabled after paying");
return contractInstance.getTotalPaid(userID);
})
.then(function(totalPaid) {
assert.equal(totalPaid.toNumber(), paidAmount, "The users payments have been recorded");
return contractInstance.getPaidUntil(userID);
})
.then(function(paidUntil) {
console.log(paidUntil.toNumber());
assert.equal(paidUntil.toNumber() > 0, true, 'Paid until should be positive (this is a bad test...)')
});
});
it("Should allow price to be changed by the owner", function () {
let contractInstance;
let owner = accounts[1];
return ServiceContract
.new(
"name",
owner,
web3.toWei(1, 'ether'),
0)
.then(function(instance) {
contractInstance = instance;
return contractInstance.price();
})
.then(function (price){
return contractInstance.changePrice(web3.toWei(1, 'finney'), {from: owner});
})
.then(function(result) {
return contractInstance.price();
})
.then(function(price) {
assert.equal(price.toNumber(), web3.toWei(1, 'finney'), "New price should have been updated in contract");
});
});
it("Should NOT allow price to be changed by another address", function () {
let contractInstance;
let owner = accounts[1];
return ServiceContract
.new(
"name",
owner,
web3.toWei(1, 'ether'),
0)
.then(function(instance) {
contractInstance = instance;
return contractInstance.price();
})
.then(function (price){
return contractInstance.changePrice(web3.toWei(1, 'finney'), {from: accounts[2]});
})
.then(assert.fail)
.catch(function(error) {
assert.include(
error.message,
'VM Exception while processing transaction: invalid opcode',
'Should throw invalid opcode if non-owner attempts to change price'
)
})
.then(function() {
return contractInstance.price();
})
.then(function(price) {
assert.equal(price.toNumber(), web3.toWei(1, 'ether'), "Price should be unchanged");
});
});
it("Should allow billing period to be changed by the owner", function () {
let contractInstance;
let owner = accounts[1];
return ServiceContract
.new(
"name",
owner,
web3.toWei(1, 'ether'),
0)
.then(function(instance) {
contractInstance = instance;
return contractInstance.billingPeriod();
})
.then(function (billingPeriod){
return contractInstance.changeBillingPeriod(10, {from: owner});
})
.then(function(result) {
return contractInstance.billingPeriod();
})
.then(function(billingPeriod) {
assert.equal(billingPeriod.toNumber(), 10, "New billingPeriod should have been updated in contract");
});
});
it("Should NOT allow billing period to be changed by another address", function () {
let contractInstance;
let owner = accounts[1];
return ServiceContract
.new(
"name",
owner,
web3.toWei(1, 'ether'),
0)
.then(function(instance) {
contractInstance = instance;
return contractInstance.billingPeriod();
})
.then(function (billingPeriod){
return contractInstance.changeBillingPeriod(10, {from: accounts[2]});
})
.then(assert.fail)
.catch(function(error) {
assert.include(
error.message,
'VM Exception while processing transaction: invalid opcode',
'Should throw invalid opcode if non-owner attempts to change billing period'
)
})
.then(function() {
return contractInstance.billingPeriod();
})
.then(function(billingPeriod) {
assert.equal(billingPeriod.toNumber(), 0, "billingPeriod should be unchanged");
});
});
});
|
module.exports = {
url: function() {
return "http://cpsv-ap.semic.eu:8890/cpsv-ap_mapping/mapped_relations";
},
elements: {
tab: {
selector: '//div[@id = "main-menu"]/ul[1]/li[3]/a[text() = "Mappings"]',
locateStrategy: 'xpath'
},
select_source_datamodel: {
selector: '#edit-did1-selective'
},
select_source_class: {
selector: '#edit-coreclass-selective'
},
select_source_property: {
selector: '#edit-coreproperty-selective'
},
select_relation: {
selector: '#edit-relation-selective'
},
select_target_datamodel: {
selector: '#edit-did2-selective'
},
select_target_class: {
selector: '#edit-mappedclass-selective'
},
select_target_property: {
selector: '#edit-mappedproperty-selective'
},
table_rows: {
selector: '#datatable-1 > tbody > tr'
},
table_rows_message: {
selector: '#datatable-1_info'
},
table_row1_source_datamodel: {
selector: '//table[@id = "datatable-1"]/tbody/tr[1]/td[1]',
locateStrategy: 'xpath'
},
table_row1_target_datamodel: {
selector: '//table[@id = "datatable-1"]/tbody/tr[1]/td[2]',
locateStrategy: 'xpath'
},
table_row1_source_class: {
selector: '//table[@id = "datatable-1"]/tbody/tr[1]/td[3]',
locateStrategy: 'xpath'
},
table_row1_source_property: {
selector: '//table[@id = "datatable-1"]/tbody/tr[1]/td[4]',
locateStrategy: 'xpath'
},
table_row1_relation: {
selector: '//table[@id = "datatable-1"]/tbody/tr[1]/td[5]',
locateStrategy: 'xpath'
},
table_row1_target_property: {
selector: '//table[@id = "datatable-1"]/tbody/tr[1]/td[6]',
locateStrategy: 'xpath'
},
table_row1_target_class: {
selector: '//table[@id = "datatable-1"]/tbody/tr[1]/td[7]',
locateStrategy: 'xpath'
},
statistics: {
selector: '//h2[text() = "Statistics"]/../div[1]',
locateStrategy: 'xpath'
}
},
commands: [{
select() {
return this.click('@tab');
},
set_select_source_datamodel(value) {
return this.click('@select_source_datamodel',()=>{
this.click("option[value='" + value + "']");
});
},
set_select_target_datamodel(value) {
return this.click('@select_target_datamodel',()=>{
this.click("option[value='" + value + "']");
});
},
set_select_source_class(value) {
return this.click('@select_source_class',()=>{
this.click("option[value='" + value + "']");
});
},
set_select_source_property(value) {
return this.click('@select_source_property',()=>{
this.click("option[value='" + value + "']");
});
},
set_select_target_class(value) {
return this.click('@select_target_class',()=>{
this.click("option[value='" + value + "']");
});
},
set_select_relation(value) {
return this.click('@select_relation',()=>{
this.click("option[value='" + value + "']");
});
},
set_select_target_property(value) {
return this.click('@select_target_property',()=>{
this.click("option[value='" + value + "']");
});
},
wait_for_table_row1_source_datamodel_visible(value) {
return this.waitForElementVisible('@table_row1_source_datamodel', value);
},
assert_table_rows(value){
//return this.assert.elementPresent('#datatable-1 > tbody > tr:nth-of-type(' + value + ')');
return this.assert.elementCount(this.elements.table_rows.selector, value);
},
assert_table_rows_message(value){
return this.assert.containsText('@table_rows_message', "Showing 1 to " + value + " of " + value + " entries");
},
assert_table_row1_source_datamodel(value){
return this.assert.containsText('@table_row1_source_datamodel', value);
},
assert_table_row1_target_datamodel(value){
return this.assert.containsText('@table_row1_target_datamodel', value);
},
assert_table_row1_source_class(value){
return this.assert.containsText('@table_row1_source_class', value);
},
assert_table_row1_source_property(value){
return this.assert.containsText('@table_row1_source_property', value);
},
assert_table_row1_relation(value){
return this.assert.containsText('@table_row1_relation', value);
},
assert_table_row1_target_property(value){
return this.assert.containsText('@table_row1_target_property', value);
},
assert_table_row1_target_class(value){
return this.assert.containsText('@table_row1_target_class', value);
},
assert_stats_number_relations(value){
var that = this;
return this.getText('@statistics', function(result) {
var relations = result.value.split("\n")[0];
var num_rels = relations.split(" = ")[1];
console.log(num_rels);
that.assert.equal(parseInt(num_rels), value );
//return stats;
//expect(result.value).to.equal("Gmail");
//console.log(msg.toString()+result.value);
});
},
assert_stats_percentage(match, value) {
var that = this;
return this.getText('@statistics', function(result) {
var splitat;
if(match == "Broad match") {
splitat = 1;
} else if(match == "Close match") {
splitat = 2;
} else if (match == "Exact match") {
splitat = 3;
} else if (match == "Narrow match") {
splitat = 4;
} else if (match == "Related match") {
splitat = 5;
}
var matches = result.value.split("\n")[splitat];
var num_matches = matches.split(" = ")[1];
console.log(num_matches);
that.assert.equal(num_matches, value )
});
},
assert_stats_percentage_close_match(value){
var that = this;
return this.getText('@statistics', function(result) {
var close_matches = result.value.split("\n")[2];
var num_close_matches = close_matches.split(" = ")[1];
console.log(num_close_matches);
that.assert.equal(num_close_matches, value );
//return stats;
//expect(result.value).to.equal("Gmail");
//console.log(msg.toString()+result.value);
});
},
assert_stats_percentage_exact_match(value){
var that = this;
return this.getText('@statistics', function(result) {
var exact_matches = result.value.split("\n")[3];
var num_exact_matches = exact_matches.split(" = ")[1];
console.log(num_exact_matches);
that.assert.equal(num_exact_matches, value );
//return stats;
//expect(result.value).to.equal("Gmail");
//console.log(msg.toString()+result.value);
});
}
}]
};
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TouchableOpacity,
StatusBar,
ScrollView,
View
} from 'react-native';
import { withNavigation } from 'react-navigation';
import { colorObject } from '../constants/index';
class ColorPalettes extends Component {
render() {
return (
<View>
<TouchableOpacity
style={styles.main}
onPress={() =>
this.props.navigation.push('ColorDetails', {
colorDetails: this.props.colorDetails
})
}
>
<View style={styles.colorName}>
<Text style={styles.name}>{this.props.colorDetails.name}</Text>
</View>
<View style={styles.colorBox}>
<View
style={{
width: '25%',
backgroundColor: this.props.colorDetails.color1,
paddingVertical: 40,
borderBottomLeftRadius: 10
}}
/>
<View
style={{
width: '25%',
paddingVertical: 40,
backgroundColor: this.props.colorDetails.color2
}}
/>
<View
style={{
width: '25%',
paddingVertical: 40,
backgroundColor: this.props.colorDetails.color3
}}
/>
<View
style={{
width: '25%',
paddingVertical: 40,
backgroundColor: this.props.colorDetails.color4,
borderBottomRightRadius: 10
}}
/>
</View>
</TouchableOpacity>
</View>
);
}
}
const Color = withNavigation(ColorPalettes);
class ColorList extends Component {
render() {
return (
<View style={{ flex: 1 }}>
<ScrollView style={styles.mainBG}>
<StatusBar hidden={true} />
{colorObject.map(item => {
return <Color colorDetails={item} key={item.name} />;
})}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
mainBG: {
backgroundColor: '#dcdde1'
},
main: {
margin: 10,
borderWidth: 1,
borderRadius: 10,
backgroundColor: 'white',
elevation: 10
},
colorName: {
alignSelf: 'center',
paddingVertical: 10
},
name: {
fontWeight: 'bold'
},
colorBox: {
flexDirection: 'row'
}
});
export default ColorList;
|
import axios from "axios";
import {
FETCH_TODOS,
ADD_TODO,
UPDATE_TODO,
DELETE_TODO,
EDIT_TODO,
TOGGLE_TAB,
} from "./actionsTypes";
const TODOLIST_API_BASE_URL = "http://localhost:8080/api/todoList";
export const fetchTodos = () => async (dispatch) => {
const res = await axios.get(TODOLIST_API_BASE_URL);
dispatch({ type: FETCH_TODOS, payload: res.data.result });
};
export const addTodo = (name) => async (dispatch) => {
const res = await axios.post(TODOLIST_API_BASE_URL, { itemName: name });
dispatch({ type: ADD_TODO, payload: res.data.result });
};
export const updateTodo = (id, name) => async (dispatch) => {
const res = await axios.put(TODOLIST_API_BASE_URL + "/" + id, name);
dispatch({ type: UPDATE_TODO, payload: { ...res.data.result, name } });
};
export const deleteTodo = (id) => async (dispatch) => {
const res = await axios.delete(TODOLIST_API_BASE_URL + "/" + id);
dispatch({ type: DELETE_TODO, payload: res.data.result });
};
export const editTodo = (todo) => async (dispatch) => {
const res = axios.put(TODOLIST_API_BASE_URL + '/' + todo.id, todo);
dispatch({ type: EDIT_TODO, payload: res.data });
};
export const toggleTab = (tab) => async (dispatch) => {
dispatch({ type: TOGGLE_TAB, filter: tab });
};
|
import createElement from "../../lib/create-element.js";
export default class DoubleSlider {
constructor({ min, max, formatValue, selected }) {
this.min = min;
this.max = max;
this.formatValue = formatValue;
this.selected = selected || { from: min, to: max };
this.onThumbPointerMove = this.onThumbPointerMove.bind(this);
this.onThumbPointerUp = this.onThumbPointerUp.bind(this);
this.render();
}
render() {
this.elem = createElement(`<div class="range-slider">
<span data-elem="from" class="range-slider__price range-slider__price_from"></span>
<div data-elem="inner" class="range-slider__inner">
<span data-elem="progress" class="range-slider__progress"></span>
<span data-elem="thumbLeft" class="range-slider__thumb range-slider__thumb_left"></span>
<span data-elem="thumbRight" class="range-slider__thumb range-slider__thumb_right"></span>
</div>
<span data-elem="to" class="range-slider__price range-slider__price_to"></span>
</div>`);
this.elem.ondragstart = () => false;
this.elems = {};
for (let subElem of this.elem.querySelectorAll("[data-elem]")) {
this.elems[subElem.dataset.elem] = subElem;
}
this.elems.thumbLeft.addEventListener("pointerdown", e =>
this.onThumbPointerDown(e)
);
this.elems.thumbRight.addEventListener("pointerdown", e =>
this.onThumbPointerDown(e)
);
this.update();
}
update() {
let rangeTotal = this.max - this.min;
this.elems.progress.style.left =
Math.floor(((this.selected.from - this.min) / rangeTotal) * 100) + "%";
this.elems.progress.style.right =
Math.floor(((this.max - this.selected.to) / rangeTotal) * 100) + "%";
this.elems.from.innerHTML = this.formatValue(this.selected.from);
this.elems.to.innerHTML = this.formatValue(this.selected.to);
}
onThumbPointerDown(e) {
let thumbElem = e.target;
e.preventDefault();
let thumbCoords = thumbElem.getBoundingClientRect();
if (thumbElem === this.elems.thumbLeft) {
this.shiftX = thumbCoords.right - event.clientX;
} else {
this.shiftX = thumbCoords.left - event.clientX;
}
this.dragging = thumbElem;
this.elem.classList.add("range-slider_dragging");
document.addEventListener("pointermove", this.onThumbPointerMove);
document.addEventListener("pointerup", this.onThumbPointerUp);
}
onThumbPointerMove(e) {
e.preventDefault();
if (this.dragging === this.elems.thumbLeft) {
let newLeft =
(e.clientX -
this.elems.inner.getBoundingClientRect().left +
this.shiftX) /
this.elems.inner.offsetWidth;
if (newLeft < 0) newLeft = 0;
newLeft *= 100;
let right = parseFloat(this.elems.thumbRight.style.right);
if (newLeft + right > 100) newLeft = 100 - right;
this.dragging.style.left = this.elems.progress.style.left = newLeft + "%";
} else {
let newRight =
(this.elems.inner.getBoundingClientRect().right -
event.clientX -
this.shiftX) /
this.elems.inner.offsetWidth;
if (newRight < 0) newRight = 0;
newRight *= 100;
let left = parseFloat(this.elems.thumbLeft.style.left);
if (left + newRight > 100) newRight = 100 - left;
this.dragging.style.right = this.elems.progress.style.right =
newRight + "%";
}
}
onThumbPointerUp() {
this.elem.classList.remove("range-slider_dragging");
document.removeEventListener("pointermove", this.onThumbPointerMove);
document.removeEventListener("pointerup", this.onThumbPointerUp);
}
}
// Dashboard page
let slider = new DoubleSlider({
min: 0,
max: 4000,
formatValue: value => "$" + value
});
// document.querySelector(".content__top-panel").append(slider.elem);
|
'use strict';
$(function () {
var $header = $('header');
var $window = $(window);
var $links = $('nav a');
var $arrow = $('#arrow');
var $projects = $('#projects-link');
var $menu = $('.menu');
$window.scroll(updateHeader).trigger('scroll');
$links.on('click', scrollToSection);
$arrow.on('click', scrollToSection);
$projects.on('click', scrollToSection);
$menu.on('click', toggleMenu);
function toggleMenu() {
$('.dropdown').slideToggle();
}
function updateHeader() {
var bottomOfHeader = $header.offset().top + $header.height();
var viewportHeight = $window.height();
if (bottomOfHeader >= viewportHeight) {
$header.addClass('opaque');
} else {
$header.removeClass('opaque');
}
}
function scrollToSection() {
if ($window.width() <= 720) {
$('.dropdown').slideUp();
}
var section = $(this).attr('link');
$('html, body').animate({
scrollTop: $(section).offset().top
}, 1500);
}
});
|
import React, { Component } from 'react';
import { Row, Col } from 'antd';
import neteaseMusicLogo from './images/netease_32.ico';
import qqMusicLogo from './images/qq_32.ico';
import xiamiMusicLogo from './images/xiami_32.ico';
import kuwoMusicLogo from './images/kuwo_32.ico';
class Wrapper extends Component {
constructor(props) {
super(props);
}
render() {
const { provider } = this.props;
const { logo, link } = providers[provider];
return (
<div className="white-card"
style={{
marginTop: '10px',
}}
>
<Row type="flex" align="middle" style={{ marginBottom: '10px' }}>
<Col span={10}>
<a href={link} target="_blank" alt={provider}>
<img src={logo} alt="" />
</a>
</Col>
<Col span={8}>
{this.props.pagination}
</Col>
<Col span={6} style={{ textAlign: 'right' }}>
{this.props.operatingBar}
</Col>
</Row>
{this.props.children}
</div>
);
}
}
const providers = {
netease: {
logo: neteaseMusicLogo,
link: 'https://music.163.com/'
},
qq: {
logo: qqMusicLogo,
link: 'https://y.qq.com/'
},
xiami: {
logo: xiamiMusicLogo,
link: 'https://www.xiami.com/'
},
kuwo: {
logo: kuwoMusicLogo,
link: 'http://www.kuwo.cn',
},
};
export default Wrapper;
|
'use-strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var tblSchema = new Schema({
tblID : { type: Number, required: true, unique: true , index: true},
collectionName : String,
fieldName : String,
val : Number,
LastValue : Number,
});
tblSchema.virtual('PrimaryKey').get(function(){
return 'tblID';
});
tblSchema.virtual('CollectionName').get(function(){
return 'TBL';
});
var TBL = mongoose.model('TBL',tblSchema);
module.exports = TBL;
|
// Complete the birthday function below.
//apporaching 1 brute force
function apporaching1(s, d, m) {
let count = 0;
for (let i = 0; i < s.length; i++) {
let temp = 0;
if (i + m - 1 < s.length) {
for (let j = i; j <= i + m - 1; j++) {
temp += s[j];
}
} else {
break;
}
if (temp == d) {
count++;
}
}
return count;
}
//apporaching 2 use an array to record the sum
function birthday(s, d, m) {
let count = 0;
let sumArray = [];
for (let i = 0; i < s.length; i++) {
if (i == 0) {
sumArray.push(s[i]);
} else {
let temp = s[i] + sumArray[i - 1];
sumArray.push(temp); // sum all the elements before index
}
}
for (let j = m - 1; j < sumArray.length; j++) {
let overflow = j - m >= 0 ? sumArray[j - m] : 0; //j - m out of the index
let sum = sumArray[j] - overflow;
if (sum == d) {
count++;
}
}
return count;
}
|
var Clay = require('pebble-clay');
var clayConfig = require('./config');
var clay = new Clay(clayConfig);
var myAPIKey = '';
var startDate = '';
var startTime = '';
var teamName = '';
// var stadium = '';
var xhrRequest = function (url, type, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
callback(this.responseText);
};
xhr.open(type, url, false);
xhr.send();
};
function locationSuccess(pos) {
// Construct URL
var weatherUrl = 'https://api.darksky.net/forecast/' + myAPIKey + '/' + pos.coords.latitude + ',' + pos.coords.longitude;
// // to limit runs for Aggie games
// // Import.io is only free up to 500 hits a month
// var d = new Date();
// var h = d.getHours();
// construct football schedule URL
var scheduleUrl = "";
// if(h>9 && h<11) {
xhrRequest(scheduleUrl, 'GET',
function(responseText) {
var data = JSON.parse(responseText);
var quantity = data.result.extractorData.data[0].group.length;
for(var i=0; i<quantity; i++) {
if(data.result.extractorData.data[0].group[i].start_date[0].text) {
startDate = data.result.extractorData.data[0].group[i].start_date[0].text;
startDate = shortenDate(startDate);
}
if(checkDate(startDate)===true) {
if(data.result.extractorData.data[0].group[i].start_time[0].text) {
startTime = data.result.extractorData.data[0].group[i].start_time[0].text;
}
if(data.result.extractorData.data[0].group[i].team_name[0].text) {
teamName = data.result.extractorData.data[0].group[i].team_name[0].text;
}
// if(data.result.extractorData.data[0].group[i].stadium[0].text) {
// stadium = data.result.extractorData.data[0].group[i].stadium[0].text;
// if(stadium=='Kyle Field') {
// stadium = '@Home';
// }
// }
console.log('startDate = ' + startDate);
console.log('startTime = ' + startTime);
console.log('teamName = ' + teamName);
// console.log('stadium = ' + stadium);
break;
}
}
});
// }
// get forecast through dark sky
xhrRequest(weatherUrl, 'GET',
function(responseText) {
var json = JSON.parse(responseText);
// round temperature
var curTemp = Math.round(json.currently.temperature);
console.log("Temperature in Fahrenheit is " + curTemp);
// icon for weather condition
var icon = json.currently.icon;
console.log("Current icon is " + icon);
// assemble dictionary using keys
var dictionary = {
"KEY_TEMP": curTemp,
"KEY_ICON": icon,
"KEY_START_DATE_TIME": startDate + ' ' + startTime,
"KEY_TEAM_STADIUM": teamName,
};
// Send to Pebble
Pebble.sendAppMessage(dictionary,
function(e) {
console.log("Weather info sent to Pebble successfully!");
},
function(e) {
console.log("Error sending weather info to Pebble!");
}
);
}
);
}
function locationError(err) {
console.log("Error requesting location!");
}
function getWeather() {
navigator.geolocation.getCurrentPosition(
locationSuccess,
locationError,
{timeout: 15000, maximumAge: 60000}
);
}
// Listen for when the watchface is opened
Pebble.addEventListener('ready',
function(e) {
console.log("PebbleKit JS ready!");
// Get the initial weather
getWeather();
}
);
// Listen for when an AppMessage is received
Pebble.addEventListener('appmessage',
function(e) {
console.log("AppMessage received!");
getWeather();
}
);
// returns true if today or later
function checkDate(date) {
// console.log('checkDate started with ' + date);
var today = new Date();
var dt = new Date(date);
dt.setFullYear(today.getFullYear());
// console.log('today = ' + today);
// console.log('dt = ' + dt);
if(dt>=today) {
// console.log('checkDate = TRUE');
return true;
}
// console.log('checkDate = FALSE');
}
function shortenDate(date) {
var month = date.split(" ")[1];
var day = date.split(" ")[2];
var temp;
switch(month) {
case "January":
temp = 1;
break;
case "February":
temp = 2;
break;
case "March":
temp = 3;
break;
case "April":
temp = 4;
break;
case "May":
temp = 5;
break;
case "June":
temp = 6;
break;
case "July":
temp = 7;
break;
case "August":
temp = 8;
break;
case "September":
temp = 9;
break;
case "October":
temp = 10;
break;
case "November":
temp = 11;
break;
case "December":
temp = 12;
break;
}
return temp + '-' + day;
}
|
/*$Rev: 2692 $ Revision number must be in the first line of the file in exactly this format*/
/*
Copyright (C) 2009 Innectus Corporation
All rights reserved
This code is proprietary property of Innectus Corporation. Unauthorized
use, distribution or reproduction is prohibited.
$HeadURL: http://info.innectus.com.cn/innectus/trunk/loom/App/app/public/jscript_dev/widgets/searchmanager.js $
$Id: searchmanager.js 2692 2011-05-24 00:09:43Z volkmuth $
*/
///////////////////////////////////////
//Search Manager
///////////////////////////////////////
(function(){
var _WF = INNECTUS.WidgetFactory
var _Base = _WF.getWidgetClass('input','collectionList');
var _Object = INNECTUS.Object;
//Create a search widget group based off the input group.
_WF.createGroup("search", "input");
/**
* Registered as 'collectionList' in the group 'search'.
* This is the collection widget for the search group.
* @class
* @augments INNECTUS.WidgetFactory.CollectionWidget
* @name INNECTUS.WidgetFactory.CollectionWidgetSearch
*/
function CollectionWidgetSearch(){
_Base.call(this);
};
CollectionWidgetSearch.prototype = new _Base;
/**
* Initializes the search manager.
* @name INNECTUS.WidgetFactory.CollectionWidgetSearch#init
* @param {Object} options Options to use for this widget. See Widget.init for more options!
* @param {Function} [onSearch=null] Callback to use when the search button has been pressed.
* @param {String} [autoCompleteUrl=null] The url to set the auto complete to point to.
* @param {boolean} [autoCompleteSubstring=false] If true autoComplete matches substrings, otherwise match start of word
* @param {Number} [width=350] The width of a popup window.
* @param {Number} [options.height=350] The height of a popup window.
* @param {String} [options.skipAttr="noSearch"] An attribute to look at for skipping a widget. Set
* to null if you want all fields to be searchable.
*/
CollectionWidgetSearch.prototype.initInternal = function(options){
options = _Object.clone(options);
options.skipAttr = "noSearch";
this.setTitle("What do you want to find?");
options.okText = "Search!";
var defaultOptions = {
autoCompleteUrl:options.autoCompleteUrl,
autoCompleteSubstring:options.autoCompleteSubstring,
smiles:true
};
if(!options.defaultOptions){
options.defaultOptions = defaultOptions;
} else {
Object.merge(options,defaultOptions);
}
_Base.prototype.initInternal.call(this,options);
};
_WF.registerWidget(CollectionWidgetSearch, "search", "collectionList");
}());
///////////////////////////////////////
//custom search widgets
///////////////////////////////////////
//String
(function(){
var _Base = INNECTUS.WidgetFactory.getWidgetClass("input");
var _Object = INNECTUS.Object;
var _Convert = INNECTUS.Convert;
var _Keyboard = INNECTUS.Event.Keyboard;
/**
* Registered as 'string' in the group 'search'.
* This is the widget for string input for a search that allows multiple string values
* to be inputed.
* @class
* @augments INNECTUS.WidgetFactory.BaseWidgetInput
* @name INNECTUS.WidgetFactory.StringWidgetSearch
*/
function StringWidgetSearch(){
this.setHelpMessage("Type in a single value or type in a list of values, separating them by hitting the 'enter' key. You may type in a full value or just the start");
this.setType({inputType:"textarea", autoGrow:true, subClass:"singleLine"});
};
StringWidgetSearch.prototype = new _Base;
StringWidgetSearch.prototype.renderStatic = function(parent){
_Base.prototype.renderStatic.call(this,parent);
if(this._autoCompleteUrl){
this._autoComplete = new INNECTUS.AutoComplete();
this._autoComplete.init({
id:this.getId(),
url:this._autoCompleteUrl,
substring:this._autoCompleteSubstring,
parent:this._input
});
}
};
/**
* Registered as 'cas' in the group 'search'.
* This is the widget for multiple cas number input.
* @class
* @augments INNECTUS.WidgetFactory.BaseWidgetInput
* @name INNECTUS.WidgetFactory.CasWidgetSearch
*/
function CasWidgetSearch(){
this.setType({inputType:"textarea", autoGrow:true, subClass:"singleLine"});
this.setHelpMessage("Type in a single CAS number or type in a list of CAS numbers, separating them by hitting the 'enter' key.");
this.setErrorMessage("You entered in an invalid CAS number. Make sure you typed it in correctly!");
};
CasWidgetSearch.prototype = new StringWidgetSearch;
CasWidgetSearch.prototype._prettyError = function(index, value){
var pretty = "th";
if(index === 0)
pretty = "st";
else if(index === 1)
pretty = "nd";
else if(index === 2)
pretty = "rd";
pretty = (index+1) + pretty;
this.setErrorMessage("The "+pretty+" entry of '"+value+"' is not a valid CAS number. Make sure you typed it in correctly!");
};
CasWidgetSearch.prototype._fullCasValidate = function(values, length){
for(var i = 0; i < length; i++){
if(values[i] !== "" && _Convert.stringToCasNumber(values[i]) === null){
this._prettyError(i, values[i]);
return false;
}
}
return true;
};
var allDigits = new RegExp("^\\d*$");
CasWidgetSearch.prototype.validateInternal = function(value){
if(value){
var vals = value.split("\n");
if(vals.length > 0){
return this._fullCasValidate(vals, vals.length);
}
}
return true;
};
var _StructureBase = INNECTUS.WidgetFactory.getWidgetClass('input','structure');
//create a search structure widget (mainly just for the help message)
function StructureWidgetSearch(){
this.setHelpMessage("Double click on the image to bring up the structure editor. Then draw a structure or sub-structure to search for.");
this._showChirality = false;
};
StructureWidgetSearch.prototype = new _StructureBase;
//register it!
INNECTUS.WidgetFactory.registerWidget(StringWidgetSearch, "search", "string");
INNECTUS.WidgetFactory.registerWidget(CasWidgetSearch, "search", "cas");
INNECTUS.WidgetFactory.registerWidget(StructureWidgetSearch, "search", "structure");
INNECTUS.WidgetFactory.registerWidget(StringWidgetSearch, 'search', 'jsoncombo');
INNECTUS.WidgetFactory.registerWidget(StringWidgetSearch, 'search', 'comboedit');
INNECTUS.WidgetFactory.registerWidget(StringWidgetSearch, 'search', 'comboeditdelete');
}());
|
export { default as CarCard } from './CarCard.vue';
|
import React from 'react';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import Layout from 'components';
import { Home, Add, About } from 'containers';
// App routes
const Routes = (
<Router history={hashHistory}>
<Route path="/" component={Layout}>
{/* IndexRoute renders Home container by default */}
<IndexRoute component={Home} />
<Route path="Add" component={Add} />
<Route path="About" component={About} />
</Route>
</Router>
);
export default Routes;
|
// $Id: scale.js,v 1.1.2.4 2010/11/05 16:14:48 falcon Exp $
/**
* @file
* Javascript functions for the scale question type.
*/
/**
* Refreshes alternatives when a preset is selected.
*
* @param selection
* The select item used to select answer collection
*/
function refreshAlternatives(selection) {
clearAlternatives();
var colId = selection.options[selection.selectedIndex].value;
var numberOfOptions = scaleCollections[colId].length;
for(var i = 0; i<numberOfOptions;i++){
$('#edit-alternative' + (i)).val(scaleCollections[colId][i]);
}
}
/**
* Clears all the alternatives on the scale node form
*/
function clearAlternatives() {
for ( var i = 0; i < scale_max_num_of_alts; i++) {
$('#edit-alternative' + (i)).val('');
}
}
|
/**
* Created by Phani on 7/23/2016.
*/
import {Meteor} from "meteor/meteor";
import {ValidatedMethod} from "meteor/mdg:validated-method";
import {SimpleSchema} from "meteor/aldeed:simple-schema";
import {CountryCodes} from "meteor/3stack:country-codes";
import * as Charts from "/imports/api/charts/charts.js";
import {Users, PROFILE, PROFILE_NAME} from "./users.js";
export const UPVOTES = "upvotes";
export const DOWNVOTES = "downvotes";
const DEFAULT_SEARCH_LIMIT = 10;
export const currentUser = function () {
return Users.findOne({_id: Meteor.userId()});
};
export const getUserName = new ValidatedMethod({
name: "users.getUserName",
validate: new SimpleSchema({
userId: {
type: String,
regEx: SimpleSchema.RegEx.Id
}
}).validator(),
run({userId:userId}){
let user = Users.findOne({_id: userId});
if (user) {
return user[PROFILE][PROFILE_NAME];
}
return null;
}
});
export const searchUsers = new ValidatedMethod({
name: "users.searchUsers",
validate: function ({query, limit, skip}) {
},
run({query, limit, skip}){
if (!limit) {
limit = DEFAULT_SEARCH_LIMIT;
}
if (!skip) {
skip = 0;
}
let sel = {};
if (query) {
sel = {$text: {$search: query}}
}
let proj = {
fields: {score: {$meta: "textScore"}},
sort: {score: {$meta: "textScore"}},
limit: limit,
skip: skip
};
return Users.find(sel, proj).fetch();
}
});
export const updateUserProfile = new ValidatedMethod({
name: "users.updateUserProfile",
validate: new SimpleSchema({
user: {
type: Object
},
"user._id": {
type: String,
regEx: SimpleSchema.RegEx.Id
},
"user.name": {
type: String,
optional: true
},
"user.organization": {
type: String,
optional: true
},
"user.expertises": {
type: [String],
optional: true
},
"user.countryCode": {
type: String,
regEx: /[A-Z]{2}/,
optional: true
}
}).validator({
clean: true,
filter: true
}),
run({user}){
let id = user._id;
delete user._id;
let profile = {};
_.each(user, function (val, key) {
if (key === "countryCode") {
profile["profile.country.code"] = val;
profile["profile.country.name"] = CountryCodes.countryName(val);
} else {
profile["profile." + key] = val;
}
});
let set = {$set: profile};
return Users.update({_id: id}, set);
}
});
export const getUserVotedCharts = new ValidatedMethod({
name: "getUserVotedCharts",
validate: new SimpleSchema({
userId: {
type: String,
regEx: SimpleSchema.RegEx.Id
}
}).validator(),
run({userId:userId}){
let results = {};
let upSelector = {};
upSelector[Charts.UPVOTED_IDS] = userId;
let downSelector = {};
downSelector[Charts.DOWNVOTED_IDS] = userId;
let fields = {};
fields[Charts.CHART_ID] = 1;
let upResults = Charts.Charts.find(upSelector, {fields: fields}).fetch();
let downResults = Charts.Charts.find(downSelector, {fields: fields}).fetch();
results[UPVOTES] = _.pluck(upResults, Charts.CHART_ID);
results[DOWNVOTES] = _.pluck(downResults, Charts.CHART_ID);
return results;
}
});
|
import React, {Component} from 'react'
import {reduxForm} from 'redux-form'
import Input from '../../../ui/Input'
import Button from '../../../ui/Button'
import './style.css'
const OPTIONS = [
{title: 'title1', value: 0},
{title: 'title2', value: 1}
]
class FormEntry extends Component {
render() {
return (
<div className="form">
<div className="form__block">
<div className="form__column">
<Input label="Ответственный участник" name="name"/>
<Input label="Адрес электронной почты" name="email" hint="Мы вышлем Вам на почту квитанцию об оплате"/>
</div>
<div className="form__column">
<Input label="Дата рождения" name="date" component="time"/>
<Input label="Номер телефона" name="phone" hint="Обещаем, что не будем рассылать рекламу"/>
</div>
</div>
<div className="form__block">
<div className="form__column">
<Input label="Участник №" name="people"/> {/*TODO динамические номера участников и name*/}
<Input label="Участник №" name="people2"/>
<Input label="Участник №" name="people3"/>
<span className="link-like-button">Добавить участника</span>
</div>
<div className="form__column">
<div className="form__row">
<div className="form__column">
<Input label="Категория" name="categoty" component="select" options={OPTIONS}/>
<Input label="Категория" name="categoty2" component="select" options={OPTIONS}/>
<Input label="Категория" name="categoty3" component="select" options={OPTIONS}/>
</div>
<div className="form__column">
<Input label="Дистанция" name="distance" component="select" options={OPTIONS}/>
<Input label="Дистанция" name="distance2" component="select" options={OPTIONS}/>
<Input label="Дистанция" name="distance3" component="select" options={OPTIONS}/>
</div>
</div>
</div>
</div>
<div className="label">
<p className="label__title">Итоговая сумма благотворительного взноса:</p>
<p className="label__value">850 руб.</p>
</div>
<div className="form__row">
<Button noMargin>Перейти к оплате</Button>
<span className="form__notify" style={{display: 'block', alignSelf: 'center'}}>Незабудьте захватить документ удостоверяющий личность.</span>
</div>
</div>
)
}
}
export default reduxForm({
form: 'formEntry'
})(FormEntry)
|
import React from 'react'
import { StyleSheet } from 'quantum'
import { ArrowIcon } from '../icons'
const styles = StyleSheet.create({
self: {
transition: 'all 0.3s',
background: '#f5f5f5',
border: '1px solid #9e9e9e',
cursor: 'pointer',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
boxSizing: 'border-box',
width: '25px',
height: '24px',
'& svg': {
fill: '#000000',
position: 'relative',
top: '-1px',
},
},
down: {
'& svg': {
transform: 'rotate(180deg)',
top: '2px',
},
},
active: {
background: '#546e7a',
'& svg': {
fill: '#ffffff',
},
},
})
const Item = ({ active, down, onSelect }) => (
<span className={styles({ active, down })} onClick={onSelect}>
<ArrowIcon
width={16}
/>
</span>
)
const Direction = ({ direction = 'asc', onChange }) => (
<span>
<Item
down
active={direction === 'desc'}
onSelect={() => onChange && onChange('desc')}
/>
<Item
active={direction === 'asc'}
onSelect={() => onChange && onChange('asc')}
/>
</span>
)
export default Direction
|
const fs = require("fs");
const crypto = require("crypto");
const data = require("../data.json");
const { handleAge, handleDate, handleGraduation } = require("../utils");
exports.index = (req, res) => {
const teachers = data.teachers.map((teacher) => {
const formatServices = teacher.services.split(",");
const foundTeacher = {
...teacher,
services: formatServices,
};
return foundTeacher;
});
return res.render("teachers/index", { teachers });
};
exports.create = (req, res) => {
const keys = Object.keys(req.body);
let { avatar_url, name, birth, schooling, type_class, services } = req.body;
keys.map((key) => {
if (req.body[key] === "") {
return res.send("Please, fill all fields!");
}
});
birth = Date.parse(req.body.birth);
const created_at = Date.now();
const id = crypto.randomBytes(6).toString("hex");
data.teachers.push({
id,
avatar_url,
name,
birth,
schooling,
type_class,
services,
created_at,
});
fs.writeFile("data.json", JSON.stringify(data, null, 2), (err) => {
if (err) return res.send("Write file error!");
return res.redirect("/teachers");
});
};
exports.show = (req, res) => {
const { id } = req.params;
const foundTeacher = data.teachers.find((teacher) => {
return teacher.id == id;
});
if (!foundTeacher) return res.send("Teacher not found!");
const date = new Intl.DateTimeFormat("pt-BR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(foundTeacher.created_at);
const teacher = {
...foundTeacher,
schooling: handleGraduation(foundTeacher.schooling),
age: handleAge(foundTeacher.birth),
services: foundTeacher.services.split(","),
created_at: handleDate(date),
};
return res.render("teachers/show", { teacher });
};
exports.showEdit = (req, res) => {
const { id } = req.params;
const foundTeacher = data.teachers.find((teacher) => {
return teacher.id == id;
});
if (!foundTeacher) return res.send("Instructor not found!");
const date = new Intl.DateTimeFormat("pt-BR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
timeZone: "UTC",
}).format(foundTeacher.birth);
const teacher = {
...foundTeacher,
birth: date,
};
return res.render("teachers/edit", { teacher });
};
exports.update = (req, res) => {
const { id } = req.body;
let index = 0;
const foundTeacher = data.teachers.find((teacher, foundIndex) => {
if (teacher.id == id) {
index = foundIndex;
return true;
}
});
if (!foundTeacher) return res.send("Teacher not found!");
birth = Date.parse(req.body.birth);
const teacher = {
...foundTeacher,
...req.body,
birth,
};
data.teachers[index] = teacher;
fs.writeFile("data.json", JSON.stringify(data, null, 2), (err) => {
if (err) return res.send("Write file error!");
return res.redirect(`/teachers/${id}`);
});
};
exports.deleteUser = (req, res) => {
const { id } = req.body;
const filteredTeacher = data.teachers.filter((teacher) => {
return teacher.id != id;
});
data.teachers = filteredTeacher;
fs.writeFile("data.json", JSON.stringify(data, null, 2), (err) => {
if (err) return res.send("Write file error!");
return res.redirect(`/teachers`);
});
};
|
//運用FOCUS 與 BLUR 事件
function checkUsername(){ //宣告函式
let username = el.value; //將輸入的文字儲存於變數username
if(username.length < 5){ //若username少於5個字元
elMsg.className = 'warning'; //變更訊息元件的class屬性
elMsg.textContent = 'Not long enough, yet....'; //變更文字訊息
}else{ //否則
elMsg.textContent = ''; //清除文字訊息
}
}
function tipUsername(){ //宣告函式
elMsg.className = 'tip'; //變更訊息元件的class屬性
elMsg.innerHTML = 'Username must be at least 5 characters'; //加入訊息文字
}
let el = document.getElementById('username'); //取得id屬性值為username的元件
let elMsg = document.getElementById('feedback'); //取得id屬性值為feedback的元件
//此元件用以顯示文字提示訊息
el.addEventListener('focus', tipUsername, false); //當取得焦點時,呼叫tipUsername()
el.addEventListener('blur', checkUsername, false); //當失去焦點時,呼叫checkUsername()
|
import React from "react";
const Blob = props => {
return (
<svg
id={`svg-${props.id}`}
className={`svg-circle svg-circle-${props.current}`}
width={300}
height={300}
xmlns="http://www.w3.org/2000/svg"
filter="url(#goo)"
>
<defs>
<filter id="goo">
<feGaussianBlur in="SourceGraphic" stdDeviation="10" result="blur" />
<feColorMatrix
in="blur"
mode="matrix"
values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 19 -9"
result="goo"
/>
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
</defs>
<circle className={`circle${props.blobs[0]}`} />
<circle className={`circle${props.blobs[1]}`} />
<circle className={`circle${props.blobs[2]}`} />
<circle className={`circle${props.blobs[3]}`} />
</svg>
);
};
export default Blob;
|
'use strict';
var Element = require('elements').Element;
var Select = function Select () {
Element.call(this);
Element.apply(this, arguments);
};
Select.prototype = new Element();
Select.prototype.constructor = Select;
Select.prototype.getOptions = function () {
return this.rootElement.all(by.tagName('option')).map(function(option) {
return option.getText();
});
};
Select.prototype.getSelectedOption = function () {
return this.rootElement.$('option:checked').getText();
};
Select.prototype.select = function (option) {
logger.info('selecting - option: [%s], list: [%s]', option, this.toString());
click(this.rootElement, 'opening select list');
return click(this.rootElement.element(by.cssContainingText('option', option)), 'selecting specified option');
};
Select.prototype.selectPromise = function (option) {
return Promise.resolve()
.then(function() { logger.info('selecting - option: [%s], list: [%s]', option, this.toString());}.bind(this))
.then(function() { return click(this.rootElement, 'opening select list');}.bind(this))
.then(function() { return click(this.rootElement.element(by.cssContainingText('option', option)), 'selecting specified option');}.bind(this))
.catch(function(err) {
logger.error('selecting failed - option: [%s], list: [%s], error: [%s]', option, this.toString(), err.message);
return Promise.reject(err);
}.bind(this));
};
module.exports = Select;
|
//Preloader
$(window).on('load', function () {
$('#status').fadeOut();
$('#preloader').delay(350).fadeOut('slow');
});
//Animate
$(window).on('load', function () {
$("#home-page").addClass("animated slideInUp");
});
//Image Blur
$(document).ready(function () {
$(".image-container").hover(function () {
$(this).find('img').css("filter", "blur(3px)");
}, function () {
$(this).find('img').css("filter", "none");
});
});
//Tooltip
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
});
//Top
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function () {
scrollFunction();
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
//Form Validation
//name check
document.querySelector("#name").addEventListener('input', (e) => {
let inp = e.target.value;
let regex = new RegExp("^[a-zA-Z ]+$");
if (regex.test(inp)) {
document.querySelector("#name").style.animation = "none";
document.querySelector("#name").style.color = "black";
document.querySelector("#sendmessage").disabled = false;
} else {
document.querySelector("#name").style.animation = "wrong 2s infinite";
document.querySelector("#name").style.color = "white";
document.querySelector("#sendmessage").disabled = true;
}
});
//email check
document.querySelector("#email").addEventListener('input', (e) => {
let inp = e.target.value;
let regex = new RegExp("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
if (regex.test(inp)) {
document.querySelector("#email").style.animation = "none";
document.querySelector("#email").style.color = "black";
document.querySelector("#sendmessage").disabled = false;
} else {
document.querySelector("#email").style.animation = "wrong 2s infinite";
document.querySelector("#email").style.color = "white";
document.querySelector("#sendmessage").disabled = true;
}
});
//phone check
document.querySelector("#phone").addEventListener('input', (e) => {
document.querySelector("#phone").style.fontFamily="'Inconsolata', monospace";
let inp = e.target.value;
let regex = new RegExp("^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$");
if (regex.test(inp)) {
document.querySelector("#phone").style.animation = "none";
document.querySelector("#phone").style.color = "black";
document.querySelector("#sendmessage").disabled = false;
} else {
document.querySelector("#phone").style.animation = "wrong 2s infinite";
document.querySelector("#phone").style.color = "white";
document.querySelector("#sendmessage").disabled = true;
}
});
//subject check
document.querySelector("#subject").addEventListener('input', (e) => {
let inp = e.target.value;
if (inp) {
document.querySelector("#subject").style.animation = "none";
document.querySelector("#subject").style.color = "black";
document.querySelector("#sendmessage").disabled = false;
} else {
document.querySelector("#subject").style.animation = "wrong 2s infinite";
document.querySelector("#subject").style.color = "white";
document.querySelector("#sendmessage").disabled = true;
}
});
//subject check
document.querySelector("#message").addEventListener('input', (e) => {
let inp = e.target.value;
if (inp) {
document.querySelector("#message").style.animation = "none";
document.querySelector("#message").style.color = "black";
document.querySelector("#sendmessage").disabled = false;
} else {
document.querySelector("#message").style.animation = "wrong 2s infinite";
document.querySelector("#message").style.color = "white";
document.querySelector("#sendmessage").disabled = true;
}
});
//==========================
|
import React from 'react';
import {
Avatar,
Button,
Grid,
Paper,
TextField,
Typography,
Link,
} from "@material-ui/core";
import HttpsOutlinedIcon from "@material-ui/icons/HttpsOutlined";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
import {Formik, Form, Field, ErrorMessage} from 'formik';
import * as Yup from 'yup';
import {connect} from 'react-redux';
import {loginUser} from "./../auth/actions/userActions"
import {useHistory} from "react-router-dom"
import background from "../assets/bg.jpg"
const Login = ({loginUser}) => {
const history = useHistory();
const paperStyle = {
padding: 20,
width: 300,
margin: "0px auto",
marginTop:150
};
const avatarStyle = { backgroundColor: "tomato" };
const textFieldStyle = {
color: "tomato",
fontColor: "tomato",
borderColor: "tomato",
};
const checkboxStyle = { color: "tomato", borderColor: "white" };
const buttonStyle = {
color: "white",
backgroundColor: "tomato",
margin: "8px 0",
};
const linkStyle = { color: "tomato" };
const initialValues = {
email:'',
password:'',
remember: false,
}
const styledContainer = {margin: 0, display: "flex", justifyContent: "center",
backgroundImage:`url(${background})`,
backgroundSize: "cover",
backgroundAttachment: "fixed",
height: "100%", width:"100%"
}
const validationSchema = Yup.object().shape({
email:Yup.string().email('please enter valid email').required('Required'),
password:Yup.string().required('Required')
})
const onSubmit = (values, {setFieldError, setSubmitting}) =>{
console.log(values);
loginUser(values, history, setFieldError, setSubmitting)
// setTimeout(()=>{
// props.resetForm()
// props.setSubmitting(false)
// }, 1000)
}
return (
<section style={styledContainer}>
<Grid>
<Paper elevation={10} style={paperStyle}>
<Grid align="center">
<Avatar style={avatarStyle}>
<HttpsOutlinedIcon />
</Avatar>
<h1>Sign in</h1>
</Grid>
<Formik initialValues={initialValues} onSubmit={onSubmit} validationSchema={validationSchema}>
{(props) => (
<Form>
<Field as = {TextField}
style={textFieldStyle}
label="Email"
name = "email"
placeholder="Enter email"
fullWidth
required
helperText={<ErrorMessage name= "email" />}
/>
<Field as = {TextField}
label="Password"
name="password"
type="password"
placeholder="Enter password"
fullWidth
required
helperText={<ErrorMessage name= "password" />}
/>
<Field as = {FormControlLabel}
name="remember"
control={
<Checkbox
style={checkboxStyle}
name="checkedB"
color="default"
/>
}
label="Remember me"
/>
<Button
type="submit"
variant="contained"
style={buttonStyle}
color="default"
fullWidth>{props.isSubmitting
?
"Loading":"Sign in"}
</Button>
</Form>
)}
</Formik>
<Typography>
<Link style={linkStyle} href="#">
Forgot password?
</Link>
</Typography>
</Paper>
</Grid>
</section>
);
};
export default connect(null, {loginUser})(Login);
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');
// set up a mongoose model
var UserSchema = new mongoose.Schema({
name: String,
local: { email: String, password: String },
tasks: [{type: mongoose.Schema.Types.ObjectId, ref: 'List'}]
});
// firstName: String,
// lastName: String,
// email: String,
// password: String,
// tasks: [{type: mongoose.Schema.Types.ObjectId, ref: 'List'}]
// hash passwords
UserSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
module.exports = mongoose.model('User', UserSchema);
|
const board = document.querySelector('#board'),
height = document.documentElement.clientHeight,
width = document.documentElement.clientWidth,
SQUARES_NUMBER = (height * width) / 100;
console.log(height);
console.log(SQUARES_NUMBER);
const colors = ['#f6bd60','#f7ede2','#f5cac3','#84a59d','#f28482','#8e9aaf','#cbc0d3','#efd3d7','#feeafa','#dee2ff'];
for (let i = 0; i < SQUARES_NUMBER; i++) {
const square = document.createElement('div');
square.classList.add('square');
square.addEventListener('mouseover', () => setColor(square));
square.addEventListener('mouseleave', () => removeColor(square));
board.append(square);
}
function setColor(elem) {
let color = getColor();
elem.style.backgroundColor = color;
elem.style.boxShadow = `0 0 2px ${color}, 0 0 10px ${color}`;
}
function removeColor(elem) {
elem.style.backgroundColor = '#bcb8b1';
elem.style.boxShadow = `0 0 2px #bcb8b1`;
}
function getColor() {
const index = Math.floor(Math.random() * colors.length);
return colors[index]
}
|
import uuid from "uuid";
/**
* {id:''}
*/
export default class Circle {
constructor(cx, cy, r, fillColor, text) {
this.cx = cx || 50;
this.cy = cy || 50;
this.r = r || 30;
this.fill = fillColor || "pink";
this.id = uuid.v4();
this.text = text;
}
}
|
import { css } from 'styled-components';
import { SPACE_SIZE } from '@/utils/styleConstants';
// import { SUNBURST_CHART_SIZE } from './constants';
const StreamChartStyles = css`
position: relative;
width: 584px;
height: 600px;
padding-bottom: ${SPACE_SIZE.M};
`;
export default StreamChartStyles;
|
const fs = require('fs');
const ensureDir = require('ensure-dir');
const promisify = require('es6-promisify');
const less = require('less');
const LessPluginAutoPrefix = require('less-plugin-autoprefix');
const LessPluginCleanCSS = require('less-plugin-clean-css');
const htmlmin = require('htmlmin');
const watch = require('watch');
const rollup = require('rollup');
const rollupConfig = require('./rollup.config');
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const reICON = /'__(\w+)__'/g;
const lessPlugins = [
new LessPluginAutoPrefix(),
new LessPluginCleanCSS(),
];
var cache;
function loadData(key) {
if (key.startsWith('ICON_')) {
return readFile(`src/assets/${key.slice(5)}.svg`, 'utf8')
.then(value => ({key, value}), err => {console.error(err);});
}
}
function buildCSS() {
return readFile('src/style.less', 'utf8')
.then(input => less.render(input, {
plugins: lessPlugins,
}))
.then(output => output.css);
}
function buildHTML() {
return readFile('src/template.html', 'utf8')
.then(input => htmlmin(input));
}
function buildJS() {
return rollup.rollup(Object.assign({cache}, rollupConfig))
.then(bundle => {
cache = bundle;
const res = bundle.generate(rollupConfig);
return res.code;
})
}
function buildAll() {
return Promise.all([
buildHTML(),
buildCSS(),
buildJS(),
ensureDir('lib'),
])
.then(([html, css, js]) => {
const promises = [];
js.replace(reICON, (m, key) => {
promises.push(loadData(key));
});
return Promise.all(promises)
.then(results => results.reduce((res, item) => Object.assign(res, item && {
[item.key]: item.value,
}), {
STYLE: css,
TEMPLATE: html,
}))
.then(icons => js.replace(reICON, (m, key) => JSON.stringify(icons[key] || '')))
.then(code => writeFile(rollupConfig.dest, code, 'utf8'));
});
}
const safeBuild = function () {
function build() {
willBuild = false;
building = true;
console.time('Build');
return buildAll()
.catch(err => {
console.error(err);
})
.then(() => {
console.timeEnd('Build');
building = false;
return willBuild && build();
});
}
function safeBuild() {
if (building) {
willBuild = true;
return;
}
build();
}
let building, willBuild;
return safeBuild;
}();
if (process.argv.includes('-w')) {
watch.watchTree('src', e => {
safeBuild();
});
} else {
safeBuild();
}
|
import React from 'react';
import './EditorHeader.scss';
import { HeaderLogo } from 'components/HeaderLogo';
import { MdMoreVert } from 'react-icons/md';
import { IconContext } from 'react-icons';
import html2canvas from 'html2canvas';
import { read_cookie } from 'sfcookies';
const EditorHeader = () => {
const fileDownLoad = () => {
console.log(document.getElementsByClassName('EditorView')[0].innerHTML);
html2canvas(document.getElementsByClassName('EditorView')[0]).then(
canvas => {
const data = canvas.toDataURL('image/png', 0.9);
const src = encodeURI(data);
console.log(src);
//document.getElementById('screenshot').src = src;
}
);
};
// nickname
// htmlCont
// thumbnail
const fileUpload = () => {
const user = JSON.parse(localStorage.getItem('webber_user'));
const formData = new FormData();
formData.append('access_token', read_cookie('access_token'));
formData.append(
'htmlCont',
document.getElementsByClassName('EditorView')[0].innerHTML
);
if (localStorage.getItem('webber_user')) {
console.log(
document.getElementsByClassName('EditorView')[0].innerHTML
);
html2canvas(document.getElementsByClassName('EditorView')[0])
.then(canvas => {
const data = canvas.toDataURL('image/png', 0.9);
const src = encodeURI(data);
console.log(src);
formData.append('photo', src);
//document.getElementById('screenshot').src = src;
})
.then(() => {
fetch('http://localhost:9090/api/template', {
method: 'post',
body: formData
}).then(res => {
res.json().then(data => {
if (data.result === 'success') {
console.log(data);
setTimeout(() => {
window.location.href = '/template';
}, 3000);
//window.location.replace('/template');
}
});
});
});
}
};
return (
<div className="EditorHeader">
<div className="EditorHeader_title">
<HeaderLogo />
<div className="EditorHeaderTitle">webber Editor</div>
</div>
<div className="EditorHeader_btns">
{/* <div className="EditorHeader_btn_download" onClick={fileDownLoad}>
다운로드
</div> */}
<div className="EditorHeader_btn_save" onClick={fileUpload}>
저장하기
</div>
{/* <IconContext.Provider
value={{ size: 27, className: 'EditorHeader_btns_more' }}
>
<MdMoreVert />
</IconContext.Provider> */}
</div>
</div>
);
};
export default EditorHeader;
|
import React, {useRef} from 'react';
import './StatisticPage.scss';
import TreeView from '@material-ui/lab/TreeView';
import TreeItem from '@material-ui/lab/TreeItem';
import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';
import ArrowRightIcon from '@material-ui/icons/ArrowRight';
import { makeStyles } from '@material-ui/core/styles';
import {NavLink} from "react-router-dom";
import StatisticObjectPage from "./StatisticObjectPage/StatisticObjectPage";
import StatisticUserPage from "./StatisticUserPage/StatisticUserPage";
import StatisticDevicePage from "./StatisticDevicePage/StatisticDevicePage";
import {Route} from "react-router";
import StatisticAgregatorPage from "./StatisticAgregatorPage/StatisticAgregatorPage";
const treeData = [
{
name: 'Объект 1',
id: 1,
children: [
{
name: 'Потребитель 1',
id: 1,
children: [
{
name: 'Прибор учета 1',
id: 1,
children: []
},
{
name: 'Прибор учета 2',
id: 2,
children: []
}
]
}
]
},
{
name: 'Объект 2',
id: 2,
children: [
{
name: 'Потребитель 1',
id: 1,
children: [
{
name: 'Прибор учета 1',
id: 1,
children: []
}
]
},
{
name: 'Потребитель 2',
id: 2,
children: [
{
name: 'Прибор учета 1',
id: 1,
children: []
}
]
}
]
}
];
const styledNode = makeStyles(theme => ({group: { marginLeft: 16 }}));
function StyledTreeItem(props) {
const { link, name, nodeId, ...others } = props;
const classes = styledNode();
return (
<TreeItem
name="b"
label={
<NavLink activeClassName='active-tree-link' className="link-label" to={'/statistic' + link}>{ name }</NavLink>
}
classes={{ group: classes.group }}
nodeId={nodeId}
{...others}
/>
);
}
function StatisticPage() {
const [expanded, setExpanded] = React.useState([]);
const handleChange = (event, nodes) => {
if (event.target && (event.target.nodeName === 'svg' || event.target.nodeName === 'path')) {
setExpanded(nodes);
}
};
let data = treeData;
let nodeCounter = 0;
return (
<div className="addresses-page statistic-page">
<div className="tree-nav-block">
<div className="search-input regular-text">
<input placeholder="Поиск по имени"/>
<svg width="11" height="10" viewBox="0 0 11 10" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.66453 5.29883C3.13848 5.77279 3.71401 6.00977 4.39109 6.00977C5.06817 6.00977 5.64369 5.77279 6.11765 5.29883C6.59161 4.82487 6.82859 4.24935 6.82859 3.57227C6.82859 2.89518 6.59161 2.31966 6.11765 1.8457C5.64369 1.37174 5.06817 1.13477 4.39109 1.13477C3.71401 1.13477 3.13848 1.37174 2.66453 1.8457C2.19057 2.31966 1.95359 2.89518 1.95359 3.57227C1.95359 4.24935 2.19057 4.82487 2.66453 5.29883ZM7.64109 6.00977L10.3325 8.70117L9.51999 9.51367L6.82859 6.82227V6.39062L6.67624 6.23828C6.03302 6.79688 5.2713 7.07617 4.39109 7.07617C3.40932 7.07617 2.57143 6.73763 1.87742 6.06055C1.20033 5.38346 0.861792 4.55404 0.861792 3.57227C0.861792 2.59049 1.20033 1.76107 1.87742 1.08398C2.57143 0.389974 3.40932 0.0429688 4.39109 0.0429688C5.37286 0.0429688 6.20229 0.389974 6.87937 1.08398C7.55645 1.76107 7.89499 2.59049 7.89499 3.57227C7.89499 3.92773 7.81036 4.33398 7.64109 4.79102C7.47182 5.23112 7.27716 5.58659 7.0571 5.85742L7.20945 6.00977H7.64109Z" fill="#1AA5B8"/>
</svg>
</div>
<NavLink activeClassName='active-tree-link' to={'/statistic'} className="agregator-link">Агрегатор</NavLink>
<TreeView defaultEndIcon={<div style={{ width: 24 }} />} defaultCollapseIcon={<ArrowDropDownIcon/>} defaultExpandIcon={<ArrowRightIcon/>} expanded={expanded} onNodeToggle={handleChange}>
{
data.map(firstLevel =>
<StyledTreeItem nodeId={(nodeCounter++).toString()} key={nodeCounter} name={firstLevel.name} link={'/' + firstLevel.id}>
{
firstLevel.children && firstLevel.children.map(secondLevel =>
<StyledTreeItem nodeId={(nodeCounter++).toString()} key={nodeCounter} name={secondLevel.name} link={`/${firstLevel.id}/${secondLevel.id}`}>
{
secondLevel.children && secondLevel.children.map(thirdLevel => <StyledTreeItem nodeId={(nodeCounter++).toString()} key={nodeCounter} name={thirdLevel.name} link={`/${firstLevel.id}/${secondLevel.id}/${thirdLevel.id}`}/>)
}
</StyledTreeItem>
)
}
</StyledTreeItem>
)
}
<StyledTreeItem nodeId="1" />
</TreeView>
</div>
<div className="page-content">
<Route path={'/statistic'} exact={true} component={StatisticAgregatorPage}/>
<Route path={'/statistic/:objectId'} exact={true} component={StatisticObjectPage}/>
<Route path={'/statistic/:objectId/:consumerId'} exact={true} component={StatisticUserPage}/>
<Route path={'/statistic/:objectId/:consumerId/:deviceId'} exact={true} component={StatisticDevicePage}/>
</div>
</div>
);
}
export default StatisticPage;
|
window.onload = function() {
$(window).on('beforeunload', function() {
$("html body").scrollTop(0);
});
//var bottom = $(document).height() - $(window).height();
//console.log($(window).height());
$("html body").scrollTop(0);
window.scrollTo(0,0);
$(document).scrollTop();
setTimeout(function() {
$("html body").animate({scrollTop:$(document).height()}, 30000);
setTimeout(function () {
$("html body").animate({scrollTop:0}, 30000);
setTimeout(function() {
location.reload();
}, 33000);
}, 35000);
}, 6000);
}
$(function() {
$("html body").scrollTop(0);
$(document).scrollTop(0);
window.scrollTo(0,0);
});
|
const path = require('path');
const Build = require('./index');
class DevBuild extends Build {
constructor(program) {
super(program);
}
init() {
(async () => {
const lib = await this.copyBatch(this.config.lib['dev'], this.config.lib.dist);
})();
(async () => {
const publicDir = await this.copyDir(path.join(this.config.src, 'public'), this.config.build);
const template = await this.formatIndex(path.join(this.config.src, 'public', 'index.html'));
})();
(async () => {
const src = await this.compile();
})();
}
}
module.exports = DevBuild;
|
import React from "react";
export class API {
constructor(basePath, getState, setState) {
this.basePath = basePath;
this.getState = getState;
this.setState = setState;
}
checkFetchAndSet(key, endpoint) {
let value = this.getState(key);
if (!value && !this.fetching) {
this.fetching = true;
fetch(this.basePath + endpoint)
.then(response => response.json())
.then(json => {
this.setState(key, json);
value = json;
this.fetching = false;
})
.catch(error => {
console.error(error);
this.fetching = false;
});
}
return value;
}
getNumBlogs() {
let numBlogs = this.checkFetchAndSet("numBlogs", "blogs/count");
return numBlogs ? numBlogs.count : 0;
}
getLatestPosts(lang = "en") {
return this.checkFetchAndSet("posts-latest-" + lang, "latest/" + lang);
}
}
export const APIContext = React.createContext(new API());
|
const express = require("express");
const Task = require("../../models/task");
const mongoose = require('mongoose');
const validator = require('validator');
const { body, validationResult } = require('express-validator');
const validation = require("../../validation/validation");
const addTaskController = require('./addTask');
const readTasksController = require('./getTasks');
const readTaskController = require('./getTask');
const updateTaskController = require('./patchTask')
const router = new express.Router();
router.post(
'/tasks',
validation.validTask(),
addTaskController
)
router.get(
'/tasks',
readTasksController
)
router.get(
'/tasks/:id',
readTaskController,
)
router.patch(
'/tasks/update/:id',
updateTaskController
)
module.exports = router
|
function update_user_name() {
var userName = $('#userName').val();
if (userName == null || userName == "") {
alert("用户名不能为空");
return false;
}
$.post('/userController/getUserPass', {'userName': userName}, function (data) {
$('#update_pass_name').html(data.ff);
if (data.userEmail != null) {
var email = data.userEmail;
var id = data.userId;
if (confirm('是否往' + email + '发送修改密码的连接')) {
$.post('/email/UpdateUserPass',{'email':email,'id':id},function (yy) {
alert(yy.msg+'即将返回登录页');
location.href = '/login';
});
} else {
alert('您选择了取消找回密码,即将返回登录页面');
location.href = '/login';
}
}
}, "JSON");
}
|
const ERC20 = artifacts.require('./erc20/ERC20.sol')
module.exports = async deployer => {
await deployer.deploy(ERC20, 'Test', 'Test', 1)
}
|
import React from 'react';
import axios from 'axios';
import styles from './styles.css';
import SearchWidget from '../SearchWidget';
import UserInfo from '../UserInfo';
class ListenUp extends React.Component {
constructor(props) {
super(props);
this.state = {
user: null,
showError: false
};
}
searchHandler = (userId) => {
axios.get(`/users/${userId}`)
.then((response) => {
this.setState({
user: response.data,
showError: false
});
})
.catch((err) => {
this.setState({
showError: true
});
})
}
render() {
return (
<div className={styles.main}>
<header className={styles.header}>
<h1>🎧 Listen Up</h1>
</header>
<main className={styles.content}>
<div className={styles.search}>
<SearchWidget searchHandler={this.searchHandler} />
</div>
<div className={styles.results}>
<UserInfo {...this.state} />
</div>
</main>
<footer className={styles.footer}>
Copyright Listen Up 2018
</footer>
</div>
);
}
}
export default ListenUp;
|
import React, {Fragment} from 'react';
import {connect} from 'react-redux';
import {createStructuredSelector} from 'reselect';
import CheckoutItem from '../../components/checkoutItem/';
import {selectcartItems, selectcartTotal} from '../../store/cart/cart.selectors';
import StripeButton from '../../components/stripe-button/';
import {
CheckoutPageContainer,
CheckoutHeaderContainer,
HeaderBlockContainer,
TotalBlock,
WarningDiv
} from './checkout.styles';
import PropTypes from 'prop-types';
const Checkout = ({cartItems, total}) => {
const renderStripeButtonAndWarning = () => {
return (
<>
{
cartItems.length > 0 ?
<Fragment>
<WarningDiv>
*Please use the following test credit card for payment
<br/>
4242 4242 4242 4242
<br/>
Exp: 01/22 - CVV: 123
</WarningDiv>
<div
style={{
margin: '50px 0px'
}}
>
<StripeButton
price={total}
isDisabled={cartItems.length > 0}
/>
</div>
</Fragment>
:null
}
</>
)
}
return (
<CheckoutPageContainer>
<CheckoutHeaderContainer>
<HeaderBlockContainer>
<span>Product</span>
</HeaderBlockContainer>
<HeaderBlockContainer>
<span>Description</span>
</HeaderBlockContainer>
<HeaderBlockContainer>
<span>Quantity</span>
</HeaderBlockContainer>
<HeaderBlockContainer>
<span>Price</span>
</HeaderBlockContainer>
<HeaderBlockContainer>
<span>Remove</span>
</HeaderBlockContainer>
</CheckoutHeaderContainer>
{
cartItems.map(cartItem =>
<CheckoutItem key={cartItem.id} cartItem={cartItem}/>
)
}
<TotalBlock>
<span>TOTAL: ${total}</span>
</TotalBlock>
{renderStripeButtonAndWarning()}
</CheckoutPageContainer>
)
}
const mapStateToProps = createStructuredSelector({
cartItems: selectcartItems,
total: selectcartTotal
});
Checkout.propTypes = {
cartItems: PropTypes.array,
total: PropTypes.number.isRequired
}
export default connect(mapStateToProps,null)(Checkout);
|
import Vue from 'vue'
import Vuex from 'vuex'
import despesas from './modules/despesas'
import poupanca from './modules/poupanca'
import produtos from './modules/produtos'
import tarefas from './modules/tarefas'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
modules: {
despesas,
poupanca,
produtos,
tarefas
},
strict: debug
})
|
import * as yup from 'yup';
const validationSchemaCreateProject = yup.object({
name: yup
.string('Enter your user name')
.min(1, 'It should be of minimum 1 characters length')
.max(50, 'It should be less 50 characters')
.required('Git user name is required'),
project: yup
.string('Enter your project name')
.min(1, 'It should be of minimum 1 characters length')
.max(50, 'It should be less 50 characters')
.required('Git project name is required'),
});
export { validationSchemaCreateProject };
|
const express = require('express')
const router = express.Router()
const GithubController = require('../controllers/github')
const { authentication } = require('../middlewares/auth')
router.use(authentication)
router.get('/stars/:username', GithubController.searchStar)
router.get('/stars/:username/:repo', GithubController.searchStar)
router.post('/repos/create', GithubController.createRepo)
router.get('/repos/:username', GithubController.searchRepo)
router.get('/repos/:username/:repo', GithubController.searchRepo)
router.get('/readme/:username/:repo', GithubController.getReadme)
router.get('/orgs/members/:org', GithubController.getOrgMember)
router.put('/stars/:username/:repo', GithubController.star)
router.delete('/stars/:username/:repo', GithubController.unstar)
module.exports = router
|
const v = {
errors: {},
validateEnter: function (userData) {
this.errors = {};
for (let prop in userData) {
if (userData[prop].length > 50) {
if (!this.errors.hasOwnProperty(prop)) this.errors[prop] = [];
this.errors[prop].push("Too many symbols");
}
if (userData[prop] === "") {
if (!this.errors.hasOwnProperty(prop)) this.errors[prop] = [];
this.errors[prop].push("Empty input");
}
}
if (/[а-яА-я]+/.test(userData.password)) {
if (!this.errors.hasOwnProperty("password")) this.errors["password"] = [];
this.errors["password"].push("Passwrod cant contain cyrillic alphabet");
}
if (!/^\S+@\S+\.\S+$/.test(userData.email)) {
if (!this.errors.hasOwnProperty("email")) this.errors["email"] = [];
this.errors["email"].push("Not an email");
}
if (/\D+/g.test(userData.phone)) {
if (!this.errors.hasOwnProperty("phone")) this.errors["phone"] = [];
this.errors["phone"].push("Phone number can contain only numbers");
}
},
};
export default v;
|
/*EXPECTED
9
*/
class _Main {
static function f (x : number, f : (number) -> number) : number {
return f(x);
}
static function main (args : string[]) : void {
var a = 3;
log _Main.f(a, x => {
return x * x;
});
}
}
|
export default {
header: "FAQ",
view: "Faq"
};
|
var test = require('./lib/test');
var colors = require('cli-color');
var Conf = require('./config/Config');
var fs = require('fs');
return Promise.resolve()
.then(test.createAdmin)
.then(test.createEmission)
.then(() => {
console.log(colors.yellow('Create asset: ' + Conf.asset));
return test.createAsset();
})
.then(() => {
console.log(colors.yellow('Create distr agent'));
return test.createAgent(test.keypairs.distr.accountId(), StellarSdk.xdr.AccountType.accountDistributionAgent().value);
})
//set trust for distr agent created previously
.then(() => {
console.log(colors.yellow('Set trust for distr agent'));
return test.setTrust(test.keypairs.distr);
})
//set commission for all incoming payments for distr agent created previously
.then(() => {
var opts = {
to: test.keypairs.distr.accountId(),
asset: test.asset
};
var flat = 0;
var percent = 0.01;
console.log(colors.yellow('Set commission for distr agent'));
return test.setCommission(opts, flat, percent);
})
//make emission for distr agent created previously
.then(() => {
var amount = 100;
return test.makeEmission(amount);
})
.then(test.createAnonym)
.then(() => {
console.log(colors.yellow('Set trust for anonym'));
return test.setTrust(test.keypairs.anonym);
})
//set commission for all incoming payments for anonymous account
.then(() => {
var opts = {
to: test.keypairs.anonym.accountId(),
asset: test.asset
};
var flat = 0.01;
var percent = 0;
console.log(colors.yellow('Set commission for anonym'));
return test.setCommission(opts, flat, percent);
})
.then(() => {
return test.createInvoice(test.keypairs.anonym, 90);
})
.then((response) => {
if (typeof response == 'undefined' || typeof response.data == 'undefined' || typeof response.data.id == 'undefined') {
return Promise.reject('Unexpected response from api while create invoice');
}
return test.getInvoice(test.keypairs.distr, response.data.id);
})
.then((response) => {
if (
typeof response == 'undefined' ||
typeof response.data == 'undefined' ||
typeof response.data.asset == 'undefined' ||
typeof response.data.amount == 'undefined' ||
typeof response.data.account == 'undefined'
) {
return Promise.reject('Unexpected response from api while get invoice');
}
console.log(colors.yellow('Send money from distr to anonym'));
return test.sendMoney(test.keypairs.distr, response.data.account, response.data.amount);
})
.then(test.createRegisteredUser)
.then(() => {
console.log(colors.yellow('Set trust for registered user'));
return test.setTrust(test.keypairs.registered);
})
.then(() => {
console.log(colors.yellow('Send money from anonym to registered'));
return test.sendMoney(test.keypairs.anonym, test.keypairs.registered.accountId(), 70);
})
.then(() => {
var limits = {
max_operation_out: "-1",
daily_max_out: "-1",
monthly_max_out: "-1",
max_operation_in: "-1",
daily_max_in: "-1",
monthly_max_in: "-1"
};
return test.limitAgent(test.keypairs.distr.accountId(), limits);
})
.then(() => {
return test.restrictAgent(test.keypairs.distr.accountId(), true, true);
})
.then(() => {
console.log(colors.yellow('Create merchant'));
return test.createAgent(test.keypairs.merchant.accountId(), StellarSdk.xdr.AccountType.accountMerchant().value);
})
.then(() => {
console.log(colors.yellow('Set trust for merchant'));
return test.setTrust(test.keypairs.merchant);
})
.then(() => {
console.log(colors.yellow('Send money from registered to merchant'));
return test.sendMoney(test.keypairs.registered, test.keypairs.merchant.accountId(), 50);
})
.then(() => {
return test.createCard(5);
})
.then(() => {
return test.useCard(test.keypairs.card, test.keypairs.anonym.accountId(), 5);
})
//unset commission for all incoming payments for distr agent created previously
.then(() => {
var opts = {
to: test.keypairs.distr.accountId(),
asset: test.asset
};
console.log(colors.yellow('Unset commission for distr agent'));
return test.unsetCommission(opts);
})
//unset commission for all incoming payments for anonymous account
.then(() => {
var opts = {
to: test.keypairs.anonym.accountId(),
asset: test.asset
};
console.log(colors.yellow('Unset commission for anonym'));
return test.unsetCommission(opts);
})
.then(() => {
console.log(colors.yellow('Create exchange'));
return test.createAgent(test.keypairs.exchange.accountId(), StellarSdk.xdr.AccountType.accountExchangeAgent().value);
})
// .then(() => {
// console.log(colors.yellow('Make external payment'));
// return test.makeExternalPayment(23.03, Conf.master_key, test.keypairs.anonym.accountId())
// })
//clear after test
.then(test.deleteAdmin)
.then(test.deleteEmission)
.then(() => {
console.log(colors.black.bgBlue.underline('Test finished'));
})
.catch(err => {
console.error(err);
if (
typeof err != 'undefined' &&
typeof err.response != 'undefined' &&
typeof err.response.data != 'undefined' &&
typeof err.response.data.extras != 'undefined'
) {
console.log(colors.yellow("EXTRAS:"));
console.error(err.response.data.extras);
//StellarSdk.xdr.TransactionEnvelope.fromXDR(
console.log(StellarSdk.xdr.TransactionEnvelope.fromXDR(err.response.data.extras.envelope_xdr, 'base64'));
}
})
.then(() => {
//remove .env
console.log('Remove .env file...');
fs.unlink('../.env');
})
.catch((err) => {
console.error(err);
console.error('Can not delete generated .env file! Remove it manually!!!');
})
.then(() => {
process.exit(0);
});
|
import React from "react";
// node.js library that concatenates classes (strings)
// import classnames from "classnames";
// javascipt plugin for creating charts
// import Chart from "chart.js";
// react plugin used to create charts
// import { Line, Bar } from "react-chartjs-2";
// layout for this page
import Admin from "layouts/Admin.js";
// core components
// import {
// chartOptions,
// parseOptions,
// chartExample1,
// chartExample2,
// } from "variables/charts.js";
import Header from "components/Headers/Header.js";
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
activeNav: 1,
chartExample1Data: "data1",
};
// if (window.Chart) {
// parseOptions(Chart, chartOptions());
// }
}
toggleNavs = (e, index) => {
e.preventDefault();
this.setState({
activeNav: index,
chartExample1Data:
this.state.chartExample1Data === "data1" ? "data2" : "data1",
});
};
render() {
return (
<>
<Header />
{/* Page content */}
<div>
Dashboard
</div>
</>
);
}
}
Dashboard.layout = Admin;
export default Dashboard;
|
import React, { useState } from 'react';
import styled from 'styled-components';
import { ChevronRight } from '@sparkpost/matchbox-icons';
import { Box, ScreenReaderOnly, styles } from '@sparkpost/matchbox';
import { Link } from 'gatsby';
import { tokens } from '@sparkpost/design-tokens';
const StyledHeader = styled(Box)`
cursor: pointer;
`;
const StyledLink = styled(Link)`
text-decoration: none;
`;
const StyledChevronButton = styled(Box)`
${styles.buttonReset}
${styles.focusOutline({ offset: '1px' })}
cursor: pointer;
`;
const StyledChevronRight = styled(ChevronRight)`
transform: ${props => (props.expanded ? 'rotate(-90deg)' : 'rotate(90deg)')};
transition: transform ${tokens.motionDuration_medium}
${tokens.motionEase_in_out};
`;
function ExpandableMenuItem(props) {
const { value, defaultExpanded, firstRoute, children } = props;
const [expanded, setExpanded] = useState(defaultExpanded || false);
const WrapperComponent = defaultExpanded ? Box : StyledLink;
function toggleExpanded() {
setExpanded(!expanded);
}
return (
<Box>
<Box display="flex" mt="500" mb="300">
<Box flex="1">
<WrapperComponent to={!defaultExpanded ? firstRoute : ''}>
<StyledHeader
width="200px"
display="flex"
justifyContent="space-between"
onClick={toggleExpanded}
>
<Box fontSize="300" fontWeight="500" color="gray.700">
{value}
</Box>
</StyledHeader>
</WrapperComponent>
</Box>
<Box flex="0" pr="100" color="gray.500">
<StyledChevronButton as="button" px="300" onClick={toggleExpanded}>
<StyledChevronRight expanded={expanded} />
<ScreenReaderOnly>Toggle Menu Item</ScreenReaderOnly>
</StyledChevronButton>
</Box>
</Box>
{expanded && <Box pl="300">{children}</Box>}
</Box>
);
}
export default ExpandableMenuItem;
|
import createError from './createError'
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
function settle(resolve, reject, response) {
const { validateCode } = response.config;
if (!response.code || !validateCode || validateCode(response.code)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.code,
response.config,
null,
));
}
};
export default settle;
|
import React from 'react';
import BoardUsers from './BoardUsers';
import SidebarInfo from '../../../util/SidebarInfo/SidebarInfo';
const BoardSidebar = () => (
<div className='sidebar'>
<div className='sidebar-wrap'>
<BoardUsers />
<SidebarInfo list='React, React Hooks, Axios, JSONPlaceholder API' />
</div>
</div>
);
export default BoardSidebar;
|
const express = require("express");
const app = express();
const PORT = 4000;
const MySQL = require("mysql");
const Database = require("./database");
const DB = new Database();
const cors = require("cors");
app.use(cors());
const bcrypt = require("bcryptjs");
const SALT_ROUNDS = 8;
const BodyParser = require("body-parser");
app.use(BodyParser.urlencoded({extended: true}));
app.use(BodyParser.json());
const cron = require("node-cron");
const child_process = require("child_process");
cron.schedule("0 18 * * *", function() {
child_process.execFile("yarn", ["run", "backup_sql"], function(err, stdout) {
if (err) console.log(err);
else console.log(stdout);
});
})
const LOW_THRESHOLD = 10;
const multer = require("multer");
const disk_storage = multer.diskStorage({
destination: "client/src/uploads/",
filename: function(req, file, cb) {
let ext;
if (file.mimetype == "image/png")
ext = ".png";
else if (file.mimetype == "image/jpeg")
ext = ".jpeg";
const u = Date.now() + Math.round(Math.random() * 1E9);
cb(null, u + ext);
}
});
const upload = multer({storage: disk_storage});
app.post("/upload_item_images", upload.array("img_items"), function(req, res) {
const files = req.files;
const body = req.body;
const params = [];
const query = `INSERT INTO tbl_image(item_id, filename, path) VALUES ?`;
for (let i = 0; i < files.length; i++) {
const file = files[i];
params.push([body.item_id, file.filename, file.path]);
}
DB.query(query, [params]).then(data => {
res.json(data);
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/backup_data_now", (req, res) => {
child_process.execFile("yarn", ["run", "backup_sql"], function(err, stdout) {
if (err) res.json({success: false, err: err});
else res.json({success: true});
});
});
app.post("/remove_item_image", (req, res) => {
const args = req.body;
const params = [args.item_id, args.filename];
const query = `DELETE FROM tbl_image WHERE image_id = ? AND filename = ?`;
DB.query(query, params).then(data => {
res.json(data);
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/validate_email/:email", (req, res) => {
const args = req.params;
const params = [args.email];
const query = `SELECT user_id FROM tbl_user WHERE email = ?`
DB.query(query, params).then(data => {
res.json(data);
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/register_user", (req, res) => {
const args = req.body;
const pw_hash = bcrypt.hashSync(args.password, SALT_ROUNDS);
const q_user = `INSERT INTO tbl_user(email, pw_hash) VALUES(?, ?)`;
const q_acc = `INSERT INTO tbl_account(fname, mname, lname, birthdate) VALUES(?, ?, ?, ?)`;
DB.query(q_user, [args.email, pw_hash])
.then(data => {
if (data.success) {
DB.query(q_acc, [args.fname, args.mname, args.lname, args.birthdate])
.then(data => {
if (data.success)
res.json(data);
else res.json({success: false});
});
} else res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/sign_in", (req, res) => {
const args = req.body;
const query = `SELECT email, pw_hash FROM tbl_user WHERE email = ?`;
DB.query(query, [args.email])
.then(data => {
if (data.success && data.results.length > 0) {
const match = bcrypt.compareSync(args.password, data.results[0].pw_hash);
res.json({
email: data.results[0].email,
success: match,
});
} else res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/get_profile", (req, res) => {
const args = req.body;
const query = `SELECT fname, mname, lname, birthdate
FROM tbl_account
INNER JOIN tbl_user
ON tbl_account.account_id = tbl_user.user_id
WHERE email = ?`;
DB.query(query, [args.email])
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_item/:item_id", (req, res) => {
const args = req.params;
const query = `SELECT
item.item_id,
item.name,
item.code,
item.qty,
item.orig_price,
item.ret_price,
item.supplier_id,
supplier.name AS supplier_name,
image.image_id,
image.filename
FROM tbl_item as item
LEFT JOIN tbl_image as image ON item.item_id = image.item_id
LEFT JOIN tbl_supplier as supplier ON item.supplier_id = supplier.supplier_id
WHERE item.item_id = ${args.item_id}`;
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_items", (req, res) => {
const args = req.params;
const query = `SELECT
item.item_id,
item.name,
item.code,
item.qty,
item.orig_price,
item.ret_price,
item.supplier_id,
supplier.name AS supplier_name,
image.image_id,
image.filename,
image.path
FROM tbl_item as item
LEFT JOIN tbl_image as image ON item.item_id = image.item_id
LEFT JOIN tbl_supplier as supplier ON item.supplier_id = supplier.supplier_id
GROUP BY item.item_id`;
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_items/:limit", (req, res) => {
const args = req.params;
const query = `SELECT * FROM tbl_item LIMIT ${args.limit}`;
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_items_list", (req, res) => {
const args = req.params;
const query = `SELECT
item_id, name, code, qty, orig_price, ret_price
FROM tbl_item`;
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_items_low", (req, res) => {
const args = req.params;
const query = `SELECT
item_id, name, code, qty, orig_price, ret_price
FROM tbl_item WHERE qty > 0 AND qty < ${LOW_THRESHOLD}`;
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_items_out", (req, res) => {
const args = req.params;
const query = `SELECT
item_id, name, code, qty, orig_price, ret_price
FROM tbl_item WHERE qty = 0`;
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_customers", (req, res) => {
const args = req.params;
const query = `SELECT * FROM tbl_customer`;
DB.query(query)
.then(data => {
if (data.success) res.json(data);
else res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
})
app.get("/get_suppliers", (req, res) => {
const args = req.params;
const query = `SELECT * FROM tbl_supplier`;
DB.query(query)
.then(data => {
if (data.success) res.json(data);
else res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
})
app.get("/get_all_transactions", (req, res) => {
const args = req.params;
const query = `SELECT
t.transaction_id,
DATE_FORMAT(t.transaction_dt, '%m/%d/%Y') AS date,
DATE_FORMAT(t.transaction_dt, '%h:%i:%s %p') AS time,
t.type,
c.customer_id,
c.fullname,
c.address
FROM tbl_transaction as t
INNER JOIN tbl_customer as c ON t.customer_id = c.customer_id`;
DB.query(query)
.then(data => {
if (data.success) res.json(data);
else res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
})
app.post("/get_transactions_range", (req, res) => {
const args = req.body;
const query = `SELECT
t.transaction_id,
DATE_FORMAT(t.transaction_dt, '%m/%d/%Y') AS date,
DATE_FORMAT(t.transaction_dt, '%h:%i:%s %p') AS time,
t.type,
c.customer_id,
c.fullname AS customer_name,
c.address AS customer_address,
sold.item_sold_id,
sold.item_id,
sold.qty_sold,
sold.total_price,
sold.profit,
i.item_id,
i.name AS item_name,
i.code AS item_code
FROM tbl_transaction as t
INNER JOIN tbl_customer as c ON t.customer_id = c.customer_id
INNER JOIN tbl_item_sold as sold ON t.transaction_id = sold.transaction_id
INNER JOIN tbl_item as i ON i.item_id = sold.item_id
WHERE CAST(t.transaction_dt AS DATE) BETWEEN
CAST(? AS DATE) AND CAST(? AS DATE)`;
DB.query(query, [args.date_from, args.date_to])
.then(data => {
if (data.success) res.json(data);
else res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
})
app.get("/get_transaction/:t_id", (req, res) => {
const args = req.params;
const query = `SELECT
t.transaction_id,
DATE_FORMAT(t.transaction_dt, '%m/%d/%Y') AS date,
DATE_FORMAT(t.transaction_dt, '%h:%i:%s %p') AS time,
t.type,
c.customer_id,
c.fullname,
c.address,
sold.item_sold_id,
sold.item_id,
sold.qty_sold,
sold.total_price,
sold.profit,
i.item_id,
i.name,
i.code
FROM tbl_transaction as t
INNER JOIN tbl_customer as c ON t.customer_id = c.customer_id
INNER JOIN tbl_item_sold as sold ON t.transaction_id = sold.transaction_id
INNER JOIN tbl_item as i ON i.item_id = sold.item_id
WHERE t.transaction_id = ${args.t_id};`
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.get("/get_image_by_item_id/:item_id", (req, res) => {
const args = req.params;
const query = `SELECT * FROM tbl_image WHERE item_id = ${args.item_id}`;
DB.query(query)
.then(data => {
if (data.success)
res.json(data);
else
res.json({success: false});
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/upload_item", (req, res) => {
const args = req.body;
const params = [args.name, args.code, args.qty,
args.orig_price, args.ret_price, args.supplier_id];
const query = `INSERT INTO
tbl_item(name, code, qty, orig_price, ret_price, supplier_id)
VALUES(?, ?, ?, ?, ?, ?)`;
DB.query(query, params).then(data => {
res.json(data);
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/update_item", (req, res) => {
const args = req.body;
const params = [args.name, args.code, args.qty,
args.orig_price, args.ret_price, args.supplier_id];
const query = `UPDATE tbl_item SET
name = ?,
code = ?,
qty = ?,
orig_price = ?,
ret_price = ?,
supplier_id = ?
WHERE item_id = ${args.item_id}`;
DB.query(query, params).then(data => {
res.json(data);
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/new_supplier", (req, res) => {
const args = req.body;
const params = [args.name];
const query = `INSERT INTO tbl_supplier(name) VALUES(?)`;
DB.query(query, params).then(data => {
res.json(data);
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/new_customer", (req, res) => {
const args = req.body;
const params = [args.fullname, args.address];
const query = `INSERT INTO tbl_customer(fullname, address) VALUES(?, ?)`;
DB.query(query, params).then(data => {
res.json(data);
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/new_transaction", (req, res) => {
const args = req.body;
const params = [args.type, args.customer_id];
const query = `INSERT INTO tbl_transaction(transaction_dt, type, customer_id)
VALUES(NOW(), ?, ?)`;
DB.query(query, params).then(data => {
if (data.success) {
res.json(data);
}
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.post("/add_item_sold", (req, res) => {
const args = req.body;
const params = [];
const params2 = [];
const query = `INSERT INTO
tbl_item_sold(item_id, qty_sold, total_price, profit, transaction_id)
VALUES ?`;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
params.push([
arg.item_id, arg.qty_sold, arg.total_price,
arg.profit, arg.transaction_id
]);
params2.push([arg.qty_sold, arg.item_id]);
}
DB.query(query, [params]).then(data => {
if (data.success) {
let queries = "";
for (let i = 0; i < params2.length; i++) {
const p = params2[i];
const data = [p[0], p[1]];
queries += MySQL.format("UPDATE tbl_item SET qty = qty - ? WHERE item_id = ?;", data);
}
DB.query(queries).then(data2 => {
res.json(data2);
}).catch(err => res.json({
success: false,
err: err,
}));
}
}).catch(err => res.json({
success: false,
err: err,
}));
});
app.listen(PORT, () => {
console.log(`server listening at http://localhost:${PORT}`)
});
|
const fs = require('fs');
const path = require('path');
const Webpack = require('webpack');
const webpackConfig = require('./webpack.config');
const compiler = Webpack(webpackConfig);
compiler.run((err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
if (stats.hasErrors()) {
console.log(stats.toJson().errors[0]);
return;
}
console.log(
stats.toString({
chunks: !false, // Makes the build much quieter
colors: true // Shows colors in the console
})
);
// write in file
fs.writeFile(
path.resolve(__dirname, 'dist/stats.json'),
JSON.stringify(stats.toJson(), null, 2),
function(err, data) {
if (err) {
console.error(err);
}
console.log('----------file wirte success: dist/stats.json-------------');
}
);
});
|
// Manejo al inicio
$(document).ready(function(){
$("#menu").menu();
$("#capaMensajes").dialog( {autoOpen:false,
modal:true,
width:400
}
);
$('#mnuAltaCliente').click(function(){
// Verifico si ya he cargado el formulario antes
if( $('#capaFrmAltaCliente').size() == 0 ){
$('<div title="Alta cliente" id="capaFrmAltaCliente"></div>').appendTo('#formularios').load("html/frmCliente.html", function(){ $.getScript("js/altaCliente.js")});
} else {
// Lo abro si está cerrado
$('#capaFrmAltaCliente').dialog("open");
}
});
$('#mnuModificarCliente').click(function(){
// Verifico si ya he cargado el formulario antes
if( $('#capaFrmModCliente').size() == 0 ){
$('<div id="capaFrmModCliente"></div>').appendTo('#formularios').load("html/frmModCliente.html", function(){ $.getScript("js/modificarCliente.js")});
} else {
// Lo abro si está cerrado
$('#capaFrmModCliente').dialog("open");
}
});
$('#mnuAltaAlquiler').click(function(){
// Verifico si ya he cargado el formulario antes
if( $('#capaFrmAltaAlquiler').size() == 0 ){
$('<div title="Alta alquiler" id="capaFrmAltaAlquiler"></div>').appendTo('#formularios').load("html/frmAlquiler1.html", function(){ $.getScript("js/altaAlquiler.js")});
} else {
// Lo abro si está cerrado
$('#capaFrmAltaAlquiler').dialog("open");
}
});
//------------------------------------------------------------------------------------------------------
//Aziz---->Vehiculo
$('#mnuAltaVehiculo').click(function(){
// Verifico si ya he cargado el formulario antes
if( $('#frmAltaVehiculo').size() == 0 ){
$('<div title="Alta Vehiculo" id="capaFrmAltaVehiculo"></div>').appendTo('#formularios').load("html/frmVehiculo.html", function(){ $.getScript("js/altaVehiculo.js")});
} else {
// Lo abro si está cerrado
$('#capaFrmAltaVehiculo').dialog("open");
}
});
$('#mnuModificarVehiculo').click(function(){
// Verifico si ya he cargado el formulario antes
if( $('#frmModVehiculo').size() == 0 ){
$('<div title="Modificar Vehiculo" id="capaFrmModVehiculo"></div>').appendTo('#formularios').load("html/frmVehiculo2.html", function(){ $.getScript("js/modVehiculo.js")});
} else {
// Lo abro si está cerrado
$('#capaFrmModVehiculo').dialog("open");
}
});
$('#mnuListado').click(function(){
// Verifico si ya he cargado el formulario antes
if( $('#frmListado').size() == 0 ){
$('<div title="Listados" id="capaListados"></div>').appendTo('#formularios').load("html/frmlistado.html", function(){ $.getScript("js/listados.js")});
} else {
// Lo abro si está cerrado
$('#capaListados').dialog("open");
}
});
});
|
/**
* Created by HP on 30-May-17.
*/
function confirmProduct(product_id, type) {
btn = document.getElementById('action-' + product_id);
status = document.getElementById('status-' + product_id);
$.ajax({
url : "/confirm-product/",
data: {product_id : product_id, type : type, csrfmiddlewaretoken: csrftoken},
type: "POST",
dataType: "json",
success:function(data){
if(data > 0)
{
btn.className="btn btn-success disabled btn-xs";
btn.innerHTML="confirmed!";
}
else
{
btn.className="btn btn-danger btn-xs";
btn.innerHTML="error!";
}
},
error:function () {
btn.className="btn btn-danger btn-xs";
btn.innerHTML="error!";
}
});
}
|
import { useState, useEffect } from "react";
import * as PusherPushNotifications from "@pusher/push-notifications-web";
import Pusher from "pusher-js";
import states from "./userComponents/states/states";
import Nav from "./userComponents/header/nav/nav";
import States from "./userComponents/states/index";
import Details from "./userComponents/details";
import Footer from "./userComponents/footer/footer";
import icon from "./images/pusher-logo.svg";
function App() {
const sampleData = [
[1, "Alabama", 0, 0, 0, 0, 0, 0, 0, 0, "inprogress"],
[1, "Delaware", 0, 0, 0, 0, 0, 0, 0, 0, "inprogress"],
[1, "Florida", 0, 0, 0, 0, 0, 0, 0, 0, "inprogress"],
[1, "Hawaii", 0, 0, 0, 0, 0, 0, 0, 0, "inprogress"],
[1, "Idaho", 0, 0, 0, 0, 0, 0, 0, 0, "inprogress"],
[1, "Kentucky", 0, 0, 0, 0, 0, 0, 0, 0, "inprogress"],
];
const [data, updateData] = useState(sampleData);
const [total, updateTotal] = useState({ message: sampleData[0] });
const [subStatus, updateSubStatus] = useState("subscribe");
const pusher = new Pusher(process.env.REACT_APP_KEY, {
//
cluster: process.env.REACT_APP_CLUSTER,
});
const channel = pusher.subscribe("votes");
channel.bind("vote-event", function (dataFromServer) {
updateData((data) => {
data.splice(
Number(dataFromServer.message[11]),
1,
dataFromServer.message
);
const arr = [...data];
return arr;
});
updateTotal(dataFromServer);
});
useEffect(async () => {
const res = await fetch("https://cryptic-lake-12063.herokuapp.com/"); //https://cryptic-lake-12063.herokuapp.com/
const json = await res.json();
updateTotal(json);
updateData((data) => {
data.splice(Number(json.message[11]), 1, json.message);
const arr = [...data];
return arr;
});
}, []);
const beamsClient = new PusherPushNotifications.Client({
instanceId: process.env.REACT_APP_INSTANCEID,
});
beamsClient
.start()
.then(() => beamsClient.getDeviceId())
.then((deviceId) => {
console.log(deviceId); // Will log something like web-1234-1234-1234-1234
})
.catch((e) => console.error("Could not get device id", e));
function sub() {
if (subStatus === "unsubscribe") {
beamsClient
.start()
.then(() => beamsClient.removeDeviceInterest("hello"))
.then(() => {
// Build something beatiful 🌈
alert("You will not be notified when voting is completed");
updateSubStatus("subscribe");
});
}
beamsClient
.start()
.then(() => beamsClient.addDeviceInterest("vote-event"))
.then(() => {
// Build something beatiful 🌈
alert("You will notified when voting is completed");
updateSubStatus("unsubscribe");
});
}
const [showDetails, setShowDetails] = useState(false);
return (
<div style={{ display: " flex", flexDirection: "row", minHeight: "100vh" }}>
<div
style={{
display: "flex",
justifyContent: "center",
width: "104px",
backgroundColor: "#F2F1F9",
paddingTop: "32px",
flexShrink: "0",
}}
>
<img
src={icon}
alt="Pusher"
width="40px"
height="40px"
style={{ width: "40px", height: "40px" }}
/>
</div>
<div
style={{
width: "100%",
marginLeft: "65px",
marginRight: "65px",
maxWidth: "1208px",
paddingRight: "24px",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
flexWrap: "wrap",
backgroundColor: "",
marginTop: "100px",
minWidth: "539px",
}}
>
<Nav />
<button
onClick={() => sub()}
style={{
color: "white",
backgroundColor: "#7F7FA3",
borderRadius: "4px",
fontSize: "16px",
lineHeight: "28px",
fontWeight: 600,
padding: "4px 16px",
border: "none",
alignSelf: "flex-end",
cursor: "pointer",
marginBottom: "12px",
}}
>
{subStatus}
</button>
</div>
<div
style={{
width: "100%",
height: "2px",
marginTop: "12px",
backgroundColor: "#EEEBFF",
minWidth: "539px",
}}
/>
<div>
{showDetails !== false ? (
<Details
index={showDetails}
regions={data}
src={states[showDetails].src}
col={states[showDetails].color}
candidate={states[showDetails].name}
setShowDetails={setShowDetails}
/>
) : (
<>
<States
total={total}
data={data}
states={states}
setShowDetails={setShowDetails}
/>
<div>
<Footer />
</div>
</>
)}
</div>
</div>
</div>
);
}
export default App;
|
function getHealthCheck(request, response) {
return response.status(200).send({
status: 200,
message: 'api response success!'
})
}
module.exports = getHealthCheck;
|
'use strict';
app.controller('signupController', function($scope, $state, authFactory){
$scope.submitSignup = function(){
authFactory.createUser($scope.email, $scope.password)
.then(res => $state.go('home'));
}
});
|
import React, { useState } from 'react';
import { AsyncStorage } from 'react-native';
const STORAGE_KEY = "@_to_do_data";
export const _storeData = (data) => {
try {
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(data));
} catch (error) {
console.log("Error is saving data", error);
}
}
export const _retrieveData = () => {
try {
return AsyncStorage.getItem(STORAGE_KEY);
} catch (error) {
console.log("Error in fetching data", error);
}
}
export const _deleteData = () => {
try {
AsyncStorage.removeItem(STORAGE_KEY);
} catch (error) {
console.log("Error in fetching data", error);
}
}
|
import React from 'react'
import ModalRoute from 'Components/ModalRoute'
import HardwareWalletModal from 'Components/HardwareWalletModal'
import Layout from 'Components/Layout'
import Access from 'Components/Access'
const Connect = ({ match }) => (
<Layout className='pt-3'>
<Access/>
<ModalRoute basePath={match.path} path='/hw/:walletType' render={(props) => (
<HardwareWalletModal walletType={props.match.params.walletType} {...props}/>
)}/>
</Layout>
)
export default Connect
|
function countHurt(a,b){
return Math.floor(Math.random() * (a-b)) + b;
}
const app = Vue.createApp({
data() {
return {
playerHealth: 100,
monsterHealth: 100,
countGameRound: 0,
storeHumanLog: null,
storeMonsterLog: null,
showLogArr: [],
winning: null
}
},
watch: {
playerHealth(value){
if( value<=0 && this.monsterHealth <=0){
this.winning = "draw";
}
else if(value <= 0){
this.winning = "monster";
}
},
monsterHealth(value){
if( value<=0 && this.playerHealth <=0){
this.winning = "draw";
}
else if(value <= 0){
this.winning = "player";
}
}
},
computed: {
countMonsterHealth(){
if (this.monsterHealth < 0){
return { width: "0%" };
}
return { width: this.monsterHealth + "%"};
},
countPlayerHealth(){
if(this.playerHealth < 0){
return { width: "0%"};
}
return { width: this.playerHealth + "%"};
},
countSpecialAttack(){
return this.countGameRound % 3 !== 0;
},
},
methods: {
restartGame(){
this.playerHealth = 100;
this.monsterHealth = 100;
this.countGameRound = 0;
this.showLog = "";
this.winning = null;
this.showLogArr= [];
},
attackMonster() {
let attackCount = countHurt(5,12);
this.monsterHealth -= attackCount;
this.attackPlayer();
this.showTheLog("player","attack",attackCount);
this.countGameRound++;
},
attackPlayer() {
let attackCount = countHurt(5,15);
this.showTheLog("monster","attack",attackCount);
this.playerHealth -= attackCount;
},
specialAttack() {
let attackCount = countHurt(10,25);
this.monsterHealth -= attackCount;
this.attackPlayer();
this.showTheLog("monster","speailattck",attackCount);
this.countGameRound++;
},
healPlayer() {
let healCount = countHurt(8,16);
if (this.playerHealth + healCount >= 100){
this.playerHealth = 100;
}
else {
this.playerHealth += healCount;
this.showTheLog("player","heal",healCount);
}
this.attackPlayer();
this.countGameRound++;
},
showTheLog(who, what, value) {
this.showLogArr.unshift({
actionBy: who,
actionType: what,
actionValue: value
});
},
surrender(){
this.winning = "monster";
this.playerHealth = 0;
}
}
});
app.mount("#game");
|
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "ts",
typescriptOptions: {
"tsconfig": true
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
packages: {
"app": {
"defaultExtension": "ts",
"meta": {
"*.ts": {
"loader": "ts"
}
}
}
},
map: {
"angular": "github:angular/bower-angular@1.5.8",
"angular-animate": "github:angular/bower-angular-animate@1.5.8",
"angular-aria": "github:angular/bower-angular-aria@1.5.8",
"angular-cookies": "github:angular/bower-angular-cookies@1.5.8",
"angular-material": "github:angular/bower-material@1.0.9",
"angular-messages": "github:angular/bower-angular-messages@1.5.8",
"angular-resource": "github:angular/bower-angular-resource@1.5.8",
"angular-spring-data-rest": "npm:angular-spring-data-rest@0.4.4",
"angular-translate": "github:angular-translate/bower-angular-translate@2.11.1",
"angular-translate-loader-static-files": "github:angular-translate/bower-angular-translate-loader-static-files@2.11.1",
"angular-translate-storage-cookie": "github:angular-translate/bower-angular-translate-storage-cookie@2.11.1",
"angular-translate-storage-local": "github:angular-translate/bower-angular-translate-storage-local@2.11.1",
"angular-trix": "npm:angular-trix@1.0.2",
"angular-ui-bootstrap": "npm:angular-ui-bootstrap@2.0.1",
"bootstrap": "github:twbs/bootstrap@3.3.7",
"css": "github:systemjs/plugin-css@0.1.26",
"lf-ng-md-file-input": "npm:lf-ng-md-file-input@1.4.8",
"ng-table": "github:esvit/ng-table@1.0.0",
"ngmap": "github:allenhwkim/angularjs-google-maps@1.17.6",
"ts": "github:frankwallis/plugin-typescript@5.0.8",
"ts-runtime": "npm:babel-runtime@5.8.38",
"typescript": "npm:typescript@1.8.10",
"github:angular-translate/bower-angular-translate-loader-static-files@2.11.1": {
"angular-translate": "github:angular-translate/bower-angular-translate@2.11.1"
},
"github:angular-translate/bower-angular-translate-storage-cookie@2.11.1": {
"angular-translate": "github:angular-translate/bower-angular-translate@2.11.1"
},
"github:angular-translate/bower-angular-translate-storage-local@2.11.1": {
"angular-translate": "github:angular-translate/bower-angular-translate@2.11.1"
},
"github:angular-translate/bower-angular-translate@2.11.1": {
"angular": "github:angular/bower-angular@1.5.8"
},
"github:angular/bower-angular-animate@1.5.8": {
"angular": "github:angular/bower-angular@1.5.8"
},
"github:angular/bower-angular-aria@1.5.8": {
"angular": "github:angular/bower-angular@1.5.8"
},
"github:angular/bower-angular-cookies@1.5.8": {
"angular": "github:angular/bower-angular@1.5.8"
},
"github:angular/bower-angular-messages@1.5.8": {
"angular": "github:angular/bower-angular@1.5.8"
},
"github:angular/bower-angular-resource@1.5.8": {
"angular": "github:angular/bower-angular@1.5.8"
},
"github:angular/bower-material@1.0.9": {
"angular": "github:angular/bower-angular@1.5.8",
"angular-animate": "github:angular/bower-angular-animate@1.5.8",
"angular-aria": "github:angular/bower-angular-aria@1.5.8",
"css": "github:systemjs/plugin-css@0.1.26"
},
"github:frankwallis/plugin-typescript@5.0.8": {
"typescript": "npm:typescript@2.0.0"
},
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.4.1"
},
"github:jspm/nodelibs-buffer@0.1.0": {
"buffer": "npm:buffer@3.6.0"
},
"github:jspm/nodelibs-constants@0.1.0": {
"constants-browserify": "npm:constants-browserify@0.0.1"
},
"github:jspm/nodelibs-crypto@0.1.0": {
"crypto-browserify": "npm:crypto-browserify@3.11.0"
},
"github:jspm/nodelibs-events@0.1.1": {
"events": "npm:events@1.0.2"
},
"github:jspm/nodelibs-http@1.7.1": {
"Base64": "npm:Base64@0.2.1",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"github:jspm/nodelibs-https@0.1.0": {
"https-browserify": "npm:https-browserify@0.0.0"
},
"github:jspm/nodelibs-net@0.1.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"http": "github:jspm/nodelibs-http@1.7.1",
"net": "github:jspm/nodelibs-net@0.1.2",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"timers": "github:jspm/nodelibs-timers@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"github:jspm/nodelibs-os@0.1.0": {
"os-browserify": "npm:os-browserify@0.1.2"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.9"
},
"github:jspm/nodelibs-stream@0.1.0": {
"stream-browserify": "npm:stream-browserify@1.0.0"
},
"github:jspm/nodelibs-string_decoder@0.1.0": {
"string_decoder": "npm:string_decoder@0.10.31"
},
"github:jspm/nodelibs-timers@0.1.0": {
"timers-browserify": "npm:timers-browserify@1.4.2"
},
"github:jspm/nodelibs-tty@0.1.0": {
"tty-browserify": "npm:tty-browserify@0.0.0"
},
"github:jspm/nodelibs-url@0.1.0": {
"url": "npm:url@0.10.3"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"github:jspm/nodelibs-vm@0.1.0": {
"vm-browserify": "npm:vm-browserify@0.0.4"
},
"github:twbs/bootstrap@3.3.7": {
"jquery": "npm:jquery@2.2.4"
},
"npm:align-text@0.1.4": {
"kind-of": "npm:kind-of@3.0.4",
"longest": "npm:longest@1.0.1",
"repeat-string": "npm:repeat-string@1.5.4"
},
"npm:amdefine@1.0.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"module": "github:jspm/nodelibs-module@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:angular-spring-data-rest@0.4.4": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:angular-trix@1.0.2": {
"angular": "npm:angular@1.5.8",
"trix": "npm:trix@0.9.9"
},
"npm:arr-diff@2.0.0": {
"arr-flatten": "npm:arr-flatten@1.0.1"
},
"npm:asn1.js@4.8.1": {
"bn.js": "npm:bn.js@4.11.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:assert@1.4.1": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"util": "npm:util@0.10.3"
},
"npm:async@0.2.10": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:babel-runtime@5.8.38": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:beeper@1.1.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:bn.js@4.11.6": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:brace-expansion@1.1.6": {
"balanced-match": "npm:balanced-match@0.4.2",
"concat-map": "npm:concat-map@0.0.1"
},
"npm:braces@1.8.5": {
"expand-range": "npm:expand-range@1.8.2",
"preserve": "npm:preserve@0.2.0",
"repeat-element": "npm:repeat-element@1.1.2"
},
"npm:browserify-aes@1.0.6": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"buffer-xor": "npm:buffer-xor@1.0.3",
"cipher-base": "npm:cipher-base@1.0.3",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:browserify-cipher@1.0.0": {
"browserify-aes": "npm:browserify-aes@1.0.6",
"browserify-des": "npm:browserify-des@1.0.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0"
},
"npm:browserify-des@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.3",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"des.js": "npm:des.js@1.0.0",
"inherits": "npm:inherits@2.0.1"
},
"npm:browserify-rsa@4.0.1": {
"bn.js": "npm:bn.js@4.11.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"constants": "github:jspm/nodelibs-constants@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"randombytes": "npm:randombytes@2.0.3"
},
"npm:browserify-sign@4.0.0": {
"bn.js": "npm:bn.js@4.11.6",
"browserify-rsa": "npm:browserify-rsa@4.0.1",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.3.2",
"inherits": "npm:inherits@2.0.1",
"parse-asn1": "npm:parse-asn1@5.0.0",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:buffer-xor@1.0.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:buffer@3.6.0": {
"base64-js": "npm:base64-js@0.0.8",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"ieee754": "npm:ieee754@1.1.8",
"isarray": "npm:isarray@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:bufferstreams@1.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"readable-stream": "npm:readable-stream@1.0.34",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:builtin-modules@1.1.1": {
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:camelcase-keys@2.1.0": {
"camelcase": "npm:camelcase@2.1.1",
"map-obj": "npm:map-obj@1.0.1"
},
"npm:center-align@0.1.3": {
"align-text": "npm:align-text@0.1.4",
"lazy-cache": "npm:lazy-cache@1.0.4"
},
"npm:chalk@1.1.3": {
"ansi-styles": "npm:ansi-styles@2.2.1",
"escape-string-regexp": "npm:escape-string-regexp@1.0.5",
"has-ansi": "npm:has-ansi@2.0.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"strip-ansi": "npm:strip-ansi@3.0.1",
"supports-color": "npm:supports-color@2.0.0"
},
"npm:cipher-base@1.0.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"string_decoder": "github:jspm/nodelibs-string_decoder@0.1.0"
},
"npm:clean-css@3.4.20": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"commander": "npm:commander@2.8.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"http": "github:jspm/nodelibs-http@1.7.1",
"https": "github:jspm/nodelibs-https@0.1.0",
"os": "github:jspm/nodelibs-os@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"source-map": "npm:source-map@0.4.4",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:cliui@2.1.0": {
"center-align": "npm:center-align@0.1.3",
"right-align": "npm:right-align@0.1.3",
"wordwrap": "npm:wordwrap@0.0.2"
},
"npm:clone-stats@0.0.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:clone@0.2.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:clone@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:commander@2.8.1": {
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"graceful-readlink": "npm:graceful-readlink@1.0.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:constants-browserify@0.0.1": {
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:core-util-is@1.0.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:create-ecdh@4.0.0": {
"bn.js": "npm:bn.js@4.11.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"elliptic": "npm:elliptic@6.3.2"
},
"npm:create-hash@1.1.2": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"cipher-base": "npm:cipher-base@1.0.3",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"ripemd160": "npm:ripemd160@1.0.1",
"sha.js": "npm:sha.js@2.4.5"
},
"npm:create-hmac@1.1.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"inherits": "npm:inherits@2.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:crypto-browserify@3.11.0": {
"browserify-cipher": "npm:browserify-cipher@1.0.0",
"browserify-sign": "npm:browserify-sign@4.0.0",
"create-ecdh": "npm:create-ecdh@4.0.0",
"create-hash": "npm:create-hash@1.1.2",
"create-hmac": "npm:create-hmac@1.1.4",
"diffie-hellman": "npm:diffie-hellman@5.0.2",
"inherits": "npm:inherits@2.0.1",
"pbkdf2": "npm:pbkdf2@3.0.9",
"public-encrypt": "npm:public-encrypt@4.0.0",
"randombytes": "npm:randombytes@2.0.3"
},
"npm:currently-unhandled@0.4.1": {
"array-find-index": "npm:array-find-index@1.0.2",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:dateformat@1.0.12": {
"get-stdin": "npm:get-stdin@4.0.1",
"meow": "npm:meow@3.7.0"
},
"npm:defaults@1.0.3": {
"clone": "npm:clone@1.0.2"
},
"npm:des.js@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"inherits": "npm:inherits@2.0.1",
"minimalistic-assert": "npm:minimalistic-assert@1.0.0"
},
"npm:detect-file@0.1.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"fs-exists-sync": "npm:fs-exists-sync@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:diffie-hellman@5.0.2": {
"bn.js": "npm:bn.js@4.11.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"miller-rabin": "npm:miller-rabin@4.0.0",
"randombytes": "npm:randombytes@2.0.3",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:duplexer2@0.0.2": {
"readable-stream": "npm:readable-stream@1.1.14"
},
"npm:elliptic@6.3.2": {
"bn.js": "npm:bn.js@4.11.6",
"brorand": "npm:brorand@1.0.6",
"hash.js": "npm:hash.js@1.0.3",
"inherits": "npm:inherits@2.0.1",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:end-of-stream@0.1.5": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"net": "github:jspm/nodelibs-net@0.1.2",
"once": "npm:once@1.3.3",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:error-ex@1.3.0": {
"is-arrayish": "npm:is-arrayish@0.2.1",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:evp_bytestokey@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0"
},
"npm:expand-brackets@0.1.5": {
"is-posix-bracket": "npm:is-posix-bracket@0.1.1"
},
"npm:expand-range@1.8.2": {
"fill-range": "npm:fill-range@2.2.3"
},
"npm:expand-tilde@1.2.2": {
"os-homedir": "npm:os-homedir@1.0.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:extglob@0.3.2": {
"is-extglob": "npm:is-extglob@1.0.0"
},
"npm:fancy-log@1.2.0": {
"chalk": "npm:chalk@1.1.3",
"process": "github:jspm/nodelibs-process@0.1.2",
"time-stamp": "npm:time-stamp@1.0.1"
},
"npm:fill-range@2.2.3": {
"is-number": "npm:is-number@2.1.0",
"isobject": "npm:isobject@2.1.0",
"randomatic": "npm:randomatic@1.1.5",
"repeat-element": "npm:repeat-element@1.1.2",
"repeat-string": "npm:repeat-string@1.5.4"
},
"npm:find-up@1.1.2": {
"path": "github:jspm/nodelibs-path@0.1.0",
"path-exists": "npm:path-exists@2.1.0",
"pinkie-promise": "npm:pinkie-promise@2.0.1"
},
"npm:findup-sync@0.4.2": {
"detect-file": "npm:detect-file@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"is-glob": "npm:is-glob@2.0.1",
"micromatch": "npm:micromatch@2.3.11",
"path": "github:jspm/nodelibs-path@0.1.0",
"resolve-dir": "npm:resolve-dir@0.1.1"
},
"npm:fined@1.0.2": {
"expand-tilde": "npm:expand-tilde@1.2.2",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"lodash.assignwith": "npm:lodash.assignwith@4.2.0",
"lodash.isempty": "npm:lodash.isempty@4.4.0",
"lodash.isplainobject": "npm:lodash.isplainobject@4.0.6",
"lodash.isstring": "npm:lodash.isstring@4.0.1",
"lodash.pick": "npm:lodash.pick@4.4.0",
"parse-filepath": "npm:parse-filepath@1.0.1",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:first-chunk-stream@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:flagged-respawn@0.3.2": {
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:for-own@0.1.4": {
"for-in": "npm:for-in@0.1.6"
},
"npm:fs-exists-sync@0.1.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:gaze@0.5.2": {
"events": "github:jspm/nodelibs-events@0.1.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"globule": "npm:globule@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"timers": "github:jspm/nodelibs-timers@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:get-stdin@4.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:glob-base@0.3.0": {
"glob-parent": "npm:glob-parent@2.0.0",
"is-glob": "npm:is-glob@2.0.1",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:glob-parent@2.0.0": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"is-glob": "npm:is-glob@2.0.1",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:glob-stream@3.1.18": {
"glob": "npm:glob@4.5.3",
"glob2base": "npm:glob2base@0.0.12",
"minimatch": "npm:minimatch@2.0.10",
"ordered-read-streams": "npm:ordered-read-streams@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"through2": "npm:through2@0.6.5",
"unique-stream": "npm:unique-stream@1.0.0"
},
"npm:glob-watcher@0.0.6": {
"events": "github:jspm/nodelibs-events@0.1.1",
"gaze": "npm:gaze@0.5.2"
},
"npm:glob2base@0.0.12": {
"find-index": "npm:find-index@0.1.1",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:glob@3.1.21": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"graceful-fs": "npm:graceful-fs@1.2.3",
"inherits": "npm:inherits@1.0.2",
"minimatch": "npm:minimatch@0.2.14",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:glob@4.5.3": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inflight": "npm:inflight@1.0.5",
"inherits": "npm:inherits@2.0.1",
"minimatch": "npm:minimatch@2.0.10",
"once": "npm:once@1.3.3",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:global-modules@0.2.3": {
"global-prefix": "npm:global-prefix@0.1.4",
"is-windows": "npm:is-windows@0.2.0",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:global-prefix@0.1.4": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"ini": "npm:ini@1.3.4",
"is-windows": "npm:is-windows@0.2.0",
"osenv": "npm:osenv@0.1.3",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"which": "npm:which@1.2.11"
},
"npm:globule@0.1.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"glob": "npm:glob@3.1.21",
"lodash": "npm:lodash@1.0.2",
"minimatch": "npm:minimatch@0.2.14",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:glogg@1.0.0": {
"sparkles": "npm:sparkles@1.0.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:graceful-fs@1.2.3": {
"constants": "github:jspm/nodelibs-constants@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:graceful-fs@3.0.11": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"constants": "github:jspm/nodelibs-constants@0.1.0",
"natives": "npm:natives@1.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:graceful-fs@4.1.9": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"constants": "github:jspm/nodelibs-constants@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:graceful-readlink@1.0.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2"
},
"npm:gulp-minify-css@1.2.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"clean-css": "npm:clean-css@3.4.20",
"gulp-util": "npm:gulp-util@3.0.7",
"object-assign": "npm:object-assign@4.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"readable-stream": "npm:readable-stream@2.0.6",
"vinyl-bufferstream": "npm:vinyl-bufferstream@1.0.1",
"vinyl-sourcemaps-apply": "npm:vinyl-sourcemaps-apply@0.2.1"
},
"npm:gulp-uglify@1.5.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"deap": "npm:deap@1.0.0",
"fancy-log": "npm:fancy-log@1.2.0",
"gulp-util": "npm:gulp-util@3.0.7",
"isobject": "npm:isobject@2.1.0",
"through2": "npm:through2@2.0.1",
"uglify-js": "npm:uglify-js@2.6.4",
"uglify-save-license": "npm:uglify-save-license@0.4.1",
"vinyl-sourcemaps-apply": "npm:vinyl-sourcemaps-apply@0.2.1"
},
"npm:gulp-util@3.0.7": {
"array-differ": "npm:array-differ@1.0.0",
"array-uniq": "npm:array-uniq@1.0.3",
"beeper": "npm:beeper@1.1.0",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"chalk": "npm:chalk@1.1.3",
"dateformat": "npm:dateformat@1.0.12",
"fancy-log": "npm:fancy-log@1.2.0",
"gulplog": "npm:gulplog@1.0.0",
"has-gulplog": "npm:has-gulplog@0.1.0",
"lodash._reescape": "npm:lodash._reescape@3.0.0",
"lodash._reevaluate": "npm:lodash._reevaluate@3.0.0",
"lodash._reinterpolate": "npm:lodash._reinterpolate@3.0.0",
"lodash.template": "npm:lodash.template@3.6.2",
"minimist": "npm:minimist@1.2.0",
"multipipe": "npm:multipipe@0.1.2",
"object-assign": "npm:object-assign@3.0.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"replace-ext": "npm:replace-ext@0.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0",
"through2": "npm:through2@2.0.1",
"util": "github:jspm/nodelibs-util@0.1.0",
"vinyl": "npm:vinyl@0.5.3"
},
"npm:gulp@3.9.1": {
"archy": "npm:archy@1.0.0",
"chalk": "npm:chalk@1.1.3",
"deprecated": "npm:deprecated@0.0.1",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"gulp-util": "npm:gulp-util@3.0.7",
"interpret": "npm:interpret@1.0.1",
"liftoff": "npm:liftoff@2.3.0",
"minimist": "npm:minimist@1.2.0",
"orchestrator": "npm:orchestrator@0.3.7",
"path": "github:jspm/nodelibs-path@0.1.0",
"pretty-hrtime": "npm:pretty-hrtime@1.0.2",
"process": "github:jspm/nodelibs-process@0.1.2",
"semver": "npm:semver@4.3.6",
"systemjs-json": "github:systemjs/plugin-json@0.1.2",
"tildify": "npm:tildify@1.2.0",
"util": "github:jspm/nodelibs-util@0.1.0",
"v8flags": "npm:v8flags@2.0.11",
"vinyl-fs": "npm:vinyl-fs@0.3.14"
},
"npm:gulplog@1.0.0": {
"glogg": "npm:glogg@1.0.0"
},
"npm:has-ansi@2.0.0": {
"ansi-regex": "npm:ansi-regex@2.0.0"
},
"npm:has-gulplog@0.1.0": {
"sparkles": "npm:sparkles@1.0.0"
},
"npm:hash.js@1.0.3": {
"inherits": "npm:inherits@2.0.1"
},
"npm:hosted-git-info@2.1.5": {
"url": "github:jspm/nodelibs-url@0.1.0"
},
"npm:https-browserify@0.0.0": {
"http": "github:jspm/nodelibs-http@1.7.1"
},
"npm:indent-string@2.1.0": {
"repeating": "npm:repeating@2.0.1"
},
"npm:inflight@1.0.5": {
"once": "npm:once@1.3.3",
"process": "github:jspm/nodelibs-process@0.1.2",
"wrappy": "npm:wrappy@1.0.2"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:ini@1.3.4": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:is-absolute@0.2.5": {
"is-relative": "npm:is-relative@0.2.1",
"is-windows": "npm:is-windows@0.1.1"
},
"npm:is-buffer@1.1.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:is-builtin-module@1.0.0": {
"builtin-modules": "npm:builtin-modules@1.1.1"
},
"npm:is-equal-shallow@0.1.3": {
"is-primitive": "npm:is-primitive@2.0.0"
},
"npm:is-finite@1.0.2": {
"number-is-nan": "npm:number-is-nan@1.0.1"
},
"npm:is-glob@2.0.1": {
"is-extglob": "npm:is-extglob@1.0.0"
},
"npm:is-number@2.1.0": {
"kind-of": "npm:kind-of@3.0.4"
},
"npm:is-relative@0.2.1": {
"is-unc-path": "npm:is-unc-path@0.1.1"
},
"npm:is-unc-path@0.1.1": {
"unc-path-regex": "npm:unc-path-regex@0.1.2"
},
"npm:is-windows@0.1.1": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:is-windows@0.2.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:isexe@1.1.2": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:isobject@2.1.0": {
"isarray": "npm:isarray@1.0.0"
},
"npm:kind-of@3.0.4": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"is-buffer": "npm:is-buffer@1.1.4"
},
"npm:lazy-cache@1.0.4": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:lf-ng-md-file-input@1.4.8": {
"gulp": "npm:gulp@3.9.1",
"gulp-minify-css": "npm:gulp-minify-css@1.2.4",
"gulp-uglify": "npm:gulp-uglify@1.5.4",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:liftoff@2.3.0": {
"events": "github:jspm/nodelibs-events@0.1.1",
"extend": "npm:extend@3.0.0",
"findup-sync": "npm:findup-sync@0.4.2",
"fined": "npm:fined@1.0.2",
"flagged-respawn": "npm:flagged-respawn@0.3.2",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"lodash.isplainobject": "npm:lodash.isplainobject@4.0.6",
"lodash.isstring": "npm:lodash.isstring@4.0.1",
"lodash.mapvalues": "npm:lodash.mapvalues@4.6.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"rechoir": "npm:rechoir@0.6.2",
"resolve": "npm:resolve@1.1.7",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:load-json-file@1.1.0": {
"graceful-fs": "npm:graceful-fs@4.1.9",
"parse-json": "npm:parse-json@2.2.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"pify": "npm:pify@2.3.0",
"pinkie-promise": "npm:pinkie-promise@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"strip-bom": "npm:strip-bom@2.0.0"
},
"npm:lodash._basetostring@3.0.1": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:lodash.escape@3.2.0": {
"lodash._root": "npm:lodash._root@3.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:lodash.isempty@4.4.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:lodash.keys@3.1.2": {
"lodash._getnative": "npm:lodash._getnative@3.9.1",
"lodash.isarguments": "npm:lodash.isarguments@3.1.0",
"lodash.isarray": "npm:lodash.isarray@3.0.4"
},
"npm:lodash.mapvalues@4.6.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:lodash.template@3.6.2": {
"lodash._basecopy": "npm:lodash._basecopy@3.0.1",
"lodash._basetostring": "npm:lodash._basetostring@3.0.1",
"lodash._basevalues": "npm:lodash._basevalues@3.0.0",
"lodash._isiterateecall": "npm:lodash._isiterateecall@3.0.9",
"lodash._reinterpolate": "npm:lodash._reinterpolate@3.0.0",
"lodash.escape": "npm:lodash.escape@3.2.0",
"lodash.keys": "npm:lodash.keys@3.1.2",
"lodash.restparam": "npm:lodash.restparam@3.6.1",
"lodash.templatesettings": "npm:lodash.templatesettings@3.1.1"
},
"npm:lodash.templatesettings@3.1.1": {
"lodash._reinterpolate": "npm:lodash._reinterpolate@3.0.0",
"lodash.escape": "npm:lodash.escape@3.2.0"
},
"npm:lodash@1.0.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:loud-rejection@1.6.0": {
"currently-unhandled": "npm:currently-unhandled@0.4.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"signal-exit": "npm:signal-exit@3.0.1",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:meow@3.7.0": {
"camelcase-keys": "npm:camelcase-keys@2.1.0",
"decamelize": "npm:decamelize@1.2.0",
"loud-rejection": "npm:loud-rejection@1.6.0",
"map-obj": "npm:map-obj@1.0.1",
"minimist": "npm:minimist@1.2.0",
"normalize-package-data": "npm:normalize-package-data@2.3.5",
"object-assign": "npm:object-assign@4.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"read-pkg-up": "npm:read-pkg-up@1.0.1",
"redent": "npm:redent@1.0.0",
"trim-newlines": "npm:trim-newlines@1.0.0"
},
"npm:micromatch@2.3.11": {
"arr-diff": "npm:arr-diff@2.0.0",
"array-unique": "npm:array-unique@0.2.1",
"braces": "npm:braces@1.8.5",
"expand-brackets": "npm:expand-brackets@0.1.5",
"extglob": "npm:extglob@0.3.2",
"filename-regex": "npm:filename-regex@2.0.0",
"is-extglob": "npm:is-extglob@1.0.0",
"is-glob": "npm:is-glob@2.0.1",
"kind-of": "npm:kind-of@3.0.4",
"normalize-path": "npm:normalize-path@2.0.1",
"object.omit": "npm:object.omit@2.0.0",
"parse-glob": "npm:parse-glob@3.0.4",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"regex-cache": "npm:regex-cache@0.4.3"
},
"npm:miller-rabin@4.0.0": {
"bn.js": "npm:bn.js@4.11.6",
"brorand": "npm:brorand@1.0.6"
},
"npm:minimatch@0.2.14": {
"lru-cache": "npm:lru-cache@2.7.3",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"sigmund": "npm:sigmund@1.0.1"
},
"npm:minimatch@2.0.10": {
"brace-expansion": "npm:brace-expansion@1.1.6",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:mkdirp@0.5.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"minimist": "npm:minimist@0.0.8",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:multipipe@0.1.2": {
"duplexer2": "npm:duplexer2@0.0.2",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:natives@1.1.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"module": "github:jspm/nodelibs-module@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:normalize-package-data@2.3.5": {
"hosted-git-info": "npm:hosted-git-info@2.1.5",
"is-builtin-module": "npm:is-builtin-module@1.0.0",
"semver": "npm:semver@5.3.0",
"systemjs-json": "github:systemjs/plugin-json@0.1.2",
"url": "github:jspm/nodelibs-url@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0",
"validate-npm-package-license": "npm:validate-npm-package-license@3.0.1"
},
"npm:object.omit@2.0.0": {
"for-own": "npm:for-own@0.1.4",
"is-extendable": "npm:is-extendable@0.1.1"
},
"npm:once@1.3.3": {
"wrappy": "npm:wrappy@1.0.2"
},
"npm:orchestrator@0.3.7": {
"end-of-stream": "npm:end-of-stream@0.1.5",
"events": "github:jspm/nodelibs-events@0.1.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"sequencify": "npm:sequencify@0.0.7",
"stream-consume": "npm:stream-consume@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:ordered-read-streams@0.1.0": {
"stream": "github:jspm/nodelibs-stream@0.1.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:os-browserify@0.1.2": {
"os": "github:jspm/nodelibs-os@0.1.0"
},
"npm:os-homedir@1.0.2": {
"os": "github:jspm/nodelibs-os@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:os-tmpdir@1.0.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:osenv@0.1.3": {
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"os-homedir": "npm:os-homedir@1.0.2",
"os-tmpdir": "npm:os-tmpdir@1.0.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:parse-asn1@5.0.0": {
"asn1.js": "npm:asn1.js@4.8.1",
"browserify-aes": "npm:browserify-aes@1.0.6",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"evp_bytestokey": "npm:evp_bytestokey@1.0.0",
"pbkdf2": "npm:pbkdf2@3.0.9",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:parse-filepath@1.0.1": {
"is-absolute": "npm:is-absolute@0.2.5",
"map-cache": "npm:map-cache@0.2.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"path-root": "npm:path-root@0.1.1"
},
"npm:parse-glob@3.0.4": {
"glob-base": "npm:glob-base@0.3.0",
"is-dotfile": "npm:is-dotfile@1.0.2",
"is-extglob": "npm:is-extglob@1.0.0",
"is-glob": "npm:is-glob@2.0.1"
},
"npm:parse-json@2.2.0": {
"error-ex": "npm:error-ex@1.3.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:path-exists@2.1.0": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"pinkie-promise": "npm:pinkie-promise@2.0.1"
},
"npm:path-root@0.1.1": {
"path-root-regex": "npm:path-root-regex@0.1.2"
},
"npm:path-type@1.1.0": {
"graceful-fs": "npm:graceful-fs@4.1.9",
"pify": "npm:pify@2.3.0",
"pinkie-promise": "npm:pinkie-promise@2.0.1"
},
"npm:pbkdf2@3.0.9": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hmac": "npm:create-hmac@1.1.4",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:pify@2.3.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:pinkie-promise@2.0.1": {
"pinkie": "npm:pinkie@2.0.4"
},
"npm:process-nextick-args@1.0.7": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:process@0.11.9": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"vm": "github:jspm/nodelibs-vm@0.1.0"
},
"npm:public-encrypt@4.0.0": {
"bn.js": "npm:bn.js@4.11.6",
"browserify-rsa": "npm:browserify-rsa@4.0.1",
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"create-hash": "npm:create-hash@1.1.2",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"parse-asn1": "npm:parse-asn1@5.0.0",
"randombytes": "npm:randombytes@2.0.3"
},
"npm:punycode@1.3.2": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:randomatic@1.1.5": {
"is-number": "npm:is-number@2.1.0",
"kind-of": "npm:kind-of@3.0.4"
},
"npm:randombytes@2.0.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:read-pkg-up@1.0.1": {
"find-up": "npm:find-up@1.1.2",
"read-pkg": "npm:read-pkg@1.1.0"
},
"npm:read-pkg@1.1.0": {
"load-json-file": "npm:load-json-file@1.1.0",
"normalize-package-data": "npm:normalize-package-data@2.3.5",
"path": "github:jspm/nodelibs-path@0.1.0",
"path-type": "npm:path-type@1.1.0"
},
"npm:readable-stream@1.0.34": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
},
"npm:readable-stream@1.1.14": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@0.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream-browserify": "npm:stream-browserify@1.0.0",
"string_decoder": "npm:string_decoder@0.10.31"
},
"npm:readable-stream@2.0.6": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"core-util-is": "npm:core-util-is@1.0.2",
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"isarray": "npm:isarray@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"process-nextick-args": "npm:process-nextick-args@1.0.7",
"string_decoder": "npm:string_decoder@0.10.31",
"util-deprecate": "npm:util-deprecate@1.0.2"
},
"npm:rechoir@0.6.2": {
"path": "github:jspm/nodelibs-path@0.1.0",
"resolve": "npm:resolve@1.1.7"
},
"npm:redent@1.0.0": {
"indent-string": "npm:indent-string@2.1.0",
"strip-indent": "npm:strip-indent@1.0.1"
},
"npm:regex-cache@0.4.3": {
"is-equal-shallow": "npm:is-equal-shallow@0.1.3",
"is-primitive": "npm:is-primitive@2.0.0"
},
"npm:repeating@2.0.1": {
"is-finite": "npm:is-finite@1.0.2"
},
"npm:replace-ext@0.0.1": {
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:resolve-dir@0.1.1": {
"expand-tilde": "npm:expand-tilde@1.2.2",
"global-modules": "npm:global-modules@0.2.3",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:resolve@1.1.7": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:right-align@0.1.3": {
"align-text": "npm:align-text@0.1.4"
},
"npm:ripemd160@1.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:semver@4.3.6": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:semver@5.3.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:sha.js@2.4.5": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:sigmund@1.0.1": {
"http": "github:jspm/nodelibs-http@1.7.1",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:signal-exit@3.0.1": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"events": "github:jspm/nodelibs-events@0.1.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:source-map@0.4.4": {
"amdefine": "npm:amdefine@1.0.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:source-map@0.5.6": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:sparkles@1.0.0": {
"events": "github:jspm/nodelibs-events@0.1.1"
},
"npm:spdx-correct@1.0.2": {
"spdx-license-ids": "npm:spdx-license-ids@1.2.2"
},
"npm:spdx-expression-parse@1.0.4": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:spdx-license-ids@1.2.2": {
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:stream-browserify@1.0.0": {
"events": "github:jspm/nodelibs-events@0.1.1",
"inherits": "npm:inherits@2.0.1",
"readable-stream": "npm:readable-stream@1.1.14"
},
"npm:string_decoder@0.10.31": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0"
},
"npm:strip-ansi@3.0.1": {
"ansi-regex": "npm:ansi-regex@2.0.0"
},
"npm:strip-bom@1.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"first-chunk-stream": "npm:first-chunk-stream@1.0.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"is-utf8": "npm:is-utf8@0.2.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:strip-bom@2.0.0": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"is-utf8": "npm:is-utf8@0.2.1"
},
"npm:strip-indent@1.0.1": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"get-stdin": "npm:get-stdin@4.0.1",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:supports-color@2.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:through2@0.6.5": {
"process": "github:jspm/nodelibs-process@0.1.2",
"readable-stream": "npm:readable-stream@1.0.34",
"util": "github:jspm/nodelibs-util@0.1.0",
"xtend": "npm:xtend@4.0.1"
},
"npm:through2@2.0.1": {
"process": "github:jspm/nodelibs-process@0.1.2",
"readable-stream": "npm:readable-stream@2.0.6",
"util": "github:jspm/nodelibs-util@0.1.0",
"xtend": "npm:xtend@4.0.1"
},
"npm:tildify@1.2.0": {
"os-homedir": "npm:os-homedir@1.0.2",
"path": "github:jspm/nodelibs-path@0.1.0"
},
"npm:timers-browserify@1.4.2": {
"process": "npm:process@0.11.9"
},
"npm:typescript@1.8.10": {
"os": "github:jspm/nodelibs-os@0.1.0"
},
"npm:typescript@2.0.0": {
"crypto": "github:jspm/nodelibs-crypto@0.1.0",
"os": "github:jspm/nodelibs-os@0.1.0"
},
"npm:uglify-js@2.6.4": {
"async": "npm:async@0.2.10",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"source-map": "npm:source-map@0.5.6",
"uglify-to-browserify": "npm:uglify-to-browserify@1.0.2",
"yargs": "npm:yargs@3.10.0"
},
"npm:uglify-to-browserify@1.0.2": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:unique-stream@1.0.0": {
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:url@0.10.3": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"punycode": "npm:punycode@1.3.2",
"querystring": "npm:querystring@0.2.0",
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:user-home@1.1.1": {
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.2"
},
"npm:util-deprecate@1.0.2": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:v8flags@2.0.11": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"child_process": "github:jspm/nodelibs-child_process@0.1.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"os": "github:jspm/nodelibs-os@0.1.0",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"user-home": "npm:user-home@1.1.1"
},
"npm:validate-npm-package-license@3.0.1": {
"spdx-correct": "npm:spdx-correct@1.0.2",
"spdx-expression-parse": "npm:spdx-expression-parse@1.0.4"
},
"npm:vinyl-bufferstream@1.0.1": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"bufferstreams": "npm:bufferstreams@1.0.1"
},
"npm:vinyl-fs@0.3.14": {
"defaults": "npm:defaults@1.0.3",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"glob-stream": "npm:glob-stream@3.1.18",
"glob-watcher": "npm:glob-watcher@0.0.6",
"graceful-fs": "npm:graceful-fs@3.0.11",
"mkdirp": "npm:mkdirp@0.5.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"strip-bom": "npm:strip-bom@1.0.0",
"through2": "npm:through2@0.6.5",
"vinyl": "npm:vinyl@0.4.6"
},
"npm:vinyl-sourcemaps-apply@0.2.1": {
"source-map": "npm:source-map@0.5.6"
},
"npm:vinyl@0.4.6": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"clone": "npm:clone@0.2.0",
"clone-stats": "npm:clone-stats@0.0.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:vinyl@0.5.3": {
"buffer": "github:jspm/nodelibs-buffer@0.1.0",
"clone": "npm:clone@1.0.2",
"clone-stats": "npm:clone-stats@0.0.1",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"replace-ext": "npm:replace-ext@0.0.1",
"stream": "github:jspm/nodelibs-stream@0.1.0"
},
"npm:vm-browserify@0.0.4": {
"indexof": "npm:indexof@0.0.1"
},
"npm:which@1.2.11": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"isexe": "npm:isexe@1.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:window-size@0.1.0": {
"process": "github:jspm/nodelibs-process@0.1.2",
"tty": "github:jspm/nodelibs-tty@0.1.0"
},
"npm:yargs@3.10.0": {
"assert": "github:jspm/nodelibs-assert@0.1.0",
"camelcase": "npm:camelcase@1.2.1",
"cliui": "npm:cliui@2.1.0",
"decamelize": "npm:decamelize@1.2.0",
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"window-size": "npm:window-size@0.1.0"
}
}
});
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Dropdown, DropdownItem, DropdownMenu, DropdownToggle} from 'reactstrap';
const rowsPerPageVars = [10, 25, 50, 100];
class RowsPerPageDropDown extends Component {
constructor(props) {
super(props);
this.state = {
isDropDownOpen: false
};
this.toggle = this.toggle.bind(this);
this.handleChange = this.handleChange.bind(this);
}
toggle() {
this.setState((prevState) => {
return {
isDropDownOpen: !prevState.isDropDownOpen
}
});
}
handleChange(count) {
this.props.onChange(count)
}
render() {
return (
<Dropdown isOpen={this.state.isDropDownOpen} toggle={this.toggle}>
<DropdownToggle color='primary' caret>
{this.props.rowsPerPage}
</DropdownToggle>
<DropdownMenu>
<DropdownItem header>Rows per page</DropdownItem>
{rowsPerPageVars.map((vr => (<DropdownItem onClick={() => this.handleChange(vr)}>{vr}</DropdownItem>)))}
</DropdownMenu>
</Dropdown>
)
}
}
RowsPerPageDropDown.propTypes = {
onChange: PropTypes.func.isRequired
};
RowsPerPageDropDown.defaultProps = {
rowsPerPage: 10
};
export default RowsPerPageDropDown;
|
import Qua from 'qua'
import Util from 'util'
import react from 'Reactd'
import Console from 'console'
import star from 'star.pngd';
import OS from 'os'
|
import React, {Component} from 'react'
class Main extends Component {
render(){
let body = <h1>MAP</h1>
switch(this.props.page) {
case 'map':
body = <h1>MAP</h1>
break;
case 'profile':
body = <h1>PROFILE</h1>
break;
case 'login':
body = <h1>LOGIN</h1>
break;
default:
body = null;
break;
}
return (
<main>
{body}
</main>
)
}
}
export default Main
|
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.addConstraint(
'Genres',['teacherId'],{type:'FOREIGN KEY',references:{table:'Teachers',field: 'id',name:'add-fk-to-genre'}}
)
},
down: (queryInterface, Sequelize) => {
return queryInterface.removeConstraint(
'Genres','add-fk-to-genre'
)
}
};
|
import { html } from "./../../node_modules/lit-html/lit-html.js";
export let navTemplate = (model) => html`
<section class="navbar-dashboard">
<a href="/dashboard">Dashboard</a>
${model.isLoggedIn
? html`
<div id="user">
<span>Welcome, ${model.email}</span>
<a class="button" href="/my-books">My Books</a>
<a class="button" href="/create">Add Book</a>
<a class="button" href="javascript:void(0)" @click=${model.logoutHandler}>Logout</a>
</div>`
: html`
<div id="guest">
<a class="button" href="/login">Login</a>
<a class="button" href="/register">Register</a>
</div>`}
</section>`;
|
var DB_VERSION = 20;
var DB_NAME = 'db_02';
var COMPANY_STORE = 'customer_store';
var PRODUCT_STORE = "product_store";
var CONFIG_STORE = 'config_store';
var RESTURL="";
var ricoApp = angular.module('ricoApp', [ 'pascalprecht.translate', 'ngRoute',
'ngAnimate', 'ngResource','ui.bootstrap', 'ngSanitize', 'uiGmapgoogle-maps' ]);
ricoApp.service('GoogleAuth',function($q, $http,IndexedDb){
this.authDrive =function(){
var defer = $q.defer();
var config = {'client_id':CLIENT_ID, 'scope': SCOPE};
gapi.auth.authorize(config,
function(data) {
console.info(angular.toJson(data));
defer.resolve(data);
},
function(reason) {
console.error(angular.toJsn(reason));
defer.resolve(reason);
}
);
return defer.promise;
};
});
|
import React from "react";
import ReactDOM from "react-dom";
import "./styles/index.css";
import "./styles/app.scss";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
window.$USE_LOCAL_ENDPOINT = false;
// set this flag to true if you want to use a local endpoint
// set this flag to false if you want to use the online endpoint
window.$ENDPOINT_URL = "https://avigael-shop-fitness.herokuapp.com";
ReactDOM.render(<App />, document.getElementById("root"));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
//объект ядра очередей работы игры
function coreGame(options)
{
var obj = this;
obj.drawBuffer = new Array();
obj.showBuffer = new Array();
obj.intervalDraw = false;
obj.intervalShow = false;
obj.prevTimeShow = 0;
obj.prevTimeDraw = 0;
if (options == undefined) {
options = new Object();
}
if (options.speedDraw != undefined) {
obj.speedDraw = options.speedDraw;
} else {
obj.speedDraw = 16;
}
if (options.speedShow != undefined) {
obj.speedShow = options.speedShow;
} else {
obj.speedShow = 16;
}
//функция начинает работу задач
obj.start = function() {
var time = new Date().getTime();
obj.prevTimeDraw = time + obj.speedDraw;
obj.prevTimeShow = time + obj.speedShow;
obj.intervalDraw = setTimeout(obj.draw, obj.speedDraw);
obj.intervalShow = setTimeout(obj.show, obj.speedShow);
obj.drawBuffer = new Array();
obj.showBuffer = new Array();
}
//функция останавливает работу задач
obj.stop = function() {
if (obj.intervalDraw) {
clearTimeout(obj.intervalDraw);
}
if (obj.intervalShow) {
clearTimeout(obj.intervalShow);
}
obj.intervalDraw = false;
obj.intervalShow = false;
}
//функция выполняет очередь показа задач
obj.show = function() {
var tmpBuffer = obj.showBuffer;
obj.showBuffer = new Array();
tmpBuffer.reverse();
var functionName;
while (functionName = tmpBuffer.pop()) {
functionName();
}
do {
obj.prevTimeShow += obj.speedShow;
} while(new Date().getTime() > obj.prevTimeShow);
obj.intervalShow = setTimeout(obj.show, obj.prevTimeShow - new Date().getTime());
}
//функция добавляет в очередь показа задачу
obj.pushShow = function(functionName) {
obj.showBuffer.push(functionName);
}
//функция очищает очередь показа задач
obj.clearShow = function() {
obj.showBuffer = new Array();
}
//функция выполняет очередь задач
obj.draw = function() {
do {
var tmpBuffer = obj.drawBuffer;
obj.drawBuffer = new Array();
tmpBuffer.reverse();
var tmp;
while(tmp = tmpBuffer.pop()) {
tmp[0]--;
if (tmp[0] > 0) {
obj.drawBuffer.push(tmp);
} else {
if(tmp.length == 5) {
tmp[1](tmp[2], tmp[3], tmp[4]);
} else if(tmp.length == 4) {
tmp[1](tmp[2], tmp[3]);
} else if(tmp.length == 3) {
tmp[1](tmp[2]);
} else {
tmp[1]();
}
}
}
obj.prevTimeDraw += obj.speedDraw;
} while(new Date().getTime() > obj.prevTimeDraw);
obj.intervalDraw = setTimeout(obj.draw, obj.prevTimeDraw - new Date().getTime());
}
//функция добавляет очередь задач
obj.pushDraw = function(functionName, time, param1, param2, param3) {
var tmp = new Array();
if(time!=undefined) {
tmp.push(Math.ceil(time));
} else {
tmp.push(1);
}
tmp.push(functionName);
if(param1!=undefined) {
tmp.push(param1);
}
if(param2!=undefined) {
tmp.push(param2);
}
if(param3!=undefined) {
tmp.push(param3);
}
obj.drawBuffer.push(tmp);
}
//функция очищает очередь задач
obj.clearDraw = function() {
obj.drawBuffer = new Array();
}
}
//функция отрисовки объекта с свойствами
function drawImage(obj)
{
ctx.drawImage(obj.image,
obj.scrollX, obj.scrollY,
obj.width, obj.height,
obj.X, obj.Y,
obj.width, obj.height
);
}
//функция действия объекта со временем
function drawStart(obj)
{
if(!obj.bShow) {
obj.bShow = true;
if(obj.show != undefined) {
obj.show();
}
}
if(!obj.bDraw) {
obj.bDraw = true;
if(obj.draw != undefined) {
obj.draw();
}
}
}
//функция очистки поля для старта отрисовки
function clearCanvas()
{
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
cGame.pushShow(clearCanvas);
}
//функция проверяет пересеклись ли объекты
function isContactObj(obj1, obj2)
{
var contactX1 = (obj1.contactX != undefined ? obj1.contactX : 0);
var contactY1 = (obj1.contactY != undefined ? obj1.contactY : 0);
var contactWidth1 = (obj1.contactWidth != undefined ? obj1.contactWidth : obj1.width);
var contactHeight1 = (obj1.contactHeight != undefined ? obj1.contactHeight : obj1.height);
var fX1 = obj1.X + contactX1;
var fX2 = obj1.X + contactX1 + contactWidth1;
var fY1 = obj1.Y + contactY1;
var fY2 = obj1.Y + contactY1 + contactHeight1;
var contactX2 = (obj2.contactX != undefined ? obj1.contactX : 0);
var contactY2 = (obj2.contactY != undefined ? obj1.contactY : 0);
var contactWidth2 = (obj2.contactWidth != undefined ? obj2.contactWidth : obj2.width);
var contactHeight2 = (obj2.contactHeight != undefined ? obj2.contactHeight : obj2.height);
var uX1 = obj2.X+contactX2;
var uX2 = obj2.X+contactX2+contactWidth2;
var uY1 = obj2.Y+contactY2;
var uY2 = obj2.Y+contactY2+contactHeight2;
if((fX1 >= uX1 && fX1 <= uX2 && fY1 >= uY1 && fY1 <= uY2)
|| (fX2 >= uX1 && fX2 <= uX2 && fY1 >= uY1 && fY1 <= uY2)
|| (fX1 >= uX1 && fX1 <= uX2 && fY2 >= uY1 && fY2 <= uY2)
|| (fX2 >= uX1 && fX1 <= uX2 && fY2 >= uY1 && fY2 <= uY2)
) {
return true;
}
return false;
}
|
import React,{Component} from 'react';
import './index.css';
export default class Login extends Component{
render(){
return(
<div className="login">
用户名
<input className="loginput1" type="text" name="username" />
<br/>
密码
<input className="loginput2" type = "password" name="pwd" />
<br/>
<input onClick={()=>{this.props.history.push('/home')}} className="submit" type = "submit" name="login" value="登录"/>
</div>
)
}
}
|
/*
* ecommerceTaskApi.js
*
* Copyright (c) 2017 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* API to support display eCommerce task details.
*
* @author vn40486
* @since 2.14.0
*/
(function () {
angular.module('productMaintenanceUiApp').factory('EcommerceTaskApi', ecommerceTaskApi);
ecommerceTaskApi.$inject = ['$http', 'urlBase', '$resource'];
/**
* Constructs the API to call the backend functions related to ecommerce tasks.
*
* @param urlBase The Base URL for the back-end.
* @param $resource Angular $resource factory used to create the API.
* @returns {*}
*/
function ecommerceTaskApi($http, urlBase, $resource) {
return $resource(null, null, {
getActiveEcommerceTaskCount: {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/ecommerceTaskCount',
isArray: false
},
getAllTasks : {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/tasks',
isArray: false
},
createTask : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/create',
isArray: false
},
getTaskInfo : {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/taskInfo',
isArray: false
},
deleteTask : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/delete',
isArray: false
},
updateTask : {
method: 'PUT',
url: urlBase + '/pm/task/ecommerceTask/:taskId',
params: {taskId:'@taskId'},
isArray: false
},
updateTaskNotes : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/notes/update',
isArray: false
},
deleteTaskNotes : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/notes/delete',
isArray: false
},
updateProductNotes : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/productNotes/update',
isArray: false
},
deleteProductNotes : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/productNotes/delete',
isArray: false
},
getTaskDetail : {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/taskDetail',
isArray: false
},
getTaskProducts : {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/taskProducts',
isArray: false
},
getProductNotes : {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/productNotes/:workRequestId',
isArray: true
},
addProductNotes : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/productNotes/add',
isArray: false
},
addProducts : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/products/add',
isArray: false
},
removeProducts : {
method: 'DELETE',
url: urlBase + '/pm/task/ecommerceTask/products/delete',
isArray: false
},
removeAllProducts : {
method: 'DELETE',
url: urlBase + '/pm/task/ecommerceTask/products/deleteAll',
isArray: false
},
getProductsAssignee : {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/products/assignee/:trackingId',
isArray: true
},
getTaskNotes : {
method: 'GET',
url: urlBase + '/pm/task/ecommerceTask/notes/:taskId',
isArray: true
},
addTaskNotes : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/notes/add',
isArray: false
},
updateMassFillToProduct : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/updateMassFillToProduct',
isArray: false
},
assignToBDM : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/assignToBdm',
isArray: false
},
assignToEBM : {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/assignToEbm',
isArray: false
},
publishProduct: {
method: 'POST',
url: urlBase + '/pm/task/ecommerceTask/publishProduct',
isArray: false
}
});
}
})();
|
// Models
const Log = require('../models/log')
const Count = require('../models/count')
const mongoose = require('mongoose')
const getCurrentCount = async (req, res, next) => {
try {
const doc = await Count.findOne({ doorId: 'muilab-715' }).exec()
res.json({
code: 200,
type: 'success',
data: {
count: doc.count,
updatedAt: doc.updatedAt
}
})
} catch (error) {
console.error(error)
res.json({
code: 200,
type: 'error',
message: error
})
}
}
const setCurrentCount = async (req, res, next) => {
console.log(req.body)
const { doorId, count } = req.body
if (doorId && count !== undefined && count !== null) {
const updateObj = {
doorId,
count,
updatedAt: new Date()
}
try {
const doc = await Count.findOneAndUpdate({ doorId: 'muilab-715' }, updateObj, { new: true, upsert: true })
res.json({
code: 200,
type: 'success',
data: doc
})
} catch (error) {
console.error(error)
res.status(200).send({
code: 500,
type: 'error',
message: error
})
}
} else {
res.status(200).send({
code: 500,
type: 'error',
message: '參數設定錯誤,請確認有管制門ID以及人數參數有填入'
})
}
}
const addLog = async (req, res, next) => {
const { doorId, action, phoneNumber, name } = req.body
if (doorId && action && phoneNumber && name) {
try {
const log = new Log({
_id: mongoose.Types.ObjectId(),
doorId,
phoneNumber,
name,
action,
createdAt: new Date()
})
await log.save()
const countResult = await Count.findOne({ doorId: 'muilab-715' })
let count = action === 'in'? countResult.count + 1 : countResult.count - 1
if(count <= 0){
count = 0
}
const updateObj = {
doorId,
count,
updatedAt: new Date()
}
const currentCountDoc = await Count.findOneAndUpdate({ doorId: 'muilab-715' }, updateObj, { new: true, upsert: true })
res.json({
code: 200,
type: 'success',
data: {
count: currentCountDoc.count,
updatedAt: currentCountDoc.updatedAt
}
})
} catch (error) {
console.error(error)
res.status(200).send({
code: 500,
type: 'error',
message: error
})
}
} else {
res.status(200).send({
code: 500,
type: 'error',
message: '參數設定錯誤,請確認門、姓名、電話、動作等參數有填入'
})
}
}
module.exports = {
getCurrentCount,
setCurrentCount,
addLog
}
|
/**
*
*/
requirejs.config({
baseUrl: "js/",
paths: {
'jquery' : '../lib/jquery/js/jquery.min',
'jquery-ui' : '../lib/jquery/js/jquery-ui',
'kendo' : '../lib/kendo/js/kendo.all.min',
'logger' : '../lib/log4javascript/js/log4javascript',
'atmosphere' : '../lib/atmosphere/js/jquery.atmosphere',
'jquery-xml2json' : '../lib/jquery/js/jquery.xml2json',
'siViewerNamespace' : 'common/com.spacetimeinsight.viewer.namespace',
'siViewerLogger' : 'common/com.spacetimeinsight.viewer.logger',
'siViewerData' : 'common/com.spacetimeinsight.viewer.viewerData',
'siSessionTimeOut' : 'common/com.spacetimeinsight.viewer.sessionTimeOut',
'siAjaxUtil' : 'common/com.spacetimeinsight.viewer.ajaxutil',
'siRouter' : 'common/com.spacetimeinsight.viewer.router',
'siWebSockets' : 'common/com.spacetimeinsight.viewer.websocketsutil',
'dateTimeFormat' : '../lib/dateFormattingAPI/moment',
},
shim: {
"jquery-ui": ["jquery"],
"kendo": ["jquery","jquery-ui"],
},
waitSeconds: 7
});
/*
* Here we are fetching the parameters that we have passed while opening this window.
* All the parameters will be present in the params object.
*/
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
/*
* Here we are checking the js file name and opening the corresponding window. We will also specify the rendererType for this window.
*/
if(params.jsFileName == "alerts"){
requirejs(["jquery","jquery-ui","viewer/com.spacetimeinsight.viewer.alertExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.viewer.AlertExportAsCSVRenderer");
$("#exportViewer").siAlertExportAsCSV({});
});
}else if(params.jsFileName == "clientSideTable"){
requirejs(["jquery","jquery-ui","window/tableWindow/com.spacetimeinsight.viewer.clientSideTableExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.window.impl.WindowRenderer");
$("#exportViewer").siClientSideTableExportAsCSV({});
});
}else if(params.jsFileName == "serverSideTable"){
requirejs(["jquery","jquery-ui","window/tableWindow/com.spacetimeinsight.viewer.serverSideTableExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.window.impl.WindowRenderer");
$("#exportViewer").siServerSideTableExportAsCSV({});
});
}else if(params.jsFileName == "xyChart"){
requirejs(["jquery","jquery-ui","window/charts/xyChart/com.spacetimeinsight.viewer.xyChartExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.window.impl.WindowRenderer");
$("#exportViewer").siXYChartExportAsCSV({});
});
}else if(params.jsFileName == "treemapChart"){
requirejs(["jquery","jquery-ui","window/charts/treemapChart/com.spacetimeinsight.viewer.treemapChartExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.window.impl.WindowRenderer");
$("#exportViewer").siTreemapChartExportAsCSV({});
});
}else if(params.jsFileName == "radarChart"){
requirejs(["jquery","jquery-ui","window/charts/radarChart/com.spacetimeinsight.viewer.radarChartExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.window.impl.WindowRenderer");
$("#exportViewer").siRadarChartExportAsCSV({});
});
}else if(params.jsFileName == "meterChart"){
requirejs(["jquery","jquery-ui","window/charts/meterChart/com.spacetimeinsight.viewer.meterChartExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.window.impl.WindowRenderer");
$("#exportViewer").siMeterChartExportAsCSV({});
});
}else if(params.jsFileName == "pieChart"){
requirejs(["jquery","jquery-ui","window/charts/pieChart/com.spacetimeinsight.viewer.pieChartExportAsCSV"],function(){
$('form').append("<div id='exportViewer' class='exportViewer'></div>");
$("#renderertype").val("com.spacetimeinsight.renderer.window.impl.WindowRenderer");
$("#exportViewer").siPieChartExportAsCSV({});
});
}else{
requirejs(["jquery","jquery-ui","viewer/com.spacetimeinsight.viewer.ui.exportViewer"],function(){
$('body').append("<div id='exportViewer' class='exportViewer'></div>");
$("#exportViewer").siViewerExportViewer({});
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.