text
stringlengths 7
3.69M
|
|---|
import React, { Component } from "react";
import styled from "styled-components";
const Form = styled.form`
display: flex;
font-family: "Dosis", sans-serif;
justify-content: center;
background: #d84c73;
margin: 10px 10px 0 10px;
padding: 10px 10px 0 10px;
color: #ffffff;
font-weight: 600;
font-size: 20px;
border-radius: 20px 20px 0 0;
label {
margin: 40px;
}
input {
margin: 40px 0px;
border-radius: 10px;
border: none;
padding: 10px;
}
.submit {
margin-left: 20px;
width: 100px;
background: #5c3b6f;
color: #ffffff;
cursor: pointer;
}
`;
const Output = styled.ul`
background: #ff8484;
margin: -10px 10px 0 10px;
display: flex;
flex-direction: column;
border-radius: 0 0 20px 20px;
li {
color: #ffffff;
padding: 10px 0 10px 0;
}
`;
const Title = styled.h1`
padding-left: 20px;
font-family: "Dosis", sans-serif;
`;
class TodoForm extends Component {
constructor() {
super();
this.state = {
input: "",
todos: [
{
id: 0,
text: "Eat"
},
{
id: 1,
text: "Swimming"
}
]
};
}
handleTodoInput = event => {
this.setState({ input: event.target.value });
};
handleTodoSubmit = event => {
event.preventDefault();
console.log("Todo Submitted", this.state.input);
const newTodo = {
id: this.state.todos.length,
text: this.state.input
};
const newTodos = this.state.todos.concat(newTodo);
this.setState({
input: "",
todos: newTodos
});
};
// handleTodoRemove = indexRemove => {
// this.setState({todos: this.state.todos.filter(event => {
// return event !== indexRemove.target.value ;
// })
// });
// };
handleTodoRemove = indexToRemove => {
const newTodos = this.state.todos.filter((todo, index) => {
return index !== indexToRemove;
});
this.setState({
todos: newTodos
});
};
render() {
return (
<div>
<Title>Todo App</Title>
<Form onSubmit={this.handleTodoSubmit}>
<input
type="text"
placeholder="Do Something"
onChange={this.handleTodoInput}
value={this.state.input}
/>
<input className="submit" type="submit" value="Add" />
</Form>
<Output>
{this.state.todos.map((todo, index) => {
return (
<li key={index}>
{todo.text}
<input
type="button"
value="remove"
onClick={() => this.handleTodoRemove(todo.id)}
/>
</li>
);
})}
</Output>
</div>
);
}
}
export default TodoForm;
|
import background from '../assets/1-playBaby.png';
import BackgroundManager from '../js/managers/background';
import DialogManager from '../js/managers/dialog';
import State from '../js/managers/state';
import nextNode from "./0-stayWithNoFace";
const text1 = 'Salut, je suis le bébé de Yubaba. J\'ai ton médicament. Si tu le veux, tu dois jouer avec moi et gagner.\n' +
'Es-tu prête? Allons-y!' ;
export default function (){
BackgroundManager.setBackground(background);
DialogManager.showDialog('Bébé :', text1, ()=> {State.switchToState(nextNode)}, true);
}
|
import React from "react";
import {
Button,
Card,
FormControlLabel,
FormControl,
Collapse,
Chip as MuiChip,
Tooltip,
TextField
} from "@mui/material";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import styled from "styled-components";
import { MainContext } from "../../App.js";
const FilterButton = styled(Button)`
min-width: 0;
width: 45px;
height: 45px;
font-size: 20px;
margin-top: 2px;
color: ${props => props.textcolor};
`;
const FilterStats = styled.div`
padding-left: 15px;
padding-top: 15px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: 11pt;
float: left;
color: ${props => props.textcolor};
`;
const FilterChip = styled(MuiChip)`
margin-left: 10px;
margin-top: 10px;
margin-bottom: 10px;
`;
const FilterBox = styled.div`
height: 60px;
padding-top: 5px;
padding-bottom: 5px;
`;
const FilterContainer = styled(Card)`
background-color: #fff;
border-top: 1px solid rgba(0, 0, 0, 0.12);
cursor: pointer;
box-shadow: 0 0 14px 0 rgba(53, 64, 82, 0.15);
z-index: 200;
position: relative;
border-radius: 0px;
`;
const FilterFormControl = styled(FormControl)`
background-color: #fff;
flex-wrap: wrap;
display: block;
`;
const FilterPanel = styled.div`
background-color: #fff;
border-right: 1px solid rgba(0, 0, 0, 0.12);
border-bottom: 1px solid rgba(0, 0, 0, 0.12);
`;
const FilterControl = styled(FormControlLabel)`
float: right;
margin-right: 10px;
`;
const FilterIcon = styled(FontAwesomeIcon)`
cursor: "pointer";
padding-left: 5px;
`;
const typeName = {
data: "dataset",
flow: "flow",
run: "run",
study: "collection",
benchmark: "benchmark",
task: "task",
task_type: "task type",
user: "user",
measure: "measure"
};
export class FilterBar extends React.Component {
static contextType = MainContext;
constructor(props) {
super(props);
this.state = {
showFilter: false,
sortVisible: false,
activeFilter: false,
splitToggleVisible: (window.innerWidth >= 600 ? true : false)
};
}
sortChange = value => {
console.log("Set sort to", value);
this.props.sortChange({ sort: value });
};
orderChange = value => {
console.log("Set order to", value);
this.props.sortChange({ order: value });
};
activateFilter = value => {
console.log(value);
this.setState({ activeFilter: value });
};
filterChange = filters => {
let filter = {
name: this.props.filterOptions[this.state.activeFilter].value,
type: filters.type,
value: filters.value,
value2: filters.value2
};
//this.setState({ showFilter: false });
this.props.filterChange([filter]);
};
flipFilter = () => {
this.setState(state => ({ showFilter: !state.showFilter }));
};
closeFilter = () => {
this.setState(state => ({ showFilter: false }));
};
flipSorter = () => {
this.setState(state => ({ sortVisible: !state.sortVisible }));
};
toggleSelect = () => {
if (!this.context.displaySplit) {
if (this.context.id) {
this.props.selectEntity(null);
this.context.setID(undefined);
} else {
this.context.toggleStats();
}
} else if (this.context.displayStats){
this.context.toggleSplit();
} else {
this.context.toggleStats();
this.context.toggleSplit();
}
};
getExampleTags = () => {
return [
"OpenML-CC18",
"OpenML-Reg19",
"uci",
"concept_drift",
"artificial",
"finance"
].join(", ");
};
isActiveOption = option => {
let oname = this.props.filterOptions[this.state.activeFilter].value;
if (oname in this.context.filters) {
if (
option.type === this.context.filters[oname].type &&
option.value === this.context.filters[oname].value
) {
return true;
}
}
return false;
};
filterLabel = key => {
if (this.context.filters[key]["value"] === "active"){
return "verified";
} else if (this.context.filters[key]["value"] === "ARFF"){
return "dense";
} else if (this.context.filters[key]["value"] === "Sparse_ARFF"){
return "sparse";
} else if (key.includes("NumberOfClasses")) {
if (this.context.filters[key]["value"] === "1") {
return "regression";
} else if (this.context.filters[key]["type"] === "gte" && this.context.filters[key]["value"] === "2") {
return "multi-class";
} else {
return "binary class";
}
} else if (key.includes("NumberOf")) {
let keyname = key.split("s.")[1].replace("NumberOf","").toLowerCase();
if (this.context.filters[key]["type"] === "lte"){
return "<10 "+keyname;
} else {
return ">" + this.context.filters[key]["value"] + " " + keyname;
}
} else if (key.includes("tasktype")) {
console.log(this.context.filters[key]);
if (this.context.filters[key]["value"] === "1"){
return "classification";
} else if (this.context.filters[key]["value"] === "2"){
return "regression";
} else if (this.context.filters[key]["value"] === "4"){
return "stream classification";
} else if (this.context.filters[key]["value"] === "5"){
return "clustering";
}
} else if (key.includes("s.")) {
return key.split("s.")[1].replace("_"," ") + "s " + this.context.filters[key]["value"];
} else if (key.includes(".")) {
return key.split(".")[0].replace("_"," ") + " " + this.context.filters[key]["value"];
} else {
return this.context.filters[key]["value"];
}
}
render() {
return (
<React.Fragment>
<FilterContainer>
<FilterBox>
<FilterStats textcolor={this.props.searchColor}>
{this.context.updateType === "query" ? "Loading..." : this.context.counts +
" " +
typeName[this.context.type] + (this.context.counts !== 1 ? "s" : "") +
" found"}
</FilterStats>
{Object.keys(this.context.filters).map((key) => {
return this.context.filters[key]["value"] !== "any" &&
<FilterChip
label={this.filterLabel(key)}
key={key + this.context.filters[key]["value"]}
clickable
color="secondary"
variant="outlined"
onClick={this.flipFilter}
onDelete={() => {
this.props.clearFilters(key);
this.closeFilter();
this.setState({ activeFilter: false })
}}
deleteIcon={<FontAwesomeIcon size="lg" icon="times-circle" />}
/>
})}
<Tooltip title="Filter results" placement="bottom-start">
<FilterControl
style={{
marginRight: window.innerWidth < 600 ? 10 : 3,
}}
control={
<FilterButton
onClick={this.flipFilter}
textcolor={this.props.searchColor}
>
<FontAwesomeIcon icon="filter" />
</FilterButton>
}
/>
</Tooltip>
<Tooltip title="Sort results" placement="bottom-start">
<FilterControl
style={{
borderLeft: "1px solid rgba(0,0,0,0.12)",
paddingLeft: 10,
marginLeft: 0
}}
control={
<FilterButton
onClick={this.flipSorter}
textcolor={this.props.searchColor}
>
<FontAwesomeIcon icon="sort-amount-down" />
</FilterButton>
}
/>
</Tooltip>
{this.state.splitToggleVisible &&
<Tooltip
title="Toggle split pane"
placement="bottom-start"
>
<FilterControl
control={
<FilterButton
onClick={this.context.toggleSplit}
textcolor={this.props.searchColor}
>
<FontAwesomeIcon
icon={this.context.displaySplit ? ["far", "window-maximize"] : "columns"}
/>
</FilterButton>
}
/>
</Tooltip>
}
<Tooltip
title={
this.context.displaySplit ? (this.context.id ? "Maximize view" : "Show overview") :
(this.context.id ? "Back to list" : (this.context.displayStats ? "Show list" : "Show overview"))
}
placement="bottom-start"
>
<FilterControl
control={
<FilterButton
onClick={this.toggleSelect}
textcolor={this.props.searchColor}
>
<FontAwesomeIcon
icon={this.context.displaySplit ? (this.context.id ? "expand-alt" : "poll") :
(this.context.id ? "angle-left" : (this.context.displayStats ? "list" : "poll"))}
/>
</FilterButton>
}
/>
</Tooltip>
</FilterBox>
<Collapse in={this.state.sortVisible}>
<FilterPanel>
<FilterFormControl>
<FilterStats textcolor={this.props.searchColor}>
Sort by
</FilterStats>
{this.props.sortOptions.map(item => (
<FilterChip
label={item.name}
key={item.name}
clickable
onClick={() => this.sortChange(item.value)}
color={
this.context.sort === item.value ? "primary" : "default"
}
variant={
this.context.sort === item.value ? "default" : "outlined"
}
/>
))}
<FilterChip
label={
this.context.order === "desc" ? "Descending" : "Ascending"
}
key="order"
clickable
onClick={() =>
this.orderChange(
this.context.order === "desc" ? "asc" : "desc"
)
}
variant="outlined"
color="secondary"
icon={
this.context.order === "desc" ? (
<FilterIcon icon="chevron-down" />
) : (
<FilterIcon icon="chevron-up" />
)
}
/>
</FilterFormControl>
</FilterPanel>
</Collapse>
<Collapse in={this.state.showFilter}>
<FilterPanel>
<FilterFormControl key="filters">
<FilterStats textcolor={this.props.searchColor}>
Filter by
</FilterStats>
{Object.entries(this.props.filterOptions).map(
([key, option]) => (
<FilterChip
label={option.name}
key={key}
clickable
onClick={() => this.activateFilter(option.name)}
color={
option.name === this.state.activeFilter
? "primary"
: "default"
}
variant={
option.name === this.state.activeFilter
? "default"
: "outlined"
}
icon={<FilterIcon icon="chevron-down" />}
/>
)
)}
<FilterChip
label={"Tag"}
key={"Tag"}
clickable
onClick={() => this.activateFilter("Tag")}
color={
this.state.activeFilter === "Tag" ? "primary" : "default"
}
variant={
this.state.activeFilter === "Tag" ? "default" : "outlined"
}
icon={<FilterIcon icon="chevron-down" />}
/>
</FilterFormControl>
<FilterFormControl key="options">
{this.state.activeFilter &&
this.props.filterOptions[this.state.activeFilter] &&
this.props.filterOptions[this.state.activeFilter].options.map(
option => (
<FilterChip
label={option.name}
key={option.name}
clickable
onClick={() => this.filterChange(option)}
color={
this.isActiveOption(option) ? "primary" : "default"
}
variant={
this.isActiveOption(option) ? "default" : "outlined"
}
/>
)
)}
</FilterFormControl>
<FilterFormControl key="tag">
{this.state.activeFilter === "Tag" && (
<TextField
style={{ margin: 8, paddingRight: 16 }}
placeholder={"Type tag name. e.g. " + this.getExampleTags()}
defaultValue={this.context.filters['tags.tag'] ? this.context.filters['tags.tag']['value'] : undefined}
fullWidth
margin="dense"
variant="outlined"
onKeyPress={event => {
if (event.key === "Enter") {
event.preventDefault();
this.props.tagChange(event.target.value);
}
}}
/>
)}
</FilterFormControl>
</FilterPanel>
</Collapse>
</FilterContainer>
</React.Fragment>
);
}
updateWindowDimensions = () => {
if( window.innerWidth < 600) {
this.setState({splitToggleVisible: false});
} else {
this.setState({splitToggleVisible: true});
}
};
componentDidMount() {
// Reflow when the user changes the window size
window.addEventListener("resize", this.updateWindowDimensions);
}
}
|
var Q = require("q");
var start = Date.now();
function getValue() {
var value = Math.random() * 5000;
console.log("getValue will return", value);
return Q.delay(value)
.then(function() {
if (Math.round(value) % 8) return value;
console.log("getValue will throw error");
throw new Error("Get value error");
});
}
var promises = [
getValue(),
getValue(),
getValue(),
getValue(),
getValue(),
getValue()
];
var runAll = Q.all(promises);
var runAllSettled = Q.allSettled(promises);
var runAny = Q.any(promises);
function readAsArray(promise) {
promise.then(function(values) {
console.log(values);
})
.catch(function(error) {
console.log(error);
})
.finally(function() {
console.log("promise state:", promise.inspect().state);
console.log("Done in", Date.now() - start, "ms");
});
}
function readAsItems(promise) {
promise.spread(function(val1, val2, val3, val4, val5, val6) {
console.log("val1", val1);
console.log("val2", val2);
console.log("val3", val3);
console.log("val4", val4);
console.log("val5", val5);
console.log("val6", val6);
})
.catch(function(error) {
console.log(error);
})
.finally(function() {
console.log("promise state:", promise.inspect().state);
console.log("Done in", Date.now() - start, "ms");
});
}
//readAsArray(runAll);
readAsItems(runAllSettled);
//readAsArray(runAny);
|
const debug = require('debug')('messengerFunctions')
const request = require('request')
const config = require('../config')
debug('Startup: Loading in MESSENGERFUNCTIONS')
function sendGenericMessage(recipientId, messageText) {
// To be expanded in later sections
}
function sendTextMessage(recipientId, messageText) {
debug('Sending text message')
// Splits string by max length accepted by API
const splitString = chunkString(messageText, 630)
console.log(splitString)
splitString.map((messageTextSplit, key)=>{
debug('LENGTH: ', messageTextSplit.length)
//set time out to try and conserver message order
setTimeout(()=>{
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageTextSplit
}
};
callSendAPI(messageData);
}, key*100)
})
}
function chunkString(str, len) {
var _size = Math.ceil(str.length/len),
_ret = new Array(_size),
_offset
;
for (var _i=0; _i<_size; _i++) {
_offset = _i * len;
_ret[_i] = str.substring(_offset, _offset + len);
}
return _ret;
}
function sendArticleMessage(senderID, article) {
debug('Sending article message')
const messageData = {
recipient: {
id: senderID
},
message: {
attachment:{
type:"template",
payload:{
template_type:"generic",
elements:[{
image_url:article.main_image,
title:article.title,
"buttons":[
{
"type":"web_url",
"url":article.url,
"title":"View Article"
},{
"type":"postback",
"title":"Read Here",
"payload":JSON.stringify({ type: "VIEW_FULL_PHYSICS_ARTICLE", article_id: article._id})
}
]
}]
}
}
}
}
callSendAPI(messageData)
}
function sendButtonMessage(senderID, text, buttons){
debug('Sending button message')
const messageData = {
recipient: {
id: senderID
},
message: {
attachment:{
type:"template",
payload:{
template_type:"button",
text: text,
buttons: buttons
}
}
}
}
callSendAPI(messageData)
}
function sendListMessage(senderID, listElements){
debug('Constructing list message')
const messageData = {
recipient: {
id: senderID
},
message: {
attachment:{
type:"template",
"payload": {
template_type: "list",
elements: listElements,
// buttons: [
// {
// "title": "View More",
// "type": "postback",
// "payload": "payload"
// }
// ]
}
}
}
}
callSendAPI(messageData)
}
function callSendAPI(messageData) {
debug('Calling send API')
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: config.external_API.messenger_PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s",
messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
module.exports = {
sendTextMessage: sendTextMessage,
sendArticleMessage: sendArticleMessage,
sendListMessage: sendListMessage,
sendButtonMessage: sendButtonMessage
}
|
var PixelController = (function() {
var drawModel = DrawModel(JSON_RPC_URL);
var currentPaintBuffer = null;
function strokeWithBrush(layer, brush, parts) {
for (var i = 0; i < 5; i++) {
layer.paintWithBrush(MAX_ZOOM - i, brush, parts);
}
}
return {
clearAll: function(map) {
drawModel.clearAll()(function(err) { if (err) { throw err; } });
map.canvasLayer.clear();
map.backgroundLayer.clear();
},
paintWithBrush: function(map, brushDesc, x, y, color) {
var brush = BrushPool.get(brushDesc);
var part = {x: x, y: y, color: color};
if (!currentPaintBuffer) {
currentPaintBuffer = { brushDesc: brushDesc, parts: [part] };
}
currentPaintBuffer.parts.push(part);
map.canvasLayer.paintWithBrush(map.internalMap.getZoom(), brush, currentPaintBuffer.parts.slice());
},
stopPainting: function() {
drawModel.sendBrushStroke(currentPaintBuffer.brushDesc, currentPaintBuffer.parts)(function(err, res) {
if (err) { throw err; }
});
currentPaintBuffer = null;
},
startUpdateLoop: function(map) {
function asyncForEach(list, func) {
return function(callback) {
function next(index) {
if (index >= list.length) { return callback(); }
func(list[index], index, list)(function(err) {
if (err) { return callback(err); }
next(index + 1);
});
}
next(0);
};
}
var lastTimeStamp = new Date(0).getTime();
function drawAndWaitForChanges(err, changes) {
if (err) {
throw err;
return drawModel.getChanges(Date.now())(drawAndWaitForChanges);
}
var backgroundLayer = map.backgroundLayer;
asyncForEach(changes, function(change) {
return function(callback) {
var brush = BrushPool.get(change.brush);
var strokes = change.strokes;
asyncForEach(strokes, function(stroke, index) {
return function(callback) {
strokeWithBrush(backgroundLayer, brush, strokes.slice(0, index + 1));
setTimeout(function() { callback(); }, 0);
};
})(callback);
};
})(function(err) {
if (err) { throw err; }
var lastChange = changes[changes.length - 1];
lastTimeStamp = lastChange ? lastChange.timeStamp : lastTimeStamp;
drawModel.getChanges(lastTimeStamp)(drawAndWaitForChanges);
});
}
drawModel.getChanges(lastTimeStamp)(drawAndWaitForChanges);
}
};
})();
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsFormatTextdirectionRToL = {
name: 'format_textdirection_r_to_l',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M10 10v5h2V4h2v11h2V4h2V2h-8C7.79 2 6 3.79 6 6s1.79 4 4 4zm-2 7v-3l-4 4 4 4v-3h12v-2H8z"/></svg>`
};
|
var Word = require("./word.js");
var inquirer = require("./node_modules/inquirer");
var ranWord = require("./node_modules/random-words")
// Global Variables
var numberOfGuesses;
var currentWord;
var newWord;
// Testing initial functionality //
// var testGuess = "r";
// var testLetter = newWord.guessLetter(testGuess);
// console.log(testLetter);
// Game initializer
initGame();
// Acquiring User Input by using NPM Inquier
function userInput() {
if (numberOfGuesses > 0) {
inquirer
.prompt({
type: "input",
message: "Guess a letter or the word! ",
name: "guessInput"
}).then(function (response) {
if (currentWord = newWord.guessedCorrectly(response.guessInput)) {
console.log("You WON!");
initGame();
} else if (newWord.guessLetter(response.guessInput)) {
userInput();
} else {
numberOfGuesses--;
if (numberOfGuesses === 0) {
console.log("NOPE! The Word is: " + newWord.solution());
initGame();
} else {
console.log("Wrong, Number of Guesses Left: " + numberOfGuesses);
userInput();
}
}
})
}
}
function initGame() {
numberOfGuesses = 10;
currentWord = newWord;
newWord = new Word("harrison");
console.log(newWord.toString());
userInput();
}
// if (newWord.guessLetter(testGuess) === true) {
// return testLetter();
// } console.log("guess again")// Use user feedback for... whatever!!
// });
|
TeamProfiles = new Meteor.Collection("teamProfiles");
TeamProfileSortOrder = new Meteor.Collection("teamProfileSortOrder");
TeamProfiles.attachSchema(new SimpleSchema({
name: {
type: String
},
photoUrl: {
type: String
},
bio: {
type: String,
autoform: {
afFieldInput: {
rows: 6
}
}
}
}));
TeamProfileSortOrder.attachSchema(new SimpleSchema({
order: {
type: [new SimpleSchema({
id: {
type: String,
autoform: {
options: function(){
return _.map(TeamProfiles.find().fetch(), function(profile){
return {
label: profile.name,
value: profile._id
};
});
}
}
}
})]
}
}));
if(Meteor.isServer){
Meteor.publish("teamProfiles", function(){
return TeamProfiles.find();
});
Meteor.publish("teamProfileSortOrder", function(){
return TeamProfileSortOrder.find();
});
}else{
Meteor.subscribe("teamProfiles");
Meteor.subscribe("teamProfileSortOrder");
}
|
const mongoose = require("mongoose");
const { Schema } = mongoose;
const schema = new Schema(
{
matchId: { type: Number, required: true },
serverId: { type: String, required: true },
matchType: { type: String, required: true },
matchVersion: { type: String, required: true },
matchMode: { type: String, required: true },
seasonId: { type: Number, required: true },
mapId: { type: Number, required: true },
duration: { type: Number, required: true },
matchDate: { type: Date, required: true },
},
{ timestamps: true },
);
schema.set("toJSON", { virtuals: true });
module.exports = mongoose.model("Match", schema);
|
app.controller('ScoreController',['$scope',function($scope){
$scope.scores = [
{id:2017010101,name:'周杰伦',sex:'男',age:39,hostel:'203',address:'河北邯郸',phone:1234567890,teacher:'李荣浩',class:'四年级'},
{id:2017010102,name:'周杰伦',sex:'男',age:39,hostel:'203',address:'河北邯郸',phone:1234567890,teacher:'李荣浩',class:'四年级'},
{id:2017010103,name:'周杰伦',sex:'男',age:39,hostel:'203',address:'河北邯郸',phone:1234567890,teacher:'李荣浩',class:'四年级'},
{id:2017010104,name:'周杰伦',sex:'男',age:39,hostel:'203',address:'河北邯郸',phone:1234567890,teacher:'李荣浩',class:'四年级'},
{id:2017010105,name:'周杰伦',sex:'男',age:39,hostel:'203',address:'河北邯郸',phone:1234567890,teacher:'李荣浩',class:'四年级'},
{id:2017010106,name:'周杰伦',sex:'男',age:39,hostel:'203',address:'河北邯郸',phone:1234567890,teacher:'李荣浩',class:'四年级'}
];
}]);
|
/*jshint globalstrict:false, strict:false */
/* global getOptions, assertEqual, assertFalse, assertTrue */
////////////////////////////////////////////////////////////////////////////////
/// @brief test for security-related server options
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB Inc, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2019, ArangoDB Inc, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
if (getOptions === true) {
return {
'server.authentication': 'true',
'server.jwt-secret': 'haxxmann',
};
}
const jsunity = require('jsunity');
const request = require('@arangodb/request').request;
const crypto = require('@arangodb/crypto');
function testSuite() {
return {
testUnauthorized : function() {
let result = request({ url: "/_api/version", method: "get" });
assertEqual(401, result.status);
assertTrue(result.headers.hasOwnProperty('www-authenticate'));
},
testUnauthorizedOmit : function() {
let result = request({ url: "/_api/version", method: "get", headers: { 'x-omit-WWW-authenticate': 'abc' } });
assertEqual(401, result.status);
assertFalse(result.headers.hasOwnProperty('www-authenticate'));
},
testAuthorized : function() {
const jwtSecret = 'haxxmann';
const jwtRoot = crypto.jwtEncode(jwtSecret, {
"preferred_username": "root",
"iss": "arangodb",
"exp": Math.floor(Date.now() / 1000) + 3600
}, 'HS256');
let result = request({ url: "/_api/version", method: "get", auth: { bearer: jwtRoot } });
assertEqual(200, result.status);
assertFalse(result.headers.hasOwnProperty('www-authenticate'));
},
};
}
jsunity.run(testSuite);
return jsunity.done();
|
/**
* Copyright IBM Corp. 2016, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { FormItem, NumberInput } from 'carbon-components-react';
export default {
title: 'FormItem',
};
export const Default = () => (
<FormItem>
<NumberInput id="number-input-1" hideLabel />
</FormItem>
);
Default.story = {
parameters: {
info: {
text: 'Form item.',
},
},
};
|
import React, { useEffect } from 'react';
import { FooterThree, HeaderSix, Wrapper } from '../../layout';
import { animationCreate } from '../../utils/utils';
import Breadcrumb from '../common/breadcrumb/breadcrumb';
import AboutContact from './about-contact';
import AboutMeArea from './about-me-area';
import ExperienceArea from './experience-area';
const AboutMe = ({team}) => {
useEffect(() => {
setTimeout(() => {
animationCreate();
}, 500);
}, []);
return (
<Wrapper>
<HeaderSix />
<Breadcrumb title={team?.name ? team?.name : 'Ritarexa Diramen'} />
<AboutMeArea team={team}/>
<ExperienceArea/>
<AboutContact/>
<FooterThree />
</Wrapper>
);
};
export default AboutMe;
|
import styled from 'styled-components'
import look from '@a/images/vegetables/look.png'
import light from '@a/images/vegetables/look-light.png'
import comment from '@a/images/vegetables/comment.png'
import vegetables from '@a/images/vegetables/vegetables.png'
const LookAndComment = styled.div`
display:${props => props.display ? props.display : "flex" };
justify-content:space-between;
.item{
width:100%;
height:100%;
margin-right:.2rem;
display:flex;
text-align:center;
align-items:center;
i{
width:.35rem;
height:.2rem;
display:block;
}
span{
font-weight: 400;
font-style: normal;
color:${props => props.light ?" #fff" : "#C9C9C9;"};
}
}
.look{
i{
background: url(${props=> props.light ? light : look}) no-repeat center ;
}
}
.comment{
i{
background: url(${props=> props.other ? vegetables : comment}) no-repeat center;
}
}
`
export default LookAndComment
|
import * as constants from './constants';
export function getTopStories() {
return {
type: constants.TOP_STORIES_REQUEST,
};
}
export function topStoriesSuccess(ids) {
return {
type: constants.TOP_STORIES_SUCCESS,
payload: {
ids,
},
};
}
export function topStoriesFailure(message, error) {
return {
type: constants.TOP_STORIES_FAILURE,
payload: {
message,
error,
},
};
}
export function topStoriesUpdates(ids) {
return {
type: constants.TOP_STORIES_UPDATES,
payload: {
ids,
},
};
}
export function loadStories(ids) {
return {
type: constants.LOAD_STORIES_REQUEST,
payload: {
ids,
},
};
}
export function loadStoriesSuccess(stories) {
return {
type: constants.LOAD_STORIES_SUCCESS,
payload: {
stories,
},
};
}
export function loadStoriesFailure(message, error) {
return {
type: constants.LOAD_STORIES_FAILURE,
payload: {
message,
error,
},
};
}
|
import { schema } from 'normalizr';
export const posts = new schema.Entity('posts');
export const arrayOfPosts = new schema.Array(posts);
export const users = new schema.Entity('users');
export const arrayOfUsers = new schema.Array(users);
export const comments = new schema.Entity('comments');
export const arrayOfComments = new schema.Array(comments);
|
//TODO: create event listener for cardList
//TODO: create event listener for add card button and prevent default. add card to list
//TODO: add event listener for delete button and send JSON obj with id through delete request
document.addEventListener('DOMContentLoaded',function(){
var table = document.getElementById('deckTable');
table.addEventListener('click',function(event){tableClick(event)})
})
function tableClick(event) {
console.log('click registered');
if (event.target.name === 'delete') {
var xhr = new XMLHttpRequest();
xhr.open('DELETE','/',true);
xhr.setRequestHeader('Content-Type','application/json');
var payload = {};
// go to parent node of event target, getElementsByTagName(input)
var current = event.target;
current = current.parentNode;
current = current.parentNode; // this will be the row element
var inputs = current.getElementsByTagName('input');
// select id node and get value, store in payload.id
var idNode = inputs[0];
payload.id = idNode.value;
console.log(payload)
xhr.addEventListener('load',function(){
if (xhr.status>=200 && xhr.status<400) {
var result = JSON.parse(xhr.responseText);
// check result
if (result.deleteStatus==="success") {
console.log('successful delete');
var tbody = current.parentNode;
tbody.removeChild(current);
document.getElementById('cardCount').textContent--;
}
else {
console.log("delete not successful");
}
}
else {
console.log('network error');
}
})
current.style.background = "grey";
xhr.send(JSON.stringify(payload));
event.preventDefault();
}
if (event.target.name ==='edit') {
if (event.target.value==='Edit') {
var current = event.target;
current = current.parentNode;
current = current.parentNode;
var inputs = current.querySelectorAll('input');
for (let input of inputs) {
input.removeAttribute('disabled');
}
event.target.setAttribute('value','Done');
event.target.style.backgroundColor = 'hsl(192, 96%, 48%)';
current.style.backgroundColor = "hsl(192, 0%, 89%)";
}
else if (event.target.value==='Done'){
var xhr = new XMLHttpRequest();
xhr.open('put','/',true);
xhr.setRequestHeader('Content-Type','application/json');
var payload = {};
var current = event.target;
current = current.parentNode;
current = current.parentNode;
var inputs = current.querySelectorAll('input');
for (let input of inputs) {
payload[input.name] = input.value;
}
payload.deck = document.getElementById('deckTable').getAttribute('deckName');
console.log(payload)
xhr.addEventListener('load',function(){
if (xhr.status>=200 && xhr.status<400) {
var result = JSON.parse(xhr.responseText);
if (result.update==='success') {
console.log('successful edit');
/*
var appendNode = document.getElementById('deckTable');
appendNode = appendNode.lastElementChild; // tbody
appendNode.appendChild(createRow);
console.log('debug');
*/
for (let input2 of inputs) {
if (input2.getAttribute('type')!=='submit'){
input2.setAttribute('disabled','true');
}
}
event.target.setAttribute('value','Edit');
event.target.style.background = "none";
current.style.background = 'white';
}
}
else {
console.log('network error');
}
})
xhr.send(JSON.stringify(payload));
event.preventDefault();
}
}
}
function createRow(row) {
var tr = document.createElement('tr');
var td;
for (var prop in row) {
td = document.createElement('td');
td.name = row.name;
td.value = row.value;
td.disabled = disabled;
if (row.name === 'id' || row.name === 'review_count' || row.name === 'correct_count') {
td.hidden = true;
td.setAttribute('type','submit');
}
if (row.name === 'username') {
td.hidden = true;
}
if (row.name === 'edit' || row.name === 'delete') {
td.setAttribute('type','submit');
}
tr.appendChild(td);
}
return tr;
}
|
import React from 'react';
import FormInput from './FormInput';
export default {
title: 'Remote/FormInput',
component: FormInput,
};
const Template = (args) => <FormInput {...args} />;
export const DefaultFormInput = Template.bind({});
DefaultFormInput.args = {
label: 'Name',
placeholder: 'eg: Jane Doe',
helperText: 'First and last names',
};
|
import React, { useState } from 'react';
import './About.css';
import texts from './../../helper/texts';
function About() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<div className='about'>
<h3>About</h3>
<p>{texts.about}</p>
</div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default About;
|
/**
功能: js 解析|缩小|压缩|美化 工具
教程:
https://github.com/mishoo/UglifyJS2#api-reference
http://lisperator.net/uglifyjs/parser
UglifyJS.minify(code, options)
code: 源js代码
options: {
warnings:
}
*/
var UglifyJS = require('uglify-js')
var options = {
warnings: false | true | 'verbose', //默认false,true时得到result.warnings,'verbose'时得到更多warings
parse: {
bare_returns: false, //默认false, support top level return statements
html5_comments: true, //默认true
shebang: true, //支持'#!command'作为第一行
},
compress: false | { //默认{},好多属性。。
},
mangle: true | { //默认true,损坏变量,函数名
reserved: [], //跳过指定的变量
toplevel: '', //损坏在顶级范围内声明的名字
eval: '',
keep_fnames: false, //true时不损坏函数名
properties: {
}
},
output: null | { //默认null,好多属性。。
},
sourceMap: { //默认false
},
toplevel: false | true, //默认false
ie8: false | true //默认false,true时支持ie8
}
var result = UglifyJS.minify(code, options)
console.log(result.code | error | warnins)
|
var userId;
//Access user Doc
var userRef;
//Initialize array that contains resources the user has accessed
var accessedResources = [];
var user = firebase.auth().currentUser;
var name, email, photoUrl, uid, emailVerified;
var openness, conscientiousness, extroversion, agreeableness, neuroticism;
var npercentile, epercentile, opercentile, apercentile, cpercentile;
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
document.getElementById("signIn").style.display = "none";
document.getElementById("home").style.display = "flex";
document.getElementById("topNav").style.display = "flex";
userId = user.uid;
console.log(userId);
var accessedRef = db.collection("users").doc(userId);
accessedRef.get().then(function(doc) {
if (doc.exists) {
if (!(doc.data().neuroticism)) {
document.getElementById("testNotification").style.display = "flex";
} else {
console.log(doc.data());
openness = doc.data().openness;
conscientiousness = doc.data().conscientiousness;
extroversion = doc.data().extroversion;
agreeableness = doc.data().agreeableness;
neuroticism = doc.data().neuroticism;
npercentile = roundToTwo(ztable((neuroticism - 3.095192454) / 0.6716282482) * 100);
epercentile = roundToTwo(ztable((extroversion - 3.076565749) / 0.3522392277) * 100);
opercentile = roundToTwo(ztable((openness - 3.313479385) / 0.384431613) * 100);
apercentile = roundToTwo(ztable((agreeableness - 3.204935388) / 0.3543837412) * 100);
cpercentile = roundToTwo(ztable((conscientiousness - 3.154749227) / 0.3885176637) * 100);
}
//Show test notification if the user has no trait database
if (doc.data().accessed) {
doc.data().accessed.forEach(function(resource) {
accessedResources.push(resource);
})
}
} else {
console.log("No such document");
}
}).catch(function(error) {
console.log("Error getting document: ", error);
})
userRef = db.collection("users").doc(`${userId}`);
//Access user document in database, and create one if this is the first time they log in
db.collection("users").doc(userId).set({}, {merge: true});
} else {
loadPage("signIn");
}
if (user != null) {
name = user.displayName;
email = user.email;
document.getElementById("userName").innerHTML = `<button onclick="loadPage('')">${name}</button>`;
if (email) {
document.getElementById("userEmail").innerHTML = `${email}`;
}
}
});
function hideAll() {
//use document.getelement to hide all pages
document.getElementById("signIn").style.display = "none";
document.getElementById("home").style.display = "none";
document.getElementById("profile").style.display = "none";
document.getElementById("paths").style.display = "none";
document.getElementById("popular").style.display = "none";
document.getElementById("submit").style.display = "none";
document.getElementById("topics").style.display = "none";
document.getElementById("about").style.display = "none";
}
var queryArray = new Array();
var videoArray = new Array();
var loadedTopics = false;
var loadedPopular = false;
var popularVideos;
hideAll();
function loadPage(page) {
switch (page) {
case "signIn":
hideAll();
document.getElementById("topNav").style.display = "none";
document.getElementById("signIn").style.display = "flex";
document.getElementById("footerContainer").style = "position: absolute; bottom: 0;";
break;
case "home":
hideAll();
document.getElementById("home").style.display = "flex";
break;
case "paths":
hideAll();
document.getElementById("paths").style.display = "flex";
break;
case "popular":
hideAll();
document.getElementById("popularContent").innerHTML = ``;
document.getElementById("popular").style.display = "flex";
if (loadedPopular) {
document.getElementById("popularContent").innerHTML = popularVideos;
}
else {
videosRef = db.collection("videos");
videosRef.orderBy("views").limit(20)
.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var title = doc.data().title;
var link = doc.data().link;
var author = doc.data().author;
var resourceId = doc.id;
if (accessedResources.includes(`${resourceId}`)) {
var complete = "Complete";
} else {
var complete = "Not Complete";
}
document.getElementById("popularContent").innerHTML += `\<div class='card' onclick='gotoResource("${link}", "${resourceId}")'><p class="title">${title}</p><p class="author">${author}</p><p id="${resourceId}_complete">${complete}</p></div>`
popularVideos = document.getElementById("popularContent").innerHTML;
});
loadedPopular = true;
})
}
//Fetch all videos and sort by views
break;
case "submit":
hideAll();
document.getElementById("submit").style.display = "flex";
break;
case "profile":
hideAll();
document.getElementById("profile").style.display = "flex";
loadCharts();
break;
case "topics":
hideAll();
document.getElementById("displayTopic").style.display = "none";
document.getElementById("topics").style.display = "flex";
document.getElementById("topicHeader").innerHTML = "<h3>Browse by Topic</h3><div id='resourceSelect'></div>"
document.getElementById("topicsCards").innerHTML = ``;
document.getElementById("resourceSelect").innerHTML = ``;
document.getElementById("topicsCards").style.display = "flex";
//Get every topic from database and display alphabetically
//If topics have already been loaded, show them
if (loadedTopics) {
queryArray.forEach(function(el) {
if (!(el == undefined)) {
document.getElementById("topicsCards").innerHTML += `\<div class="card" onclick="loadResources('${el}')"><h3>${capitalizeFirstLetter(el)}</h3></div>`;
}
})
}
//If topics have not been loaded, fetch them from database
else {
db.collection("videos").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var topic = (doc.data().topic);
if (!(queryArray.includes(topic)))
queryArray.push(topic);
queryArray.sort();
});
queryArray.forEach(function(el) {
document.getElementById("topicsCards").innerHTML += `\<div class="card" onclick="loadResources('${el}')"><h3>${capitalizeFirstLetter(el)}</h3></div>`;
})
});
loadedTopics = true;
}
break;
case "about":
hideAll();
document.getElementById("about").style.display = "flex";
break;
}
}
function printArray(array) {
(array).forEach(function(el) {
console.log(el);
});
};
function loadAssessment() {
window.open("./test.html", "_self")
}
function login() {
var userEmail = document.getElementById("email_field").value;
var userPassword = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert(errorMessage);
if (errorMessage) {
return;
} else {
sendHome();
}
});
};
function loginWithGoogle() {
firebase.auth().signInWithRedirect(googleAuth);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// ...
}
// The signed-in user info.
var user = result.user;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
}
function loginWithFacebook() {
firebase.auth().signInWithRedirect(facebookAuth);
}
function logout() {
firebase.auth().signOut().then(function() {
// Sign-out successful.
hideAll();
}).catch(function(error) {
// An error happened.
});
}
function submitResource() {
if (document.getElementById('resourceTypeVideo').checked) {
var type = "video";
}
if (document.getElementById('resourceTypeBook').checked) {
var type = "book";
}
var link = document.getElementById('link').value;
var title = document.getElementById('title').value;
var topic = document.getElementById('topic').value;
var author = document.getElementById('author').value;
//Send submission to video database
if (type == "video") {
db.collection("videos").add({
link: link,
title: title,
topic: topic,
author: author
})
};
//Send submission to book database
if (type == "book") {
db.collection("books").add({
link: link,
title: title,
topic: topic,
author: author
})
};
//wipe form
document.getElementById('resourceTypeVideo').checked = false;
document.getElementById('resourceTypeBook').checked = false;
document.getElementById('link').value = "";
document.getElementById('title').value = "";
document.getElementById('topic').value = "";
document.getElementById('author').value = "";
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function gotoResource(link, resourceId) {
window.open(link, "_blank");
userRef = db.collection("users").doc(`${userId}`);
userRef.update({
accessed: firebase.firestore.FieldValue.arrayUnion(`${resourceId}`)
});
var docRef = db.collection("videos").doc(resourceId);
docRef.get()
.then(function(doc) {
//Check doc views to increment later
//If doc hasn't been viewed, set views to 0
if (isNaN(doc.data().views)) {
viewCount = parseInt(0);
} else {
viewCount = parseInt(doc.data().views);
}
docRef.update({
views: (viewCount + 1)
});
console.log(doc.data().views);
});
accessedResources.push(`${resourceId}`);
//refresh card to reflect completion
document.getElementById(`${resourceId}_complete`).innerHTML = "Complete";
}
var accessedTopics = [];
var accessedObj = new Object();
function loadResources(topic) {
//Change topicHeader
document.getElementById("topicHeader").innerHTML = `<h3>${capitalizeFirstLetter(topic)}</h3><div id="resourceSelect"></div>`;
//Hide topic categories
document.getElementById("topicsCards").style.display = "none";
//Show pertinent topic cards
document.getElementById("displayTopic").style.display = "flex";
//Clear cards if topic has been opened already to prevent duplicates
document.getElementById("displayTopic").innerHTML = ``;
//Generate Resource Select Buttons (vid/text)
document.getElementById("resourceSelect").innerHTML = `\<button id="vidLoad" onclick='vidLoad("${topic}")'>Videos</button>\<button id="bookLoad" onclick='bookLoad("${topic}")'>Books</button>`
//If topic has already been accessed, load data from local storage
if (accessedTopics.includes(topic)) {
document.getElementById("displayTopic").innerHTML = accessedObj[`${topic}`];
}
//Otherwise, fetch topic data from database and store locally
else {
var docRef = db.collection("videos").where("topic", "==", topic)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var title = doc.data().title;
var link = doc.data().link;
var author = doc.data().author;
var resourceId = doc.id;
if (accessedResources.includes(`${resourceId}`)) {
var complete = "Complete";
} else {
var complete = "Not Complete";
}
document.getElementById("displayTopic").innerHTML += `\<div class='card' onclick='gotoResource("${link}", "${resourceId}")'><p class="title">${title}</p><p class="author">${author}</p><p id="${resourceId}_complete">${complete}</p></div>`
});
accessedObj[`${topic}`] = document.getElementById("displayTopic").innerHTML;
accessedTopics.push(topic);
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
}
}
//Functions for sorting resources by their type (video/book)
function vidLoad(topic) {
//Change button colors
document.getElementById("bookLoad").style = "background-color: #D0FFFA;"
document.getElementById("vidLoad").style = "background-color: #1FEBD5;"
//If topic has already been accessed, load data from local storage
if (accessedTopics.includes(topic)) {
document.getElementById("displayTopic").innerHTML = accessedObj[`${topic}`];
}
//Otherwise, fetch topic data from database and store locally
else {
var docRef = db.collection("videos").where("topic", "==", topic)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var title = doc.data().title;
var link = doc.data().link;
var author = doc.data().author;
var resourceId = doc.id;
if (accessedResources.includes(`${resourceId}`)) {
var complete = "Complete";
} else {
var complete = "Not Complete";
}
document.getElementById("displayTopic").innerHTML += `\<div class='card' onclick='gotoResource("${link}", "${resourceId}")'><p class="title">${title}</p><p class="author">${author}</p><p id="${resourceId}_complete">${complete}</p></div>`
});
accessedObj[`${topic}`] = document.getElementById("displayTopic").innerHTML;
accessedTopics.push(topic);
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
}
}
function bookLoad(topic) {
//Change button colors
document.getElementById("bookLoad").style = "background-color: #1FEBD5;"
document.getElementById("vidLoad").style = "background-color: #D0FFFA;"
//Get books on topic
document.getElementById("displayTopic").innerHTML = ``;
var docRef = db.collection("books").where("topic", "==", topic)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
var title = doc.data().title;
var link = doc.data().link;
var author = doc.data().author;
var resourceId = doc.id;
if (accessedResources.includes(`${resourceId}`)) {
var complete = "Complete";
} else {
var complete = "Not Complete";
}
document.getElementById("displayTopic").innerHTML += `\<div class='card' onclick='gotoResource("${link}", "${resourceId}")'><p class="title">${title}</p><p class="author">${author}</p><p id="${resourceId}_complete">${complete}</p></div>`
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
}
//Plug data into profile charts
function loadCharts() {
//Plug in percentiles
document.getElementById("nPercentile").innerHTML = `Percentile: ${npercentile}`;
document.getElementById("ePercentile").innerHTML = `Percentile: ${epercentile}`;
document.getElementById("oPercentile").innerHTML = `Percentile: ${opercentile}`;
document.getElementById("aPercentile").innerHTML = `Percentile: ${apercentile}`;
document.getElementById("cPercentile").innerHTML = `Percentile: ${cpercentile}`;
//Draw charts
var ctx = document.getElementById("overviewChart").getContext('2d');
var overviewChart = new Chart(ctx, {
scaleFontColor: "#220606",
type: 'bar',
data: {
labels: ["Neuroticism", "Extroversion", "Openness", "Agreeableness", "Conscientiousness"],
datasets: [{
label: 'My Trait',
data: [neuroticism, extroversion, openness, agreeableness, conscientiousness],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 2
}, {
label: 'Average of Others',
data: [3.095192454, 3.076565749, 3.313479385, 3.204935388, 3.154749227]
}]
},
options: {
title: {
display: false,
text: "Your Personality",
fontFamily: "'Roboto', 'Arial', 'sans-serif'",
fontSize: 40,
fontColor: "#220606"
},
legend: {
labels: {
fontColor: "#220606"
}
},
defaultFontFamily: "'Roboto', 'Arial', 'sans-serif'",
defaultFontSize: 20,
defaultFontColor: "220606",
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {
autoSkip: false,
fontColor: "#220606",
fontSize: 16
}
}],
yAxes: [{
ticks: {
suggestedMin: 1,
suggestedMax: 5,
fontColor: "#220606",
fontSize: 16,
beginAtZero: false
}
}]
}
}
});
var n_chartData = {
datasets: [
{
data: [
{x:1, y:0.004576815021},
{x:1.2, y:0.01108534101},
{x:1.4, y:0.02457104418},
{x:1.6, y:0.04984103205},
{x:1.8, y:0.0925207828},
{x:2, y:0.1571738997},
{x:2.2, y:0.2443489163},
{x:2.4, y:0.3476396179},
{x:2.6, y:0.4526233647},
{x:2.8, y:0.539303864},
{x:3, y:0.5880563626},
{x:3.2, y:0.586804226},
{x:3.4, y:0.5358662074},
{x:3.6, y:0.4478250331},
{x:3.8, y:0.3424910452},
{x:4, y:0.2397060158},
{x:4.2, y:0.1535315039},
{x:4.4, y:0.08999221328},
{x:4.6, y:0.04827265883},
{x:4.8, y:0.02369661789},
{x:5, y:0.0106453604}],
pointRadius: 0,
backgroundColor: "rgba(255, 99, 132, 0.2)",
borderColor: "rgba(255,99,132,1)"
}
]
};
var e_chartData = {
datasets: [
{
data: [
{x:1.0, y:0.00000003214723514195},
{x:1.2, y:0.00000077780319755499},
{x:1.4, y:0.0000136327245544213},
{x:1.6, y:0.000173094167473},
{x:1.8, y:0.0015920952514403},
{x:2.0, y:0.0106082195223683},
{x:2.2, y:0.051203870201856},
{x:2.4, y:0.179039936937765},
{x:2.6, y:0.453506883059907},
{x:2.8, y:0.83215588353705},
{x:3.0, y:1.10614569068931},
{x:3.2, y:1.06514029315185},
{x:3.4, y:0.742998837972865},
{x:3.6, y:0.375453617965446},
{x:3.8, y:0.137439412881212},
{x:4.0, y:0.0364462732869391},
{x:4.2, y:0.00700135021245128},
{x:4.4, y:0.000974310347583334},
{x:4.6, y:0.0000982199404532679},
{x:4.8, y:0.00000717280222966508},
{x:5.0, y:0.00000037945902372752}],
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgba(54, 162, 235, 1)",
pointRadius: 0,
}
]
};
var o_chartData = {
datasets: [
{
data: [
{x:1.0, y:0.0000000141912455736},
{x:1.2, y:0.00000028375501248241},
{x:1.4, y:0.00000432833672514484},
{x:1.6, y:0.0000503678030442194},
{x:1.8, y:0.000447135804611572},
{x:2.0, y:0.00302817073533691},
{x:2.2, y:0.0156450061959461},
{x:2.4, y:0.061663133729869},
{x:2.6, y:0.185408617334732},
{x:2.8, y:0.425293465067687},
{x:3.0, y:0.744221093003705},
{x:3.2, y:0.993504208307053},
{x:3.4, y:1.01179357729395},
{x:3.6, y:0.786083347859887},
{x:3.8, y:0.465907547136839},
{x:4.0, y:0.210661593822477},
{x:4.2, y:0.0726650299190197},
{x:4.4, y:0.0191214146239577},
{x:4.6, y:0.00383856634896984},
{x:4.8, y:0.00058785816635039},
{x:5.0, y:0.0000686800386009074}],
backgroundColor: "rgba(255, 206, 86, 0.2)",
borderColor: "rgba(255, 206, 86, 1)",
pointRadius: 0,
}
]
};
var a_chartData = {
datasets: [
{
data: [
{x:1.0, y:0.00000000441835259249},
{x:1.2, y:0.00000012620398120156},
{x:1.4, y:0.00000262157326464925},
{x:1.6, y:0.0000396029194713139},
{x:1.8, y:0.000435079544526076},
{x:2.0, y:0.00347605297887058},
{x:2.2, y:0.0201966978310677},
{x:2.4, y:0.0853396010155034},
{x:2.6, y:0.262238895752793},
{x:2.8, y:0.586030023127313},
{x:3.0, y:0.952398897343282},
{x:3.2, y:1.12562611657086},
{x:3.4, y:0.967488245418181},
{x:3.6, y:0.604746679854177},
{x:3.8, y:0.27490177713156},
{x:4.0, y:0.0908778117927531},
{x:4.2, y:0.0218481382085377},
{x:4.4, y:0.00381985842301869},
{x:4.6, y:0.000485686864819817},
{x:4.8, y:0.0000449098608166591},
{x:5.0, y:0.00000301997480053798}],
backgroundColor: "rgba(75, 192, 192, 0.2)",
borderColor: "rgba(75, 192, 192, 1)",
pointRadius: 0,
}
]
};
var c_chartData = {
datasets: [
{
data: [
{x:1.0, y:0.0000002149174350137},
{x:1.2, y:0.00000327067002882764},
{x:1.4, y:0.000038187017678437},
{x:1.6, y:0.000342065033217706},
{x:1.8, y:0.00235079928357218},
{x:2.0, y:0.0123947093182335},
{x:2.2, y:0.0501384692954331},
{x:2.4, y:0.155603630062398},
{x:2.6, y:0.370494961511818},
{x:2.8, y:0.676797610257725},
{x:3.0, y:0.94852603394984},
{x:3.2, y:1.01989067885372},
{x:3.4, y:0.84134073851848},
{x:3.6, y:0.532481032757202},
{x:3.8, y:0.258553425086208},
{x:4.0, y:0.0963186476867017},
{x:4.2, y:0.0275286165263518},
{x:4.4, y:0.00603632096610902},
{x:4.6, y:0.00101548658559564},
{x:4.8, y:0.000131065982038121},
{x:5.0, y:0.0000129783567957114}],
backgroundColor: "rgba(153, 102, 255, 0.2)",
borderColor: "rgba(153, 102, 255, 1)",
pointRadius: 0,
}
]
};
var n_ctx = document.getElementById("n-chart").getContext("2d");
new Chart(n_ctx, {
type: "line",
data: n_chartData,
options: {
legend: {
display: false
},
title: {
display: true,
text: "Neuroticism",
fontFamily: "'Roboto', 'Arial', 'sans-serif'",
fontSize: 30,
fontColor: "#220606"
},
maintainAspectRatio: false,
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
value: neuroticism,
borderColor: "rgba(255, 99, 132, 1)",
borderWidth: 3,
label: {
content: "You",
enabled: true,
position: "middle"
}
}
]
},
scales: {
xAxes: [{
type: "linear",
ticks: {
fontColor: "#220606",
fontSize: 16,
autoSkip: true
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: "Density of Probability"
},
ticks: {
// Include a percent sign in the ticks
callback: function(value, index, values) {
return (value);
},
suggestedMin: 0,
suggestedMax: .6,
stepSize: .2,
fontColor: "#220606",
fontSize: 16,
}
}]
}
}
});
var e_ctx = document.getElementById("e-chart").getContext("2d");
new Chart(e_ctx, {
type: "line",
data: e_chartData,
options: {
legend: {
display: false
},
title: {
display: true,
text: "Extroversion",
fontFamily: "'Roboto', 'Arial', 'sans-serif'",
fontSize: 30,
fontColor: "#220606"
},
maintainAspectRatio: false,
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
value: extroversion,
borderColor: "rgba(54, 162, 235, 1)",
borderWidth: 3,
label: {
content: "You",
enabled: true,
position: "middle"
}
}
]
},
scales: {
xAxes: [{
type: "linear",
ticks: {
fontColor: "#220606",
fontSize: 16,
autoSkip: true
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: "Density of Probability"
},
ticks: {
// Include a percent sign in the ticks
callback: function(value, index, values) {
return (value);
},
suggestedMin: 0,
suggestedMax: .6,
stepSize: .2,
fontColor: "#220606",
fontSize: 16,
}
}]
}
}
});
var o_ctx = document.getElementById("o-chart").getContext("2d");
new Chart(o_ctx, {
type: "line",
data: o_chartData,
options: {
legend: {
display: false
},
title: {
display: true,
text: "Openness",
fontFamily: "'Roboto', 'Arial', 'sans-serif'",
fontSize: 30,
fontColor: "#220606"
},
maintainAspectRatio: false,
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
value: openness,
borderColor: "rgba(255, 206, 86, 1)",
borderWidth: 3,
label: {
content: "You",
enabled: true,
position: "middle"
}
}
]
},
scales: {
xAxes: [{
type: "linear",
ticks: {
fontColor: "#220606",
fontSize: 16,
autoSkip: true
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: "Density of Probability"
},
ticks: {
// Include a percent sign in the ticks
callback: function(value, index, values) {
return (value);
},
suggestedMin: 0,
suggestedMax: .6,
stepSize: .2,
fontColor: "#220606",
fontSize: 16,
}
}]
}
}
});
var a_ctx = document.getElementById("a-chart").getContext("2d");
new Chart(a_ctx, {
type: "line",
data: a_chartData,
options: {
legend: {
display: false
},
title: {
display: true,
text: "Agreeableness",
fontFamily: "'Roboto', 'Arial', 'sans-serif'",
fontSize: 30,
fontColor: "#220606"
},
maintainAspectRatio: false,
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
value: agreeableness,
borderColor: "rgba(75, 192, 192, 1)",
borderWidth: 3,
label: {
content: "You",
enabled: true,
position: "middle"
}
}
]
},
scales: {
xAxes: [{
type: "linear",
ticks: {
fontColor: "#220606",
fontSize: 16,
autoSkip: true
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: "Density of Probability"
},
ticks: {
// Include a percent sign in the ticks
callback: function(value, index, values) {
return (value);
},
suggestedMin: 0,
suggestedMax: .6,
stepSize: .2,
fontColor: "#220606",
fontSize: 16,
}
}]
}
}
});
var c_ctx = document.getElementById("c-chart").getContext("2d");
new Chart(c_ctx, {
type: "line",
data: c_chartData,
options: {
legend: {
display: false
},
title: {
display: true,
text: "Conscientiousness",
fontFamily: "'Roboto', 'Arial', 'sans-serif'",
fontSize: 30,
fontColor: "#220606"
},
maintainAspectRatio: false,
annotation: {
annotations: [
{
type: "line",
mode: "vertical",
scaleID: "x-axis-0",
value: conscientiousness,
borderColor: "rgba(153, 102, 255, 1)",
borderWidth: 3,
label: {
content: "You",
enabled: true,
position: "middle"
}
}
]
},
scales: {
xAxes: [{
type: "linear",
ticks: {
fontColor: "#220606",
fontSize: 16,
autoSkip: true
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: "Density of Probability"
},
ticks: {
// Include a percent sign in the ticks
callback: function(value, index, values) {
return (value);
},
suggestedMin: 0,
suggestedMax: .6,
stepSize: .2,
fontColor: "#220606",
fontSize: 16,
}
}]
}
}
});
};
var ZTABLE =
{
'z': [0.09, 0.08,0.07,0.06,0.05,0.04,0.03,0.02,0.01,0],
'-3.4': [ 0.0002, 0.0003, 0.0003, 0.0003, 0.0003, 0.0003, 0.0003, 0.0003, 0.0003, 0.0003],
'-3.3': [ 0.0003, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0004, 0.0005, 0.0005, 0.0005],
'-3.2': [ 0.0005, 0.0005, 0.0005, 0.0006, 0.0006, 0.0006, 0.0006, 0.0006, 0.0007, 0.0007],
'-3.1': [ 0.0007, 0.0007, 0.0008, 0.0008, 0.0008, 0.0008, 0.0009, 0.0009, 0.0009, 0.0010],
'-3.0': [ 0.0010, 0.0010, 0.0011, 0.0011, 0.0011, 0.0012, 0.0012, 0.0013, 0.0013, 0.0013],
'-2.9': [ 0.0014, 0.0014, 0.0015, 0.0015, 0.0016, 0.0016, 0.0017, 0.0018, 0.0018, 0.0019],
'-2.8': [ 0.0019, 0.0020, 0.0021, 0.0021, 0.0022, 0.0023, 0.0023, 0.0024, 0.0025, 0.0026],
'-2.7': [ 0.0026, 0.0027, 0.0028, 0.0029, 0.0030, 0.0031, 0.0032, 0.0033, 0.0034, 0.0035],
'-2.6': [ 0.0036, 0.0037, 0.0038, 0.0039, 0.0040, 0.0041, 0.0043, 0.0044, 0.0045, 0.0047],
'-2.5': [ 0.0048, 0.0049, 0.0051, 0.0052, 0.0054, 0.0055, 0.0057, 0.0059, 0.0060, 0.0062],
'-2.4': [ 0.0064, 0.0066, 0.0068, 0.0069, 0.0071, 0.0073, 0.0075, 0.0078, 0.0080, 0.0082],
'-2.3': [ 0.0084, 0.0087, 0.0089, 0.0091, 0.0094, 0.0096, 0.0099, 0.0102, 0.0104, 0.0107],
'-2.2': [ 0.0110, 0.0113, 0.0116, 0.0119, 0.0122, 0.0125, 0.0129, 0.0132, 0.0136, 0.0139],
'-2.1': [ 0.0143, 0.0146, 0.0150, 0.0154, 0.0158, 0.0162, 0.0166, 0.0170, 0.0174, 0.0179],
'-2.0': [ 0.0183, 0.0188, 0.0192, 0.0197, 0.0202, 0.0207, 0.0212, 0.0217, 0.0222, 0.0228],
'-1.9': [ 0.0233, 0.0239, 0.0244, 0.0250, 0.0256, 0.0262, 0.0268, 0.0274, 0.0281, 0.0287],
'-1.8': [ 0.0294, 0.0301, 0.0307, 0.0314, 0.0322, 0.0329, 0.0336, 0.0344, 0.0351, 0.0359],
'-1.7': [ 0.0367, 0.0375, 0.0384, 0.0392, 0.0401, 0.0409, 0.0418, 0.0427, 0.0436, 0.0446],
'-1.6': [ 0.0455, 0.0465, 0.0475, 0.0485, 0.0495, 0.0505, 0.0516, 0.0526, 0.0537, 0.0548],
'-1.5': [ 0.0559, 0.0571, 0.0582, 0.0594, 0.0606, 0.0618, 0.0630, 0.0643, 0.0655, 0.0668],
'-1.4': [ 0.0681, 0.0694, 0.0708, 0.0721, 0.0735, 0.0749, 0.0764, 0.0778, 0.0793, 0.0808],
'-1.3': [ 0.0823, 0.0838, 0.0853, 0.0869, 0.0885, 0.0901, 0.0918, 0.0934, 0.0951, 0.0968],
'-1.2': [ 0.0985, 0.1003, 0.1020, 0.1038, 0.1056, 0.1075, 0.1093, 0.1112, 0.1131, 0.1151],
'-1.1': [ 0.1170, 0.1190, 0.1210, 0.1230, 0.1251, 0.1271, 0.1292, 0.1314, 0.1335, 0.1357],
'-1.0': [ 0.1379, 0.1401, 0.1423, 0.1446, 0.1469, 0.1492, 0.1515, 0.1539, 0.1562, 0.1587],
'-0.9': [ 0.1611, 0.1635, 0.1660, 0.1685, 0.1711, 0.1736, 0.1762, 0.1788, 0.1814, 0.1841],
'-0.8': [ 0.1867, 0.1894, 0.1922, 0.1949, 0.1977, 0.2005, 0.2033, 0.2061, 0.2090, 0.2119],
'-0.7': [ 0.2148, 0.2177, 0.2206, 0.2236, 0.2266, 0.2296, 0.2327, 0.2358, 0.2389, 0.2420],
'-0.6': [ 0.2451, 0.2483, 0.2514, 0.2546, 0.2578, 0.2611, 0.2643, 0.2676, 0.2709, 0.2743],
'-0.5': [ 0.2776, 0.2810, 0.2843, 0.2877, 0.2912, 0.2946, 0.2981, 0.3015, 0.3050, 0.3085],
'-0.4': [ 0.3121, 0.3156, 0.3192, 0.3228, 0.3264, 0.3300, 0.3336, 0.3372, 0.3409, 0.3446],
'-0.3': [ 0.3483, 0.3520, 0.3557, 0.3594, 0.3632, 0.3669, 0.3707, 0.3745, 0.3783, 0.3821],
'-0.2': [ 0.3829, 0.3897, 0.3936, 0.3974, 0.4013, 0.4052, 0.4090, 0.4129, 0.4168, 0.4207],
'-0.1': [ 0.4247, 0.4286, 0.4325, 0.4364, 0.4404, 0.4443, 0.4483, 0.4522, 0.4562, 0.4602],
'0.0': [ 0.4641, 0.4681, 0.4721, 0.4761, 0.4801, 0.4840, 0.4880, 0.4920, 0.4960, 0.5000]
};
function ztable(zscore) {
zscore = parseFloat(zscore);
if (isNaN(zscore)) {
throw new TypeError('zscore is not a valid number');
}
var yZscore = -3.4;
var xZscore = 0.09;
if(zscore === 0) {
return 0.5000;
}
if(zscore > 0) {
if(zscore > 3.49) {
return 1;
}
zscore = Math.floor(zscore * 100) / 100;
yZscore = Math.floor(zscore * 10) / 10;
yZscore = -yZscore;
} else {
if(zscore < -3.49) {
return 0;
}
zscore = Math.ceil(zscore * 100) / 100;
yZscore = Math.ceil(zscore * 10) / 10;
}
xZscore = Math.abs(Math.round((zscore % yZscore) * 10000) / 10000);
var z100 = isNaN(xZscore) ? Math.abs(zscore) : xZscore;
var z10 = yZscore === 0 ? '0.0' : yZscore.toFixed(1);
var col = ZTABLE.z.indexOf(z100);
var perc = ZTABLE[z10][col];
if(zscore > 0) {
perc = Math.round((1 - perc) * 10000) / 10000;
}
return perc;
};
|
import React from "react";
import "./ChatMessage.css";
import SentMessage from "./SentMessage";
import ReceivedMessage from "./ReceivedMessage";
// keep this in chatmessage file snd create two subfiles with above
function ChatMessage(props) {
if (props.messageType === "sent") {
return <SentMessage message={props.message} user={props.message.user} />;
} else {
return (
<ReceivedMessage message={props.message} user={props.message.user} />
);
}
}
export default ChatMessage;
|
angular.module("ngApp.security", []);
|
/**
* Created by Hild Franck on 8/12/2015.
*/
var loki = require('lokijs');
var enemies = require('../entities/enemies.js');
var attacks = require('../entities/attacks.js');
var players = require('../entities/players.js');
var EventEmitter = require('events').EventEmitter;
module.exports = new EventEmitter();
var db = new loki('game.json');
console.log("Chargement de la base de données");
db.loadDatabase({}, function(){
if(db.getCollection('Players') !== null &&
db.getCollection('EnemiesOnMap') !== null &&
db.getCollection('Attacks') !== null){
console.log("Base de données chargée");
module.exports.database = db;
module.exports.emit('ready');
}
else{
console.log("Initialisation de la base de donnée...");
if(db.getCollection('Players') === null){
var playersDb = db.addCollection('Players');
playersDb.insert(new players.Player(50, 50, 0));
playersDb.insert(new players.Player(100, 50, 1));
console.log("Base de donnée Player crée");
}
if(db.getCollection('EnemiesOnMap') === null){
var enemiesOnMapDb = db.addCollection('EnemiesOnMap');
enemiesOnMapDb.insert(new enemies.Flower(10,10));
enemiesOnMapDb.insert(new enemies.Flower(300, 300));
console.log("Base de donnée EnemiesOnMap crée");
}
if(db.getCollection('Attacks') === null){
var attacksDb = db.addCollection('Attacks');
for(var attack in attacks) {
if(attacks.hasOwnProperty(attack))
attacksDb.insert(attacks[attack]);
}
console.log("Base de donnée Attacks crée");
}
console.log("Bases de données créées");
db.saveDatabase();
module.exports.database = db;
module.exports.emit('ready');
}
});
|
import React, { useState } from 'react';
import { Field, Form, Formik } from 'formik';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUser } from '@fortawesome/free-regular-svg-icons';
import {
faCheck,
faPortrait,
faSignature,
faUpload,
} from '@fortawesome/free-solid-svg-icons';
import * as Yup from 'yup';
import psalmday from '../../apis/psalmday';
import axios from 'axios';
const ProfileEditSchema = Yup.object().shape({
nickname: Yup.string()
.lowercase('Username must be lowercase.')
.required('Required.')
.max(20, 'Username cannot exceed 20 characters.'),
given_name: Yup.string(),
family_name: Yup.string(),
description: Yup.string().max(
150,
'Description cannot exceed 150 characters.'
),
});
const ProfileEdit = ({ user, onProfileSaved }) => {
const [hideSaved, setHideSaved] = useState(true);
const [filePlaceholder, setFilePlaceholder] = useState('Upload a file...');
const [pictureUrl, setPictureUrl] = useState('');
const [fileError, setFileError] = useState('');
const [disabled, setDisabled] = useState(false);
let initialValues = {
nickname: user?.nickname,
given_name: user?.given_name,
family_name: user?.family_name,
description: user?.user_metadata?.description,
version: user?.user_data?.version,
font_size: user?.user_data?.font_size,
};
const handleFileUpload = e => {
if (!e.target.files[0].name.match(/(\.jpg|\.jpeg|\.png|\.gif)/)) {
setFileError('Invalid file type.');
e.target.files = null;
setDisabled(true);
} else {
setFileError('');
setDisabled(false);
}
setFilePlaceholder(e.target.files[0].name.replaceAll(' ', '-'));
getSignedRequest(e.target.files[0]);
};
const getSignedRequest = async file => {
const { data } = await axios.get(
`/sign-s3?file-name=${file.name.replaceAll(' ', '-')}&file-type=${
file.type
}`
);
uploadFile(file, data.signedRequest, data.url);
};
const uploadFile = async (file, signedRequest, url) => {
setPictureUrl(url);
await axios.put(signedRequest, file, {
headers: {
'X-Content-Type-Options': 'nosniff',
},
});
};
const renderSelect = props => {
return (
<div className='my-10'>
<label className='label mr-10'>{props.title}</label>
<div className='select'>
<select {...props.field}>{props.children}</select>
</div>
</div>
);
};
const renderInput = props => {
return (
<div className='field'>
<label className='label'>{props.title}</label>
<div className='control has-icons-left has-icons-right'>
<input
className={`input ${
props.form.errors[props.error] ? 'is-danger' : ''
}`}
{...props.field}
placeholder={props.placeholder || ''}
/>
<span className='icon is-small is-left'>
<FontAwesomeIcon icon={props.icon} />
</span>
{!props.form.errors[props.error] ? (
<span className='icon is-small is-right'>
<FontAwesomeIcon icon={faCheck} />
</span>
) : null}
</div>
{props.form.errors[props.error] ? (
<p className='help is-danger'>{props.form.errors[props.error]}</p>
) : null}
</div>
);
};
const renderDescriptionTextarea = props => {
return (
<div className='field'>
<label className='label'>{props.title}</label>
<textarea
{...props.field}
className='textarea'
placeholder={props.placeholder}></textarea>
</div>
);
};
const renderFileUpload = props => {
return (
<div className='flex my-10 flex-col'>
<label className='label mr-10'>{props.title}</label>
<div className='file is-primary'>
<label className='file-label'>
<input
className='file-input'
type='file'
name='picture'
{...props.field}
onChange={handleFileUpload}
/>
<span className='file-cta'>
<span className='file-icon'>
<FontAwesomeIcon icon={faUpload} />
</span>
<span className='file-label'>Upload an image</span>
</span>
<span className='file-name'>{filePlaceholder}</span>
</label>
</div>
<p className='help is-danger italic'>{fileError}</p>
</div>
);
};
const renderSavedNotification = () => {
return (
<div className='notification is-primary' hidden={hideSaved}>
<button
type='button'
className='delete'
onClick={() => setHideSaved(true)}></button>
Saved!
</div>
);
};
const handleSubmit = async values => {
setHideSaved(false);
await psalmday.patch(`/users/${user?.user_id}`, {
...values,
picture: pictureUrl || user?.picture,
user_metadata: {
description: values.description,
},
});
await psalmday.patch(`/users/${user?.user_id}/userData`, {
user_data: {
version: values.version || 'NLT',
font_size: values.font_size || 'text-base',
},
});
onProfileSaved();
initialValues = values;
};
return (
<Formik
enableReinitialize={true}
initialValues={initialValues}
validationSchema={ProfileEditSchema}
onSubmit={handleSubmit}>
{({ isSubmitting }) => (
<Form className='animate-none'>
<Field name='version' component={renderSelect} title='Version'>
<option value='NLT'>New Living Translation</option>
<option value='ESV'>English Standard Version</option>
</Field>
<Field name='font_size' component={renderSelect} title='Font Size'>
<option value='text-sm'>Small</option>
<option value='text-base'>Normal</option>
<option value='text-lg'>Large</option>
<option value='text-xl'>Extra Large</option>
<option value='text-2xl'>Huge</option>
</Field>
<Field
type='file'
name='picture'
component={renderFileUpload}
error='picture'
title='Profile Picture'
/>
<Field
type='text'
name='nickname'
component={renderInput}
error='nickname'
title='Username'
placeholder='Enter your username'
icon={faUser}
/>
<Field
type='text'
name='given_name'
component={renderInput}
error='given_name'
title='First Name'
placeholder='Enter your first name'
icon={faPortrait}
/>
<Field
type='text'
name='family_name'
component={renderInput}
error='family_name'
title='Last Name'
placeholder='Enter your last name'
icon={faSignature}
/>
<Field
type='textarea'
name='description'
title='Description'
placeholder='Enter a brief description'
component={renderDescriptionTextarea}
/>
<div className='my-5 animate-none'>{renderSavedNotification()}</div>
<div className='control'>
<button
type='submit'
className='button is-primary'
disabled={isSubmitting || disabled}>
Save
</button>
</div>
</Form>
)}
</Formik>
);
};
export default ProfileEdit;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const SendInBlue = require("sendinblue-api");
const emailExistence = require("email-existence");
const config_1 = require("../config");
class MailHelper {
static sendMailAdvanced(fromData, toData, subject, html) {
return new Promise((resolve, reject) => {
if (!toData || !subject || !html)
reject(false);
if (!fromData || !fromData.email || !fromData.name)
fromData = {
email: config_1.Config.PROJECT.SENDINBLUE.SENDER.EMAIL,
name: config_1.Config.PROJECT.SENDINBLUE.SENDER.NAME
};
let data = {
from: [`${fromData.email.trim().toLowerCase()}`, `${fromData.name}`],
to: toData,
subject,
html
};
let sendInBlueClient = new SendInBlue({ 'apiKey': config_1.Config.PROJECT.SENDINBLUE.API_KEY, 'timeout': 10000 });
sendInBlueClient.send_email(data, (err, response) => {
if (err)
reject(false);
else
resolve(true);
});
});
}
static loadMailTemplate(path, param) {
let content = fs.readFileSync(path, 'utf8');
if (param) {
Object.keys(param).forEach(key => {
content = content.replace(new RegExp(`{{${key}}}`, 'g'), param[key]);
});
}
return content;
}
static checkRealEmail(email) {
return new Promise((resolve, reject) => {
emailExistence.check(email, (error, response) => {
if (error) {
console.error(error);
resolve(false);
}
resolve(response);
});
});
}
}
Object.seal(MailHelper);
exports.default = MailHelper;
|
import React from 'react'
import Link from './Link'
import Icon from './Icon'
import QriLogo from './QriLogo'
import { trackGoal } from '../utils/analytics'
const Footer = () => {
const fireAnalyticsEvent = () => {
// home-click-footer-link event
trackGoal('L6ZTBPVH', 0)
}
return (
<div className='bg-qrigray-1000 text-white py-14 px-5 md:px-10 lg:px-20 text-base w-full overflow-hidden flex-shrink-0 z-20'>
<div className='flex flex-wrap -mx-10'>
<div className='mb-10 px-10 w-full overflow-hidden lg:w-auto flex items-center self-start'>
<QriLogo size='lg'/>
<div className='text-4xl inline font-black ml-5'>Qri</div>
</div>
<div className='my-2 px-10 w-full overflow-hidden lg:w-auto flex-grow flex flex-wrap justify-start' >
<div className='mr-16 mb-5'>
<h5 className='text-qritile-600 font-bold mb-5'>Learn</h5>
<ul>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='/docs'>Docs</Link></li>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='/docs/tutorials'>Tutorials</Link></li>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='/faq'>FAQs</Link></li>
</ul>
</div>
<div className='mr-16'>
<h5 className='text-qritile-600 font-bold mb-5'>Company</h5>
<ul>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='/about'>About</Link></li>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='https://medium.com/qri-io'>Blog</Link></li>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='/jobs'>Jobs</Link></li>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='/contact'>Contact</Link></li>
</ul>
</div>
<div className='mr-16'>
<h5 className='text-qritile-600 font-bold mb-5'>Explore</h5>
<ul>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='https://qri.cloud/search'>Dataset Search</Link></li>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='https://qri.cloud'>Qri.cloud</Link></li>
</ul>
</div>
<div>
<h5 className='text-qritile-600 font-bold mb-5'>Install</h5>
<ul>
<li className='text-sm mb-3'><Link onClick={fireAnalyticsEvent} colorClassName='text-white' to='https://github.com/qri-io/qri/releases'>Qri CLI</Link></li>
</ul>
</div>
</div>
<div className='my-2 px-10 w-full overflow-hidden lg:w-auto flex flex-col'>
<div className='flex'>
<div className='inline mr-4'>
<Link onClick={fireAnalyticsEvent} colorClassName='text-qritile-600' to='https://github.com/qri-io'><Icon icon='github'/></Link>
</div>
<div className='inline mr-4'>
<Link onClick={fireAnalyticsEvent} colorClassName='text-qritile-600' to='https://www.youtube.com/channel/UC7E3_hURgFO2mVCLDwPSyOQ'><Icon icon='youtube'/></Link>
</div>
<div className='inline mr-4'>
<Link onClick={fireAnalyticsEvent} colorClassName='text-qritile-600' to='https://twitter.com/qri_io'><Icon icon='twitter'/></Link>
</div>
<div className='inline mr-4'>
<Link onClick={fireAnalyticsEvent} colorClassName='text-qritile-600' to='https://discordapp.com/invite/thkJHKj'><Icon icon='discord'/></Link>
</div>
</div>
</div>
</div>
</div>
)
}
export default Footer
|
/**
Integrated tests for ArrayUtilities
@author laifrank2002
@date 2020-01-02
*/
var TestArrayUtilities = (
function()
{
Engine.log("Adding tests for ArrayUtilities...");
/*
Tests the function ArrayUtilities.removeElement(array, element) by using a test array with values, then checking if the element can still be found in the array.
Note, that if the same value is repeated in an array, this test will FAIL.
@author laifrank2002
@date 2020-01-02
*/
function TestRemoveElement()
{
var testArray = ["me","que","testing","154"];
ArrayUtilities.removeElement(testArray, "me");
return testArray.indexOf("me");
}
/*
Tests the function ArrayUtilities.removeElementByIndex(array, element, index) by creating a test array, removing an element, and checking if it's the right element removed.
@author laifrank2002
@date 2020-01-03
*/
function TestRemoveElementByIndex()
{
var testArray = ["me","que","testing","154"];
ArrayUtilities.removeElementByIndex(testArray, 2);
return testArray.indexOf("testing");
}
/*
Tests the function ArrayUtilities.insertElement(array, element, index) by using a test array with values, then seeing if the element is inserted in the right place.
@author laifrank2002
@date 2020-01-03
*/
function TestInsertElement()
{
var testArray = ["me","que","testing","154"];
ArrayUtilities.insertElement(testArray, "five", 3);
return testArray[3];
}
TestingManager.addTest("TestArrayUtilitiesRemoveElement", TestRemoveElement, -1);
TestingManager.addTest("TestArrayUtilitiesRemoveElementByIndex", TestRemoveElementByIndex, -1);
TestingManager.addTest("TestArrayUtilitiesInsertElement", TestInsertElement, "five");
}
);
|
import React from "react";
import SearchBar from "./component/SearchBar";
import unsplash from "./api/unsplash";
import ImageList from "./component/ImageList";
import "./App.css";
class App extends React.Component {
state = { images: [], selectedImage: null };
componentDidMount() {
this.onSearchSubmit("dog");
}
onSearchSubmit = async (term) => {
const resolve = await unsplash.get("/search/photos", {
params: { query: term },
});
console.log(resolve);
this.setState({
images: resolve.data.results,
});
};
render() {
return (
<div className="container ui container">
<SearchBar onSubmit={this.onSearchSubmit} />
<ImageList images={this.state.images} />
</div>
);
}
}
export default App;
|
document.addEventListener("load", setTimeout(function(){
document.querySelector(".cover").style.right = "100%"
}, 1000))
// document.querySelector("#mybtn").addEventListener("click", function(){
// document.querySelector(".cover").style.right = "100%"
// })
btns = document.querySelectorAll(".btn")
for(let i=0; i<btns.length; i++){
btns[i].addEventListener("click", function(){
btns[i].parentElement.querySelector("input").readOnly = false
val = btns[i].parentElement.querySelector("input").value
btns[i].parentElement.querySelector("input").value = ""
btns[i].parentElement.querySelector("input").value = val
btns[i].parentElement.querySelector("input").focus()
document.querySelector("#buttons button:nth-child(1)").style.opacity = "1"
document.querySelector("#buttons button:nth-child(2)").style.opacity = "1"
document.querySelector("#buttons button:nth-child(1)").disabled = false
document.querySelector("#buttons button:nth-child(2)").disabled = false
})
}
document.querySelector("#buttons button:nth-child(1)").addEventListener("click", function(){
alert("Sas")
})
|
function kaliTerusRekursif(angka) {
// you can only write your code here!
var newStr = angka.toString()
var kalipertama = 1
for (var i = 0; i < newStr.length; i++){
// console.log ( Number(newStr[i]))
kalipertama*=Number(newStr[i])
}
// console.log (kalipertama)
if (newStr.length === 1) {
return kalipertama
} else {
return kaliTerusRekursif(kalipertama)
}
}
// TEST CASES
console.log(kaliTerusRekursif(66)); // 8
console.log(kaliTerusRekursif(3)); // 3
console.log(kaliTerusRekursif(24)); // 8
console.log(kaliTerusRekursif(654)); // 0
console.log(kaliTerusRekursif(1231)); // 6
|
const Database = require('better-sqlite3');
const db = {
verbose:console.log,
path:'../database/memory.sqlite3',
getDataBase(){
return new Database(this.path,{verbose: this.verbose});
}
};
module.exports = db;
|
// Copyright 2012 Dmitry Monin. 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.
/**
* @fileoverview 3-state checkbox widget. Fires CHECK or UNCHECK events before toggled and
* CHANGE event after toggled by user.
* The checkbox can also be enabled/disabled and get focused and highlighted.
*/
goog.provide('morning.forms.Checkbox');
goog.require('goog.dom.dataset');
goog.require('goog.ui.Checkbox');
goog.require('morning.forms.IControl');
/**
* 3-state checkbox widget. Fires CHECK or UNCHECK events before toggled and
* CHANGE event after toggled by user.
* The checkbox can also be enabled/disabled and get focused and highlighted.
*
* @param {goog.ui.Checkbox.State=} opt_checked Checked state to set.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @param {goog.ui.CheckboxRenderer=} opt_renderer Renderer used to render or
* decorate the checkbox; defaults to {@link goog.ui.CheckboxRenderer}.
* @constructor
* @implements {morning.forms.IControl}
* @extends {goog.ui.Checkbox}
*/
morning.forms.Checkbox = function(opt_checked, opt_domHelper, opt_renderer)
{
goog.base(this, opt_checked, opt_domHelper, opt_renderer);
/**
* @type {string}
* @private
*/
this.fieldName = '';
};
goog.inherits(morning.forms.Checkbox, goog.ui.Checkbox);
/** @inheritDoc */
morning.forms.Checkbox.prototype.decorateInternal = function(el)
{
goog.base(this, 'decorateInternal', el);
this.fieldName = /** @type {string} */ (goog.dom.dataset.get(el, 'name'));
};
/**
* Returns checkbox field name
*
* @return {string}
*/
morning.forms.Checkbox.prototype.getFieldName = function()
{
return this.fieldName;
};
/**
* Returns checkbox value
*
* @return {*} value.
*/
morning.forms.Checkbox.prototype.getValue = function()
{
return this.isChecked() ? '1' : '0';
};
/** @inheritDoc */
morning.forms.Checkbox.prototype.reset = function()
{
this.setChecked(false);
};
/**
* Sets control display to invalid state
*
* @param {boolean} isInvalid
*/
morning.forms.Checkbox.prototype.setInvalid = function(isInvalid)
{
goog.dom.classlist.enable(this.getElement(), 'invalid', isInvalid);
};
/**
* Sets checkbox configugration
*
* @param {Object} config
*/
morning.forms.Checkbox.prototype.setConfig = function(config)
{
if (goog.isDef(config['fieldName']))
{
this.fieldName = config['fieldName'];
}
};
/**
* @param {*} value
*/
morning.forms.Checkbox.prototype.setValue = function(value)
{
value = /** @type {number} */ (value);
this.setChecked(value == 1);
};
/**
* Register this control so it can be created from markup.
*/
goog.ui.registry.setDecoratorByClassName(
'checkbox',
function() {
return new morning.forms.Checkbox();
});
|
import React, { Component } from 'react'
import axios from 'axios'
import './style.css'
import { base_url } from '../../../assets/env'
class Profil extends Component {
state = {
step: 'Coordonnées',
info: {
gender: 'female'
},
education: {
degree: 'Licence'
},
assos: {
board: false,
member: false
},
upload: ''
}
componentDidMount = async () => {
await this.loadUser()
}
loadUser = async () => {
try {
const response = await axios.get(
base_url + '/api/user/' + window.localStorage.user_id,
{
headers: { token: window.localStorage.access_token }
}
)
if (response.status === 200) this.setState(response.data)
} catch (error) {
console.log(error)
}
}
userUpdate = async () => {
try {
const response = await axios.put(
base_url + '/api/user/' + window.localStorage.user_id,
{
info: this.state.info,
education: this.state.education,
assos: this.state.assos
},
{
headers: { token: window.localStorage.access_token }
}
)
return response.status === 200
} catch (error) {
console.log(error)
return false
}
}
handleFileUpload = async e => {
let formData = new FormData()
formData.append('degreeFile', e.target.files[0])
formData.append('id', window.localStorage.user_id)
try {
const response = await axios.post(
base_url + '/api/user/upload',
formData,
{
headers: { token: window.localStorage.access_token }
}
)
response.status === 200 &&
response.data.success &&
this.setState({ upload: 'Succées' })
response.status === 200 &&
!response.data.success &&
this.setState({ upload: response.data.message })
} catch (error) {
this.setState({ upload: 'Error uploading file' })
console.log(error)
}
}
handleInfoInputChange = e => {
this.setState({
info: { ...this.state.info, [`${e.target.name}`]: e.target.value }
})
}
handleEduInputChange = e => {
this.setState({
education: {
...this.state.education,
[`${e.target.name}`]: e.target.value
}
})
}
handleAssosInputChange = e => {
this.setState({
assos: {
...this.state.assos,
[`${e.target.name}`]: e.target.value
}
})
}
renderPerosnalDataForm = () => {
return (
<React.Fragment>
<div className="form-container">
<div className="form-group">
<label className="label-right">Nom</label>
<input
name="firstName"
value={this.state.info.firstName || ''}
onChange={this.handleInfoInputChange}
type="text"
required
/>
</div>
<div className="form-group">
<label className="label-right">Prénom</label>
<input
name="lastName"
value={this.state.info.lastName || ''}
onChange={this.handleInfoInputChange}
type="text"
required
/>
</div>
<div className="form-group">
<label className="label-right">Sexe</label>
<div className="toggle-group">
<button
onClick={() =>
this.setState({
info: { ...this.state.info, gender: 'female' }
})
}
className={
this.state.info.gender === 'female'
? 'toggle toggle-active'
: 'toggle'
}
>
Femme
</button>
<button
onClick={() =>
this.setState({
info: { ...this.state.info, gender: 'male' }
})
}
className={
this.state.info.gender === 'male'
? 'toggle toggle-active'
: 'toggle'
}
>
Homme
</button>
</div>
</div>
<div className="form-group">
<label className="label-right label-small">Date de naissance</label>
<input
name="birthdate"
onChange={this.handleInfoInputChange}
value={this.state.info.birthdate || ''}
type="Date"
required
/>
</div>
<div className="form-group">
<label className="label-right">CIN</label>
<input
name="cin"
onChange={this.handleInfoInputChange}
value={this.state.info.cin || ''}
type="text"
required
/>
</div>
</div>
<div className="form-container">
<div className="form-group">
<label className="label-right">Email</label>
<input
name="email"
onChange={this.handleInfoInputChange}
value={this.state.email || ''}
type="email"
required
/>
</div>
<div className="form-group">
<label className="label-right">Numéro Tél</label>
<input
name="phone"
onChange={this.handleInfoInputChange}
value={this.state.info.phone || ''}
type="text"
required
/>
</div>
<div className="form-group">
<label className="label-right">Gouvernorat</label>
<select
name="governorate"
onChange={this.handleInfoInputChange}
value={this.state.info.governorate || ''}
>
<option value="" />
<option value="Ariana">Ariana</option>
<option value="Béja">Béja</option>
<option value="Ben Arous">Ben Arous</option>
<option value="Bizerte">Bizerte</option>
<option value="Gabès">Gabès</option>
<option value="Gafsa">Gafsa</option>
<option value="Jendouba">Jendouba</option>
<option value="Kairouan">Kairouan</option>
<option value="Kasserine">Kasserine</option>
<option value="Kébili">Kébili</option>
<option value="Le Kef">Le Kef</option>
<option value="Mahdia">Mahdia</option>
<option value="La Manouba">La Manouba</option>
<option value="Médenine">Médenine</option>
<option value="Monastir">Monastir</option>
<option value="Nabeul">Nabeul</option>
<option value="Sfax">Sfax</option>
<option value="Sidi">Sidi</option> Bouzid
<option value="Siliana">Siliana</option>
<option value="Sousse">Sousse</option>
<option value="Tataouine">Tataouine</option>
<option value="Tozeur">Tozeur</option>
<option value="Tunis">Tunis</option>
<option value="Zaghouan">Zaghouan</option>
</select>
</div>
<div className="form-group">
<label className="label-right">Ville</label>
<input
name="city"
onChange={this.handleInfoInputChange}
value={this.state.info.city || ''}
type="text"
required
/>
</div>
<div className="form-group">
<label className="label-right">Adresse</label>
<input
name="address"
onChange={this.handleInfoInputChange}
value={this.state.info.address || ''}
type="text"
/>
</div>
</div>
</React.Fragment>
)
}
renderEducationForm = () => {
return (
<React.Fragment>
<div className="form-container">
<div className="form-group">
<label className="label-right">Année Obtention Bac</label>
<select
name="bacYear"
onChange={this.handleEduInputChange}
value={this.state.education.bacYear || ''}
>
<option value="" />
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
</select>
</div>
<div className="form-group">
<label className="label-right">Spécialité Bac</label>
<select
name="bacMajor"
onChange={this.handleEduInputChange}
value={this.state.education.bacMajor || ''}
>
<option value="" />
<option value="Sciences expérimentales">
Sciences expérimentales
</option>
<option value="Mathématiques">Mathématiques</option>
<option value="Économie et gestion">Économie et gestion</option>
<option value="Technique">Technique</option>
<option value="Lettres">Lettres</option>
<option value="Sport">Sport</option>
<option value="Informatique">Informatique</option>
</select>
</div>
<div className="form-group">
<label className="label-right">Moyenne Bac</label>
<input
name="bacAvg"
onChange={this.handleEduInputChange}
value={this.state.education.bacAvg || ''}
type="text"
/>
</div>
<div className="form-group">
<label className="label-right">Diplôme</label>
<div className="toggle-group">
<button
onClick={() =>
this.setState({
education: { ...this.state.education, degree: 'Licence' }
})
}
className={
this.state.education.degree === 'Licence'
? 'toggle toggle-active'
: 'toggle'
}
>
Licence
</button>
<button
onClick={() =>
this.setState({
education: { ...this.state.education, degree: 'Ing' }
})
}
className={
this.state.education.degree === 'Ing'
? 'toggle toggle-active'
: 'toggle'
}
>
Ingénieur
</button>
<button
onClick={() =>
this.setState({
education: { ...this.state.education, degree: 'Master' }
})
}
className={
this.state.education.degree === 'Master'
? 'toggle toggle-active'
: 'toggle'
}
>
Master
</button>
</div>
</div>
<div className="form-group file-upload">
<label className="label-right">Copie Diplôme</label>
<input
name="degreeFile"
onChange={this.handleFileUpload}
type="file"
/>
</div>
<div className="form-group file-upload">
<label />
<div className="file-upload-feedback">
{this.state.upload || ''}
</div>
</div>
<div className="form-group">
<label className="label-right label-small">
Dernier Établissement fréquenté
</label>
<input
name="uni"
onChange={this.handleEduInputChange}
value={this.state.education.uni || ''}
type="text"
/>
</div>
<div className="form-group">
<label className="label-right">Spécialité</label>
<input
name="major"
onChange={this.handleEduInputChange}
value={this.state.education.major || ''}
type="text"
/>
</div>
</div>
</React.Fragment>
)
}
renderVolunteerWorkForm = () => {
return (
<React.Fragment>
<div className="form-container">
<div className="form-group">
<p className="profile-text">
Étiez-vous membre dans le conseil d’administration d’une
association ?
</p>
<div className="toggle-group">
<button
onClick={() =>
this.setState({
...this.state,
assos: { ...this.state.assos, board: false }
})
}
className={
this.state.assos.board === false
? 'toggle toggle-active'
: 'toggle'
}
>
Non
</button>
<button
onClick={() =>
this.setState({
assos: { ...this.state.assos, board: true }
})
}
className={
this.state.assos.board === true
? 'toggle toggle-active'
: 'toggle'
}
>
Oui
</button>
</div>
</div>
{this.state.assos.board && (
<div className="form-group">
<label>Laquelle ?</label>
<input
name="organization"
onChange={this.handleAssosInputChange}
value={this.state.assos.organization || ''}
type="text"
/>
</div>
)}
{!this.state.assos.board && (
<div className="form-group">
<p className="profile-text">
Étiez-vous membre actif dans une association ?
</p>
<div className="toggle-group">
<button
onClick={() =>
this.setState({
assos: { ...this.state.assos, member: false }
})
}
className={
this.state.assos.member === false
? 'toggle toggle-active'
: 'toggle'
}
>
Non
</button>
<button
onClick={() =>
this.setState({
assos: { ...this.state.assos, member: true }
})
}
className={
this.state.assos.member === true
? 'toggle toggle-active'
: 'toggle'
}
>
Oui
</button>
</div>
</div>
)}
{!this.state.assos.board &&
this.state.assos.member && (
<div className="form-group">
<label>Laquelle ?</label>
<input
name="organization"
onChange={this.handleAssosInputChange}
value={this.state.assos.organization || ''}
type="text"
/>
</div>
)}
</div>
</React.Fragment>
)
}
backStep = () => {
switch (this.state.step) {
case 'Education':
return this.setState({ step: 'Coordonnées' })
case 'Vie Associative':
return this.setState({ step: 'Education' })
default:
return this.setState({ step: 'Coordonnées' })
}
}
nextStep = () => {
switch (this.state.step) {
case 'Coordonnées':
//validate inputs
return this.setState({ step: 'Education' })
case 'Education':
//validate inputs
return this.setState({ step: 'Vie Associative' })
case 'Vie Associative':
if (this.userUpdate()) return this.props.setTab('Background')
return
default:
return this.setState({ step: 'Coordonnées' })
}
}
render() {
return (
<div className="Profile">
<div>
<span className="profile-title">Dis-nous un peu plus sur toi : </span>
<span>{this.state.step}</span>
</div>
<div className="double-form-container">
{this.state.step === 'Coordonnées' && this.renderPerosnalDataForm()}
{this.state.step === 'Education' && this.renderEducationForm()}
{this.state.step === 'Vie Associative' &&
this.renderVolunteerWorkForm()}
</div>
<div className="navigation">
{!(this.state.step === 'Coordonnées') && (
<button className="btn-next" onClick={() => this.backStep()}>
back
</button>
)}
<button className="btn-next" onClick={() => this.nextStep()}>
Next
</button>
</div>
</div>
)
}
}
export default Profil
|
function create () {
game.physics.startSystem(Phaser.Physics.ARCADE);
//autoalign the game stage
game.scale.pageAlignHorizontally = true;
game.scale.pageAlignVertically = true;
game.scale.setScreenSize(true);
// Initialize player
player = game.add.sprite(initialPlayerPosition, 940, 'ship');
player.scale.setTo(0.16,0.16);
player.anchor.setTo(0.5, 0.5);
game.physics.enable(player, Phaser.Physics.ARCADE);
player.body.bounce.x = 0.5;
player.body.collideWorldBounds = true;
// Initialize bullets
bullets = game.add.group();
// bullets.scale.setTo(0.1,0.1);
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(5, 'bullet');
bullets.setAll('anchor.x', 0.5);
bullets.setAll('anchor.y', 1);
bullets.setAll('checkWorldBounds', true);
bullets.setAll('outOfBoundsKill', true);
// Initialize aliens
createAliens();
animateAliens();
// Initialize bombs
bombs = game.add.group();
bombs.scale.setTo(1.4,1.4);
bombs.enableBody = true;
bombs.physicsBodyType = Phaser.Physics.ARCADE;
bombs.createMultiple(10, 'bomb');
bombs.setAll('anchor.x', 0.5);
bombs.setAll('anchor.y', 0.5);
bombs.setAll('checkWorldBounds', true);
bombs.setAll('outOfBoundsKill', true);
bombs.forEach(setupBomb, this);
// Initialize explosions
explosions = game.add.group();
explosions.createMultiple(10, 'explosion');
explosions.setAll('anchor.x', 0.5);
explosions.setAll('anchor.y', 0.5);
explosions.forEach(setupExplosion, this);
// Text bits
livesText = game.add.text(game.world.bounds.width - 16, 16, "LIVES: " + lives, style);
livesText.anchor.set(1, 0);
scoreText = game.add.text(game.world.centerX, 16, '', style);
scoreText.anchor.set(0.5, 0);
highScoreText = game.add.text(16, 16, '', style);
highScoreText.anchor.set(0, 0);
getHighScore();
updateScore();
// Initialize sounds
shootSound = game.add.audio('shoot', 1, false);
explodeSound = game.add.audio('explode', 1, false);
bombSound = game.add.audio('bomb', 1, false);
// Add gamebase
gameBase = game.add.sprite(game.world.centerX, 960,'gameBase');
gameBase.anchor.setTo(0.5, 0.5);
gameBase.enableBody = true;
game.physics.enable(gameBase, Phaser.Physics.ARCADE);
// startButton = game.add.button(game.world.centerX - 95, 400, 'startButton', actionOnClick, this, 'down');
fireButton = game.add.button(game.world.centerX - 350, 1050, 'fireButton', fireBullet);
fireButton.scale.setTo(2.5,2.5);
moveLeftButton = game.add.button(game.world.centerX - 30, 1050, 'moveLeftButton', null, this, 0,1,0,1);
moveLeftButton.scale.setTo(2.4,2.4);
moveLeftButton.events.onInputOver.add(function(){left=true;});
moveLeftButton.events.onInputOut.add(function(){left=false;});
moveLeftButton.events.onInputDown.add(function(){left=true;});
moveLeftButton.events.onInputUp.add(function(){left=false;});
moveRightButton = game.add.button(game.world.centerX + 180, 1050, 'moveRightButton', null, this, 0,1,0,1);
moveRightButton.scale.setTo(2.5,2.5);
moveRightButton.events.onInputOver.add(function(){right=true;});
moveRightButton.events.onInputOut.add(function(){right=false;});
moveRightButton.events.onInputDown.add(function(){right=true;});
moveRightButton.events.onInputUp.add(function(){right=false;});
}
|
// const bigInt = 1234567890123456789012345678901234567890n;
// console.log(bigInt);
let height = null;
let width = null;
let bigInt=1234567n;
let area = (height ?? 100) * (width ?? 50);
console.log(area);
let a = "1";
console.log(typeof(+a));
|
import React, { Component } from 'react';
import TaskList from './components/TaskList';
import Header from './components/Header'
import { BrowserRouter, Route } from 'react-router-dom';
import './App.css';
class App extends Component {
constructor(props) {
super(props)
this.state = {
tasks: [{title: 'Watch Movie', elapsedTime: 10, timer: false}, {title:'Learn React', elapsedTime: 10, timer: false}]
}
}
getTasks() {
return this.state.tasks
}
addTask(task) {
this.setState(prevState => {
tasks : prevState.tasks.push(task)
})
}
setTimer(title) {
var tasks = this.state.tasks
for(var i=0;i<this.state.tasks.length;i++) {
if(this.state.tasks[i].title === title) {
console.log("inside1st")
tasks[i].timer = true
this.setState({
tasks: tasks
})
}else{
tasks[i].timer = false
this.tasks.clearTimer(i)
this.setState({
tasks: tasks
})
}
}
console.log(this.state.tasks)
}
TaskListComponent = () => {
}
render() {
return (
<div>
<Header />
<BrowserRouter>
<div>
<Route exact path="/tasks" render={()=> <TaskList ref={tasks=> {this.tasks = tasks}} setTimer={this.setTimer.bind(this)} title="First Task" getTasks={this.getTasks.bind(this)} addTask={this.addTask.bind(this)} />} />
</div>
</BrowserRouter>
</div>
);
}
}
export default App;
|
// Generated by CoffeeScript 1.9.2
(function() {
var app;
app = angular.module('hutCrawler', ['ngRoute']);
app.config([
'$routeProvider', function($routeProvider) {
return $routeProvider.when('/huts', {
templateUrl: 'views/huts'
}).when('/changelog', {
templateUrl: 'views/changelog'
}).when('/about', {
templateUrl: 'views/about'
}).when('/question', {
templateUrl: 'views/question'
}).when('/contact', {
templateUrl: 'views/contact'
}).otherwise({
redirectTo: '/huts'
});
}
]);
app.controller('hutCrawlerCtrl', [
'$scope', '$http', function($scope, $http) {
$scope.toggle = true;
$scope.capacity = '';
$scope.urlApply = '';
$scope.dataAfterDraw = [];
$scope.dataBeforeDraw = [];
$scope.isLoading = true;
$scope.updateDate = '';
$scope.hutGroups = [];
$scope.topBarHutNames = [];
$scope.hutNameZhSelected = '';
$scope.titleBarNameSelected = '山屋餘額';
$scope.calendarTitles = [];
$scope.titleBar = [
{
url: '#/huts',
name: '山屋餘額'
}, {
url: '#/changelog',
name: '更新日誌'
}, {
url: '#/about',
name: '關於'
}, {
url: '#/question',
name: '常見問題'
}, {
url: '#/contact',
name: '聯絡我'
}
];
$http.get('/api/hut').success(function(result, statusCode) {
$scope.isLoading = false;
$scope.hutGroups = result.hutGroups;
return $scope.huts = result.huts;
}).error(function(e) {
return console.log(e);
});
$scope.toggleClicked = function() {
return $scope.toggle = !$scope.toggle;
};
$scope.hutNameClicked = function(hutNameZh) {
var hut, istatus, j, k, len, len1, ref, ref1, results, status;
$scope.toggle = false;
$scope.dataAfterDraw = [];
$scope.dataBeforeDraw = [];
$scope.calendarTitles = ['日', '一', '二', '三', '四', '五', '六'];
$scope.hutNameZhSelected = hutNameZh;
ref = $scope.huts;
results = [];
for (j = 0, len = ref.length; j < len; j++) {
hut = ref[j];
if (hut.nameZh === hutNameZh) {
$scope.urlApply = hut.urlApply;
$scope.capacity = hut.capacity;
$scope.updateDate = moment(hut.capacityStatuses.dateCrawl).format('M月D日 H:mm');
ref1 = hut.capacityStatuses.status;
for (istatus = k = 0, len1 = ref1.length; k < len1; istatus = ++k) {
status = ref1[istatus];
if (status.isDrawn) {
$scope.dataAfterDraw.push({
date: status.date,
remaining: parseInt(status.remaining),
applying: parseInt(status.applying)
});
} else {
$scope.dataBeforeDraw.push({
date: status.date,
remaining: parseInt(status.remaining),
applying: parseInt(status.applying)
});
}
}
break;
} else {
results.push(void 0);
}
}
return results;
};
return $scope.titleBarNameClicked = function(titleBarName) {
return $scope.titleBarNameSelected = titleBarName;
};
}
]);
app.directive('barChartAfterDraw', function() {
return {
restrict: 'E',
scope: {
data: '=data'
},
link: function(scope, element, attrs) {
/*
Structure
svg
groupChart
groupBarRemaining
groupBarApplying
groupLabelRemaing
groupLabelApplying
groupXAxis
*/
var barInterval, barWidth, groupChartHeight, groupChartPadding;
groupChartHeight = 150;
groupChartPadding = 20;
barWidth = 14;
barInterval = 24;
return scope.$watch('data', function(g) {
var applyingMax, groupChart, groupChartWidth, j, remainingMax, results, sizeData, svg, xAxis, yScale;
sizeData = scope.data.length;
if (sizeData !== 0) {
d3.select(element[0]).selectAll('*').remove();
groupChartWidth = (barWidth * 2 + barInterval) * sizeData;
svg = d3.select(element[0]).append('svg').attr('width', groupChartWidth + groupChartPadding * 2).attr('height', groupChartHeight + groupChartPadding * 2);
groupChart = svg.append('g').attr('width', groupChartWidth).attr('height', groupChartHeight).attr('transform', 'translate(' + groupChartPadding + ',' + groupChartPadding + ')');
remainingMax = d3.max(scope.data, function(d) {
return d.remaining;
});
applyingMax = d3.max(scope.data, function(d) {
return d.applying;
});
yScale = d3.scale.linear().range([groupChartHeight, 0]).domain([0, d3.max([remainingMax, applyingMax])]);
groupChart.append('g').selectAll('rect').data(scope.data).enter().append('rect').attr('x', function(d, i) {
return barInterval / 2 + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return yScale(d.remaining);
}).attr('width', barWidth).attr('height', function(d) {
return groupChartHeight - yScale(d.remaining);
}).attr('class', 'bar remaining');
groupChart.append('g').selectAll('rect').data(scope.data).enter().append('rect').attr('x', function(d, i) {
return barInterval / 2 + barWidth + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return yScale(d.applying);
}).attr('width', barWidth).attr('height', function(d) {
return groupChartHeight - yScale(d.applying);
}).attr('class', 'bar applying');
xAxis = groupChart.append('g');
xAxis.append('line').attr('x1', 0).attr('y1', groupChartHeight).attr('x2', groupChartWidth).attr('y2', groupChartHeight).attr('class', 'xaxis');
xAxis.append('g').selectAll('line').data((function() {
results = [];
for (var j = 0; 0 <= sizeData ? j <= sizeData : j >= sizeData; 0 <= sizeData ? j++ : j--){ results.push(j); }
return results;
}).apply(this)).enter().append('line').attr('x1', function(d, i) {
return i * (barWidth * 2 + barInterval);
}).attr('y1', groupChartHeight).attr('x2', function(d, i) {
return i * (barWidth * 2 + barInterval);
}).attr('y2', groupChartHeight + 5).attr('class', 'xaxis');
xAxis.append('g').selectAll('text').data(scope.data).enter().append('text').text(function(d) {
return moment(d.date).utc().format('M/D');
}).attr('x', function(d, i) {
return barInterval / 2 + barWidth + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return groupChartHeight + 20;
}).attr('class', function(d) {
switch (new Date(d.date).getDay()) {
case 0:
case 6:
return 'label date weekend';
default:
return 'label date weekday';
}
});
groupChart.append('g').selectAll('text').data(scope.data).enter().append('text').text(function(d) {
if (d.remaining !== 0) {
return d.remaining;
} else {
return '';
}
}).attr('x', function(d, i) {
return barInterval / 2 + barWidth * 0.6 + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return yScale(d.remaining) - 5;
}).attr('class', 'label remaining');
return groupChart.append('g').selectAll('text').data(scope.data).enter().append('text').text(function(d) {
if (d.applying !== 0) {
return d.applying;
} else {
return '';
}
}).attr('x', function(d, i) {
return barInterval / 2 + barWidth * 1.4 + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return yScale(d.applying) - 5;
}).attr('class', 'label applying');
}
}, true);
}
};
});
app.directive('barChartBeforeDraw', function() {
return {
restrict: 'E',
scope: {
data: '=data'
},
link: function(scope, element, attrs) {
/*
Structure
svg
groupChart
groupBarRemaining
groupBarApplying
groupLabelRemaing
groupLabelApplying
groupXAxis
*/
var barInterval, barWidth, groupChartHeight, groupChartPadding;
groupChartHeight = 150;
groupChartPadding = 20;
barWidth = 14;
barInterval = 24;
return scope.$watch('data', function(g) {
var groupChart, groupChartWidth, j, results, sizeData, svg, xAxis, yScale;
sizeData = scope.data.length;
if (sizeData !== 0) {
d3.select(element[0]).selectAll('*').remove();
groupChartWidth = (barWidth * 2 + barInterval) * sizeData;
svg = d3.select(element[0]).append('svg').attr('width', groupChartWidth + groupChartPadding * 2).attr('height', groupChartHeight + groupChartPadding * 2);
groupChart = svg.append('g').attr('width', groupChartWidth).attr('height', groupChartHeight).attr('transform', 'translate(' + groupChartPadding + ',' + groupChartPadding + ')');
yScale = d3.scale.linear().range([groupChartHeight, 0]).domain([
0, d3.max(scope.data, function(d) {
return d.applying;
})
]);
groupChart.append('g').selectAll('rect').data(scope.data).enter().append('rect').attr('x', function(d, i) {
return barInterval / 2 + barWidth / 2 + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return yScale(d.applying);
}).attr('width', barWidth).attr('height', function(d) {
return groupChartHeight - yScale(d.applying);
}).attr('class', 'bar draw-list');
xAxis = groupChart.append('g');
xAxis.append('line').attr('x1', 0).attr('y1', groupChartHeight).attr('x2', groupChartWidth).attr('y2', groupChartHeight).attr('class', 'xaxis draw-list');
xAxis.append('g').selectAll('line').data((function() {
results = [];
for (var j = 0; 0 <= sizeData ? j <= sizeData : j >= sizeData; 0 <= sizeData ? j++ : j--){ results.push(j); }
return results;
}).apply(this)).enter().append('line').attr('x1', function(d, i) {
return i * (barWidth * 2 + barInterval);
}).attr('y1', groupChartHeight).attr('x2', function(d, i) {
return i * (barWidth * 2 + barInterval);
}).attr('y2', groupChartHeight + 5).attr('class', 'xaxis draw-list');
xAxis.append('g').selectAll('text').data(scope.data).enter().append('text').text(function(d) {
return moment(d.date).utc().format('M/D');
}).attr('x', function(d, i) {
return barInterval / 2 + barWidth + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return groupChartHeight + 20;
}).attr('class', function(d) {
switch (new Date(d.date).getDay()) {
case 0:
case 6:
return 'label date weekend';
default:
return 'label date weekday draw-list';
}
});
return groupChart.append('g').selectAll('text').data(scope.data).enter().append('text').text(function(d) {
if (d.applying !== 0) {
return d.applying;
} else {
return '';
}
}).attr('x', function(d, i) {
return barInterval / 2 + barWidth + i * (barWidth * 2 + barInterval);
}).attr('y', function(d) {
return yScale(d.applying) - 5;
}).attr('class', 'label draw-list');
}
}, true);
}
};
});
}).call(this);
|
// @flow
import React from 'react';
import { Global, css } from '@emotion/core';
import emotionNormalize from 'emotion-normalize';
import { ThemeProvider } from 'emotion-theming';
import Main from 'components/main.js';
import GDPR from 'components/gdpr.js';
import type { Node } from 'react';
type Colors = $ReadOnly<{|
red: string,
cream: string,
|}>;
type Fonts = $ReadOnly<{|
primary: string,
secondary: string,
|}>;
export type Theme = $ReadOnly<{|
colors: Colors,
fonts: Fonts,
media: any,
|}>;
const breakpoints = {
xxl: 1600,
xl: 1200,
l: 992,
m: 768,
s: 576,
xs: 320,
};
const media = Object.keys(breakpoints).reduce((acc, label) => {
acc[label] = (...args) => css`
@media (min-width: ${breakpoints[label]}px) {
${css(...args)};
}
`;
return acc;
}, {});
const theme: Theme = {
colors: {
red: '#59191f',
cream: '#e9e0d2',
},
fonts: {
primary: "'Lora', serif",
secondary: "'Montserrat', serif",
},
media,
};
export default function App(): Node {
return (
<ThemeProvider theme={theme}>
<Global
styles={css`
${emotionNormalize}
@import url('https://fonts.googleapis.com/css?family=Lora:400,400i|Montserrat:700,900&display=swap&subset=cyrillic');
html,
body {
padding: 0;
margin: 0;
min-height: 100%;
font-family: ${theme.fonts.primary};
font-weight: 400;
font-size: 17px;
line-height: 1.8;
background: ${theme.colors.red};
color: ${theme.colors.cream};
overflow-x: hidden;
}
h1,
h2,
h3,
h4,
strong,
button {
font-family: ${theme.fonts.secondary};
font-weight: 900;
text-transform: uppercase;
margin: 0;
padding: 0;
}
h1 {
font-size: 36px;
}
button {
outline: none;
cursor: pointer;
border: 0;
}
`}
/>
<Main />
<GDPR />
</ThemeProvider>
);
}
|
var logoutBtn, settingsBtn, startBtn;
function init() {
var url = document.location.href, get;
get = url.split('?');
get = get[1].split('&');
get = get[0].split('=');
//document.getElementById('welcome').innerHTML = "Signed in as " + get[1];
$.ajax({
type: 'GET',
url: "http://gmfleet.azurewebsites.net/user/" + get[1],
crossDomain: true,
success: function(responseData) {
//document.getElementById('welcome').innerHTML = responseData;
var myObject = JSON.parse(responseData);
//self.location="main.html?pin=" + txtUserID.getValue() + "&user_id=" + myObject[0].user_id;
document.getElementById('welcome').innerHTML = "Signed in as " + myObject.first_name + " " + myObject.last_name;
},
error: function (responseData, textStatus, errorThrown) {
alert('Main Page: GET failed.' + responseData);
document.getElementById('welcome').innerHTML = "Signed in as Guest";
}
});
// FUNCTION CALLS
var logout = function() {
self.location="index.html";
};
// Parse incoming data and pass it back out.
var url = document.location.href, get;
get = url.split('?');
var vehiclePage = function(){
self.location="vehiclePage.html?" + get[1];
};
// BUTTON AND INPUT WIDGETS
var logoutBtn = new gm.widgets.Button({
callBack: logout,
label:"Logout",
parentElement: document.getElementById('logout')
});
logoutBtn.render(); //associated html element
var settingsBtn = new gm.widgets.Button({
//callBack: nextPage,
label:"Settings",
parentElement: document.getElementById('settings')
});
settingsBtn.render(); //associated html element
var startBtn = new gm.widgets.Button({
callBack: vehiclePage,
label:"Start",
parentElement: document.getElementById('start_trip')
});
startBtn.render(); //associated html element
}
|
/**
* Created by Huang, Fuguo (aka ken) on 16/08/2017.
*/
const shared_config = require(process.env.SHARED_CONFIG_PATH);
function WebSocketService(server) {
const wsServer = require('socket.io')(server);
// Remote Procedure Call Service
const rpcHandler = require('./Services/RemoteProcedureCallWebSocketService')(wsServer, shared_config);
return {
rpcHandler
};
}
module.exports = WebSocketService;
|
import { expect } from 'chai';
import { addNotifications, removeNotifications } from './notifications';
import * as actionTypes from '../constants/actionTypes';
describe('notifications actions', () => {
it('addNotifications action', () => {
const data = ['a', 'b', 'c'];
const action = addNotifications(data);
expect(action).to.deep.equal({
type: actionTypes.ADD_NOTIFICATIONS,
data
});
});
it('removeNotifications action', () => {
const keys = ['a', 'b', 'c'];
const action = removeNotifications(keys);
expect(action).to.deep.equal({
type: actionTypes.REMOVE_NOTIFICATIONS,
keys
});
});
});
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "27b6ef6da1d4450cce0d84eb46ae9513",
"url": "/index.html"
},
{
"revision": "c22333d0dd125413e839",
"url": "/static/css/2.1028dc60.chunk.css"
},
{
"revision": "1924d94e831b0632b2ba",
"url": "/static/css/main.c0946a67.chunk.css"
},
{
"revision": "c22333d0dd125413e839",
"url": "/static/js/2.b5448803.chunk.js"
},
{
"revision": "bc59ad81d9460d11d9865e140ec7fa82",
"url": "/static/js/2.b5448803.chunk.js.LICENSE.txt"
},
{
"revision": "1924d94e831b0632b2ba",
"url": "/static/js/main.805bd15d.chunk.js"
},
{
"revision": "43be4e19fa9d3bbff879",
"url": "/static/js/runtime-main.aaac16b6.js"
}
]);
|
'use strict';
$(function () {
console.log("jquery jestem")
/* $.ajax({
url:"http://echo.jsontest.com/userId/108/userName/Akademia108/userURL/akademia108.pl",
dataType:"json",
success: function(resultJSON){
console.log(resultJSON)
},
error: function(msg) {
console.log(msg);
}
});*/
$("#pobierz-dane").click(function() {
$.getJSON("http://echo.jsontest.com/userId/108/userName/Akademia108/userURL/akademia108.pl",
function (data) {
console.log(data);
$("body").append("<p> Nazwa użytkownika to :" + data.userName + "</p>");
$("body").append("<p> Id użytkownika to :" + data.userId + "</p>");
$("body").append("<p> URL użytkownika to :" + data.userURL + "</p>");
});
});
});
|
'use strict';
var app = app || {};
(function(module) {
function Article(rawDataObj) {
/* REVIEW: In Lab 8, we explored a lot of new functionality going on here. Let's re-examine the concept of context.
Normally, "this" inside of a constructor function refers to the newly instantiated object.
However, in the function we're passing to forEach, "this" would normally refer to "undefined" in strict mode. As a result, we had to pass a second argument to forEach to make sure our "this" was still referring to our instantiated object.
One of the primary purposes of lexical arrow functions, besides cleaning up syntax to use fewer lines of code, is to also preserve context. That means that when you declare a function using lexical arrows, "this" inside the function will still be the same "this" as it was outside the function.
As a result, we no longer have to pass in the optional "this" argument to forEach!*/
Object.keys(rawDataObj).forEach(key => this[key] = rawDataObj[key]);
}
module.Article = Article;
Article.all = [];
var toHtml = Article.prototype.toHtml = function() {
var template = Handlebars.compile($('#article-template').text());
this.daysAgo = parseInt((new Date() - new Date(this.published_on)) / 60 / 60 / 24 / 1000);
this.publishStatus = this.published_on ? `published ${this.daysAgo} days ago` : '(draft)';
this.body = marked(this.body);
return template(this);
};
module.toHtml = toHtml;
var loadAll = Article.loadAll = articleData => {
articleData.sort((a, b) => (new Date(b.published_on)) - (new Date(a.published_on)));
Article.all = articleData.map(articleObject => (new Article(articleObject)));
};
module.loadAll = loadAll;
Article.fetchAll = callback => {
$.get('/articles')
.then(results => {
Article.loadAll(results);
callback();
})
};
var numWordsAll = Article.numWordsAll = () => {
return Article.all
.map(article => article.body.split(' '))
.reduce((total, current) => total + current.length,
0)
};
module.numWordsAll = numWordsAll;
var allAuthors = Article.allAuthors = () => {
return Article.all
.map(article => article.author)
.reduce((total, current) => {
console.log(total);
if (!total.includes(current))
total.push(current);
return total;
},[]);
};
module.allAuthors = allAuthors;
var numWordsByAuthor = Article.numWordsByAuthor = () => {
return Article.allAuthors().map(author =>{
return {
name: author,
numWords: Article.all.filter(article => article.author === author)
.map(article => article.body.split(' '))
.reduce((total, current) => total + current.length, 0)
}
})
};
module.numWordsByAuthor = numWordsByAuthor;
var truncateTable = Article.truncateTable = callback => {
$.ajax({
url: '/articles',
method: 'DELETE',
})
.then(console.log)
// REVIEW: Check out this clean syntax for just passing 'assumed' data into a named function! The reason we can do this has to do with the way Promise.prototype.then() works. It's a little outside the scope of 301 material, but feel free to research!
.then(callback);
};
module.truncateTable = truncateTable;
var insertRecord = Article.prototype.insertRecord = function(callback) {
// REVIEW: Why can't we use an arrow function here for .insertRecord()?
$.post('/articles', { author: this.author, author_url: this.author_url, body: this.body, category: this.category, published_on: this.published_on, title: this.title })
.then(console.log)
.then(callback);
};
module.insertRecord = insertRecord;
var deleteRecord = Article.prototype.deleteRecord = function(callback) {
$.ajax({
url: `/articles/${this.article_id}`,
method: 'DELETE'
})
.then(console.log)
.then(callback);
};
module.deleteRecord = deleteRecord;
var updateRecord = Article.prototype.updateRecord = function(callback) {
$.ajax({
url: `/articles/${this.article_id}`,
method: 'PUT',
data: {
author: this.author,
author_url: this.author_url,
body: this.body,
category: this.category,
published_on: this.published_on,
title: this.title,
author_id: this.author_id
}
})
.then(console.log)
.then(callback);
};
module.updateRecord = updateRecord;
})(app);
|
function addEventlistener(node,type,handle){
if(node){
if(node.addEventlistener){
node.addEventListener(type,handle);
}
else if(node.attachEvent){
node["e"+type+handle]=handle;
node[type+handle]=function(){
node["e"+type+handle](window.event);
};
node.attachEvent("on"+type,node[type+handle]);
}
else{
return false;
}
}
else{
return false;
}
}
function removeEventListener(node,type,handle){
if(node){
if(node.removeEventListener){
node.removeEventListener(type,handle);
}
else if(node.detachEvent){
node["e"+type+handle]=handle;
node[type+handle]=function(){
node["e"+type+handle](window.event);
};
node.detachEvent("on"+type,node[type+handle]);
}
else{
return false;
}
}
else{
return false;
}
}
|
/**
* Created by Administrator on 2018/1/14 0014.
*/
$(function () {
var page = 1;
var pageSize = 5;
function render() {
$.ajax({
type: "get",
url: "/product/queryProductDetailList",
data: {
page: page,
pageSize: pageSize
},
success: function (info) {
$('tbody').html(template("tmp", info));
//分页渲染
$("#paginator").bootstrapPaginator({
bootstrapMajorVersion: 3,
currentPage: page,
totalPages: Math.ceil(info.total / info.size),
size: "normal",//设置控件的大小
itemTexts: function (type, page, current) {
switch (type) {
case"first":
return "首页";
case"prev":
return "上一页";
case"next":
return "下一页";
case"last":
return "尾页";
case"page":
return page
}
},
tooltipTitles: function (type, page, current) {
switch (type) {
case"first":
return "首页";
case"prev":
return "上一页";
case"next":
return "下一页";
case"last":
return "尾页";
case"page":
return "第" + page + "页"
}
},
useBootstrapTooltip: true,
onPageClicked: function (a, b, c, p) {
page = p;
render();
}
})
}
})
};
render();
$(".btn_add").on("click", function () {
$("#addModal").modal("show");
$.ajax({
type: "get",
url: "/category/querySecondCategoryPaging",
data: {
page: 1,
pageSize: 100
},
success: function (info) {
$(".dropdown-menu").html(template("tpl", info));
}
})
});
var imgArr = [];//用于储存上传的图片结果
$(".dropdown-menu").on("click", "a", function () {
$(".dropdown-text").text($(this).text());
$("#brandId").val($(this).data("id"));
$form.data("bootstrapValidator").updateStatus("brandId","VALID");
});
$("#fileupload").fileupload({
dataType: 'json',
done: function (e, data) {
if (imgArr.length >= 3) {
return false;
}
$(".img_box").append('<img src="' + data.result.picAddr + '" width="100" height="100" alt="">');
imgArr.push(data.result);
console.log(imgArr);
if(imgArr.length === 3){
$form.data("bootstrapValidator").updateStatus("productLogo", "VALID");
}else {
$form.data("bootstrapValidator").updateStatus("productLogo", "INVALID");
}
}
});
//表单校验功能
var $form = $("form");
$form.bootstrapValidator({
excluded:[],
//配置校验时显示的图标
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
//校验规则
fields: {
brandId: {
validators: {
notEmpty: {
message: "二级分类不能为空"
}
}
},
proName: {
validators: {
notEmpty: {
message: "商品名称不能为空"
}
}
},
proDesc: {
validators: {
notEmpty: {
message: "商品描述不能为空"
}
}
},
num: {
validators: {
notEmpty: {
message: "商品库存不能为空"
},
regexp : {
regexp : /^[1-9]\d*$/,
message : "请输入合法的库名"
}
}
},
size: {
validators: {
notEmpty: {
message: "商品尺码不能为空"
},
//正则:只能有数字组成,并且第一位不能是0
regexp: {
regexp: /^\d{2}-\d{2}$/,
message: "请输入合法的尺码,比如(32-44)"
}
}
},
oldPrice: {
validators: {
notEmpty: {
message: "商品原价不能为空"
}
}
},
price: {
validators: {
notEmpty: {
message: "商品价格不能为空"
}
}
},
productLogo: {
validators: {
notEmpty: {
message: "请上传3张图片"
}
}
},
}
});
//给表单注册校验成功事件
$form.on("success.form.bv",function(e){
e.preventDefault();
var param = $form.serialize();
param += "&picName1=" + imgArr[0].picName + "&picAddr1=" + imgArr[0].picAddr;
param += "&picName2=" + imgArr[1].picName + "&picAddr2=" + imgArr[1].picAddr;
param += "&picName3=" + imgArr[2].picName + "&picAddr3=" + imgArr[2].picAddr;
$.ajax({
type:'post',
url:'/product/addProduct',
data:param,
success:function(info){
if(info.success){
$("#addModal").modal("hide");
page = 1;
render();
$form.data("bootstrapValidator").resetForm(true);
$(".dropdown-text").text("请选择二级分类");
$(".img_box img").remove();//图片自杀
imgArr = [];
}
}
})
});
})
|
const {
body,
validationResult,
param,
header,
} = require("express-validator");
const ErrorHelper = require("./error-helper");
const loginValidationRules = () => {
return [
// username must not be empty
body("username")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ max: 25 })
.withMessage("Too long, not more then 25 characters."),
// password must not be empty
body("password")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ min: 8, max: 25 })
.withMessage(
"Too short or too long, needs atleast 8 characters and not more then 25.",
),
];
};
const registerValidationRules = () => {
return [
// username must not be empty
body("username")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ max: 25 })
.withMessage("Too long, not more then 25 characters."),
// password must be atleast 8 characters
body("password")
.isLength({ min: 8, max: 25 })
.withMessage(
"Too short or too long, needs atleast 8 characters and not more then 25.",
)
.exists()
.withMessage("Has to exist."),
// firstname must not be empty
body("firstName")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ max: 25 })
.withMessage("Too long, not more then 25 characters."),
// lastname must not be empty
body("lastName")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ max: 25 })
.withMessage("Too long, not more then 25 characters."),
// lastname must not be empty
body("role").not().exists(),
];
};
const updateValidationRules = () => {
return [
// username must not be empty
body("username")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ max: 25 })
.withMessage("Too long, not more then 25 characters."),
// password must be atleast 8 characters
body("password")
.isLength({ min: 8, max: 25 })
.withMessage(
"Too short or too long, needs atleast 8 characters and not more then 25.",
)
.exists()
.withMessage("Has to exist."),
// firstname must not be empty
body("firstName")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ max: 25 })
.withMessage("Too long, not more then 25 characters."),
// lastname must not be empty
body("lastName")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ max: 25 })
.withMessage("Too long, not more then 25 characters."),
// lastname must not be empty
body("role").not().exists(),
param("id")
.isLength({ min: 24, max: 24 })
.withMessage("ID must be exactly 24 Characters long."),
];
};
const checkId = () => {
// id must be exactly 24 chars long
return param("id")
.isLength({ min: 24, max: 24 })
.withMessage("ID must be exactly 24 Characters long.");
};
const checkToken = () => {
return header("authorization")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ min: 8 })
.withMessage("Too short for a JWT.");
};
const checkRefreshToken = () => {
return body("refreshToken")
.notEmpty()
.withMessage("Not Allowed to be empty.")
.exists()
.withMessage("Has to exist.")
.isLength({ min: 8 })
.withMessage("Too short for a JWT.");
};
const validate = (req, res, next) => {
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}
const extractedErrors = [];
errors
.array()
.map((err) => extractedErrors.push({ [err.param]: err.msg }));
throw new ErrorHelper("Validation Error", 422, extractedErrors);
};
module.exports = {
loginValidationRules,
registerValidationRules,
updateValidationRules,
checkId,
checkToken,
checkRefreshToken,
validate,
};
|
var new_person_list = new Array();
var new_person_id_list = new Array();
for (var i = 0; i < person.length; ++i) {
if (new_person_id_list.indexOf(person[i].id) < 0) {
new_person_id_list.push(person[i].id);
new_person_list.push(person[i]);
}
}
person = new_person_list;
var map_id_list={};
for (i in bangumi){
map_id_list[bangumi[i].id] = i.toString();
}
var company_list = {};
var cv_list = {};
var music_list = {};
var storyboard_list = {};
var director_list = {};
var script_list = {};
for (var i = 0; i < bangumi.length; i++){
for (j in bangumi[i].cv_id) {
if (cv_list.hasOwnProperty(bangumi[i].cv_id[j])){
cv_list[bangumi[i].cv_id[j]].push(bangumi[i].id);
} else {
cv_list[bangumi[i].cv_id[j]] = new Array();
cv_list[bangumi[i].cv_id[j]].push(bangumi[i].id);
}
}
for (j in bangumi[i].company_id) {
if (company_list.hasOwnProperty(bangumi[i].company_id[j])){
company_list[bangumi[i].company_id[j]].push(bangumi[i].id);
} else {
company_list[bangumi[i].company_id[j]] = new Array();
company_list[bangumi[i].company_id[j]].push(bangumi[i].id);
}
}
for (j in bangumi[i].music_id) {
if (music_list.hasOwnProperty(bangumi[i].music_id[j])){
music_list[bangumi[i].music_id[j]].push(bangumi[i].id);
} else {
music_list[bangumi[i].music_id[j]] = new Array();
music_list[bangumi[i].music_id[j]].push(bangumi[i].id);
}
}
for (j in bangumi[i].storyboard_id) {
if (storyboard_list.hasOwnProperty(bangumi[i].storyboard_id[j])){
storyboard_list[bangumi[i].storyboard_id[j]].push(bangumi[i].id);
} else {
storyboard_list[bangumi[i].storyboard_id[j]] = new Array();
storyboard_list[bangumi[i].storyboard_id[j]].push(bangumi[i].id);
}
}
for (j in bangumi[i].director_id) {
if (director_list.hasOwnProperty(bangumi[i].director_id[j])){
director_list[bangumi[i].director_id[j]].push(bangumi[i].id);
} else {
director_list[bangumi[i].director_id[j]] = new Array();
director_list[bangumi[i].director_id[j]].push(bangumi[i].id);
}
}
for (j in bangumi[i].script_id) {
if (script_list.hasOwnProperty(bangumi[i].script_id[j] )){
script_list[bangumi[i].script_id[j]].push(bangumi[i].id);
} else {
script_list[bangumi[i].script_id[j]] = new Array();
script_list[bangumi[i].script_id[j]].push(bangumi[i].id);
}
}
}
|
var namespacede =
[
[ "telekom", "namespacede_1_1telekom.html", "namespacede_1_1telekom" ]
];
|
// match.js
//
// Description: Get a list of similar users
// in order to
//
const similarity = require('../core/similarity.js')
const match = (items, you, n = 3, distanceFormula) => {
// List of users to be compared
const users = Object.keys(items)
// Exclude yourself
const others = users.filter(user => user !== you)
return others.reduce((output, user) => {
// Compute similarity score
const score = similarity(items, you, user, distanceFormula)
output.push({ user, score })
return output
}, []).sort((a, b) => {
// Sort by descending order
return b.score - a.score
}).slice(0, n)
}
module.exports = match
|
import React from "react";
import ReactDOM from "react-dom";
import Navitab from "./navitab";
import "./index.css";
const App = () => {
return <Navitab />;
};
ReactDOM.render(<App />, document.getElementById("root"));
|
const most = require("most");
const fetch = require("node-fetch");
const fetchJson = async url => fetch(url).then(res => res.json());
const fetchCurrentTasks = async (managerUrl, serviceName) =>
fetchJson(
`${managerUrl}/tasks?filters={"service":["${serviceName}"],"desired-state":["ready","running"]}`
);
const fetchServices = async managerUrl => {
try {
const services = await fetchJson(
`${managerUrl}/services?filters={"label":["bigboat.service.type"]}`
);
await Promise.all(
services.map(async service => {
const tasks = await fetchCurrentTasks(managerUrl, service.Spec.Name);
service.CurrentTasks = tasks;
})
);
return services;
} catch (ex) {
console.error(ex);
return [];
}
};
module.exports = {
watch: (mqtt, { managerUrl, networkName, scanInterval }) => {
const calcInstanceState = require("./instances")(networkName, managerUrl);
most
.periodic(scanInterval.services, managerUrl)
.map(fetchServices)
.chain(most.fromPromise)
.observe(services => {
mqtt.publish("/bigboat/instances", calcInstanceState(services));
});
}
};
|
import React, { useRef, useEffect } from "react";
import { useSelector } from "react-redux";
const LocalVideoPreview = () => {
const localVideoRef = useRef();
const { localStream } = useSelector((state) => state.call);
useEffect(() => {
if (localStream && localVideoRef && localVideoRef.current) {
localVideoRef.current.srcObject = localStream;
localVideoRef.current.onloadedmetadata = () => {
localVideoRef.current.play();
};
}
}, [localStream]);
return (
<div>
<video ref={localVideoRef} autoPlay muted className="video" />
</div>
);
};
export default LocalVideoPreview;
|
import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import './study.css';
class Study extends Component{
render(){
return (
<div id = "study_container" >
<div id = "study_text" style={{marginTop:"8%"}}>
<a href="https://docs.google.com/spreadsheets/d/1I2HBAvKZWo2eeMYtZTJ8JkHEGu8gM2yUiRyArxE5GvY/edit#gid=0" target="_blank">
<Button id="Study_btn">Program Info</Button>
</a>
</div>
</div>
)
}
}
export default Study;
|
import React, { Component } from 'react'
import { fetchRecentPosts } from '../utils/fetchPosts'
import Timer from './Timer'
import moment from 'moment'
export default class RecentPost extends Component {
constructor(props) {
super(props)
this.state = {
recentPost: null
}
}
componentDidMount = async () => {
let post = await fetchRecentPosts()
this.setState({ recentPost: post })
}
renderTimer() {
if (this.state.recentPost) {
let { data: { created_utc } } = this.state.recentPost
return (<Timer time={created_utc} />)
} else {
return
}
}
renderPost = () => {
if (this.state.recentPost) {
console.log(this.state)
let { data: { title, selftext, score, author, created_utc, permalink } } = this.state.recentPost
if(selftext === ""){selftext = "(No Post Body)"}
return (
<div>
<div className="row">
<h2 className="col-xs-8 col-offset-2 recentTitle">Most recent post:</h2>
</div>
<div className="row recentPost">
<div className="col-md-12 text-center titleDiv">
<a href={`https://reddit.com/${permalink}`} className="link align-bottom">{title}</a></div>
<div className="posttext text-center col-md-12">
<p className="postText">{selftext}</p>
</div>
<div className="col-md-6">
<p>Total Score: <span className="score">{score}</span></p>
<p className="postAuthor">Author: {author}</p>
</div>
<div className="col-md-6 date align-bottom">
<p className="postDate align-bottom">{moment.unix(created_utc).format("MMM-Do-YYYY LT")}</p>
</div>
</div>
</div>
)
} else {
return (
<div>Loading. . . </div>
)
}
}
render() {
return (
<div className="row justify-content-center">
<div className="col-md-12 timer ">
{this.renderTimer()}
</div>
{this.renderPost()}
</div>
)
}
}
|
import React, {Component} from 'react';
import './Filter.css';
class Filter extends Component {
dropdownFilter = () => {
document.querySelector(".dropdown").style.display === "block"
? document.querySelector(".dropdown").style.display = "none"
: document.querySelector(".dropdown").style.display = "block";
}
render() {
return(
<div>
<button className="mr4 btn" href="#0" onClick = {this.dropdownFilter}>
<span className="date-mtd">WTD<i className="down"></i></span>
</button>
<div className="dropdown">
<div className="triangle-with-shadow"></div>
<ul className="pa0 ma0 hover">
<li className="active">WTD</li>
<li className="active1">MTD</li>
<li className="active2">YTD</li>
<li daterangepicker="" className="active3">CUSTOM</li>
</ul>
</div>
</div>
);
}
}
export default Filter;
|
/*!
* Based on Grayscale Bootstrap Theme (http://startbootstrap.com)
* 2015-16 Kajetan Krykwiński
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
$(window).scroll(function()
{
if ($("#con-head").offset().top > 50)
{
$("#con-head").addClass("head-solid")
}
else
{
$("#con-head").removeClass("head-solid")
}
});
//płynne przewijanie linków do czesci strony
$(function()
{
$("#con-head a, .smooth-scroll").click(function()
{
$('html, body').animate(
{
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
$('#menu-container').addClass("mobile-hidden");
return false;
});
});
$(function()
{
$("#menu-button").click(function()
{
$('#menu-container').toggleClass("mobile-hidden");
return false;
});
});
function replaceForm(form_text, form_id="#form_rejestracja")
{
$( form_id ).replaceWith( '<p style="text-align: center; font-weight: bold; color: #F00">' + form_text + '</p>' );
}
$(document).ready(function() {
var frm = $('#form_rejestracja');
frm.submit(function (ev)
{
$.ajax(
{
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
error: function(request, textStatus, errorThrown)
{
var err_registered = "Ten adres został juz zarejestrowany";
var err_unknown = "Wystąpił błąd. Prosimy spróbować ponownie, a jeśli się powtórzy - skontaktować się z nami.";
if(window.location.href.indexOf("en") > -1) //wersja ang strony
{
err_registered = "This adress has been submitted already!";
err_unknown = "An error occured! Please try again, and if the issue still persists - contact us.";
}
if(request.status == 400)
{
replaceForm(err_registered);
}
else
{
replaceForm(err_unknown);
}
},
success: function (data)
{
var err_success = "Dziękujemy za rejestrację!";
if(window.location.href.indexOf("en") > -1) //wersja ang strony
{
err_success = "Thank you for signing up!";
}
replaceForm(err_success);
}
});
ev.preventDefault();
});
});
//mapy googla
google.maps.event.addDomListener(window, "load", init);
function init()
{
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(51.108828, 17.056726),
disableDefaultUI: true,
scrollwheel: false,
draggable: false,
};
var mapElement = document.getElementById("map");
var map = new google.maps.Map(mapElement, mapOptions);
var image = "img/map-marker.png";
var myLatLng = new google.maps.LatLng(51.108828, 17.056726);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
})
};
//GA
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-73387544-1', 'auto');
ga('send', 'pageview');
|
(function () {
'use strict';
VenuuDashboard.VenueIndexController = Ember.ArrayController.extend();
VenuuDashboard.VenueEditController = Ember.ObjectController.extend({
init: function () {
this._super();
this.set('allVenueTypes', this.get('store').find('venueType'));
this.set('allVenueServices', this.get('store').find('venueService'));
this.set('allEventTypes', this.get('store').find('eventType'));
this.set('allVenueGroups', this.get('store').find('venueGroup'));
},
wizardSteps: ['index', 'pricing', 'types', 'services', 'done'],
isFirstPage: function () {
return this.get('currentStep') === 'index';
}.property('currentStep'),
// Could not find a way to give parameters from template...
isIndexCompleted: function () {
return this.get('completedSteps').contains('index');
}.property('currentStep'),
isPricingCompleted: function () {
return this.get('completedSteps').contains('pricing');
}.property('currentStep'),
isTypesCompleted: function () {
return this.get('completedSteps').contains('types');
}.property('currentStep'),
isServicesCompleted: function () {
return this.get('completedSteps').contains('services');
}.property('currentStep'),
save: function () {
var self = this,
venue = this.get('model'),
venueGroup = venue.get('venueGroup');
function saveVenue() {
return venue.save();
}
if (venueGroup && venueGroup.get('isDirty')) {
return venueGroup.save().then(saveVenue);
}
return saveVenue();
},
actions: {
save: function () {
var self = this;
function failure(response) {
console.error('save failure', response);
self.get('alert').error('Save failed!');
}
this.save().catch(failure);
},
stepBack: function () {
var self = this;
var currentIndex = self.wizardSteps.indexOf(self.get('currentStep'));
if (currentIndex === 0) {
return;
}
function transitionToPrev() {
var prev = self.wizardSteps[currentIndex - 1];
self.set('currentStep', prev);
self.transitionToRoute('venue.wizard.' + prev);
}
self.save().then(transitionToPrev);
},
step: function () {
var self = this,
alert = this.get('alert');
function transitionToNext() {
alert.clear();
var currentIndex = self.wizardSteps.indexOf(self.get('currentStep'));
var next = self.wizardSteps[currentIndex + 1];
if (next === 'done') {
return self.transitionToRoute('venue');
}
self.get('completedSteps').push(self.get('currentStep'));
self.set('currentStep', next);
self.transitionToRoute('venue.wizard.' + next);
}
function failure(response) {
console.error('save failure', response);
alert.error('This is an error alert!');
}
self.save().then(transitionToNext).catch(failure);
},
edit: function () {
var self = this,
alert = this.get('alert');
function transitionToIndex() {
alert.clear();
self.transitionToRoute('venue');
}
function failure(response) {
console.error('save failure', response);
alert.error('This is an error alert!');
}
self.save().then(transitionToIndex).catch(failure);
},
destroy: function () {
var self = this;
function transitionToVenueIndex() {
self.transitionToRoute('venue');
}
this.get('model').destroyRecord()
.then(transitionToVenueIndex);
},
createVenueGroup: function () {
this.get('model').set('venueGroup',
this.get('store').createRecord('venueGroup'));
},
cancelNewVenueGroup: function () {
this.get('model').get('venueGroup').rollback();
}
}
});
})();
|
// var의 호이스팅
var yangpa5 = "Marry me";
function print_value() {
console.log(yangpa5);
var yangpa5 = "나 때문에";
console.log(yangpa5);
function nested() {
console.log(yangpa5);
yangpa5 = "사랑...그게뭔데";
console.log(yangpa5);
var yangpa5 = "한 사람";
console.log(yangpa5);
}
nested();
}
print_value();
|
define([
'backbone',
'models/user'
], function (Backbone, User) {
'use strict';
app.collections.Users = Backbone.Collection.extend({
initialize: function (options) {
Backbone.Collection.prototype.initialize.apply(this, arguments);
},
url: '/users',
model: User,
comparator: 'username',
getPictures: function () {
return this.map(function (user) {
return user.getPictureUrl();
});
},
getUsernameById: function (userId) {
return this.find(function (user) {
return user.id === userId;
}).username;
},
makeFirst: function (firstModel) {
var first = this.find(function (model, index) {
return model.id === firstModel.id;
}, this),
position = this.indexOf(first);
this.models.splice(position, 1);
this.models.unshift(first);
},
getPresentsCount: function () {
return _.reduce(this.models, function (sum, user) {
return sum + user.get('presents');
}, 0);
},
getNameById: function (id) {
var user = this.get(id),
username = user ? user.get('username') : app.language.SANTA;
return username;
}
});
return app.collections.Users;
});
|
var crypto = require('crypto');
/**
* Converts a time in milliseconds to a base32 timestamp, accurate to one about second.
* @param time a number or string that can be parsed with parseInt
* @return a base32 timestamp in the <code>ks5ijf</code>
* @static
*/
toTimestamp = function(time) {
if(!time){
time = new Date().getTime();
}
if (typeof time == 'string') {
time = parseInt(time, 10);
}
time = Math.floor(time / 1024);
return new Number(time).toString(36);
};
/**
* Converts a timestamp String to a long value in milliseconds.
* @param a base32 timestamp in the form <code>ks5ijf</code>
* @static
*/
fromTimestamp = function(timestamp) {
return parseInt(timestamp, 36) * 1024;
};
CookieModel = function() {
this.authenticated = false;
this.data = new Array();
};
CookieModel.prototype.iterator = function() {
var data = this.data;
var idx = 0;
return new function() {
this.hasNext = function() {
return data.length > idx;
};
this.next = function() {
return data[idx++];
};
};
};
/**
* Returns a cookie safe string of pipe separate urlencoded data items and the hmac tagged on the end
* made of the data and the key .
*/
secureCookieData = function(key, cookieModel) {
var sb = '';
var timestamp = toTimestamp();
sb += timestamp;
sb += "|";
var md = crypto.createHash('sha1');
var byteArray = new Buffer(key, 'utf-8');
md.update(byteArray);
byteArray = new Buffer(timestamp, 'utf-8');
md.update(byteArray);
var iter = cookieModel.iterator();
while (iter.hasNext()) {
var dataItem = iter.next();
byteArray = new Buffer(dataItem, 'utf-8');
md.update(byteArray);
dataItem = uriEncode(dataItem);
sb += dataItem + "|";
}
var base64 = md.digest('base64');
sb += uriEncode(base64.substring(0, base64.length -1 )); // crop the trailing '='
return sb;
};
/**
* @return CookieModel or throws an exception
*/
validateCookieString = function(key, cookieString, timeout, timeCheck) {
var cookieModel = new CookieModel();
var cookieData = cookieString.split("|");
// check the token is still valid
// N.B. the timestamp is checked against the digest to ensure it is not forged
var timestamp = cookieData[0];
var ts = fromTimestamp(timestamp);
if (ts + timeout < new Date().getTime()) {
if(timeCheck){
console.log("Users key expired " + new Date(ts));
throw new Error("AuthFailedCondition (timeout)");
}
}
try {
var receivedDigest = uriDecode(cookieData[cookieData.length - 1]) + '=';
var md = crypto.createHash('sha1');
var byteArray = new Buffer(key, 'utf-8');
md.update(byteArray);
byteArray = new Buffer(timestamp, 'utf-8');
md.update(byteArray);
for (var i = 1; i < cookieData.length - 1 ; i++) {
byteArray = new Buffer(uriDecode(cookieData[i]), 'utf-8');
md.update(byteArray);
cookieModel.data.push(uriDecode(cookieData[i]));
}
var realDigest = md.digest('base64');
if (realDigest == receivedDigest) {
cookieModel.authenticated = true;
return cookieModel;
}
throw new Error("AuthFailedCondition (mac)");
}
catch (ex) {
throw ex;
}
};
uriEncode = function(data) {
return encodeURIComponent(data).replace('/\\+/g', "%20");
};
uriDecode = function(data) {
return decodeURIComponent(data);
};
exports.toTimestamp = toTimestamp;
exports.fromTimestamp = fromTimestamp;
exports.secureCookieData = secureCookieData;
exports.validateCookieString = validateCookieString;
exports.CookieModel = CookieModel;
|
var searchData=
[
['bintodec',['binToDec',['../classsrc_1_1_utilities.html#a70fdc26590d16eab8a93236b4edd0186',1,'src::Utilities']]]
];
|
import React, { useContext } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import { Redirect, Route } from "react-router-dom";
import { UserDetailsContext } from "../utilities/context/context";
import SideBar from "../components/layout/sidebar/Sidebar";
import { Wrapper, Main } from "../styles/layoutStyle";
function ProtectedRoute({ component: Component, ...restOfProps }) {
const { userDetails } = useContext(UserDetailsContext);
const storeData = JSON.parse(window.localStorage.getItem("user"));
console.log(storeData);
const isAuthenticated = storeData && storeData.login;
// const isAuthenticated = userDetails && userDetails.login;
return (
<Route
{...restOfProps}
render={(props) =>
isAuthenticated ? (
<React.Fragment>
<div className="header1" />
<Wrapper>
<SideBar />
<Main>
<Component {...props} />{" "}
</Main>
</Wrapper>
</React.Fragment>
) : (
<Redirect to="/" />
)
}
/>
);
}
export default ProtectedRoute;
// <Route
// {...restOfProps}
// render={(props) =>
// isAuthenticated ? (
// <section className="container">
// <SideBar className="grid-sidebar" />
// <div className="content">
// <Component {...props} />{" "}
// </div>
// <div className="header" />
// </section>
// ) : (
// <Redirect to="/" />
// )
// }
// />
{
/* <Route
{...restOfProps}
render={(props) =>
isAuthenticated ? (
<section className="container1">
<div className="header1" />
<div className="left-sidebar">
<SideBar />
</div>
<div className="main1">
<Component {...props} />{" "}
</div>
</section>
) : (
<Redirect to="/" />
)
}
/> */
}
|
const { Plotly, hljs } = window;
export default class DomHelpers {
constructor() {
this.plot = (labels, ...data) => {
const traces = [];
data.forEach(([x, y], i) => {
traces.push({
x,
y,
type: 'scatter',
line: { shape: 'spline' },
name: labels[i],
});
});
const layout = {
xaxis: {
autorange: true,
tickmode: 'linear',
title: {
text: 'Es/N0(dB)',
font: {
size: 20,
},
},
},
yaxis: {
type: 'log',
autorange: true,
showexponent: 'all',
exponentformat: 'power',
tickmode: 'linear',
title: {
text: 'SER',
font: {
size: 20,
},
},
},
};
const config = {
responsive: true,
toImageButtonOptions: {
format: 'svg',
scale: 1,
},
};
Plotly.newPlot('plot', traces, layout, config);
};
this.indexOf = (arr1, arr2) => {
for (let i = 0; i < arr1.length; i += 1) {
if (arr1[i].toString() === arr2.toString()) return i;
}
return -1;
};
this.clone = (node) => {
const newNode = node.cloneNode(true);
node.parentNode.replaceChild(newNode, node);
return newNode;
};
this.saveData = (SB_N0_DB, SER, fileName) => {
const data = new Array(SB_N0_DB.length).fill(0)
.map((_, i) => [SB_N0_DB[i], SER[i]])
// eslint-disable-next-line no-return-assign, no-param-reassign
.reduce((acc, entry) => acc += `${entry.join(' ')}\n`, '');
const blob = new Blob([data], {
type: 'text/plain',
});
const blobURL = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = `${fileName}.dat`;
link.href = blobURL;
link.click();
};
this.fetchJS = (...urls) => {
const codeElement = document.getElementById('code');
urls.forEach(async (url) => {
const h3 = document.createElement('h3');
const code = document.createElement('code');
const pre = document.createElement('pre');
const js = await (await fetch(url)).text();
h3.textContent = url.split('/').slice(-1);
code.append(js);
pre.append(code);
codeElement.append(h3, pre);
hljs.highlightAll();
});
};
}
}
|
import React from 'react';
import { connect } from 'react-redux';
import {Panel, Row, Col} from 'react-bootstrap';
import VoteForm from '../containers/forms/VoteForm';
import {getquestion, updatevote, totalVotes} from '../actions/questions.js';
import {getMessages, sendMessage} from '../actions/chat.js';
import { isLoading, isError } from '../util/loadingObject';
import { Alert } from 'react-bootstrap';
import { Chart } from 'react-google-charts';
import Message from '../components/ChatBox/Message.js';
import Compose from '../components/ChatBox/Compose.js';
import ChatView from 'react-chatview';
import { subscribeToVotesForQuestion, unSubscribeToVotesForQuestion, subscribeToChatForQuestion, unSubscribeToChatForQuestion } from '../realtime/socket';
class QuestionPage extends React.Component {
static contextTypes = {
history: React.PropTypes.object.isRequired
}
static propTypes = {
question: React.PropTypes.object,
totalvotes : React.PropTypes.object,
messages: React.PropTypes.object,
}
fetchData(params) {
this.props.dispatch(totalVotes(params.qid));
this.props.dispatch(getquestion(params.qid));
this.props.dispatch(getMessages({qid: params.qid}));
}
componentWillMount() {
this.fetchData(this.props.params);
}
componentDidMount() {
unSubscribeToVotesForQuestion(this.props.params.qid);
subscribeToVotesForQuestion(this.props.params.qid);
unSubscribeToChatForQuestion(this.props.params.qid);
subscribeToChatForQuestion(this.props.params.qid);
}
componentWillUnmount() {
unSubscribeToVotesForQuestion(this.props.params.qid);
unSubscribeToChatForQuestion(this.props.params.qid);
}
componentDidUpdate(prevProps, prevState) {
if (this.props.params !== prevProps.params)
this.fetchData(this.props.params);
}
updateVote(vote) {
let prevVote = (this.props.survey.vote);
let nextvote = Number(vote.vote);
let qid = this.props.survey.question.id;
this.props.dispatch(updatevote({nextVote: nextvote, prevVote: prevVote, qid: qid}));
}
sendMessage(msg) {
let qid = this.props.survey.question.id;
// Send the msg to the db
console.log('Sending messag: ' + msg);
this.props.dispatch(sendMessage({qid, msg}));
}
loadMoreHistory() {
return null;
// Load more chat history
}
render() {
debugger;
const question = this.props.survey;
const messages = this.props.survey.result;
if (isLoading(question)) return (<p>Loading...</p>);
if (isError(question)) return (<Alert bsStyle='danger'>{question.error.response.statusText}</Alert>);
console.log('Messages: ' + JSON.stringify(messages));
const alternatives = question.question.choices.map((c) => ({
value: String(c.id),
description: c.description
}))
let temp = {vote: String(question.vote[0])}
// Graph set up
let fullData = [ ["Category", "Value"] ];
// Create graph data array, desciptions not found in totalvotes
// have value of 0
for (let i = 0; i < question.question.choices.length; i++) {
let descr = question.question.choices[i].description;
let value = 0;
for (let x = 0; x < question.voteresult.length; x++) {
if (question.voteresult[x].description === descr) {
value = question.voteresult[x].count;
break;
}
}
fullData.push([descr, value]);
}
var chatComponent;
if (isLoading(question)) {
chatComponent = <p> Loading... </p>;
} else {
chatComponent =
<ChatView className="messageList"
flipped={true}
scrollLoadThreshold={15}
onInfiniteLoad={this.loadMoreHistory}>
{messages.map((m) => {
return (
<Message
username={m.username}
text={m.message}
key={m.id}
time={m.time} />
);
})}
</ChatView>
}
return (
<div>
<Row>
<Col xsOffset={0} xs={10} smOffset={0} sm={6}>
<Panel header={<h1>{question.question.question}</h1>}>
<VoteForm
onSubmit={v => this.updateVote(v)}
alternatives={alternatives}
description={question.question.description}
loadingStatus={question}//may work or not
initialValues={temp} />
</Panel>
</Col>
<Col xsOffset={0} xs={10} smOffset={0} sm={6}>
<Chart
chartType="ColumnChart"
data={fullData}
options={{
animation: {
duration: 200
},
vAxis: {
maxValue: 3
},
legend: 'none'
}}
graph_id="BarChart"
width="100%"
height="300px"
legend_toggle
/>
</Col>
<Col xsOffset={0} xs={10} smOffset={1} sm={10}>
<Panel header={<h1>Discuss the question here!</h1>}>
<div className="message-display" style={{height: "225px"}}>
{chatComponent}
<Compose sendMessage={this.sendMessage.bind(this)} />
</div>
</Panel>
</Col>
</Row>
</div>
);
}
}
function mapStateToProps(state) {
debugger;
if('username' in state.survey) {
if(Object.keys(state.survey).length < 14) {
state.survey.loadingStatus = "loading"
} else {
state.survey.loadingStatus = "ok"
}
} else {
if(Object.keys(state.survey).length < 6) {
state.survey.loadingStatus = "loading"
} else {
state.survey.loadingStatus = "ok"
}
}
return {
survey: state.survey,
}
}
export default connect(mapStateToProps)(QuestionPage);
|
'use strict';
describe('locationSearch', function() {
var queryString = '?pokemon1=charmander&pokeballs=3&earthBadge=false&water-badge=true';
beforeEach(module('qsServices'));
it('should default to $location.search() if in html5 mode', function() {
var search = jasmine.createSpy('$location.search()');
module(function($locationProvider, $provide) {
$provide.decorator('$location', function($delegate) {
$delegate.search = search;
return $delegate;
});
$locationProvider.html5Mode(true);
});
inject(function(locationSearch) {
locationSearch();
expect(search).toHaveBeenCalled();
});
});
it('should use $window.location.search when available', function() {
var search = jasmine.createSpy('$window.location.search');
module(function($provide) {
var $window = { location: { href: 'http://reddit.com/r/pokemon' }};
Object.defineProperty($window.location, 'search', {
enumerable: true,
get: function() {
search();
return queryString;
}
});
$provide.value('$window', $window);
});
inject(function(locationSearch) {
locationSearch();
expect(search).toHaveBeenCalled();
});
});
it('should use custom location search if $window.location.search is not available', function() {
module(function($provide) {
var $window = {
location: {
href: 'http://reddit.com/r/pokemon' + queryString
}
};
$provide.value('$window', $window);
});
inject(function(locationSearch) {
var search = locationSearch();
expect(search).toBe(queryString);
});
});
it('should return empty string if NaN passed', function() {
var search;
module(function($provide) {
var $window = { location: { search: NaN } };
$provide.value('$window', $window);
});
inject(function(locationSearch) {
search = locationSearch();
expect(search).toBe('');
});
});
it('should return empty string if null is passed', function() {
var search;
module(function($provide) {
var $window = { location: { search: null } };
$provide.value('$window', $window);
});
inject(function(locationSearch) {
search = locationSearch();
expect(search).toBe('');
});
});
it('should return empty string if undefined is passed', function() {
var search;
module(function($provide) {
var $window = { location: { search: undefined } };
$provide.value('$window', $window);
});
inject(function(locationSearch) {
search = locationSearch();
expect(search).toBe('');
});
});
});
|
import React, { useState, useEffect } from "react";
import axios from "axios";
import Input from "../common/Input";
import Button from "../common/Button";
import Modal from "../common/Modal";
import useNotification from "../../hooks/Notification";
const StationDetail = ({ selected: card, setSelected, fetchCards }) => {
const [newValue, setNewValue] = useState(card.Value);
const [newOwner, setNewOwner] = useState(card.BelongsTo);
const notify = useNotification();
const source = axios.CancelToken.source();
const updateCardValue = async () => {
try {
await axios.post(
"/api/admin/update-card-value",
{ breezecardNum: card.BreezecardNum, newValue },
{ cancelToken: source.token }
);
console.log("hey");
await fetchCards();
setSelected(null);
notify("INFO", "Success!");
} catch (error) {
notify("ERROR", "Failed to update card value");
}
};
const updateCardOwner = async () => {
try {
await axios.post(
"/api/admin/update-card-owner",
{
breezecardNum: card.BreezecardNum,
newOwner,
},
{ cancelToken: source.token }
);
await fetchCards();
setSelected(null);
notify("INFO", "Success!");
} catch (error) {
notify("ERROR", "Failed to update card owner");
}
};
useEffect(() => () => source.cancel(), []);
useEffect(() => {
setNewValue(card.Value);
setNewOwner(card.BelongsTo);
}, [card]);
return (
<Modal mount="#modal" closeFn={() => setSelected(null)}>
<Input type="number" value={newValue} onChange={setNewValue} />
<Button isLink onClick={updateCardValue}>
Set Card Value
</Button>
<Input type="text" value={newOwner} onChange={setNewOwner} />
<Button isLink onClick={updateCardOwner} disabled={!newOwner}>
Transfer to User
</Button>
</Modal>
);
};
export default StationDetail;
|
import React from 'react';
import styles from './launchHeader.module.scss';
const LaunchHeader = () => {
return(
<div className={styles.root}>
<span>Badge</span>
<span>Rocket Name</span>
<span>Rocket Type</span>
<span>Launch Date</span>
<span>Details</span>
<span>ID</span>
<span>Article</span>
</div>
)
}
export default LaunchHeader
|
import { connect } from 'react-redux';
import { message } from 'antd';
import ConfigPanel from '../uis/ConfigPanel';
import globalStore from '../../service/globalStore';
import { deepCloneObj } from '../../service/service';
const mapStateToProps = (state) => {
const configComponentId = globalStore.get('configComponentId');
const configComponent = state.pageSchema.componentSchema.find(item => item.id === configComponentId) || {};
const componentTypeInfoList = globalStore.get('componentTypeInfoList');
const configComponentTypeId = configComponent.componentTypeId;
const configComponentTypeInfo = componentTypeInfoList.find(item => item.id === configComponentTypeId);
const { componentData } = configComponent;
return {
isComponentConfigPanelDisplayed: state.isComponentConfigPanelDisplayed,
configComponentTypeInfo,
configComponentId,
componentData: deepCloneObj(componentData),
};
};
const mapDispatchToProps = dispatch => ({
closeComponentConfigPanel: () => {
dispatch({
type: 'closeComponentConfigPanel',
});
},
editComponent: (id, componentData) => {
dispatch({
type: 'editComponent',
id,
componentData,
});
message.success('修改元素属性成功');
},
});
export default connect(mapStateToProps, mapDispatchToProps)(ConfigPanel);
|
'use strict'
import React, { Component } from 'react';
import { Platform, BackHandler, ToastAndroid } from 'react-native';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import SplashScreen from 'react-native-smart-splash-screen';
import {
StackNavigator, DrawerNavigator
} from 'react-navigation';
import AddMap from './src/layout/AgregarMapa';
import HomeScreen from './src/layout/Home';
import SideBar from './src/components/SideBar';
import ViewMap from './src/layout/ViewMap';
import EditMap from './src/layout/EditMap';
import Intro from './src/layout/Tour/Intro';
import AddMapTour from './src/layout/Tour/AgregarMapaTour';
import EditMapTour from './src/layout/Tour/EditMapTour';
import ViewMapTour from './src/layout/Tour/ViewMapTour';
import allReducers from './src/redux/reducers/index';
const store = createStore(allReducers, applyMiddleware(thunk));
//Funcion Main
const MainStack = StackNavigator(
{
Intro: { screen: Intro,
header: null,
navigationOptions: ({navigation}) => ({
header: false
})
},
AddMapTour: { screen: AddMapTour,
header: null,
navigationOptions: ({navigation}) => ({
header: false
})
},
EditMapTour :{ screen: EditMapTour,
header: null,
navigationOptions: ({navigation}) => ({
header: false
})
},
ViewMapTour: { screen: ViewMapTour },
Home: { screen: HomeScreen },
ViewMap: { screen: ViewMap },
AddMap: { screen: AddMap },
EditMap: { screen: EditMap }
},
{
initialRouteName: 'Home',
}
);
//Funcion que devuelve un componente React
//Funcion root
const App = DrawerNavigator(
{
Main: {
screen: MainStack,
}
},
{
contentComponent: props => <SideBar {...props} />
}
);
export default class GeoZ extends Component {
constructor(props) {
super(props);
this.backButtonListener = null;
this.currentRouteName = 'Home';
}
changeRouteNavigation(route){
this.currentRouteName = route;
}
componentDidMount() {
if (Platform.OS === 'android') {
this.backButtonListener = BackHandler.addEventListener('hardwareBackPress', () => {
if (this.currentRouteName !== 'Home') {
if(this.currentRouteName == 'Tour')this.currentRouteName = 'Intro';else this.currentRouteName = 'Home';
return false;
}
if (this.lastBackButtonPress + 2000 >= new Date().getTime()) {
BackHandler.exitApp();
store.dispatch({type:'EMPTY_GEOZONA'});
return true;
}
ToastAndroid.show('¡Presiona nuevamente para salir!', ToastAndroid.SHORT);
this.lastBackButtonPress = new Date().getTime();
return true;
});
}
}
componentWillUnmount() {
if (Platform.OS === 'android') this.backButtonListener.remove();
}
render() {
return (
<Provider store={store}>
<App screenProps={{ changeRouteNavigation:this.changeRouteNavigation.bind(this)}} />
</Provider>
);
}
}
// skip this line if using Create React Native App
//AppRegistry.registerComponent('GeoZ', () => GeoZ);
|
//提交回复
function post() {
let questionId = $("#question_id").val();
let content = $("#form-control").val();
comment2target(questionId, 1, content);
}
function comment2target(targetId, type, content) {
if (!content) {
alert("不能回复空内容~~")
return;
}
$.ajax({
url: "/comment",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"parentId": targetId,
"content": content,
"type": type
}),
success: function (result) {
if (result.code == 100) {
window.location.reload();
} else {
if (result.code == 102) {
const isAccepted = confirm(result.msg);
if (isAccepted) {
window.open("https://github.com/login/oauth/authorize?client_id=Iv1.dbf53619d7309d98&redirect_uri=http://localhost:8887/callback&scope=user&state=1")
window.localStorage.setItem("closable", true);
}
} else {
alert(result.msg);
}
}
}
});
}
function comment(e) {
const id = e.getAttribute("data-id");
const content = $("#form-control" + id).val();
comment2target(id, 2, content);
}
//展开二级评论
function collapseComment(e) {
const id = e.getAttribute("data-id");
const comments = $("#comment-" + id);
var $test = $("#twoComment");
//开关 单击添加,再单击移除
comments.toggleClass("in");
//获取二级评论的展开状态
const hasClass = comments.hasClass("in");
if (hasClass) {
$.getJSON("/comment/" + id, function (data) {
var html = "";
var commentDTOS = data.extend.commentDTOS;
if (commentDTOS == null || commentDTOS == "") {
return;
}
for (var i = 0; i < commentDTOS.length; i++) {
var commentDTO = commentDTOS[i];
var gmtCreate = commentDTO.gmtCreate;
html += "<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12 comments'>" +
"<div class='media'>" +
"<div class=\"media-left\">" +
"<img class=\"media-object img-circle\"\n" +
" src=" +
commentDTO.user.avatarUrl +
">" +
"</div>" +
"<div class='media-body'>" +
"<h5 class='media-heading'>" +
"<span>"
+ commentDTO.user.name +
"</span>" +
"</h5>" +
"<div>"
+ commentDTO.content +
"</div>" +
"<div class=\"menu\">" +
"<span class=\"pull-right\">" +
//moment(gmtCreate).format('YYYY-MM-DD HH:mm:ss')+
new Date(gmtCreate) +
"</span>" +
"</div>" +
"</div>" +
"</div>" +
"</div>";
}
var commentId = $("#comment-" + id);
commentId.html(html);
});
} else {
e.classList.remove("active");
}
}
function showSelectTag() {
$("#select-tag").show();
}
function selectTag(e) {
const value = e.getAttribute("data-tag");
var previous = $("#tag").val();//previous:以前的
if (previous.length != 0) {//previous.indexOf(value) == -1
$("#tag").val(previous + "," + value);
} else {
$("#tag").val(value);
}
}
|
//The Function for checking the Marks with Grade System...
let getMyGrade = function(currentMark, totalMark){
let myPercentage = (currentMark/totalMark) * 100
let myGrade = ''
if(myPercentage >= 90){
myGrade = 'A+'
}else if(myPercentage >= 80){
myGrade = 'A'
}else if(myPercentage >= 70){
myGrade = 'B'
}else if(myPercentage >= 60){
myGrade = 'C'
}else{
myGrade = 'F'
}
return `Your Grade is ${myGrade} and Percentage is ${myPercentage}%`
}
//Calling Function..
console.log(getMyGrade(120, 200))
//Let me to create another new function for this one...
let getMyAnotherFunction = function(takefromUser){
if(takefromUser %2== 0){
return `${takefromUser} is Odd Number!`
}else{
return `${takefromUser} is Even Number!`
}
}
//So lets calling this function..
var showUs = getMyAnotherFunction(12)
console.log(showUs)
|
var module = angular.module('ucms.app.core');
module.controller('dashboardCtrl', function ($scope, $xhttp) {
$scope.init = function () {
}
})
|
function WeatherForecastController($scope, ForecastWeatherService, CommonWeatherService) {
var ctrl = this;
function getforecastWeather() {
const cityName = CommonWeatherService.getWeatherCityName();
return ForecastWeatherService.getWeatherForecast(cityName).then(forecastResponse => {
ctrl.forecastDetails = forecastResponse;
}).catch(err => {
ctrl.forecastDetails = err;
})
}
getforecastWeather();
}
WeatherForecastController.$inject = ['$scope', 'ForecastWeatherService', 'CommonWeatherService'];
angular.module('weather').controller('WeatherForecastController', WeatherForecastController);
|
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/index/search/_search_select" ], {
"258a": function(e, t, n) {
var a = n("e08a");
n.n(a).a;
},
ab2a: function(e, t, n) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var a = [ "全部", "即将取证", "最新开盘", "最新摇号", "在售楼盘", "热门楼盘", "热门公寓" ], c = {
data: function() {
return {
types: a,
show_list: !1
};
},
methods: {
toggleList: function() {
this.show_list = !this.show_list;
},
changeType: function(e) {
var t = e.currentTarget.dataset.type;
this.$emit("changeType", t), this.toggleList();
}
},
props: {
selected: {
type: String,
default: "全部"
}
}
};
t.default = c;
},
c07a: function(e, t, n) {
n.d(t, "b", function() {
return a;
}), n.d(t, "c", function() {
return c;
}), n.d(t, "a", function() {});
var a = function() {
var e = this;
e.$createElement;
e._self._c;
}, c = [];
},
e08a: function(e, t, n) {},
e337: function(e, t, n) {
n.r(t);
var a = n("ab2a"), c = n.n(a);
for (var o in a) [ "default" ].indexOf(o) < 0 && function(e) {
n.d(t, e, function() {
return a[e];
});
}(o);
t.default = c.a;
},
f1da: function(e, t, n) {
n.r(t);
var a = n("c07a"), c = n("e337");
for (var o in c) [ "default" ].indexOf(o) < 0 && function(e) {
n.d(t, e, function() {
return c[e];
});
}(o);
n("258a");
var r = n("f0c5"), s = Object(r.a)(c.default, a.b, a.c, !1, null, "45cf1671", null, !1, a.a, void 0);
t.default = s.exports;
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/index/search/_search_select-create-component", {
"pages/index/search/_search_select-create-component": function(e, t, n) {
n("543d").createComponent(n("f1da"));
}
}, [ [ "pages/index/search/_search_select-create-component" ] ] ]);
|
/*
* Toady
* Copyright 2015 Tom Shawver
*/
var log = require('../../lib/log');
var util = require('util');
const CHAN_PREFIXES = '#&';
const PERMISSIONS_MOD = 'users';
/**
* Command Runner handles all execution of commands, including formatting
* and permissions enforcement. It exposes no commands of its own.
*
* Available config options:
* - fantasyChar (default "!"): The character which should precede
* commands said in a channel
* @param {Object} config A Toady config object
* @param {Object} client An IRC client object
* @param {Object} modMan The Toady ModManager object
* @returns {Object} A Toady mod
*/
module.exports = function(config, client, modMan) {
/**
* Applies a regex pattern to the string of arguments following a
* command, and returns the matches in the callback. If the pattern
* does not match, a user-appropriate error message will be sent in the
* error response.
* @param {boolean} inChan true if the command was said in a channel;
* false otherwise.
* @param {Object} cmd The command object that was triggered
* @param {string} cmdText The line of text following the command (and
* optional target)
* @returns {Array<string>} Resolves with an array of matches, with
* the first element being the full string that matched.
* @throws {Error} If the command doesn't match the pattern. This Error will
* have an additional 'userError' property set to boolean true to denote
* that the error message can be reported to the user.
*/
function applyPattern(inChan, cmd, cmdText) {
var args = [cmdText];
if (cmd.pattern) {
args = cmdText.match(cmd.pattern);
if (!args) {
var err = new Error("Sorry, that's the wrong format for '" +
cmd.id + "'. Try '" + (inChan ? config.fantasyChar : '')
+ 'help ' + cmd.id + "' for more info.");
err.userError = true;
throw err;
}
}
return args;
}
/**
* Asserts that a user has the appropriate permissions to execute a
* given command, and calls back with an error if not.
* @param {Object} cmd The command object to be tested against
* @param {string} nick The nickname of the user whose permissions are to
* be checked
* @param {string} target The command target, if applicable. Set to null
* if this command does not require a target.
* @returns {Promise} Resolves on complete.
*/
function assertPermission(cmd, nick, target) {
if (!cmd.minPermission) {
return Promise.resolve();
}
var pMod;
return Promise.resolve().then(function() {
pMod = modMan.getMod(PERMISSIONS_MOD);
if (!pMod) {
throw new Error('Permissions module not found');
}
var channel = cmd.targetChannel ? target : null;
return pMod.hasPermission(cmd.minPermission, nick, channel);
}).then(function(allowed) {
if (!allowed) {
var errMsg = 'Sorry, you must be %s or higher%s to execute "%s".';
throw new Error(util.format(errMsg,
pMod.getPermName(cmd.minPermission),
target ? ' in ' + target : '',
cmd.id
));
}
});
}
/**
* Removes the target from the command text, if the command calls for it,
* and returns both the target and the updated command args in the
* callback.
* @param {boolean} inChan true if the command was triggered in a channel;
* false otherwise
* @param {Object} cmd The command object being executed
* @param {string} cmdText The text following the command
* @param {string} context The channel name if the command was said in a
* channel, or the bot name otherwise
* @returns {{target: string, args: string}} an object containing two
* properties: The target (target) and the remaining command arguments
* (args).
* @throws {Error} if the given command requires a target, and none was
* given. This Error will have an additional 'userError' property set to
* true, denoting that its message can be shared with the user.
*/
function splitTarget(inChan, cmd, cmdText, context) {
var target = null;
var args = cmdText;
if (cmd.targetChannel || cmd.targetNick) {
var targetRegex = cmd.targetNick ? '(\\S+)' :
'([' + CHAN_PREFIXES + ']\\S+)?';
var regex = new RegExp('^' + targetRegex + '\\s?(.*)$');
var targetArgs = cmdText.match(regex);
target = targetArgs[1];
args = targetArgs[2];
if (cmd.targetChannel && !target) {
if (inChan) {
target = context;
} else {
var err = new Error("I need a target channel for the '" +
cmd.id + "' command. Try \"help " + cmd.id +
'" for more info.');
err.userError = true;
throw err;
}
}
}
return {
target: target,
args: args
};
}
/**
* Listens for a command to be spoken in a channel, or directly in a
* private message. This function is an event listener and should be
* added to the 'message' event of the IRC client library.
* @param {string} nick The nick originating the message
* @param {string} to The channel or nickname to which the message was sent
* @param {string} text The text of the message
*/
function handleMessage(nick, to, text) {
var split = text.match(/^\s*(\S+)?\s*(.*)$/);
if (!split[1]) {
split[1] = ' ';
}
var fantasy = split[1][0] === config.fantasyChar;
var cmdId = (fantasy ? split[1].substr(1) : split[1]).toLowerCase();
var inChan = CHAN_PREFIXES.indexOf(to[0]) !== -1;
var cmdText = split[2];
var cmds = modMan.getCommands();
var cmdSplit;
var args;
if (((fantasy && inChan) || !inChan) && cmds[cmdId]) {
var cmd = cmds[cmdId];
Promise.resolve().then(function() {
cmdSplit = splitTarget(inChan, cmd, cmdText, to);
args = applyPattern(inChan, cmd, cmdSplit.args);
return assertPermission(cmd, nick, cmdSplit.target);
}).then(function() {
var cmdArgs = {
nick: nick,
to: to,
target: cmdSplit.target,
args: args,
cmd: cmd
};
modMan.emit('command', cmdArgs);
modMan.emit('command:' + cmdId, cmdArgs);
cmd.handler(nick, to, cmdSplit.target, args, inChan);
}).catch(function(err) {
if (err.userError) {
client.notice(inChan ? to : nick, err.message);
} else {
log.error('Failed running command', {command: cmdId}, err);
}
});
}
}
client.on('message', handleMessage);
return {
name: 'Command Runner',
desc: 'Handles the execution of user-triggered commands',
author: 'Tom Shawver',
blockUnload: true,
unload: function() {
client.removeListener('message', handleMessage);
},
getFantasyChar: function() {
return config.fantasyChar;
}
};
};
module.exports.configDefaults = {
fantasyChar: '!'
};
|
/**
* Simple Queue data structure implemented with a doubley linked list
*/
function Queue() {
function Node(val, next, prev) {
this.val = val;
this.next = next;
this.prev = prev;
return this;
};
let head = null;
let tail = null;
let length = 0;
return {
enqueue: function(val) {
var newHead = new Node(val, head, null);
if (head) {
newHead.next = head;
head.prev = newHead;
}
head = newHead;
if (!tail) { tail = head; }
length++;
},
dequeue: function() {
if (!tail) { return null; }
const val = tail.val;
if (tail.prev) {
tail = tail.prev;
} else {
tail = null;
head = null;
}
length--;
return val;
},
peek: function() {
if (!tail) { return null; }
return tail.val;
},
length: function() {
return length;
}
};
}
module.exports = Queue;
|
angular.module('userAdd', [
'ngRoute'
]);
|
/**
* Created by py on 01/09/2018.
*/
/* ===== SHA256 with Crypto-js ===============================
| Learn more: Crypto-js: https://github.com/brix/crypto-js |
| =========================================================*/
const SHA256 = require('crypto-js/sha256');
const Block = require('../model/Block');
class Blockchain{
constructor(db){
this.storage = db;
db.isEmpty().then(result => {
if(result) {
console.log("Blockchain DB is empty. Creating new Blockchain with 1 genesis block...");
this.addBlock(new Block("First block in the chain - Genesis block"));
} else {
console.log("Blockchain DB has blocks. Reading Blockchain from DB...");
}
}).catch(err => {
throw err;
});
}
addBlock(newBlock){
let _this = this;
return new Promise((resolve, reject) => {
newBlock.time = new Date().getTime().toString().slice(0,-3);
_this.storage.getChainLength().then(chainLength => {
newBlock.height = chainLength;
if(chainLength === 0) {
return new Promise((resolve, reject) => {
console.log("chain length = 0, return null instead of block");
resolve(null);
});
} else {
console.log(`chain length is ${chainLength}, return previous block`);
return _this.storage.getBlock(chainLength - 1);
}
}).then(previousBlock => {
if(previousBlock === null) {
newBlock.previousBlockHash = "";
} else {
newBlock.previousBlockHash = previousBlock.hash;
}
newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();
return _this.storage.saveBlock(newBlock);
}).then(saveOperationResult => {
console.log("block saved");
resolve(saveOperationResult);
}).catch(err => {
reject(new Error(`${err.message}`));
});
});
}
getBlockHeight() {
let _this = this;
return new Promise((resolve, reject) => {
_this.storage.getChainLength().then(currentLength => {
resolve(currentLength);
}).catch(err => {
reject(new Error(`${err.message}`));
});
});
}
getBlock(blockHeight){
return new Promise((resolve, reject) => {
this.storage.getBlock(blockHeight).then(block => {
resolve(block);
}).catch(err => {
reject(new Error(`${err.message}`));
});
});
}
validateBlock(blockHeight){
let _this = this;
return new Promise(function(resolve, reject){
_this.storage.getBlock(blockHeight).then(block => {
let blockHash = block.hash;
block.hash = '';
let validBlockHash = SHA256(JSON.stringify(block)).toString();
if (blockHash === validBlockHash) {
resolve(true);
} else {
reject(new Error('Block #'+blockHeight+' invalid hash:\n'+blockHash+'<>'+validBlockHash));
}
});
});
}
validateChain() {
let errors = [];
let _this = this;
return new Promise((resolve, reject) => {
_this.storage.getChainLength()
.then(currentLength => {
let allBlockValidations = [];
for(let i = 0; i < currentLength; i++) {
allBlockValidations.push(
_this.validateBlock(i)
.catch(err => {
errors.push(err);
})
);
}
return Promise.all(allBlockValidations);
})
.then(value => {
if(errors.length > 0) {
reject(errors);
} else {
resolve(true);
}
})
.catch(err => {
reject(err.message);
});
});
}
}
module.exports = Blockchain;
|
'use strict';
// som json data passed from taskRepository
var Task = function (data) {
this.name = data.name;
this.time = data.time;
};
/*
* Syntax to add method in prototype object
*
* ClassName.prototype.methodName = function(arguments) {
*
* }
*/
Task.prototype.toString = function ( ) {
return this.name + " " + this.time;
}
Task.prototype.timeToComplete = function ( ) {
this.time += this.time;
}
Task.prototype.getTime = function ( ) {
return this.time;
}
// Export reference constructor
module.exports = Task;
|
function play()
{
var query = document.getElementById("q");
q = query.value;
document.getElementById("audio").innerHTML="<br /><b><span style='color:blue;font-size:20px;'>Getting your song. :)</span><br /><img src='loading.gif' height='200px' width='300px' alt='Loading...' /> <br /> "
axios.get("https://itpreprocess.herokuapp.com/music.php?q="+q).then((resp)=>{
document.getElementById("audio").innerHTML="<br /><br />Here it is. <b style='color:blue;'>Enjoy!</b><br /><br />" + resp.data;
});
}
|
function calc(){
var width = window.innerWidth;
var html = document.documentElement;
if(width<=640){
html.style.fontSize = width/7 + "px";
}else{
html.style.fontSize = 100 + "px";
}
}
window.addEventListener('resize',function(){calc()});
calc();
|
import { Component } from "react";
class Header extends Component {
render() {
return (
<div>
<h1>Calculator App</h1>
<p>
This is the calculator App to perform simple Mathematical Calculation
</p>
</div>
);
}
}
export default Header;
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
View,
Image,
StyleSheet,
YellowBox,
Dimensions,
AsyncStorage,
Platform, Keyboard,
} from 'react-native';
import { Icon } from 'react-native-elements';
import LinearGradient from 'react-native-linear-gradient';
import { Actions } from 'react-native-router-flux';
import { toggleNavigator, toggleFooter } from '../../store/actions/navigator';
import { logout } from '../../store/actions/auth';
import { getExpireDate } from '../../services/utility';
import { getProfile } from '../../store/actions/profileSetting';
import ProfileView from '../profile';
import image from '../../../assets/images/mobi-logo.png';
const initialState = {
isTablet: false,
isLandScape: false,
expireAt: null,
vw: 0,
vh: 0,
isVisible: true
};
/**
*
* @MainLogo Component
*
*/
class MainLogo extends Component {
constructor(props) {
super(props);
YellowBox.ignoreWarnings([
'Warning: componentWillMount is deprecated',
'Warning: componentWillUpdate is deprecated',
'Warning: componentWillReceiveProps is deprecated'
]);
this.state = initialState;
}
detectLayout = () => {
const { height, width } = Dimensions.get('screen');
let isLandScape = width > height ? true : false;
let isTablet = (isLandScape && width / height > 1.6) ||
(!isLandScape && height / width > 1.6) ? false : true;
let vw = width / 100;
let vh = height / 100;
let expireAt = getExpireDate();
this.setState({
isTablet: isTablet,
isLandScape: isLandScape,
vw: vw,
vh: vh,
expireAt: new Date(expireAt),
});
}
toggleProfile = stage => {
this.props.toggleNavigator(stage);
}
logout = () => {
this.toggleProfile(0);
this.props.toggleFooter(0);
clearInterval(this.timer);
this.props.logout();
}
expire = () => {
AsyncStorage.getItem('expireAt').then(res => {
let expireAt = new Date(res);
let now = new Date();
if (now >= this.state.expireAt) {
this.setState (initialState, () => {
this.toggleProfile(0);
this.props.toggleFooter(0);
clearInterval(this.timer);
this.props.logout();
});
}
});
}
componentDidMount() {
this.props.getProfile();
this.timer = setInterval(this.expire, 8000);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardHidden.bind(this));
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardShown.bind(this));
this.detectLayout();
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
clearInterval(this.timer);
}
_keyboardHidden = () => {
this.setState({
isVisible: true
})
};
_keyboardShown = () => {
this.setState({
isVisible: false
})
};
render() {
const { stage } = this.props;
const { isVisible, isTablet, isLandScape, vw, vh } = this.state;
const headerLogo = {
height: isTablet ? (isLandScape ? ( isVisible ? 7 * vh : 0 ) : 3.5 * vh) : (isLandScape ? ( isVisible ? 9 * vh : 0 ) : 5 * vh),
alignSelf: 'center',
marginTop: 0.2 * vh,
};
const iconContainer = {
//position: 'absolute',
marginRight: 1 * vw,
/*top: (Platform.OS === 'android' ?
(isLandScape ? 0.3 * vh : 0.7 * vh) : (isLandScape ? 0.2 * vh : 0.5 * vh)),*/
zIndex: 10,
borderRadius: 50,
overflow: 'hidden',
};
return(
<View style={[
{ flex: stage != 0 ? 1 : 0 },
stage != 0 && { flexBasis: '100%' }
]} onLayout={this.detectLayout}>
<View style={[styles.logoContainer, { height: isTablet ? (isLandScape ? (isVisible ? 11 * vh : 0) : 6.5 * vh) : (isLandScape ? (isVisible ? 13 * vh : 0) : 8 * vh)}]}>
<LinearGradient
colors={['#31c5d2', '#3b62ab']}
start={{ x: 0.0, y: 1.0 }}
end={{ x: 1.0, y: 1.0 }}
style={{
width: '100%',
height: isTablet ? (isLandScape ? (isVisible ? 11 * vh : 0) : 6.5 * vh) : (isLandScape ? (isVisible ? 13 * vh : 0) : 8 * vh),
flex: 0,
}}/>
<View style={{position: 'absolute', justifyContent: 'space-between', alignItems: 'center', flexDirection: 'row', width: isLandScape ? 94 * vw : 100 * vw}}>
{ stage != 0 ? (
<Icon
reverse
name='chevron-left'
type='fontawsome'
size={isLandScape ? (isVisible ? 3 * vh : 0) : 2 * vh}
color="transparent"
iconStyle={{ fontSize: isLandScape ? 5 * vh : 3 * vh, color: '#fff' }}
containerStyle={[
styles.backIcon,
{marginLeft: 1 * vw, /*top: (Platform.OS === 'android' ?
(isLandScape ? 0.3 * vh : 0.7 * vh) : (isLandScape ? 0.2 * vh : 0.5 * vh))*/}
]}
onPress={() => this.toggleProfile(stage - 1)} />
) : (
<Icon
reverse
name='person'
size={isLandScape ? (isVisible ? 3 * vh : 0) : 2 * vh}
color="#efefef"
iconStyle={{ fontSize: isLandScape ? 5 * vh : 3 * vh, color: '#414141' }}
containerStyle={[
styles.userIcon,
{marginLeft: 1 * vw, /*top: (Platform.OS === 'android' ?
(isLandScape ? 0.3 * vh : 0.7 * vh) : (isLandScape ? 0.2 * vh : 0.5 * vh)),*/ borderRadius: 50}
]}
onPress={() => this.toggleProfile(1)}
/>
)}
<View style={{position: 'absolute', width: '100%', justifyContent: 'center', alignItems: 'center'}}>
<Image
resizeMode={'contain'}
source={image}
style={headerLogo}
/>
</View>
<Icon
reverse
name='power-settings-new'
size={isLandScape ? (isVisible ? 3 * vh : 0) : 2 * vh}
color="#cf333c"
iconStyle={{ fontSize: isLandScape ? 5 * vh : 3 * vh, color: '#fff' }}
containerStyle={iconContainer}
onPress={() => this.logout()}
/>
</View>
</View>
{ stage != 0 && (<ProfileView vw={vw} vh={vh} isTablet={isTablet} isLandScape={isLandScape} />) }
</View>
);
}
}
/* Main Header Style */
const styles = StyleSheet.create({
logoContainer: {
flex: 0,
position: 'relative',
alignItems: 'center',
justifyContent: 'center',
},
userIcon: {
//position: 'absolute',
zIndex: 10,
overflow: 'hidden',
},
backIcon: {
//position: 'absolute',
zIndex: 10,
borderWidth: 0,
overflow: 'hidden',
},
});
const mapStateToProps = (state, ownProps) => {
return {
stage: state.navigator.stage,
profile: state.setting.profile,
};
};
export default connect(
mapStateToProps,
{
toggleNavigator,
toggleFooter,
logout,
getProfile,
}
)(MainLogo);
|
/* ========================================================================
* App.plugins.statistics v1.0
* 统计中心-公共组件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
// 生成公共查询条件参数
app.plugins.statistics.getOptions = function () {
var options = {};
var startTime = $("#startTime").val();
if (startTime != "") { options.startTime = startTime; }
var endTime = $("#endTime").val();
if (endTime != "") { options.endTime = endTime; }
var ids = App.services.menu.getsids($("#treeview"));
if (ids == "") {
App.alert("请选择要统计的车辆");
return;
}
options.sIds = ids;
return options;
};
// 注册导出按钮事件
app.plugins.statistics.registExport = function () {
$("#doExport").on("click", function () {
App.table.exportCSV($("#table"));
});//$("#doExport").on("click", function () {
}
// 注册重置按钮事件
app.plugins.statistics.registReset = function () {
$("#doReset").on("click", function () {
$("#startTime").val(App.util.monthFirst());
$("#endTime").val(App.util.monthLast());
});//$("#doReset").on("click", function () {
}
})(App);
/* ========================================================================
* App.plugins.statistics.location v1.0
* 统计中心-定位统计插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
app.plugins.statistics.location = function (parent) {
var TABLE_COLUMNS = ["序号", "目标ID", "目标名称", "SIM卡号", "定位次数"];
$(".modal-title").html("定位统计");
App.services.car.fill($("#treeview"));
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
App.plugins.statistics.registReset();
//查询按钮
$("#doSearch").on("click", function () {
var options = App.plugins.statistics.getOptions();
if (options) {
app.table.load({
"api": bus_cfgs.reportStatistics.locationapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addText(tr, totalindex);// 序号
App.row.addText(tr, item.targetId);// 目标ID
App.row.addBase64Text(tr, item.targetName);// 目标名称
App.row.addText(tr, item.sim);// SIM卡号
App.row.addText(tr, item.posNum);// 定位次数
}
});
}
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
/* ========================================================================
* App.plugins.statistics.mileage v1.0
* 统计中心-里程统计插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
app.plugins.statistics.mileage = function (parent) {
var TABLE_COLUMNS = ["序号", "分组名称", "车辆名称", "SIM卡号", "总里程数"];
$(".modal-title").html("里程统计");
App.services.car.fill($("#treeview"));
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
App.plugins.statistics.registReset();
//查询按钮
$("#doSearch").on("click", function () {
var options = App.plugins.statistics.getOptions();
if (options) {
app.table.load({
"api": bus_cfgs.reportStatistics.mileageStatapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addText(tr, totalindex);// 序号
App.row.addBase64Text(tr, item.group_name);// 分组名称
App.row.addBase64Text(tr, item.target_name);// 车辆名称
App.row.addText(tr, item.sim);// SIM卡号
App.row.addText(tr, item.total_mile);// 总里程数
}
});
}
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
/* ========================================================================
* App.plugins.statistics.fuelquery v1.0
* 统计中心-油耗统计插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
app.plugins.statistics.fuelquery = function (parent) {
var TABLE_COLUMNS = ["分组名称", "目标名称", "SIM卡号", "理想油耗(升)", "实际油耗(升)"];
$(".modal-title").html("油耗统计");
App.services.car.fill($("#treeview"));
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
App.plugins.statistics.registReset();
//查询按钮
$("#doSearch").on("click", function () {
var options = App.plugins.statistics.getOptions();
if (options) {
app.table.load({
"api": bus_cfgs.reportStatistics.oilCostStatapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addBase64Text(tr, item.groupName);//分组名称
App.row.addBase64Text(tr, item.targetName);// 目标名称
App.row.addText(tr, item.sim);//SIM卡号
App.row.addText(tr, item.oilMass);//理想油耗(升)
App.row.addText(tr, item.oilCost);//实际油耗(升)
}
});
}
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
/* ========================================================================
* App.plugins.statistics.trajectoryquery v1.0
* 统计中心-轨迹查询插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
var TABLE_COLUMNS = ["流水号", "终端名称", "手机号码", "车机时间", "速度", "方向", "海拔", "里程", "位置描述", "消息类型", "车机状态"];
app.plugins.statistics.trajectoryquery = function (parent) {
$(".modal-title").html("轨迹查询");
App.services.car.fill($("#treeview"));
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
App.plugins.statistics.registReset();
//查询按钮
$("#doSearch").on("click", function () {
var options = App.plugins.statistics.getOptions();
if (!options) {
return;
}
app.table.load({
"api": bus_cfgs.reportStatistics.trackStatapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addText(tr, totalindex);// 序号
App.row.addBase64Text(tr, item.tName);// 终端名称
App.row.addText(tr, item.sim);// 手机号码
App.row.addText(tr, item.bTime);// 车机时间
App.row.addText(tr, item.speed);// 速度
App.row.addText(tr, item.dir);// 方向
App.row.addText(tr, item.alt);// 海拔
App.row.addText(tr, item.mileage);// 里程
App.row.addText(tr, "");// 位置描述
App.row.addBase64Text(tr, item.rState);// 消息类型
App.row.addBase64Text(tr, item.state);// 车机状态
}
});
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
/* ========================================================================
* App.plugins.statistics.park v1.0
* 统计中心-停车统计插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
var TABLE_COLUMNS = ["序号", "车辆名称", "SIM卡号", "开始停留时间", "结束停留时间", "停留", "位置描述", "经度", "纬度"];
//条件查询根据ID找到对应的数据
app.plugins.statistics.park = function (parent) {
$(".modal-title").html("停车统计");
App.services.car.fill($("#treeview"));
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
App.plugins.statistics.registReset();
//查询按钮
$("#doSearch").on("click", function () {
var options = App.plugins.statistics.getOptions();
if (!options) {
return;
} else {
options.times = 1800;
}
app.table.load({
"api": bus_cfgs.reportStatistics.parkStatapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addText(tr, totalindex)// 序号
App.row.addBase64Text(tr, item.targetName);// 车辆名称
App.row.addText(tr, item.sim)// SIM卡号
App.row.addText(tr, item.startTime)// 开始停留时间
if (item.endTime) {
App.row.addText(tr, item.endTime);// 结束停留时间
} else {
App.row.addText(tr, item.endtime);// 结束停留时间
}
App.row.addText(tr, item.parkTime);// 停留
App.row.addText(tr, "");// 位置描述
App.row.addText(tr, item.lon);// 经度
App.row.addText(tr, item.lat);// 纬度
}
});
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
/* ========================================================================
* App.plugins.statistics.offline v1.0
* 统计中心-离线统计插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
var TABLE_COLUMNS = ["序号", "分组名称","目标名称", "SIM卡号", "离线天数"];
//条件查询根据ID找到对应的数据
app.plugins.statistics.offline = function (parent) {
$(".modal-title").html("离线统计");
App.services.car.fill($("#treeview"));
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
App.plugins.statistics.registReset();
//查询按钮
$("#doSearch").on("click", function () {
var options = App.plugins.statistics.getOptions();
if (!options) {
return;
} else {
options.times = 1800;
}
app.table.load({
"api": bus_cfgs.reportStatistics.parkStatapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addText(tr, totalindex)// 序号
App.row.addBase64Text(tr, item.targetName);// 车辆名称
App.row.addText(tr, item.sim)// SIM卡号
App.row.addText(tr, item.startTime)// 开始停留时间
if (item.endTime) {
App.row.addText(tr, item.endTime);// 结束停留时间
} else {
App.row.addText(tr, item.endtime);// 结束停留时间
}
App.row.addText(tr, item.parkTime);// 停留
App.row.addText(tr, "");// 位置描述
App.row.addText(tr, item.lon);// 经度
App.row.addText(tr, item.lat);// 纬度
}
});
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
/* ========================================================================
* App.plugins.statistics.terminalquery v1.0
* 统计中心-终端查询插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
var TABLE_COLUMNS = ["序号", "分组名称", "目标名称", "SIM卡号", "是否可用", "是否绑定", "计划名称"];
//条件查询根据ID找到对应的数据
var getOptions = function () {
var options = {};
// var gname = $("#gname").val();
// if (gname != "") {
// options.groupId = gname;
// }else{
// options.groupId = "all";
// }
options.groupId = "all"
var isbind = $("#isbind").val();
if (isbind != "") {
options.isPlan = isbind;
} else {
options.isPlan = "all";
}
options.planName = $("#taskname").val();
options.sim = $("#sim").val();
options.targetName = $("#tname").val();
var ids = App.services.menu.getsids($("#treeview"));
if (ids == "") {
App.alert("请选择要查询的车辆");
return;
}
options.sIds = ids;
return options;
};
App.plugins.statistics.terminalquery = function (parent) {
App.services.car.fill($("#treeview"));
$.each(bus_cfgs.dict.SF, function (index, item) {
$("#isbind").append($("<option/>").val(index).text((item.text) ? item.text : item));
});
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
$("#doReset").on("click", function () {
$("#isbind").val("");
$("#gname").val("");
$("#tname").val("");
$("#sim").val("");
$("#taskname").val("");
});//$("#doReset").on("click", function () {
//查询按钮
$("#doSearch").on("click", function () {
var options = getOptions();
if (!options) {
return;
}
app.table.load({
"api": bus_cfgs.reportStatistics.terminalStatapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addText(tr, totalindex);// 序号
App.row.addBase64Text(tr, item.groupName);// 分组名称
App.row.addBase64Text(tr, item.targetName);// 目标名称
App.row.addText(tr, item.sim);// SIM卡号
App.row.addDictText(tr, "SF", item.useable);// 是否可用
App.row.addBase64Text(tr, item.isPlan);// 是否绑定
App.row.addBase64Text(tr, item.planName);// 计划名称
}
});
});//$("#doSearch").on("click", function () {
};
})(App);
/* ========================================================================
* App.plugins.statistics.logquery v1.0
* 统计中心-日志查询插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
var getOptions = function () {
var options = {};
var content = $("#content").val();
if (content == "") {
options.content = "";
} else {
options.content = App.base64.encode(content);
}
var startTime = $("#startTime").val();
if (startTime != "") {
options.startTime = startTime;
}
var endTime = $("#endTime").val();
if (endTime != "") {
options.endTime = endTime;
}
return options;
};
app.plugins.statistics.logquery = function (parent) {
var TABLE_COLUMNS = ["序号", "操作员名称", "操作时间", "操作类型", "操作内容", "操作结果", "登录IP"];
App.services.car.fill($("#treeview"));
app.table.render($("#table"), TABLE_COLUMNS);
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
$("#doReset").on("click", function () {
$("#startTime").val(App.util.monthFirst());
$("#endTime").val(App.util.monthLast());
$("#content").val("");
});
//查询按钮
$("#doSearch").on("click", function () {
var options = getOptions();
if (!options) {
return;
}
app.table.load({
"api": bus_cfgs.reportStatistics.logStatapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
App.row.addText(tr, totalindex);// 序号
App.row.addBase64Text(tr, item.name);// 操作员名称
App.row.addText(tr, item.date);// 操作时间
App.row.addBase64Text(tr, item.op_type);// 操作类型
App.row.addBase64Text(tr, item.content);// 操作内容
App.row.addBase64Text(tr, item.result);// 操作结果
App.row.addText(tr, item.loginIp);// 登录ip
}
});
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
/* ========================================================================
* App.plugins.statistics.alarm v1.0
* 统计中心-告警统计插件
* ========================================================================
* Copyright 2015-2025 WangXin nvlbs,Inc.
* ======================================================================== */
(function (app) {
//条件查询根据ID找到对应的数据
var getOptions = function () {
var options = {};
var registstate = $("#registstate").val();
if (registstate != "") {
options.rType = registstate;
} else {
options.rType = "all";
}
var startTime = $("#startTime").val();
if (startTime != "") {
options.startTime = startTime;
}
var endTime = $("#endTime").val();
if (endTime != "") {
options.endTime = endTime;
}
// options.times = "5";
var ids = App.services.menu.getsids($("#treeview"));
if (ids == "") {
App.alert("请选择要统计的车辆");
return;
}
options.sIds = ids;
return options;
};
app.plugins.statistics.alarm = function (parent) {
var TABLE_COLUMNS = ["分组名称", "目标名称", "SIM卡号", "告警次数"];
App.services.car.fill($("#treeview"));
App.table.render($("#table"), TABLE_COLUMNS);
$.each(bus_cfgs.dict.GJLX, function (index, item) {
$("#registstate").append($("<option/>").val(index).text((item.text) ? item.text : item));
});
//导出按钮
App.plugins.statistics.registExport();
//重置按钮
$("#doReset").on("click", function () {
$("#startTime").val(App.util.monthFirst());
$("#endTime").val(App.util.monthLast());
$("#registstate").val("");
});
//查询按钮
$("#doSearch").on("click", function () {
var options = getOptions();
if (!options) {
return;
}
app.table.load({
"api": bus_cfgs.reportStatistics.requestlistapi
, "args": options
, "target": $("#table")
, "parsefn": function (tr, index, totalindex, item) {
$(bus_cfgs.templates.cell).text(App.base64.decode(item.gName)).appendTo(tr);//分组名称
$(bus_cfgs.templates.cell).text(App.base64.decode(item.tName)).appendTo(tr);// 目标名称
$(bus_cfgs.templates.cell).text(item.sim).appendTo(tr);//SIM卡号
$(bus_cfgs.templates.cell).text(item.count).appendTo(tr);//告警次数
}
});
});//$("#doSearch").on("click", function () {
$("#doReset").click();
};
})(App);
|
tmtModule
.config( function ($routeProvider) {
var template = function(templateName){
return 'views/08a/' + templateName
};
$routeProvider.
// Default to "signon" view
when('/', {
controller: 'signonController',
templateUrl: template('tmt_signon_view.html')
}).
// Define "list" url
when('/app/users/:userId/views/:viewId/pages', {
controller: 'listController',
templateUrl: template('tmt_list_view.html')
}).
when('/app/users/:userId/views/:viewId/pages/:pageNumber', {
controller: 'listController',
templateUrl: template('tmt_list_view.html')
}).
// Define "detail" url
when('/app/users/:userId/views/:viewId/details/:dataId', {
controller: 'detailController',
templateUrl: template('tmt_detail_view.html')
}).
// Define edit "detail" url
when('/app/users/:userId/views/:viewId/details/:dataId/edit', {
controller: 'editDetailController',
templateUrl: template('tmt_detail_view.html')
}).
// Define "View User Profile" url
when('/app/users/:userId', {
controller: 'viewUserController',
templateUrl: template('tmt_user_view.html')
}).
// Define "Edit User Profile" url
when('/app/users/:userId/edit', {
controller: 'editUserController',
templateUrl: template('tmt_user_view.html')
}).
// Default if none of the above
otherwise({
redirectTo: '/'
});
})
;
|
/**
* Смещает изображение в указанном направлении,
* при этом выходящие за пределы изображения фрагменты
* рисует на противоположной стороне
*/
import {createCanvas} from '../lib/utils';
function tile(x, y, width, height) {
return {x, y, width, height};
}
export function offset(ctx, xOffset, yOffset, state) {
var {x, y, width, height} = state;
if (!state.buffer) {
state.buffer = createCanvas(width, height);
}
xOffset = ((1 + xOffset) * width % width)|0;
yOffset = ((1 + yOffset) * height % height)|0;
width |= 0;
height |= 0;
state.buffer.width = width;
state.buffer.height = height;
state.buffer.getContext('2d').drawImage(ctx.canvas, x, y, width, height, 0, 0, width, height);
var draw = (tile, x, y) => {
if (tile.width && tile.height) {
ctx.drawImage(state.buffer,
tile.x, tile.y, tile.width, tile.height,
x, y, tile.width, tile.height);
}
};
var t = tile(Math.min(xOffset, 0), Math.min(yOffset, 0), (width - xOffset) % width, (height - yOffset) % height);
// переставляем тайлы в том порядке, в котором они должны быть отрисованы
var tiles = [
tile(t.width, t.height, width - t.width, height - t.height),
tile(t.x, t.height, t.width, height - t.height),
tile(t.width, t.y, width - t.width, t.height),
t
];
ctx.translate(x, y);
ctx.clearRect(0, 0, width, height);
draw(tiles[0], 0, 0);
draw(tiles[1], tiles[0].width, 0);
draw(tiles[2], 0, tiles[0].height);
draw(tiles[3], tiles[0].width, tiles[0].height);
}
export function offsetX(canvas, state) {
offset(canvas, state.value, 0, state);
}
export function offsetY(canvas, state) {
offset(canvas, 0, state.value, state);
}
export function offsetXY(canvas, state) {
offset(canvas, state.value, state.value, state);
}
offset.config = offsetX.config = offsetY.config = offsetXY.config = {
amount: 10,
height: '30%',
ttl: 500,
delay: 700,
baseValue: {min: 0.1, max: 0.3}
};
|
d3.selection.prototype.appendJSX = d3.jsx_append
let Bars = d3.Bars;
const data = [
{name: "Locke", value: 4},
{name: "Reyes", value: 8},
{name: "Ford", value: 15},
{name: "Jarrah", value: 16},
{name: "Shephard", value: 23},
{name: "Kwon", value: 42}
];
const width = 500;
const height = 400;
const x = d3.scaleLinear()
.range([0, height])
.domain([0, d3.max(data, (d) => d.value)]);
// const x = d3.scale.ordional()
// .rangeRoundBands([0, width], 0.2);
let svg = d3.select("body")
.appendJSX(<svg className="chart" width={width} height={height}></svg>)
.selectAll("g")
.data(data)
.enter()
.appendJSX( <Bars data={data} dimensions={[width, height]}
height={40} horizontal={false}/>);
|
/*
Fetches json data from the file persons.json
*/
let familyMembers = [{
name: "Peter Madsen",
age: 52,
hairColor: "blonde",
relation: "dad",
img: "img/dad.jpg"
}, {
name: "Ane Madsen",
age: 51,
hairColor: "brown",
relation: "mom",
img: "img/ane.jpg"
}, {
name: "Rasmus Madsen",
age: 29,
hairColor: "blonde",
relation: "brother",
img: "img/rasmus.jpg"
}, {
name: "Mie Madsen",
age: 25,
hairColor: "brown",
relation: "sister",
img: "img/mie.jpg"
}, {
name: "Mads Madsen",
age: 18,
hairColor: "dark",
relation: "brother",
img: "img/mads.jpg"
}, {
name: "Jens Madsen",
age: 14,
hairColor: "blonde",
relation: "brother",
img: "img/jenspeter.jpg"
}];
console.log(familyMembers);
/*
Appends json data to the DOM
*/
function appendPersons(persons) {
let htmlTemplate = "";
// TODO: implement loop appending the persons
document.querySelector("#persons").innerHTML = htmlTemplate;
}
appendPersons(familyMembers);
/*
Search functionality: find objects by given searchValue
*/
function search(searchValue) {
searchValue = searchValue.toLowerCase();
console.log(searchValue);
// TODO: implement search functionality
}
/*
Adds a new object to the array familyMembers
*/
function add() {
console.log("Add button clicked");
let inputName = document.getElementById('inputName');
// TODO: implement add functionality
}
|
angular.module('Hotel.Login')
.controller('LoginCtrl',
function($scope, $rootScope, $uibModal, $location, store) {
//we can use store to keep login information
var login = this;
if (!($rootScope.globals && $rootScope.globals.currentUser)) {
var modalInstance = $uibModal.open({
templateUrl: "client/src/hotel/login/tmpl/login.html",
backdrop: "static",
keyboard: false,
animation: true,
controller: "LoginModalCtrl",
controllerAs: "loginModal",
resolve: {
a: function() {
return "aaaa";
}
}
});
} else {
$location.path("/roomboard");
}
// modalInstance.result.then(function)
/* $scope.login = function() {
console.log("test");
console.log(this.username);
}*/
});
angular.module('Hotel.Login')
.controller('LoginModalCtrl', function($scope, $rootScope, $location, $uibModalInstance, store, a) {
$scope.a = a;
$scope.login = function() {
if ($scope.username == "aaa" && $scope.password == "aaa") {
$rootScope.globals = {
currentUser: {
username: $scope.username,
}
};
store.set('globals', $rootScope.globals);
$uibModalInstance.close();
$location.path('/roomboard');
} else {
$scope.error = "用户名密码错误";
}
}
});
|
module.exports = {
message: {
timeline: "Chronologie",
explore: "Explorer",
maps: "Cartes",
users: "Utilisateurs",
register: "Inscription",
login: "Connexion",
logout: "Déconnexion",
registerUserText: "Enregistrer un nouvel utilisateur",
profile: "Profil",
save: "Enregistrer",
showOnMap: "Ouvrir sur la carte",
showOnMapTooltip: "Ajouter ceci sur la carte",
reply: "Répondre",
replyTooltip: "Il a répondu avec un post",
viewReplies: "Voir les réponses",
hideReplies: "Masquer les réponses",
newPost: "Nouveau post",
accountLogin: "Connexion au compte",
name: "Nom",
password: "Mot de passe",
cancel: "Annuler",
privateCollections: "Collections privées",
publicCollections: "Collections publiques",
search: "Chercher",
loadMore: "Charger plus",
openMap: "Ouvrir la carte",
chooseCollections: "Choisir les collections à suivre",
checkCollectionsOut: "Voir les collections publiques et les suivre",
inCollection: "En collection",
existingAccount: "Compte existant",
newAccount: "Nouveau compte",
alreadyInUseMessage:
"Ce nom d'utilisateur est déjà utilisé. Merci d'en choisir un autre.",
youAreRegistered: "Vous avez été enregistré!",
youAreLoggedIn: "Vous êtes connecté!",
close: "Fermer",
post: "Post",
back: "Retour",
createdBy: "Créé par",
shareOn: "Partager le post sur",
shareLink: "Partager le lien",
linkCopied:
"Le lien a été copié. Vous pouvez coller où vous voulez avec Ctrl + V ou clic droit Coller",
userDescriptionHint:
"Ecrivez si vous voulez une brève description ici pour vous",
userNameMissing: "Nom d'utilisateur manquant.",
passwordMissing: "Mot de passe manquant.",
passwordWeak:
"Pour votre sécurité, le mot de passe doit contenir plus de 8 caractères.",
emailErrorFormat: "L'email doit être au format correct.",
emailMissing: "The email is necessary to register.",
credentialsError: "Erreur de connexion",
searchResults: "Résultats de recherche",
searchHint: "Vous devez fournir au moins 4 caractères",
noResults: "Aucun résultat",
noPublicCollections:
"Il n'y a pas de collections publiques. Ajouter un en cliquant",
publicCollectionsHint:
"Collections que tout le monde peut voir et utiliser en utilisant la boîte de recherche",
noPrivateCollections:
"Il n'y a pas de collections privées. Ajouter un en cliquant",
description: "Description",
title: "Titre",
privateCollectionsHint:
"Collections que seuls vous et les utilisateurs que vous invitez peuvent afficher, ils ne peuvent pas être recherchés à l'aide de la zone de recherche",
collectionAddedToast: "Ajouté une collection!",
ofTheUser: "de l'utilisateur",
membersNumber: "Numéro de membre",
chooseUsersToShare:
"Choisissez d'autres utilisateurs pour partager la collection",
deleteCollection: "Supprimer la collection?",
allPostsWillBeDeleted:
"Tous les posts de cette collection seront supprimés",
yes: "Oui",
no: "Non",
followCollection: "Suivre la collection",
stopFollowing: "Arrête de suivre",
choose: "Choisir",
newPostHint:
"Faire un nouveau message avec des éléments de la carte et du texte et le publier",
newPostInThisCollection: "Nouvelle post sur cette collection",
noPosts: "Il n'y a pas de post",
chooseCollectionsToFollow: "Choisissez les collections à suivre",
liveMapUpdate: "Transmission de la carte",
youMayWriteText: "Vous pouvez écrire votre texte ici",
youMayWriteAndSketch:
"Écrivez votre texte ici. Vous pouvez aussi dessiner sur la carte!",
sketchToAddToPost:
"Esquisse sur la carte et les géométries seront ajoutés à la publication!",
publish: "Publier",
chooseCollection: "Choisir une collection",
collections: "Collections",
published: "Publié!",
errorNoTextOrSketches:
"Il n'y a pas de texte ou de géométrie. Ecrire un texte ou un croquis sur la carte avant de publier",
aPostPublished:
"Un nouveau post a été publié dans les collections que vous suivez.",
aReplyPublished:
"Un message de réponse a été publié dans les collections que vous suivez.",
aReplyToYourPostPublished: "Μια απάντηση δημοσιεύτηκε στην ανάρτησή σας",
geometrySketched:
"Une géométrie a été esquissée à partir des personnes que vous suivez",
mapPublished: "Une carte a été publiée.",
invitedToCollection: "Vous avez été invité en collection.",
invitationToCollectionAccepted:
"L'invitation que vous avez envoyée a été acceptée par",
collectionWasFollowed: "Votre collection a été suivie.",
collectionWasUnfollowed: "Votre collection n'a pas été suivie.",
feature: "Géométrie",
map: "Carte",
invitation: "Invitation",
collection: "Collection",
accept: "Accepter",
decline: "Déclin",
byUser: "par l'utilisateur",
newMessage: "Nouveau message",
sendMessage: "Envoyer",
outlineColor: "Contour",
fillColor: "Remplir",
strokeWidth: "Largeur",
symbologyStyle: "Style",
noUserCollectionsFound: "Aucune collection publique trouvée",
notifications: "Notifications",
markAllAsRead: "Tout marquer comme lu",
makeCollectionPublic: "Rendre cette carte publique",
makeCollectionPrivate: "Arrêtez le partage",
sharingSettings: "Rendre cette collection publique",
questionnaires: "Questionnaires",
questionnairesIcreated: "Questionnaires que j'ai créés",
questionnairesIanswered: "Questionnaires auxquels j'ai répondu",
shareQuestionnaireMessage:
"Vous pouvez partager ce lien avec ceux à qui vous voulez répondre.",
createQuestionnaire: "Créer un questionnaire",
questionnaireTitle: "Donnez un titre au questionnaire.",
questionnaireDescription:
"Donnez plus d'informations sur le questionnaire.",
questionnaireMapExtent:
"Placez une zone de référence du questionnaire sur la carte.",
previewQuestionnaire: "Aperçu de la question",
yourAnswer: "Votre réponse",
addLine: "Ajouter une ligne",
changeSection: "Changer de section",
section: "Section",
questionOptions: "Options de question",
question: "Question",
optional: "Facultatif",
addQuestion: "Ajouter une question",
questionType: "Type de question",
saveQuestionnaire: "SAUVEGARDER LE QUESTIONNAIRE",
text: "Texte",
expandableMenu: "Menu extensible",
checkboxes: "Cases à cocher",
multipleChoice: "Choix multiple",
mapPointer: "Point sur la carte",
mapPointerMultiple: "Plusieurs points sur la carte",
mapLinesMultiple: "Plusieurs lignes sur la carte",
mapLineStringPointer: "Tracer une ligne sur la carte",
sortingOptions: "Hiérarchie des préférences",
titleAndDescription: "Titre et description",
questionNotAnswered: "Vous n'avez pas répondu à la question",
nextSection: "Section suivante",
previousSection: "Section précédente",
submitQuestionnaire: "Soumettre le questionnaire",
thereAreErrorsInQuestionnaire:
"Il y a des erreurs. Voir les questions marquées en rouge.",
questionnaireSubmitted: "Vos réponses ont été soumises avec succès.",
submitted: "Soumis",
noValue: "Aucune valeur",
listOfAnswers: "Liste de réponses",
aggregates: "Agrégé",
allAnswers: "Toutes les réponses",
from: "À partir de",
to: "cette",
exportToTable: "Exporter vers une table",
exportMapData: "Exporter des données cartographiques",
createMap: "Créer une carte",
questionnaireStart: "Accès autorisé à partir de",
questionnaireEnd: "Accès autorisé depuis",
enablePublicAccess: "Activer l'accès public",
selectLanguage: "Sélectionnez la langue",
selectValidationType: "Type de validation"
}
};
|
const router = require('express').Router();
const Workout = require('../models/Workout');
// GET routes for Workouts
router.get('/api/workouts', (req,res) => {
Workout.aggregate([
{
$addFields: {
totalDuration: {$sum: '$exercise.duration'},
totalDistance: {$sum: '$exercise.distance'}}
}
])
.then(dbWorkout => {
res.json(dbWorkout);
})
.catch(err => {
res.json(err);
});
});
// POST routes for Workouts
router.post('/api/workouts', ({ body }, res) => {
Workout.create(body)
.then(dbWorkout => {
res.json(dbWorkout);
})
.catch(err => {
res.json(err);
});
});
// PUT routes for Workouts
router.put('/api/workouts/:id', (req, res) => {
Workout.findByIdAndUpdate(req.params.id, {$push: { exercises: req.body }}, { new: true })
.then (dbWorkout => {
res.json(dbWorkout);
})
.catch(err => {
res.status(400).json(err);
})
});
router.get('/api/workouts/range', (req,res) => {
Workout.aggregate([
{
$addFields: {
totalDuration: { $sum: '$exercise.duration'},
totalWeight: {$sum: '$exercise.weight'}},
}
])
.then(dbWorkout => {
const prevWorkouts = dbWorkout.slice(-7);
res.json(prevWorkouts);
})
.catch(err => {
res.json(err);z
});
});
module.exports = router;
|
import React, {Component} from 'react'
import {Cell} from 'fixed-data-table'
import Avatar from 'material-ui/Avatar'
class ImageCell extends Component {
render() {
const {rowIndex, field, data, ...props} = this.props
return (
<Cell {...props}>
<Avatar size={32}>{data[rowIndex]['lname'].substring(0,1)}</Avatar>
</Cell>
)
}
}
export default ImageCell
|
export let PacketFacilities = [
{
"id": "e1e9c52e-a0bc-4117-b996-0fc94843ea09",
"name": "Parsippany, NJ",
"code": "ewr1",
"features": [
"baremetal",
"storage"
],
"address": null
},
{
"id": "8e6470b3-b75e-47d1-bb93-45b225750975",
"name": "Amsterdam, NL",
"code": "ams1",
"features": [
"storage"
],
"address": null
},
{
"id": "2b70eb8f-fa18-47c0-aba7-222a842362fd",
"name": "Sunnyvale, CA",
"code": "sjc1",
"features": [],
"address": null
},
{
"id": "8ea03255-89f9-4e62-9d3f-8817db82ceed",
"name": "Tokyo, JP",
"code": "nrt1",
"features": [
"baremetal"
],
"address": null
}
];
export let PacketOs = [
{
"slug": "centos_7",
"name": "CentOS 7 (legacy)",
"distro": "centos",
"version": "7",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_3"
]
},
{
"slug": "centos_7_image",
"name": "CentOS 7",
"distro": "centos",
"version": "7",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_3"
]
},
{
"slug": "coreos_stable",
"name": "CoreOS (stable)",
"distro": "coreos",
"version": "stable",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_3"
]
},
{
"slug": "coreos_beta",
"name": "CoreOS (beta)",
"distro": "coreos",
"version": "beta",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_3"
]
},
{
"slug": "coreos_alpha",
"name": "CoreOS (alpha)",
"distro": "coreos",
"version": "alpha",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_3"
]
},
{
"slug": "debian_8",
"name": "Debian 8 (legacy)",
"distro": "debian",
"version": "8",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_3"
]
},
{
"slug": "ubuntu_14_04",
"name": "Ubuntu 14.04 LTS (legacy)",
"distro": "ubuntu",
"version": "14.04",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_3"
]
},
{
"slug": "ubuntu_14_04_image",
"name": "Ubuntu 14.04 LTS",
"distro": "ubuntu",
"version": "14.04",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_3"
]
},
{
"slug": "ubuntu_16_04_image",
"name": "Ubuntu 16.04 LTS",
"distro": "ubuntu",
"version": "16.04",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_2a",
"baremetal_3"
]
},
{
"slug": "rancher",
"name": "RancherOS",
"distro": "rancher",
"version": "0.7.0",
"provisionable_on": [
"baremetal_0",
"baremetal_1",
"baremetal_2",
"baremetal_2a",
"baremetal_3"
]
}
];
export let PacketPlans = [
{
"id": "e69c0169-4726-46ea-98f1-939c9e8a3607",
"slug": "baremetal_0",
"name": "Type 0",
"description": "Our Type 0 configuration is a general use \"cloud killer\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.",
"line": "baremetal",
"specs": {
"cpus": [
{
"count": 1,
"type": "Intel Atom C2550 @ 2.4Ghz"
}
],
"memory": {
"total": "8GB"
},
"drives": [
{
"count": 1,
"size": "80GB",
"type": "SSD"
}
],
"nics": [
{
"count": 2,
"type": "1Gbps"
}
],
"features": {
"raid": false,
"txt": true
}
},
"available_in": [
{
"href": "/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd"
},
{
"href": "/facilities/8e6470b3-b75e-47d1-bb93-45b225750975"
},
{
"href": "/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09"
},
{
"href": "/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed"
}
],
"pricing": {
"hour": 0.05
}
},
{
"id": "6d1f1ffa-7912-4b78-b50d-88cc7c8ab40f",
"slug": "baremetal_1",
"name": "Type 1",
"description": "Our Type 1 configuration is a zippy general use server, with an Intel E3-1240 v3 processor and 32GB of RAM.",
"line": "baremetal",
"specs": {
"cpus": [
{
"count": 1,
"type": "Intel E3-1240 v3"
}
],
"memory": {
"total": "32GB"
},
"drives": [
{
"count": 2,
"size": "120GB",
"type": "SSD"
}
],
"nics": [
{
"count": 2,
"type": "1Gbps"
}
],
"features": {
"raid": true,
"txt": true
}
},
"available_in": [
{
"href": "/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd"
},
{
"href": "/facilities/8e6470b3-b75e-47d1-bb93-45b225750975"
},
{
"href": "/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09"
},
{
"href": "/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed"
}
],
"pricing": {
"hour": 0.4
}
},
{
"id": "a3729923-fdc4-4e85-a972-aafbad3695db",
"slug": "baremetal_2",
"name": "Type 2",
"description": "Our Type 2 configuration is the perfect all purpose virtualization server, with dual E5-2650 v4 processors, 256 GB of DDR4 RAM, and six SSDs totaling 2.8 TB of storage.",
"line": "baremetal",
"specs": {
"cpus": [
{
"count": 2,
"type": "Intel Xeon E5-2650 v4 @2.2GHz"
}
],
"memory": {
"total": "256GB"
},
"drives": [
{
"count": 6,
"size": "480GB",
"type": "SSD"
}
],
"nics": [
{
"count": 2,
"type": "10Gbps"
}
],
"features": {
"raid": true,
"txt": true
}
},
"available_in": [
{
"href": "/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd"
},
{
"href": "/facilities/8e6470b3-b75e-47d1-bb93-45b225750975"
},
{
"href": "/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed"
}
],
"pricing": {
"hour": 1.25
}
},
{
"id": "741f3afb-bb2f-4694-93a0-fcbad7cd5e78",
"slug": "baremetal_3",
"name": "Type 3",
"description": "Our Type 3 configuration is a high core, high IO server, with dual Intel E5-2640 v3 processors, 128GB of DDR4 RAM and ultra fast NVME flash drives.",
"line": "baremetal",
"specs": {
"cpus": [
{
"count": 2,
"type": "Intel E5-2640 v3"
}
],
"memory": {
"total": "128GB"
},
"drives": [
{
"count": 2,
"size": "120GB",
"type": "SSD"
},
{
"count": 1,
"size": "1.6TB",
"type": "NVME"
}
],
"nics": [
{
"count": 2,
"type": "10Gbps"
}
],
"features": {
"raid": true,
"txt": true
}
},
"available_in": [
{
"href": "/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd"
},
{
"href": "/facilities/8e6470b3-b75e-47d1-bb93-45b225750975"
},
{
"href": "/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09"
}
],
"pricing": {
"hour": 1.75
}
},
{
"id": "87728148-3155-4992-a730-8d1e6aca8a32",
"slug": "storage_1",
"name": "Standard",
"description": "TBD",
"line": "storage",
"specs": {},
"available_in": [],
"pricing": {
"hour": 0.000104
}
},
{
"id": "d6570cfb-38fa-4467-92b3-e45d059bb249",
"slug": "storage_2",
"name": "Performance",
"description": "TBD",
"line": "storage",
"specs": {},
"available_in": [],
"pricing": {
"hour": 0.000223
}
}
];
|
import React from 'react';
import Visa from './svg/visa';
import Aexpress from './svg/aexpress';
import Master from './svg/master';
import Paypal from './svg/paypal';
import Money from './svg/money';
import Post from './svg/post';
import Lock from './svg/lock';
import Pci from './svg/pci';
import McAfee from './svg/mcafee';
const FormDelivery = () => {
return (
<>
<section className="payment">
<div className="container">
<div className="row justify-content-center">
<div className="col-12">
<div className="privacy-policy__wrapper">
<div className="privacy-policy__text pb-lg-0 pb-md-0 pb-3">
<a
href="#dataPrivacyPolicy"
className="privacy-link__wrapper"
>
<Lock />
<p>Ваши персональные данные защищены в соответствии с
<span>Политикой Конфиденциальности Данных</span>
</p>
</a>
</div>
<div className="privacy-policy__img">
<div className="policy-img__wrapper">
<div className="policy-img">
<McAfee />
</div>
<div className="policy-img">
<Pci />
</div>
</div>
</div>
</div>
</div>
<div className="col-12 pb-3 ">
<p className="bold_text">Доставка заказов:</p>
<p className="card_text">Осуществляется по всему Израилю в ближайшее почтовое отделение - бесплатно, или курьером на дом по цене 19,90₪ в течение 14 раб. дней с момента оплаты.</p>
</div>
<div className="col-12">
<div className="litl_container">
<p className="bold_text">Методы оплаты:</p>
<div className="card_container">
<div className="icon_card">
<div className="img-wrap">
<Visa />
</div>
</div>
<div className="icon_card">
<div className="img-wrap">
<Aexpress />
</div>
</div>
<div className="icon_card">
<div className="img-wrap">
<Master />
</div>
</div>
<div className="icon_card">
<div className="img-wrap">
<Paypal />
</div>
</div>
<div className="icon_card">
<div className="img-wrap">
<Money />
</div>
</div>
<div className="icon_card">
<div className="img-wrap">
<Post />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<style>{`
.litl_container {
position: relative;
margin: 0 auto;
padding: 0 15px;
}
@media screen and (max-width: 768px) {
.litl_container {
padding: 0 15px 15px 15px;
}
}
.bold_text {
padding-bottom: 5px;
color: #6d6d6d;
font-size: 15px;
line-height: 18px;
}
.card_container {
display: -webkit-box;
display: flex;
align-items: center;
-webkit-box-pack: justify;
justify-content: space-between;
padding: 15px 0;
}
.icon_card {
width: 100%;
}
.icon_card svg {
width: 75%;
height: auto;
}
.card_text {
color: #959595;
font-weight: normal;
font-size: 12px;
line-height: 17px;
}
.privacy-policy__wrapper {
display: flex;
align-items: center;
margin: 0 auto;
padding: 20px 0;
max-width: unset;
}
.privacy-policy__img {
margin: 0 auto;
}
.policy-img__wrapper {
display: -webkit-box;
display: flex;
justify-content: space-around;
text-align: right;
}
.policy-img {
display: -webkit-box;
display: flex;
overflow: hidden;
-webkit-box-align: center;
align-items: center;
-ms-flex-align: center;
-webkit-box-pack: center;
justify-content: center;
height: auto;
}
.policy-img svg {
width: 90%;
}
.litl_container {
position: relative;
margin: 0 auto;
padding: 0;
}
.bold_text {
padding-bottom: 5px;
color: #6d6d6d;
font-size: 15px;
line-height: 18px;
}
.card_container {
display: -webkit-box;
display: flex;
align-items: center;
-webkit-box-pack: justify;
justify-content: space-between;
padding: 15px 0;
}
.icon_card {
margin: 0 15px;
}
.icon_card:last-child {
margin: 0 0 0 15px;
}
.icon_card:first-child {
margin: 0 15px 0 0;
}
.icon_card .img-wrap {
width: 100%;
margin: 0 auto;
}
.icon_card svg {
width: 100%;
height: auto;
}
.card_text {
color: #959595;
font-weight: normal;
font-size: 12px;
line-height: 17px;
}
@media screen and (max-width: 768px) {
.privacy-policy__wrapper {
padding: 20px 0 10px 0;
}
.litl_container {
padding: 0 0 15px 0;
}
}
@media screen and (max-width: 576px) {
.privacy-policy__img {
margin: 0 auto ;
}
}
`}</style>
</>
);
};
export default FormDelivery;
|
const dispatcher = require('../dispatcher/dispatcher');
const UserConstants = require('../constants/user_constants');
const FriendApiUtil = require('../util/friend_api_util');
const FriendActions = {
fetchAllFriends(userId){
FriendApiUtil.fetchAllFriends(userId, FriendActions.receiveSingleUser);
},
createFriend(data){
FriendApiUtil.createFriend(data, FriendActions.receiveSingleUser);
},
editFriend(id){
FriendApiUtil.updateFriend(id, FriendActions.receiveSingleUser);
},
destroyFriend(id){
FriendApiUtil.removeFriend(id, FriendActions.receiveSingleUser);
},
receiveSingleUser(user){
dispatcher.dispatch({
actionType: UserConstants.USER_RECEIVED,
user: user
});
}
};
module.exports = FriendActions;
|
$(function () {
var h = $(".container-fluid-full").height();
var h1 = $("#content .breadcrumb").height();
$("#tree").height(h - h1 - 24);
$.ajax({
url: "static/page/designcoordination/documentmgmt/doc.json",
type: "get",
dataType:"json",
success: function (data) {
var zTreeObj;
var setting = {
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: "0"
}
},
callback:{
onClick:function(event, treeId, treeNode){
if(treeNode.id==0){
return;
}
$("tbody tr").remove();
$("tbody").append(treeNode.doc);
todownload();
}
}
};
zTreeObj = $.fn.zTree.init( $("#tree"), setting, data);
zTreeObj.expandAll(true);
var node = zTreeObj.getNodeByParam("id", 1, null);
zTreeObj.selectNode(node);
todownload();
}
});
$(".btnStandard input").each(function () {
$(this).click(function () {
$(this).addClass("btnActive").siblings().removeClass("btnActive");
})
});
});
function todownload(){
$(".xz").each(function(){
$(this).click(function(){
console.log(this);
var filename = $(this).parents("tr").children().eq(0).text();
window.location.href = "download?filename="+filename;
})
});
}
|
// Data Access Object
// Se comunica con la base de datos
const pool = require('../../services/postgresql/index');
module.exports = {
async createCrop(crop) {
// Registro en tabla cultivo
query = `INSERT INTO cultivo (lotecultivadoid, productoid) VALUES
(${crop.lotecultivadoid},${crop.productoid})`;
result = await pool.query(query);
},
async getAllCrops() {
let query = `SELECT * FROM cultivo`;
let result = await pool.query(query);
return result.rows; // Devuelve array de cultivos
},
async getCrop(id) {
let query = `SELECT * FROM cultivo WHERE cultivoid = ${id}`;
let result = await pool.query(query);
return result.rows[0]; // Devuelve objeto de cultivo
},
async updateCrop(id, crop) {
let query = `UPDATE cultivo SET lotecultivadoid = '${crop.lotecultivadoid}', productoid = '${crop.productoid}'
WHERE cultivoid = ${id}`;
let result = await pool.query(query);
return result.rowCount; // Devuelve 1 si actualizó el cultivo y 0 sino lo hizo.
},
async deleteCrop(id) {
let query = `DELETE FROM cultivo WHERE cultivoid = ${id}`;
let result = await pool.query(query);
return result.rowCount; // Devuelve 1 si borró el cultivo y 0 sino lo hizo.
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.