text stringlengths 7 3.69M |
|---|
import React, { Fragment, PureComponent } from "react";
import { Link } from "react-router-dom";
import { withStyles, CardMedia } from "@material-ui/core";
import { Typography, Grid, Card, CardContent } from "@material-ui/core";
import logos from "../../assets/images/logos.png";
import styles from "./homeStyle";
import bg from "../../assets/images/bg.jpg";
class Home extends PureComponent {
render() {
const { classes } = this.props;
const user = this.props.firebase.auth().currentUser.displayName;
return (
<Fragment>
<div className={classes.root}>
<Grid container className={classes.mainFeaturedPost}>
<Grid item>
<Card className={classes.card}>
<CardMedia image={bg} className={classes.cardMedia} />
<CardContent>
<Typography
component="h1"
variant="h5"
className={classes.postTitle}
>
{user === null ? "Welcome!" : "Welcome, " + user + "!"}
</Typography>
<Typography
className={classes.postText}
variant="subtitle1"
color="inherit"
paragraph
>
Sustaingineering is a student engineering design team that
designs, develops and deploys sustainable technology
solutions for renewable energy applications in remote and
developing communities. Our goal is to create power
solutions to address the global challenge of climate change
and to improve the quality of life of the people living in
these communities.
</Typography>
</CardContent>
</Card>
</Grid>
</Grid>
<Grid container spacing={4}>
{user === null ? (
<Grid item key={"no-user-auth"} xs={12} md={6}>
<Card className={classes.card}>
<CardContent>
<Typography variant="h6" className={classes.postTitle}>
Set your name!
</Typography>
<Typography
className={classes.postText}
variant="subtitle1"
color="inherit"
>
Visit <Link to="/config">config</Link> to set your name.
</Typography>
</CardContent>
</Card>
</Grid>
) : (
undefined
)}
{this.props.posts.map(post => (
<Grid item key={post.title} xs={12} md={6}>
<Card className={classes.card}>
<CardContent>
<Typography variant="h6" className={classes.postTitle}>
{post.title}
</Typography>
<Typography
className={classes.postText}
variant="subtitle1"
color="inherit"
dangerouslySetInnerHTML={{ __html: post.text }}
/>
</CardContent>
</Card>
</Grid>
))}
</Grid>
</div>
<footer className={classes.footer}>
<img className={classes.logos} src={logos} alt="logos" />
</footer>
</Fragment>
);
}
}
export default withStyles(styles)(Home);
|
const express = require("express");
const logfmt = require("logfmt");
const microtime = require('microtime');
const app = express();
app.use(logfmt.requestLogger());
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.get('/microtime', (req, res) => {
res.send('native time: ' + microtime.nowDouble().toString());
});
const port = Number(process.env.PORT || 5000);
app.listen(port, () => {
console.log("Listening on " + port);
});
|
import { classNameBindings, classNames } from '@ember-decorators/component';
import BaseCarouselSlide from 'ember-bootstrap/components/base/bs-carousel/slide';
@classNameBindings(
'left:carousel-item-left',
'next:carousel-item-next',
'prev:carousel-item-prev',
'right:carousel-item-right'
)
@classNames('carousel-item')
export default class CarouselSlide extends BaseCarouselSlide {}
|
/**
* Copyright 2019 ForgeRock AS. All Rights Reserved
*
* Use of this code requires a commercial software license with ForgeRock AS.
* or with one of its affiliates. All use shall be exclusively subject
* to such license between the licensee and ForgeRock AS.
*/
import BootstrapVue from 'bootstrap-vue';
import { noop } from 'lodash';
import { createLocalVue, shallowMount } from '@vue/test-utils';
import ValidationError from './index';
const localVue = createLocalVue();
localVue.use(BootstrapVue);
describe('ValidationError.vue', () => {
let wrapper;
beforeEach(() => {
wrapper = shallowMount(ValidationError, {
mocks: {
$t: () => {},
},
propsData: {
localVue,
validatorErrors: {
has: noop,
first: noop,
},
fieldName: 'test',
},
});
});
it('Validation Error component loaded', () => {
expect(wrapper.name()).toEqual('ValidationErrorList');
expect(wrapper).toMatchSnapshot();
});
});
|
var moogoose = require('mongoose');
moogoose.connect('mongodb+srv://dbUser:123@cluster0.knc4f.mongodb.net/JobtestDB?retryWrites=true&w=majority', { useNewUrlParser: true, useUnifiedTopology: true });
var db = moogoose.connection;
db.on('error', function(err) {
if (err) console.log(err)
});
db.once('open', function() {
console.log("Connected !");
}); |
$(function() {
$(".avatar-div-div").mousemove(function(){
$(".avatar-div-div").css("display","inline");
});
$(".avatar-div-div").mouseleave(function(){
$(".avatar-div-div").css("display","none");
});
$("#avatar").mousemove(function(){
$(".avatar-div-div").css("display","inline");
});
$("#avatar").mouseleave(function(){
$(".avatar-div-div").css("display","none");
});
var basePath = window.document.location.href;
basePath = basePath.substring(0,basePath.lastIndexOf('/'));
var prompt = $(".prompt");
$("#housingPrice").blur(
function() {
var value = $("#housingPrice").val();
$.post(basePath + '/checkPriceAndArea.fw', 'number='
+ value, function(data) {
text = data;
prompt[1].innerText = text;
}, 'text');
});
$("#housingArea").blur(
function() {
var value = $("#housingArea").val();
$.post(basePath + '/checkPriceAndArea.fw', 'number='
+ value, function(data) {
text = data;
prompt[2].innerText = text;
}, 'text');
});
}); |
import {combineEpics} from 'redux-observable';
import {
exampleEpic
} from './epics/exampleEpic';
export default combineEpics(
exampleEpic
);
|
export { default } from './router'
export { default as args } from './args'
export { default as hash } from './hash'
export { default as params } from './params'
export { default as urlFor } from './urlFor'
|
var validator = require('mongoose-validators');
/**
* @class address
* @classdesc address class contains the address details
*/
var address = {
/** address type must be string and can be maximum 10 characters*/
addressType: { type: String, validate:[validator.isLength(0, 10)] },
/** name1 is required, must be alphabet and can be maximum 20 characters*/
name1: { type: String, required:true, validate:[validator.isLength(0, 20), validator.matches(/^[a-zA-Z0-9\s]+$/)]},
/** name2 must be alphabet and can be maximum 20 characters*/
name2: { type: String, validate:[validator.isLength(0, 20), validator.matches(/^[a-zA-Z0-9\s]+$/)] },
/** name3 must be alphabet and can be maximum 20 characters*/
name3: { type: String, validate:[validator.isLength(0, 20), validator.matches(/^[a-zA-Z0-9\s]+$/)]},
/** street must be string and can be maximum 20 characters*/
street: { type: String, validate:[validator.isLength(0, 20)] },
/** zipcode must be alphanumeric and can be maximum 10 characters */
zipCode: { type: String , validate:[validator.isAlphanumeric(), validator.isLength(0, 10)] },
/** city must be string and can be maximum 20 characters */
city: { type: String, required:true, validate:[validator.isLength(0, 20)] },
/** Po Box Zipcode must be alphanumeric and can be maximum 10 characters */
poboxZipCode: { type: String, validate:[validator.isAlphanumeric(), validator.isLength(0, 10)]},
/** Po Box must be alphanumeric and can be maximum 10 characters */
pobox: { type: String, validate:[validator.isAlphanumeric(),validator.isLength(0, 10)] },
/** isCompany must be Boolean with default value false */
isCompany: { type: Boolean, default: false },
/** phone number must be in phone number format which accepts numbers,brackets and +, - */
phoneNo: { type: String, validate: [validator.matches(/^[\0-9() -+]{3,50}$/)]},
/** fax number must be in phone number format which accepts numbers,brackets and +, - */
faxNo: { type: String, validate: [validator.matches(/^[\0-9() -+]{3,50}$/)]},
/** email must be valid */
email: { type: String, validate: [validator.isEmail]},
/** corporate url must be a valid url */
corporateURL: { type: String, validate: [validator.isURL] },
/** number Of employees must be number */
numOfEmployees: { type: Number },
/** country must be string and can be maximum 50 characters */
country: { type: String, required:true, validate:[validator.isLength(0, 50)]},
/** state must be string and can be maximum 20 characters */
state: { type: String, validate:[validator.isLength(0, 20)]}
};
module.exports = {
Address: address
}; |
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsMarkEmailUnread = {
name: 'mark_email_unread',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M22 8.98V18c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2h10.1c-.06.32-.1.66-.1 1 0 1.48.65 2.79 1.67 3.71L12 11 4 6v2l8 5 5.3-3.32c.54.2 1.1.32 1.7.32 1.13 0 2.16-.39 3-1.02zM16 5c0 1.66 1.34 3 3 3s3-1.34 3-3-1.34-3-3-3-3 1.34-3 3z"/></svg>`
};
|
const postCommentURL = "https://blog.styve.digital/wp-json/wp/v2/comments";
const contactForm = document.getElementById("blog-contact");
const successIcon = document.getElementById("form-success-check");
contactForm.addEventListener("submit", validateContactForm);
function submitContactForm() {
const [contactName, contactEmail, contactSubject, contactMessage] = event.target.elements;
const commentData = {
post: 56,
author_name: contactName.value,
author_email: contactEmail.value,
content: "Subject: " + contactSubject.value + " | " + "Message: " + contactMessage.value,
};
fetch(postCommentURL, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(commentData),
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response not OK");
}
return response.json();
})
.then((commentData) => {
console.log("Success", commentData);
successIcon.style.display = "block";
contactForm.style.fontStyle = "italic";
contactForm.innerHTML = "Your contact form was successfully submitted.";
})
.catch((error) => {
console.error(error);
});
}
const contactName = document.getElementById("contactName");
const contactEmail = document.getElementById("contactEmail");
const contactSubject = document.getElementById("contactSubject");
const contactMessage = document.getElementById("contactMessage");
const nameError = document.getElementById("nameError");
const emailError = document.getElementById("emailError");
const subjError = document.getElementById("subjError");
const msgError = document.getElementById("msgError");
function validateContactForm(event) {
event.preventDefault();
if (checkLength(contactName.value, 5)) {
contactName.style.border = "2px solid #60ab60";
nameError.innerHTML = "";
} else {
nameError.innerHTML = "Enter a valid name (min. 5 char.)";
contactName.style.border = "2px solid #ff7a7a";
}
if (validateEmail(contactEmail.value)) {
contactEmail.style.border = "2px solid #60ab60";
emailError.innerHTML = "";
} else {
emailError.innerHTML = "Enter a valid e-mail address";
contactEmail.style.border = "2px solid #ff7a7a";
}
if (checkLength(contactSubject.value, 15)) {
contactSubject.style.border = "2px solid #60ab60";
subjError.innerHTML = "";
} else {
subjError.innerHTML = "Enter a valid subject (min. 15 char.)";
contactSubject.style.border = "2px solid #ff7a7a";
}
if (checkLength(contactMessage.value, 25)) {
contactMessage.style.border = "1px solid #60ab60";
msgError.innerHTML = "";
} else {
msgError.innerHTML = "Enter a valid message (min. 25 char.)";
contactMessage.style.border = "1px solid #ff7a7a";
}
if (checkLength(contactName.value, 5) && checkLength(contactSubject.value, 15) && checkLength(contactMessage.value, 25) && validateEmail(contactEmail.value)) {
submitContactForm(event);
}
}
function checkLength(value, len) {
if (value.trim().length >= len) {
return true;
} else {
return false;
}
}
function validateEmail(email) {
const regEx = /\S+@\S+\.\S+/;
const emailMatch = regEx.test(email);
return emailMatch;
}
const newsletterURL = "https://blog.styve.digital/wp-json/wp/v2/comments";
const newsletterForm = document.querySelector(".footer-news-form");
newsletterForm.addEventListener("submit", submitNewsForm);
function submitNewsForm(e) {
e.preventDefault();
const [newsMail] = e.target.elements;
const newsletterData = {
post: 75,
author_name: "Newsletter Subscriber",
author_email: newsMail.value,
content: newsMail.value,
};
fetch(newsletterURL, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newsletterData),
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response not OK");
}
return response.json();
})
.then((newsletterData) => {
console.log("Success", newsletterData);
newsletterForm.innerHTML = `<div class="footer-news-success">Thank you for subscribing!</div>`;
})
.catch((error) => {
console.log(error);
});
}
|
const latitude = document.getElementById('lat');
const longitude = document.getElementById('long');
window.navigator.geolocation.getCurrentPosition((success) => {
const lat = success.coords.latitude;
latitude.setAttribute('value', lat);
const long = success.coords.longitude;
longitude.setAttribute('value', long);
}, (error) => {
console.log(error);
});
|
var FolderMenuItemView = Backbone.View.extend({
initialize: function (options) {
_.bindAll(this, "render", "update", "expand", "collapse");
this.criteria = options.criteria;
this.selected = options.selected;
this.model.bind('change', this.render);
this.model.view = this;
},
tagName: "li",
className: "folder",
template: Handlebars.compile($("#folder-menu-item-template").html()),
events: {
"click span.collapse-expand": "toggleFolderView",
"click span.rename-item": "rename",
"click span.delete-item": "delete",
"click span.new-tasklist": "newTaskList",
"keydown input": "updateOnEnter"
},
toggleFolderView: function (e) {
e.stopImmediatePropagation();
this.model.set({ "expanded": !this.model.get("expanded") }, { silent: true });
$(this.el).toggleClass("expanded collapsed");
},
expand: function() {
this.model.set({ "expanded": true }, { silent: true });
$(this.el).removeClass("collapsed");
$(this.el).addClass("expanded");
},
collapse: function () {
this.model.set({ "expanded": false }, { silent: true });
$(this.el).removeClass("expanded");
$(this.el).addClass("collapsed");
},
rename: function (e) {
e.stopImmediatePropagation();
$(this.el).addClass("editing");
var input = this.$("> div > div > input");
input.focus().select();
input.bind("blur", this.update);
},
delete: function (e) {
e.stopImmediatePropagation();
var view = new DeleteFolderView({
model: this.model,
criteria: this.criteria
});
view.render();
$.modal(view.el);
},
newTaskList: function (e) {
e.stopImmediatePropagation();
this.expand();
this.taskListMenuView.showNewItemForm();
},
update: function(e) {
var input = this.$("> div > div > input");
var title = $.trim(input.val());
var currentTitle = this.model.get("title");
if (title != "" && title != currentTitle) {
this.model.set({ title: title });
this.model.save();
}
$(this.el).removeClass("editing");
if (title == "")
input.val(currentTitle);
if (this.criteria.folderSelected(this.model.get("id")))
this.criteria.trigger("change");
},
updateOnEnter: function (e) {
if (e.keyCode == 13) this.update();
},
render: function () {
// Render template.
$(this.el).html(this.template(this.model.toJSON()));
// Add classes.
if (this.selected) $(this.el).addClass("selected");
if (this.model.get("expanded"))
$(this.el).addClass("expanded");
else
$(this.el).addClass("collapsed");
// Create task list menu view.
this.taskListMenuView = new TaskListMenuView({
model: this.model.get("taskLists"),
el: this.$("> .tasklist-menu"),
criteria: this.criteria,
parent: this
}).render();
// Refresh the view.
this.taskListMenuView.refreshView();
// Make the task list view menu sortable.
this.taskListMenuView.sortable();
return this;
}
}); |
import RentalsController from '../rentals';
export default RentalsController.extend({
actions: {
buttonClick() {
var $add = $(".show-block-rent");
if ($add.hasClass('hidden-block')) {
$add.removeClass('hidden-block');
}
else
$add.addClass('hidden-block');
}
}
});
|
import React, { useState, useEffect } from "react";
import axios from "axios";
import "./App.css";
import Filter from "./components/Filter";
import Countries from "./components/Countries";
const App = () => {
const [countries, setCountries] = useState([]);
const [filteredCountries, setFilteredCountries] = useState([]);
const [newFilter, setNewFilter] = useState("");
const [showCountry, setShowCountry] = useState("");
useEffect(() => {
axios.get("https://restcountries.eu/rest/v2/all").then((response) => {
setCountries(response.data);
});
}, []);
useEffect(() => {
setFilteredCountries(
countries.filter((country) => {
return country.name.toLowerCase().includes(newFilter.toLowerCase());
})
);
}, [newFilter, countries]);
const handleFilter = (event) => {
setNewFilter(event.target.value);
setShowCountry("");
};
const handleShow = (name) => {
setShowCountry(name);
};
return (
<div>
<Filter handleFilter={handleFilter} newFilter={newFilter} />
<Countries
countries={filteredCountries}
handleShow={handleShow}
showCountry={showCountry}
/>
</div>
);
};
export default App;
|
/**
* Created by Osvaldo on 20/10/15.
*/
var Mongoose = require('../Banco.js').mongoose;
var types = Mongoose.Schema.Types;
var options = {
toJSON: {
getters: true
},
toObject: {
getters: true
}
};
var situacao = Mongoose.Schema({
nome: {type: types.String, required: true},
descricao: {type: types.String}
});
module.exports = Mongoose.model('situacao', situacao); |
// @flow
import * as React from "react";
import { LibraryFactorsPhotosUploadCommon } from "./LibraryFactorsPhotosUploadCommon";
export default function LibraryFactorsPhotosUpload( props )
{
return <LibraryFactorsPhotosUploadCommon filesLocationPrefix="/custom/editions/photo/146x110" { ...props } />;
} |
import React, { Component } from "react";
import CallApi from "../../../api/api";
import "./LoginForm.css";
import classNames from "classnames";
import { withAuth } from "../../../hoc/withAuth";
class LoginForm extends Component {
constructor() {
super();
this.state = {
username: "",
password: "",
repeatPassword: "",
submitting: false,
errors: {},
};
}
handleChange = (event) => {
const name = event.target.name;
const value = event.target.value;
this.setState((prevState) => ({
[name]: value,
errors: {
...prevState.errors,
[name]: null,
base: null,
},
}));
};
handleBlur = (event) => {
const errors = this.validateErrors();
const { name } = event.target;
const error = errors[name];
if (error) {
this.setState((prevState) => ({
errors: {
...prevState.errors,
[name]: error,
},
}));
}
};
validateErrors = () => {
const errors = {};
if (this.state.username === "") {
errors.username = "Поле не должно быть пустым";
}
if (this.state.password === "") {
errors.password = "Поле не должно быть пустым";
}
if (this.state.repeatPassword !== this.state.password) {
errors.repeatPassword = "Пароли не совпадают";
}
return errors;
};
onSubmit = async () => {
try {
const data = await CallApi.get("authentication/token/new");
const requestToken = await CallApi.post(
"authentication/token/validate_with_login",
{
params: {},
body: {
username: this.state.username,
password: this.state.password,
request_token: data.request_token,
},
}
);
const { session_id } = await CallApi.post("authentication/session/new", {
body: {
request_token: requestToken.request_token,
},
});
this.props.authActions.updateSessionId(session_id);
const accountDetails = await CallApi.get("account", {
params: { session_id: session_id },
});
this.props.authActions.updateUser(accountDetails);
this.props.authActions.toggleModal();
const favorites = await CallApi.get(
"account/{account_id}/favorite/movies",
{
params: { session_id: session_id },
}
);
this.props.authActions.updateFavorites(favorites.results);
const watchList = await CallApi.get(
"account/{account_id}/watchlist/movies",
{
params: {
session_id: session_id,
},
}
);
this.props.authActions.updateWatchList(watchList.results);
} catch (error) {
this.setState({
submitting: false,
errors: {
base: error.status_message,
},
});
}
};
onLogin = (event) => {
event.preventDefault();
const errors = this.validateErrors();
if (Object.keys(errors).length > 0) {
this.setState((prevState) => ({
errors: {
...prevState.errors,
...errors,
},
}));
} else {
this.setState({
submitting: true,
});
this.onSubmit();
}
};
render() {
const errorBorder = classNames({
"form-control": !this.state.errors.username,
"form-control error": this.state.errors.username,
});
return (
<form>
<div className="form-group">
<label htmlFor="login">Имя пользователя</label>
<input
type="text"
className={errorBorder}
placeholder="Введите имя пользователя"
id="username"
name="username"
onChange={this.handleChange}
onBlur={this.handleBlur}
/>
{this.state.errors.username ? (
<div className="alert alert-danger mt-1" role="alert">
{this.state.errors.username}
</div>
) : (
""
)}
</div>
<div className="form-group">
<label htmlFor="password">Пароль</label>
<input
type="password"
className="form-control"
placeholder="Введите пароль"
id="password"
name="password"
onChange={this.handleChange}
/>
{this.state.errors.password ? (
<div className="alert alert-danger mt-1" role="alert">
{this.state.errors.password}
</div>
) : (
""
)}
</div>
<div className="form-group">
<label htmlFor="repeatPassword">Повторие пароль</label>
<input
type="password"
className="form-control"
placeholder="Повторие пароль"
id="repeatPassword"
name="repeatPassword"
onChange={this.handleChange}
/>
{this.state.errors.repeatPassword ? (
<div className="alert alert-danger mt-1" role="alert">
{this.state.errors.repeatPassword}
</div>
) : (
""
)}
</div>
<button
type="submit"
className="btn btn-primary btn-block"
disabled={this.state.submitting}
onClick={this.onLogin}
>
Войти
</button>
{this.state.errors.base ? (
<div className="alert alert-danger mt-1 text-center" role="alert">
{this.state.errors.base}
</div>
) : (
""
)}
</form>
);
}
}
export default withAuth(LoginForm);
|
/*******************************************************************************
*
* Copyright 2018 Adobe. All rights reserved.
* This file is licensed to you 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 REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
******************************************************************************/
'use strict';
const pomParser = require('pom-parser');
const semver = require('semver');
const CI = require('./ci.js');
const ci = new CI();
const fs = require('fs');
const cp = require('child_process');
ci.context();
let gitTag = process.env.CIRCLE_TAG;
if (!gitTag) {
throw 'Cannot release without a valid git tag';
}
var opts = {
filePath: __dirname + '/../pom.xml',
};
pomParser.parse(opts, function(err, response) {
if (err) {
console.error('Error when opening/parsing POM' + err);
throw err;
}
try {
ci.gitImpersonate('CircleCi', 'noreply@circleci.com', () => {
release(response.pomObject.project.version);
updateSwaggerUiIndex();
});
} finally {
// Remove release tag
ci.sh('git push --delete origin ' + gitTag);
// Remove NPM token and 'gpg' config
ci.sh('rm -f ~/.npmrc');
ci.sh('rm -rf /home/circleci/.gnupg');
}
});
function release(pomVersion) {
ci.stage('RELEASE ' + gitTag);
// We cannot find out what git branch has the tag, so we assume/enforce that releases are done on master
console.log('Checking out the master branch so we can commit and push');
ci.sh('git checkout master');
let newVersion, nextVersion;
let currentVersion = semver.coerce(pomVersion).version;
if (gitTag.endsWith('-patch')) {
if (pomVersion.includes('-SNAPSHOT')) {
newVersion = currentVersion;
} else {
newVersion = semver.inc(currentVersion, 'patch');
}
} else if (gitTag.endsWith('-minor')) {
newVersion = semver.inc(currentVersion, 'minor');
} else if (gitTag.endsWith('-major')) {
newVersion = semver.inc(currentVersion, 'major');
}
nextVersion = semver.inc(newVersion, 'patch') + '-SNAPSHOT';
console.log('Current version : ' + pomVersion);
console.log('Released version : ' + newVersion);
console.log('Next version : ' + nextVersion);
// Import PGP key into 'gpg' config
ci.sh('echo $GPG_PRIVATE_KEY | base64 --decode | gpg --batch --import');
// Configure NPM token
ci.sh('echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc');
ci.sh('mvn -B -s ci/settings.xml clean release:prepare release:perform -DreleaseVersion=' + newVersion + ' -DdevelopmentVersion=' + nextVersion);
ci.stage('RELEASE DONE');
}
/**
* Updates the Swagger UI index.html file with the newly release Swagger specification
*/
function updateSwaggerUiIndex() {
let tags = cp.execSync(`git tag -l api-model-*`).toString().trim().split('\n');
// We ignore all 0.x versions and versions 1.0.0 and 1.1.0
// Due to an issue in the first releases, versions 1.0.0 and 1.1.0 have to be handled differently
tags = tags.filter(tag => !tag.startsWith('api-model-0.') && tag != 'api-model-1.0.0' && tag != 'api-model-1.1.0');
let urls = [
{url: "http://opensource.adobe.com/commerce-cif-api/swagger-1.1.0.json", name: "CIF REST API 1.1.0"},
{url: "http://opensource.adobe.com/commerce-cif-api/swagger-1.0.0.json", name: "CIF REST API 1.0.0"}
];
tags.forEach(tag => {
urls.unshift({
url: `https://raw.githubusercontent.com/adobe/commerce-cif-api/${tag}/src/main/resources/swagger/swagger.json`,
name: 'CIF REST API ' + tag.substring(10)
});
});
// replace the 'urls' array in index.html
let index = fs.readFileSync(__dirname + '/../docs/index.html', 'utf-8');
index = index.replace(/urls: [\s\S]*?\]/, 'urls: ' + JSON.stringify(urls, null, 4));
fs.writeFileSync(__dirname + '/../docs/index.html', index);
ci.stage('COMMIT - Adding Swagger UI new index file');
ci.sh('git add -A docs/index.html');
ci.sh('git commit -m "@releng : automatically commit Swagger UI index after maven release:perform"');
ci.sh('git push git@github.com:adobe/commerce-cif-api.git');
ci.stage('COMMIT DONE');
} |
import React from 'react';
import Context from '../src/context.js';
import '../src/App.css';
import AutoCompleteInput from './AutoCompleteInput';
export default class CityCell extends React.Component {
constructor(props){
super(props);
this.state = {
}
}
consoleLog(newCity,oldCity){
if(newCity.name == oldCity.name){
console.log(newCity);
console.log(oldCity);
console.log('');
}else{
console.log("City is not Matched "+newCity.name+" != "+oldCity.name);
console.log('')
}
}
render (){
return(
<Context.Consumer>
{value=>{
let Count = 0;
return(
<React.Fragment>
{value.state.NewCityApi.map((city,i)=>{
if(i >= (value.state.CurrentPage-1)*13 && i < (value.state.CurrentPage-1)*13+13){
let backGroudColor = '#ffffff';
if(Count % 2 == 0){ backGroudColor = '#eeeeef'; }
Count++;
return(
<div className="CityCon" style={{backgroundColor:backGroudColor}} key={i}>
<div className="CityCell">
<span className="CityText">{city.name}</span>
</div>
<div className="CityCell" style={{borderLeft:0}}>
<AutoCompleteInput value={value.state.NewCityApi[i].oldCity} onSelectCity={(olddata)=>{value.state.NewCityApi[i].oldCity=olddata.name;this.consoleLog(city,olddata)}}/>
</div>
</div>
)
}
})}
</React.Fragment>
)}}
</Context.Consumer>
)
}
} |
const {assert} = require("chai");
const Helpers = {
initEthers(ethers) {
this.ethers = ethers;
},
async assertThrowsMessage(promise, message) {
try {
await promise;
console.log("It did not throw :-(");
assert.isTrue(false);
} catch (e) {
const shouldBeTrue = e.message.indexOf(message) > -1;
if (!shouldBeTrue) {
console.error("Expected:", message);
console.error("Returned:", e.message);
// console.log(e)
}
assert.isTrue(shouldBeTrue);
}
},
async deployContractBy(contractName, owner, ...args) {
const Contract = await this.ethers.getContractFactory(contractName);
const contract = await Contract.connect(owner).deploy(...args);
await contract.deployed();
return contract;
},
async deployContract(contractName, ...args) {
const Contract = await this.ethers.getContractFactory(contractName);
const contract = await Contract.deploy(...args);
await contract.deployed();
return contract;
},
async deployContractUpgradeable(contractName, args = []) {
const Contract = await this.ethers.getContractFactory(contractName);
const contract = await upgrades.deployProxy(Contract, args);
await contract.deployed();
return contract;
},
async signPackedData(
hash,
// hardhat account #4, starting from #0
privateKey = "0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a"
) {
const signingKey = new this.ethers.utils.SigningKey(privateKey);
const signedDigest = signingKey.signDigest(hash);
return this.ethers.utils.joinSignature(signedDigest);
},
async getTimestamp() {
return (await this.ethers.provider.getBlock()).timestamp;
},
addr0: "0x0000000000000000000000000000000000000000",
async increaseBlockTimestampBy(offset) {
await this.ethers.provider.send("evm_increaseTime", [offset]);
await this.ethers.provider.send("evm_mine");
},
};
module.exports = Helpers;
|
$(document).ready(function(){
//cow buttons
//function to hide ps
function hideAllCow() {
$('#cowProductText').hide();
$('#cowFeedText').hide();
$('#cowLandText').hide();
}
//immediately hide everything
hideAllCow();
$('#cowProductText').show();
//when any button is clicked make the text appear
$('.btn').click(function() {
//turn on paragraph based on button clicked
switch($(this).attr("id")) {
case "cowProduct":
hideAllCow();
$('#cowProductText').show();
// $('#corn').toggleClass('rotate');
break;
case "cowFeed":
hideAllCow();
$('#cowFeedText').show();
break;
case "cowLand":
hideAllCow();
$('#cowLandText').show();
break;
}
}); //end of click function
//pig buttons
//function to hide ps
function hideAllPig() {
$('#pigProductText').hide();
$('#pigFeedText').hide();
$('#pigLandText').hide();
}
//immediately hide everything
hideAllPig();
$('#pigProductText').show();
//when any button is clicked make the text appear
$('.btn').click(function() {
//turn on paragraph based on button clicked
switch($(this).attr("id")) {
case "pigProduct":
hideAllPig();
$('#pigProductText').show();
break;
case "pigFeed":
hideAllPig();
$('#pigFeedText').show();
break;
case "pigLand":
hideAllPig();
$('#pigLandText').show();
break;
}
}); //end of click function
//chicken buttons
//function to hide ps
function hideAllChicken() {
$('#chickenProductText').hide();
$('#chickenFeedText').hide();
$('#chickenLandText').hide();
}
//immediately hide everything
hideAllChicken();
$('#chickenProductText').show();
//when any button is clicked make the text appear
$('.btn').click(function() {
//turn on paragraph based on button clicked
switch($(this).attr("id")) {
case "chickenProduct":
hideAllChicken();
$('#chickenProductText').show();
break;
case "chickenFeed":
hideAllChicken();
$('#chickenFeedText').show();
break;
case "chickenLand":
hideAllChicken();
$('#chickenLandText').show();
break;
}
}); //end of click function
});
|
const genders = ['male', 'female']
function validate(...validators) {
return data => validators.every(v => v(data))
}
function loginValidator({ gender, searchFor}) {
console.log(gender, searchFor)
return genders.includes(gender)
&& searchFor.length >= 1 && searchFor.length <= 2 && searchFor.every(g => genders.includes(g))
}
function booleanValidator(data) {
return typeof data == 'boolean'
}
function messageValidator(message) {
return message.length > 0 && message.length <= 1024
}
module.exports = {
validate,
loginValidator,
booleanValidator,
messageValidator
}
|
$(document).ready(function() {
$("#search_word").change(function() {
var sw = $(this).val().trim();
if(sw===""){
window.alert("you have enterd nothing");
return;
}
$("#body").html("<div id='res'></div>")
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&meta=&srsearch="+sw+"&origin=*";
$.getJSON(url, writeData);
});
});
function writeData(data) {
data.query.search.forEach(function(i) {
var id = i.pageid;
var snip = i.snippet;
var title = i.title;
$("#res").append("<a href='https://en.wikipedia.org/?curid="+id+"' target='_blank'><div class='entry animated zoomIn'><h2>"+title+"</h2><p>"+snip+"</p></div></a>");
});
} |
// $(document).ready(function () {
// let ptag = $('p');
// })
// $(document).ready(function () {
// let div = $('.container div');
// let count = 1;
// let
// if (count < 10) {
// div.click(function () {
// if (count % 2 == 1 && !$(this).hasClass(clicked) ) {
// $(this).css('background-image', 'url(/asserts/x.png)');
// $(this).addClass("clicked");
// } else if( count % 2 == 0 && !$(this).hasClass(clicked)){
// $(this).css('background-image', 'url(/asserts/o.png)');
// $(this).addClass("clicked");
// }
// count++;
// })
// }
// })
$(document).ready(function () {
$('.first').click(function () {
$('.modal').addClass('active');
$('.modal').click(function () {
$('.modal').removeClass('active');
})
let data = $(this).closest('tr').find("td").toArray();
$('.content p').empty();
for (let i = 0; i < data.length; i++) {
$('.content p').append(data[i].innerText + " ");
}
})
$('.third').click(function () {
$(this).closest('tr').find("td").remove();
})
$('.second').click(function () {
})
}) |
import React from 'react';
import styled from '@emotion/styled';
export const Text = styled.div({
fontSize: '35px',
marginTop: '30%',
textAlign: 'center',
});
export default function NotFoundPage() {
return (
<>
<Text>존재하지 않는 엽서입니다.</Text>
</>
);
}
|
const express = require('express');
const router = express.Router({
mergeParams: true
});
const {
check,
validationResult,
oneOf,
} = require('express-validator/check');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const {
protectedRoute
} = require('../middlewares')
// Require controller modules.
const message_controller = require('../controllers/message');
/// Middlewares
const messageValidation = [
check('message', 'Please provide a message'),
];
const recipientValidation = oneOf(
[
check('to', 'Please provide a valid email or phone number').isMobilePhone(),
check('to', 'Please provide a valid email or phone number').isEmail(),
]
)
/// USER ROUTES ///
// Sending message
router.post('/', recipientValidation, messageValidation, protectedRoute, message_controller.send_message);
// Get/Read a specific message
router.get('/read/:message_id', protectedRoute, message_controller.get_message);
// Delete a specific message
router.delete('/delete/:message_id', protectedRoute, message_controller.delete_message);
// Get all messages
router.get('/all', protectedRoute, message_controller.all_messages);
// Get all received messages
router.get('/received', protectedRoute, message_controller.received_messages);
// Get all sent messages
router.get('/sent', protectedRoute, message_controller.sent_messages);
module.exports = router; |
// Type Coercion - string, number, boolean
console.log( '5' + 5 );
console.log( '5' - 5 );
console.log( '5' == 5 ); |
$(function() {
$( "#dialog" ).dialog({
autoOpen: false,
resizable: true,
height:512,
width:512,
modal: true,
buttons: {
"Rešeno!": function() {
$.ajax({
url: "main/finishOrder",
type: "GET",
data: { order: "done" },
success: function( responseText ) {
location.reload();
}
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
});
|
import Swiper from './swiper.vue'
export default Swiper
|
module.exports = (req, res, next) => {
if(req.user.credits < 1 ){ //if your cedits are less than 1 that means you cant buy
return res.status(403).send({ error: 'You must add credits to your account'});
}
next();
};
//https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
//to see the status code definitions ..res.status(403/401/etc..)
|
import React, { useContext } from 'react';
import Card from '../cards/Card';
import ProfileContext from '../../context/profile/profileContext';
export const Search = () => {
const profileContext = useContext(ProfileContext);
const { serchResult, language } = profileContext;
return (
<div id="search">
{
serchResult && serchResult.experiences && serchResult.experiences.length > 0 &&
<>
<div className="search-title container align-items-center justify-content-center">{language === 'en' ? 'Experiences' : 'Expériences'}</div>
{
serchResult.experiences.map(experience => {
const data = {
title: experience.title,
description: experience.company,
info: experience.location,
start: experience.start,
end: experience.end,
isCurrent: experience.isCurrent,
notes: experience.tasks,
supplements: experience.technologies
};
return <Card key={experience._id} data={data} />
})
}
</>
}
{
serchResult && serchResult.projects && serchResult.projects.length > 0 &&
<>
<div className="search-title container align-items-center justify-content-center">{language === 'en' ? 'Projects' : 'Projets'}</div>
{
serchResult.projects.map(project => {
const data = {
title: project.title,
description: project.client,
info: project.technology,
start: project.start,
end: project.end,
isCurrent: project.isCurrent,
notes: project.tasks
};
return <Card key={project._id} data={data} />
})
}
</>
}
{
serchResult && serchResult.trainings && serchResult.trainings.length > 0 &&
<>
<div className="search-title container align-items-center justify-content-center">{language === 'en' ? 'Trainings' : 'Formations'}</div>
{
serchResult.trainings.map(training => {
const data = {
title: training.title,
description: training.school,
info: training.location,
start: training.start,
end: training.end,
isCurrent: training.isCurrent
};
return <Card key={training._id} data={data} />
})
}
</>
}
</div>
);
}
export default Search;
|
import React from 'react';
import { ScrollView, Text, View, StyleSheet } from 'react-native';
import { ExpoLinksView } from '@expo/samples';
export default function ProfileScreen() {
return (
<ScrollView style={styles.container}>
<View style={styles.profiles}>
<Text>Artist Profile</Text>
</View>
</ScrollView>
);
}
ProfileScreen.navigationOptions = {
title: 'Profile',
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 15,
backgroundColor: '#fff',
},
profiles: {
padding: 10
}
});
|
//------------------------------------//
// Week 1 Day 1 //
//------------------------------------//
/* Numbers
isOdd
Input: A Number.
Output: A Boolean. true if the number is odd, otherwise false*/
// isOdd(2);
// isOdd(5);
// isOdd(-17);
//using num % 2 ===0 and num % 2 !==0, is consider a "catch-all"
//method for integers and floats.
function isOdd(num){
if(num % 2 === 0){
return false;
}
else (num % 2 !== 0)
return true;
};
isOdd(2); //false
isOdd(5); //true
isOdd(-17); //true
isOdd(10.01); //true
/* plusFive
Input: A Number.
Output: A Number. The sum of the input and 5.*/
// plusFive(0); //5
// plusFive(-2); //3
// plusFive(21); //26
function plusFive(num){
return num + 5;
}
plusFive(0); //5
plusFive(21); //26
/* threeOrSeven
Input: A Number.
Output: A Boolean. true if the number is divisible by 3 or 7*/
// threeOrSeven(3); //true
// threeOrSeven(42); //true
// threeOrSeven(8); //false
function threeOrSeven(num){
if(num % 3 === 0 || num % 7 === 0){
return true;
}
else{
return false;
}
};
threeOrSeven(3);
threeOrSeven(42);
threeOrSeven(8);
/* Order of Operations
Evaluate each expression. Check your answer in the console.
1 + 1 * 5
(1 + 1) * 5
1 + 2 - 5 / 6 - 1
5 * 5 % 13
5/(-1 * (5 - (-10))) */
//This is complete and I checked in console area:
1 + 1 * 5 // answer: 10
(1 + 1) * 5 // answer: 10
1 + 2 - 5 / 6 - 1 // answer: 1.16666
5 * 5 % 13 // answer: 12
5/(-1 * (5 - (-10))) // answer: -0.33333
/* Strings
hello
Input: A String.
Output: A String saying "Hello" to the input value.*/
hello("child"); //"Hello, child."
hello("Anthony"); //"Hello, Anthony."
hello("fsfvf"); //"Hello, fsfvf."
function hello(word){
return "Hello, " + word + ".";
}
hello("Anthony");
hello("child");
/* yell
Input: A String. Assume no punctuation.
Output: A String. A yelled version of the input.*/
yell("I want to go to the store"); //"I WANT TO GO TO THE STORE!!!"
yell("Time to program"); //"TIME TO PROGRAM!!!"
function yell(str){
return str.toUpperCase() + "!!!";
}
yell("Time to program");
yell("I want to go to the store");
/* whisper
Input: A String. Assume no punctuation.
Output: A String. A whispered version of the input.
> whisper("Hey Anthony")
"...hey anthony..."
> whisper("YEA! that was fun")
"...yea! that was fun..." */
whisper("Hey Anthony"); //"...hey anthony..."
whisper("YEA! that was fun"); //"...yea! that was fun..."
function whisper(str){
return "..." + str.toLowerCase() + "..."
}
whisper("YEA! that was fun");
whisper("Hey Anthony");
/* isSubstring
Input
1) A String, called searchString.
2) A String, called subString.
Output: A Boolean. true is the subString is apart of the searchString.
> isSubstring("The cat went to the store", "he cat went")
true
> isSubstring("Time to program", "time")
true
> isSubstring("Jump for joy", "joys")
false */
// isSubstring("Time to program", "time"); //true
// isSubstring("Jump for joy", "joys"); //false
//answer - the LONG WAY: Just keep for reference only.
// function isSubstring(searchString, subString){
// for(var i = 0; i < searchString.length; i++){
// // 'i' is defined start and subString.length is the 'length' | str.substr(start[, length])
// var sentence = searchString.substr(i, subString.length);
// if(sentence === subString){
// return true;
// }
// }
// //have the return outside the forloop and if answer is false, the code will exit at this stage.
// return false;
// }
function isSubstring(searchString, subString){
for(var i = 0; i < searchString.length; i++){
// console.log("We are in the for loop for i =", i);
var sentence = searchString.substr(i, subString.length);
if(sentence === subString){
// console.log("In the if statement")
return true;
}
}
// console.log("outside the for loop");
return false;
}
isSubstring("hello there", "there");
isSubstring("Time to program", "Time");
//optional answer: SHORTEST WAY
function isSubstring(searchString, subString){
return searchString.toLowerCase().includes(subString);
}
isSubstring("Time to program", "time");
/* echo
Input: A String.
Output: A String. The input string string echo-ized.
> echo("Mom!")
"MOM! ... Mom! ... mom!"
> echo("hey")
"HEY ... hey ... hey"
> echo("JUMp")
"JUMP ... JUMp ... jump" */
function echo(word){
var upperWord = word.toUpperCase();
var upperLtr = word.charAt(0).toUpperCase();
var remainingString = word.slice(1);
var upperString = upperLtr + remainingString;
var lowerWord = word.toLowerCase();
var stringEcho = upperWord + "..." + upperString + "..." + lowerWord;
return stringEcho;
}
echo("JUMp");
echo("hey");
echo("Mom!");
/* Boolean
isEven
Input: A Number.
Output: A Boolean. true if the number is even, otherwise false
Condition: Must be written in terms of isOdd
> isEven(2)
true
> isEven(5)
false */
function isEven(num){
if(num % 2 === 0){
return true;
}
return false;
};
isEven(5);
isEven(2);
// Write a function isEven(num) which takes as the argument a number.
// It returns a boolean, true if num is even, and false otherwise.
// Your function must use the given function isOdd in your solution.
// isOdd returns true if its argument is odd and false otherwise.
// Examples:
// isEven(2) => true
// isEven(5) => false
// isEven(-55) => false
// one potential answer: Just keep for reference only!
// function isEven(num){
// if(num % 2 === 0){
// return true;
// }
// else{
// return false;
// }
// };
// function isOdd(el){
// if(el % 2 === 0){
// return false;
// }
// else{
// return true;
// }
// };
// isEven(-55);
// isOdd(5);
// BETTER WAY: LEARN TO USE OPERATORS
function isOdd(num){
if(num % 2 !== 0){
return true;
}
else{
return false;
}
}
//constructed function in global scope and invoking
//functions.
function isEven(num){
//input opposite to get false
return !isOdd(num);
}
isEven(7);
//primary data types: numbers, strings, booleans, NAN, undefined, symbol
/*Comments from Rena:
isOdd: I've made revisions based on our Slack discussion.
isEven: I've kept one solution and other serves only as reference.
*/
/*Comment from Paris
isOdd needs a bit of work. I mentioned why in Slack
*/
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery.scrollintoview.min
//= require jquery_ujs
//= require jquery-ui/sortable
//= require local_time
//= require foundation/foundation
//= require foundation/foundation.topbar
//= require foundation/foundation.reveal
//= require foundation/foundation.accordion
//= require_directory .
$(function() {
$(document).foundation();
});
function realign_body_height() {
var el = $("footer");
if (el.length == 0) { return; } // not defined yet
$("body").height($(el).position().top + $(el).height());
}
$(document).ready(function(){
realign_body_height();
$(".alert-box")
.delay(12000)
.fadeOut("slow");
$(".stupidtable").stupidtable().bind('aftertablesort', function (event, data) {
// data.column - the index of the column sorted after a click
// data.direction - the sorting direction (either asc or desc)
var th = $(this).find("th");
$(th).siblings().removeClass('fi-arrow-up fi-arrow-down');
$(th.eq(data.column)).addClass(data.direction === "asc" ? "fi-arrow-up" : "fi-arrow-down")
});
var forms = $(".at_least_one_checked:hidden, .at_least_one_checked:visible");
$(forms)
.find('input[type="radio"], input[type="checkbox"]')
.change(function () {toggle_btns($(this).parents('.at_least_one_checked'));});
$(forms).each(function(){toggle_btns(this);});
});
function toggle_btns(form){
var checked = $(form).find("input:checked").length > 0;
var btn = $(form).find("input[type='submit']");
if (checked) {
$(btn).removeAttr("disabled");
}
else
{
$(btn).attr('disabled', 'disabled');
}
}
$(window).load(function(){ // do again after images load
realign_body_height();
});
$(window).resize(
function() {
realign_body_height();
}
);
function show_alert(alert_class, text) {
$(".alert-box.js")
.text(text)
.removeClass('success warning info alert secondary') // http://foundation.zurb.com/docs/components/alert_boxes.html
.addClass(alert_class)
.show()
.delay(7000)
.fadeOut("slow");
}
|
const express = require('express');
const router = express.Router();
const helper = require('../helper');
const pusher = require('../pusher');
const User = require('../db/controller/user');
let allUsers = [];
module.exports = (passport) => {
router.get('/', helper.isAuth, (req, res) => {
res.send(req.user);
});
router.post('/login', passport.authenticate('login'), (req, res) => {
allUsers.push(req.user.username);
pusher.trigger('Lobby', 'new_user', {
user: allUsers
});
res.status(201);
res.send(req.user.username);
});
router.post('/signup', passport.authenticate('signup'), (req, res) => {
allUsers.push(req.user.username);
pusher.trigger('Lobby', 'new_user', {
user: allUsers
});
res.status(201);
res.send(req.user.username);
});
router.post('/logout', (req, res) => {
req.logout();
res.sendStatus(200);
});
return router;
}; |
import React from 'react';
import PropTypes from 'prop-types';
const Login = (props) => {
const { onSubmit } = props;
return (<div>
<h2>Log in</h2>
<hr />
<form onSubmit={e => {
e.preventDefault();
const email = document.querySelector('#email').value;
const password = document.querySelector('#password').value;
return onSubmit(email, password, props.history.push);
}}>
<div className="form-group">
<label htmlFor="email">Email address:</label>
<input type="email" className="form-control" id="email" placeholder="alan.turing@example.com" />
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input type="password" className="form-control" id="password" placeholder="" />
</div>
<button type="submit" className="btn btn-lg btn-blackletter">Log in</button>
</form>
</div>);
};
Login.propTypes = {
onSubmit: PropTypes.func.isRequired
};
export default Login;
|
import * as React from 'react';
import { View, TouchableOpacity, Text, FlatList, StyleSheet, Image, TouchableHighlight } from 'react-native';
import * as PropTypes from 'prop-types';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import DEFAULT_AVATAR from 'kitsu/assets/img/default_avatar.png';
const styles = StyleSheet.create({
container: {
flex: 1,
},
userList: {
backgroundColor: '#fff',
paddingLeft: 8,
},
userContainer: {
paddingTop: 12,
paddingBottom: 12,
paddingRight: 8,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderBottomColor: '#979797',
borderBottomWidth: StyleSheet.hairlineWidth,
},
userAvatar: {
width: 61,
height: 61,
borderRadius: 61 / 2,
},
userLeftSection: {
flexDirection: 'row',
flex: 7,
},
userRightSection: {
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
flex: 3,
},
userMetaContainer: {
justifyContent: 'center',
marginLeft: 10,
},
userNameText: {
color: '#333333',
fontWeight: '500',
},
userFollowText: {
color: '#616161',
},
actionButton: {
backgroundColor: '#16A085',
borderRadius: 2,
paddingTop: 6,
paddingBottom: 6,
paddingLeft: 25,
paddingRight: 25,
},
actionButtonText: {
color: '#fff',
fontSize: 12,
},
moreIcon: {
color: '#ADADAD',
},
});
const onUserPress = (navigation, userId) => {
navigation.navigate('ProfilePages', { userId });
};
const User = ({ navigation, user, onFollow }) => {
const userAvatar = user.avatar ? { uri: user.avatar.small } : DEFAULT_AVATAR;
const followerTxt = user.followersCount > 1 ? 'followers' : 'follower';
return (
<TouchableOpacity onPress={() => onUserPress(navigation, user.id)} activeOpacity={0.6} style={styles.userContainer}>
<View style={styles.userLeftSection}>
<Image source={userAvatar} style={styles.userAvatar} />
<View style={styles.userMetaContainer}>
<Text style={styles.userNameText}>{user.name}</Text>
<Text style={styles.userFollowText}>{`${user.followersCount} ${followerTxt}`}</Text>
</View>
</View>
{/* <View style={styles.userRightSection}>
<TouchableHighlight style={styles.actionButton} onPress={() => onFollow(user.id)}>
<Text style={styles.actionButtonText}>Follow</Text>
</TouchableHighlight>
<FontAwesome name="ellipsis-v" size={20} style={styles.moreIcon} />
</View> */}
</TouchableOpacity>
);
};
User.propTypes = {
user: PropTypes.object.isRequired,
onFollow: PropTypes.func.isRequired,
navigation: PropTypes.object.isRequired,
};
const UsersList = ({ hits, onFollow, onData, navigation }) => {
// Send users data to reducer to maintain single source of truth
onData(hits);
return (
<FlatList
removeClippedSubviews={false}
data={hits}
style={styles.container}
scrollEnabled
contentContainerStyle={styles.userList}
renderItem={({ item }) => <User key={`${item.name}`} navigation={navigation} user={item} onFollow={onFollow} />}
/>
);
};
UsersList.propTypes = {
hits: PropTypes.array,
onFollow: PropTypes.func.isRequired,
onData: PropTypes.func.isRequired,
navigation: PropTypes.object.isRequired,
};
UsersList.defaultProps = {
hits: [],
refine: () => {},
};
export default UsersList;
|
function firstReverse(str) {
var str= "Hello My Name is Aisha";
return str.split("").reverse().join("");
}
alert(firstReverse());
var firstFactorial= function(num) {
if (num === 1)
{
return 1;
}
return num * firstFactorial( num - 1);
}
alert(firstFactorial(5));
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
//FirstFactorial(readline());
function LongestWord(sen) {
// code goes here
return sen;
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LongestWord(readline());
function LetterChanges(str) {
// code goes here
var letterElements = str.length;
var matchfound = "no";
var alphabetLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", ]
for (var i = 0; i <= lengthOfString; i + +) {
if (letterToCheck = = = alphabetLetters[ i]) {
matchFound = "yes";
alert(" It's one of the cleanest cities");
}
}
return str;
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LetterChanges(readline()); |
var Article = function (object) {
this.title = object.title;
this.category = object.category;
this.author = object.author;
this.authorUrl = object.authorUrl;
this.publishedOn = object.publishedOn;
this.body = object.body;
};
Article.prototype.toHTML = function() {
var $article = $('#article').clone();
$article.find('.title').html(this.title);
$article.find('.category').html(this.category);
$article.find('.author').html(this.author);
$article.find('.authorUrl').html(this.authorUrl);
$article.find('.publishedOn').html(this.publishedOn);
$article.find('.artbod').html(this.body);
$('main').prepend($article);
};
|
import * as test from './common/_test';
import * as test2 from './common/_test2';
test.init();
test2.init();
|
var CallidForm;
var pageSize = 25;
/**********************************************************************站臺管理主頁面**************************************************************************************/
//站臺管理Model
Ext.define('gigade.Sites', {
extend: 'Ext.data.Model',
fields: [
{ name: "map_id", type: "int" },
{ name: "site_id", type: "string" },
{ name: "page_id", type: "string" },
{ name: "area_id", type: "string" },
{ name: "packet_id", type: "string" },
{ name: "site_name", type: "string" },
{ name: "page_name", type: "string" },
{ name: "area_name", type: "string" },
{ name: "packet_name", type: "string" },
{ name: "sort", type: "int" },
{ name: "create_date", type: "string" },
{ name: "update_date", type: "string" },
{ name: "create_user_name", type: "string" }
]
});
var ElementMapStore = Ext.create('Ext.data.Store', {
autoDestroy: true,
pageSize: pageSize,
model: 'gigade.Sites',
proxy: {
type: 'ajax',
url: '/Element/ElementMapList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
Ext.getCmp("gdSites").down('#edit').setDisabled(selections.length == 0);
}
}
});
ElementMapStore.on('beforeload', function () {
Ext.apply(ElementMapStore.proxy.extraParams,
{
siteName: Ext.getCmp('siteName').getRawValue(),
searchType: Ext.getCmp('search_type').getValue()
});
});
Ext.onReady(function () {
var gdSites = Ext.create('Ext.grid.Panel', {
id: 'gdSites',
store: ElementMapStore,
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
columns: [
{ header: BANNERID, dataIndex: 'map_id', width: 60, align: 'center' },
{ header: SITENAME, dataIndex: 'site_name', width: 200, align: 'center' },
{ header: PAGENAME, dataIndex: 'page_name', width: 150, align: 'center' },
{ header: AREANAME, dataIndex: 'area_name', width: 200, align: 'center' },
{ header: PACKETNAME, dataIndex: 'packet_name', width: 200, align: 'center' },
{ header: SORT, dataIndex: 'sort', width: 150, align: 'center' },
{ header: BANNERCREATE, dataIndex: 'create_date', width: 150, align: 'center' },
{ header: BANNERUPDATE, dataIndex: 'update_date', width: 150, align: 'center' },
{ header: UPDATEUSER, dataIndex: 'create_user_name', width: 150, align: 'center' }
],
tbar: [
{ xtype: 'button', text: ADD, id: 'add', hidden: false, iconCls: 'icon-user-add', handler: onAddClick },
{ xtype: 'button', text: EDIT, id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick },
'->',
{
xtype: 'combobox',
fieldLabel: ELEMENTTYPE,
id: 'search_type',
name: 'search_type',
labelWidth: 80,
editable: false,
typeAhead: true,
queryModel: 'local',
forceSelection: false,
store: elementTypeStore,
displayField: 'parameterName',
valueField: 'parameterCode',
emptyText: SELECT,
listeners: {
change: function (newValue, oldValue, e) {
if (newValue) {
if (Ext.getCmp("search_type").getValue() != "") {
Query(1);
}
}
}
}
},
{
xtype: 'textfield', fieldLabel: SITENAME, id: 'siteName', labelWidth: 65, listeners: {
specialkey: function (field, e) {
if (e.getKey() == e.ENTER) {
Query(1);
}
}
}
},
{
xtype: 'button',
text: SEARCH,
iconCls: 'icon-search',
id: 'btnQuery',
handler: Query
},
{
xtype: 'button',
text: RESET,
id: 'btn_reset',
listeners: {
click: function () {
Ext.getCmp("siteName").setValue("");
Ext.getCmp("search_type").setValue("");
// Query(1);
}
}
}
],
bbar: Ext.create('Ext.PagingToolbar', {
store: ElementMapStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
}),
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
selModel: sm
});
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [gdSites],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
gdSites.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
ToolAuthority();
// ElementMapStore.load({ params: { start: 0, limit: 25 } });
});
/*********搜索***********/
function Query(x) {
if ((Ext.getCmp("search_type").getValue() != null && Ext.getCmp("search_type").getValue() != "") || Ext.getCmp("siteName").getValue() != "") {
ElementMapStore.removeAll();
Ext.getCmp("gdSites").store.loadPage(1, {
params: {
siteName: Ext.getCmp('siteName').getRawValue(),
searchType: Ext.getCmp('search_type').getValue()
}
});
}
else {
Ext.Msg.alert(INFORMATION, SEARCH_LIMIT);
}
}
/*************************************************************************************新增*************************************************************************************************/
onAddClick = function () {
//addWin.show();
editFunction(null, ElementMapStore);
}
/*************************************************************************************編輯*************************************************************************************************/
onEditClick = function () {
var row = Ext.getCmp("gdSites").getSelectionModel().getSelection();
//alert(row[0]);
if (row.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
} else if (row.length > 1) {
Ext.Msg.alert(INFORMATION, ONE_SELECTION);
} else if (row.length == 1) {
editFunction(row[0], ElementMapStore);
}
}
|
/*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
*/
// This code counts all permutations of a string.
function permutation(str) {
permutation2(str, "");
}
function permutation2(str, prefix) {
if (str.length == 0) {
console.log(prefix);
} else {
for (var i = 0; i < str.length; i++) {
var rem = str.substring(0, i) + str.substring(i + 1);
permutation2(rem, prefix + str[i]);
}
}
}
console.log(permutation("abcd"));
|
#! /usr/bin/env node
const getStdin = require("get-stdin");
getStdin()
.then((data) => {console.log(data)})
.catch((err) => {console.log(err)})
// POSIX
// process.stdout.write("Hello world\n");
// console.log("Hello world");
// const readable = process.stdin;
// readable.on('readable', () => {
// let chunk;
// console.log('Stream is readable (new data received in buffer)');
// // Use a loop to make sure we read all currently available data
// while (null !== (chunk = readable.read())) {
// console.log(`Read ${chunk.length} bytes of data...`);
// }
// });
// // 'end' will be triggered once when there is no more data available
// readable.on('end', () => {
// console.log('Reached end of stream.');
// }); |
function Header () {
return(
<header id="main-header">
<div>
<title>Graduation</title>
</div>
<div>
<h1>UNIVERSITY GRADUATION</h1>
</div>
</header>
);
}
export default Header; |
jest.unmock('../components/App');
import React from 'react';
import {shallow} from 'enzyme';
import App from '../components/App';
import Store from '../stores/Store';
const store = new Store();
describe('<App />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<App store={store} />);
});
afterEach(() => {
jest.runAllTimers();
});
it('has a h2 with the right content', () => {
expect(wrapper.find('h2').text()).toEqual(`Welcome to the ${store.name} project!!!`);
});
it('has a h3 with the right content', () => {
expect(wrapper.find('h3').text()).toEqual(`This project is a ${store.description}.`);
});
});
|
var router = require('express').Router();
router.get('/new_voted', function(req, res)
{
var eosapp = req.app.get('eosapp');
var bpAccount = req.query.bp_account;
if (typeof bpAccount !== 'string' || bpAccount === '')
{
res.sendStatus(404);
}
else
{
res.json({ accounts: eosapp.getNewVoted(bpAccount) });
}
});
router.get('/new_voted_count', function(req, res)
{
var eosapp = req.app.get('eosapp');
var bpAccount = req.query.bp_account;
if (typeof bpAccount !== 'string' || bpAccount === '')
{
res.sendStatus(404);
}
else
{
var newVoted = eosapp.getNewVoted(bpAccount);
res.json({ count: newVoted.length });
}
});
router.get('/new_unvoted', function(req, res)
{
var eosapp = req.app.get('eosapp');
var bpAccount = req.query.bp_account;
if (typeof bpAccount !== 'string' || bpAccount === '')
{
res.sendStatus(404);
}
else
{
res.json({ accounts: eosapp.getNewUnvoted(bpAccount) });
}
});
router.get('/new_unvoted_count', function(req, res)
{
var eosapp = req.app.get('eosapp');
var bpAccount = req.query.bp_account;
if (typeof bpAccount !== 'string' || bpAccount === '')
{
res.sendStatus(404);
}
else
{
var newUnvoted = eosapp.getNewUnvoted(bpAccount);
res.json({ count: newUnvoted.length });
}
});
router.put('/new_voted', function(req, res)
{
var eosapp = req.app.get('eosapp');
var bpAccount = req.query.bp_account;
if (typeof bpAccount !== 'string' || bpAccount === '')
{
res.sendStatus(404);
}
else
{
//TODO: check req.body.accounts
eosapp.markLocalVoted(bpAccount, req.body.accounts)
.then(() => res.sendStatus(200))
.catch(() => res.sendStatus(500));
}
});
router.put('/new_unvoted', function(req, res)
{
var eosapp = req.app.get('eosapp');
var bpAccount = req.query.bp_account;
if (typeof bpAccount !== 'string' || bpAccount === '')
{
res.sendStatus(404);
}
else
{
//TODO: check req.body.accounts
eosapp.markLocalUnvoted(bpAccount, req.body.accounts)
.then(() => res.sendStatus(200))
.catch(() => res.sendStatus(500));
}
});
module.exports = router; |
app.controller('resourceAddCtrl', function ($scope, $location, resourceSvc, resourceUtilSvc, errorMngrSvc) {
$scope.resource = {};
resourceUtilSvc.createResourceAddFormModel()
.then(function (model) {
$scope.locations = model;
}, function (error) {
errorMngrSvc.handleError();
});
$scope.addResource = function (resource) {
resourceSvc.addResource(resource)
.then(function (data) {
$location.url('/Resources');
}, function (reason) {
errorMngrSvc.handleError(reason);
});
}
}); |
import React from 'react';
import { Col, Row } from '@ctkit/layout';
import Button from '@ctkit/button';
import { styled } from '@ctkit/theme';
import { CardsStyle } from './styles';
export default (function (_ref) {
var loading = _ref.loading,
title = _ref.title,
description = _ref.description,
cta = _ref.cta,
items = _ref.items;
//TODO: Eanble Skeleton and loading mode
if (!items || items.length !== 3) {
console.warn('expected: features.length.3');
return null;
}
return React.createElement(CardsStyle, null, React.createElement("div", {
className: "clearfix text-center mb-5"
}, React.createElement(Title, {
className: "ui-title"
}, title), React.createElement(SubTitle, {
className: "ui-sub-title"
}, description)), React.createElement("div", {
className: "mt-5 mb-5 clearfix"
}, React.createElement(Row, null, items.map(function (item, index) {
return React.createElement(Col, {
md: 4,
className: "text-center",
key: index
}, React.createElement(ItemImgHolder, {
className: "item-img"
}, React.createElement("img", {
src: item.img,
alt: "",
width: 40
})), React.createElement(ItemTitle, {
className: "item-title"
}, item.title), React.createElement(ItemDesc, {
className: "item-desc"
}, item.description));
}))), cta && React.createElement("div", {
className: "clearfix text-center ui-action mt-5"
}, React.createElement(Button, {
ghost: true
}, cta.text)));
});
var Title = styled.h4.withConfig({
displayName: "Features1__Title",
componentId: "sc-14huxxz-0"
})(["line-height:1.1;font-weight:600;display:inline-block;width:'50%'"]);
var SubTitle = styled.p.withConfig({
displayName: "Features1__SubTitle",
componentId: "sc-14huxxz-1"
})(["line-height:1.2;display:inline-block;width:80%;color:#9999;"]);
var ItemTitle = styled.h5.withConfig({
displayName: "Features1__ItemTitle",
componentId: "sc-14huxxz-2"
})(["font-weight:500;display:block;"]);
var ItemImgHolder = styled.div.withConfig({
displayName: "Features1__ItemImgHolder",
componentId: "sc-14huxxz-3"
})(["width:40px;height:40px;margin:auto;overflow:hidden;"]);
var ItemDesc = styled.p.withConfig({
displayName: "Features1__ItemDesc",
componentId: "sc-14huxxz-4"
})(["padding:0 20px;font-size:0.9em;"]); |
var globalUrl = new Object();
var ctx;
//swagger路径配置-------------------------start-------------------------
//// 用户管理
//url.user = 'http://192.168.80.110:8080/wms-web-user';
//// 系统管理
////url.symgr = 'http://192.168.80.110:8080/wms-web-symgr';
//swagger本地路径配置-------------------------end-------------------------
//线上路径配置-------------------------start-------------------------
////测试环境地址
//url.path='http://192.168.80.39:8080';
////映射地址
//url.path='http://183.57.45.146:9205';
//本地地址
//url.path='http://localhost:8080';
//系统模块地址
globalUrl.symgmtPath='http://test.coewms.com:8080/wms-web-symgmt';
//入库订单模块地址
globalUrl.inwarehousePath='http://test.coewms.com:8080';
//出库订单模块地址
globalUrl.outwarehousePath='http://test.coewms.com:8080';
//基础信息模块地址
globalUrl.basePath='http://test.coewms.com:8080';
//库存模块地址
globalUrl.inventoryPath='http://test.coewms.com:8080';
//报表模块地址
globalUrl.reportPath='http://test.coewms.com:8080';
//线上路径配置-------------------------end-------------------------
|
import React, { PropTypes } from 'react';
require('./button.scss');
const Button = props => (
<button {...props} className="button" type="button">{props.children}</button>
);
Button.propTypes = {
children: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]),
};
export default Button;
|
const express = require("express")
let app = express()
const port = 3000
app.set('view engine', 'ejs')
app.use(express.json())
app.use(express.static('public'))
app.use('/css', express.static(__dirname+ 'public/css'))
app.use('/css', express.static(__dirname+ 'public/img'))
app.get('/', (req,res)=>{
res.render("home.ejs")
})
app.get('/about', (req,res)=>{
res.render("about.ejs")
})
app.get('/gutter-cleaning', (req,res)=>{
res.render("gutter.ejs")
})
app.get('/roof-cleaning', (req,res)=>{
res.render("roof.ejs")
})
app.get('/roof&gutter-cleaning', (req,res)=>{
res.render("both.ejs")
})
app.get('/pricing', (req,res)=>{
res.render("pricing.ejs")
})
app.get('/contact', (req,res)=>{
res.render("contact.ejs")
})
app.listen(port, () => console.info('Listening to port 3000')) |
var app = angular.module("komGikkApp");
app.controller("timeCtrl", function($scope, $http, $filter, properties, activityService, timeEventService) {
var prevDate;
var selectedDate;
var nextDate;
function getEvents(year, month, day) {
$http.get(properties.timeeventUrl + "/list/" + year + "/" + month + "/" + day)
.success(function(returnValue) {
timeEventService.addAllTimeEvents($scope.data, returnValue.events);
prevDate = new Date(returnValue.prevDate.year, returnValue.prevDate.month-1, returnValue.prevDate.day);
selectedDate = new Date(returnValue.selectedDate.year, returnValue.selectedDate.month-1, returnValue.selectedDate.day);
if (returnValue.nextDate) {
nextDate = new Date(returnValue.nextDate.year, returnValue.nextDate.month-1, returnValue.nextDate.day);
}
$scope.loadingState.timeEventLoaded = true;
})
.error(function (error) {
console.log("Feil ved henting av timeevents: " + error);
$scope.data.error = error;
});
}
getEvents(0, 0, 0);
function postNewTimeEvent(json) {
$http.post(properties.timeeventUrl, json)
.success(function(returnValue) {
timeEventService.addNewTimeEvent($scope.data, returnValue);
})
}
function leftPad(s, pad) {
var str = "" + s;
return pad.substring(0, pad.length - str.length) + str
}
$scope.showPreviousDay = function() {
getEvents(prevDate.getFullYear(), prevDate.getMonth()+1, prevDate.getDate());
};
$scope.showNextDay = function() {
getEvents(nextDate.getFullYear(), nextDate.getMonth()+1, nextDate.getDate());
};
$scope.showNextDayButton = function() {
return !!nextDate;
};
$scope.verboseToday = function() {
if (selectedDate) {
var dager = ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'];
return dager[selectedDate.getDay()] + " " + leftPad(selectedDate.getDate(), '00') + "." + leftPad(selectedDate.getMonth()+1, '00');
}
};
$scope.doStart = function() {
postNewTimeEvent("{\"key\":\"" + $scope.data.activities.startDayActivity.key + "\"}");
};
$scope.doStartExtra = function() {
postNewTimeEvent("{\"key\":\"" + $scope.data.activities.startExtraSession.key + "\"}");
};
$scope.doEnd = function() {
postNewTimeEvent("{\"key\":\"" + $scope.data.activities.endDayActivity.key + "\"}");
};
$scope.doEndExtra = function() {
postNewTimeEvent("{\"key\":\"" + $scope.data.activities.endExtraSession.key + "\"}");
};
$scope.startActivity = function (activity) {
postNewTimeEvent("{\"key\":\"" + activity.key + "\"}");
};
$scope.showStart = function() {
return $scope.loadingState.isReadyForUserInteraction() && !$scope.data.events.isStarted;
};
$scope.showEnd = function() {
return $scope.data.events.isStarted && !$scope.data.events.isEnded;
};
$scope.showStartExtra = function() {
return $scope.data.events.isEnded && !$scope.data.events.isExtraOngoing;
};
$scope.showEndExtra = function() {
return $scope.data.events.isEnded && $scope.data.events.isExtraOngoing;
};
$scope.filterActivities = function(activity) {
return !activity.defaultType;
};
$scope.showActivityButtons = function() {
return ($scope.data.events.isStarted && !$scope.data.events.isEnded) || $scope.data.events.isExtraOngoing;
};
$scope.activityButtonClass = function(activity) {
if ($scope.data.events.currentAction == null) {
return "btn-primary";
}
if ($scope.data.events.currentAction.key == activity.key) {
return "btn-info"
}
return "btn-primary";
};
$scope.getActivityName = function(activityKey) {
if (angular.isUndefined(activityKey)) {
return "";
}
return activityService.findActivityByKey(activityKey, $scope.data).name;
};
$scope.filterEvent = function(event) {
return event.isDeleted !== true;
};
$scope.showActivities = function(event) {
if(event.activityKey) {
return activityService.findActivityByKey(event.activityKey, $scope.data).name;
}
return '';
};
$scope.checkTime = function(data, event) {
console.log("checkTime");
//todo impl
//returner string som eventuel feilmelding
return true;
};
$scope.deleteEvent = function(event) {
event.isDeleted = true;
};
$scope.addEvent = function() {
var date = selectedDate;
$scope.data.events.list.push({
time: date.getHours() + ":" + date.getMinutes(),
date: date.getDate() + "." + (date.getMonth()+1) + "." + date.getFullYear(),
activity: {
key: null
},
isNew: true
});
};
$scope.saveTable = function() {
console.log("saveTable");
$http.put(properties.timeEventListUrl, $scope.data.events.list)
.success(function(returnValue) {
timeEventService.addAllTimeEvents($scope.data, returnValue);
})
};
$scope.cancel = function() {
for (var i = $scope.data.events.list.length; --i;) {
var event = $scope.data.events.list[i];
//remove deleted flag
if (event.isDeleted) {
delete event.isDeleted;
}
if (event.isNew) {
$scope.data.events.list.splice(i, 1);
}
}
};
$scope.rowClass = function(event) {
if (event.activity.defaultType == 'START_EXTRA') {
return "thickRow";
}
}
}); |
export default function() {
this.namespace = '/api';
let rentals = [{
type: 'rentals',
id: 'comanche-niagara-comp',
attributes: {
title: 'Comanche Niagara Comp',
owner: 'Veruca Salt',
rentalpoint: 'Москва',
type: 'Горный',
bedrooms: 24,
image: '../assets/serviceImages/Merida_Matts_6.15.jpg',
description: "Convenience is at your doorstep with this charming downtown rental. Great restaurants and active night life are within a few feet."
}
}, {
type: 'rentals',
id: 'norco-torm-7.2',
attributes: {
title: 'Norco Storm 7.2',
owner: 'Mike Teavee',
rentalpoint: 'Пермь',
type: 'Дорожный',
bedrooms: 21,
image: '../assets/serviceImages/Comanche_ONTARIO_FLY_26.jpg',
description: "Convenience is at your doorstep with this charming downtown rental. Great restaurants and active night life are within a few feet."
}
}, {
type: 'rentals',
id: 'gt-avalanche-comp',
attributes: {
title: 'GT AVALANCHE COMP',
owner: 'Mike Teavee',
rentalpoint: 'Пермь',
type: 'Дорожный',
bedrooms: 24,
image: '../assets/serviceImages/Comanche_ONTARIO_FLY_26.jpg',
description: "Convenience is at your doorstep with this charming downtown rental. Great restaurants and active night life are within a few feet."
}
}, {
type: 'rentals',
id: 'trek-2015-3500',
attributes: {
title: 'Trek-2015 3500',
owner: 'Violet Beauregarde',
rentalpoint: 'Пермь',
type: 'Дорожный',
bedrooms: 18,
image: '../assets/serviceImages/Merida_Matts_6.15.jpg',
description: "Convenience is at your doorstep with this charming downtown rental. Great restaurants and active night life are within a few feet."
}
}, {
type: 'rentals',
id: 'trek-2015-3500',
attributes: {
title: 'Trek-2015 3500',
owner: 'Violet Beauregarde',
rentalpoint: 'Пермь',
type: 'Дорожный',
bedrooms: 18,
image: '../assets/serviceImages/Merida_Matts_6.15.jpg',
description: "Convenience is at your doorstep with this charming downtown rental. Great restaurants and active night life are within a few feet."
}
}];
this.get('/rentals', function(db, request) {
if(request.queryParams.rentalpoint !== undefined) {
let filteredRentals = rentals.filter(function(i) {
return i.attributes.rentalpoint.toLowerCase().indexOf(request.queryParams.rentalpoint.toLowerCase()) !== -1;
});
return { data: filteredRentals };
} else {
return { data: rentals };
}
});
this.get('/rentals/:id', function (db, request) {
return { data: rentals.find((rental) => request.params.id === rental.id) };
});
this.get('/history-rents', function(db, request) {
if (!Ember.isNone(request.queryParams.id)) {
return { data: db.db.historyRents.where(function(paramId) {
return paramId.attributes.rentalid === request.queryParams.id})
};
} else {
return { data: db.db.historyRents};
}
});
this.post('/history-rents', function (db, request) {
let obj = JSON.parse(request.requestBody);
db.db.historyRents.insert(obj.data);
return obj;
});
}; |
/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
require('sweetalert');
require('slug');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('example', require('./components/Example.vue'));
Vue.component('pages', require('./components/Pages/Pages.vue'));
Vue.component('page-create', require('./components/Pages/PageCreate.vue'));
Vue.component('page-edit', require('./components/Pages/PageEdit.vue'));
Vue.component('users', require('./components/Users/Users.vue'));
Vue.component('user-view', require('./components/Users/UserView.vue'));
// Vue.component('chat-messages', require('./components/Chat/ChatMessages.vue'));
// Vue.component('chat-form', require('./components/Chat/ChatForm.vue'));
Vue.component('ptv', require('./components/PTV/PTV.vue'));
Vue.use(require('vue-resource'));
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#csrf-token').getAttribute('content');
const app = new Vue({
el: '#app',
data: {
messages: []
},
created() {
this.fetchMessages();
Echo.private('chat')
.listen('MessageSent', (e) => {
console.log(e);
this.messages.push({
message: e.message.message,
user: e.user
});
});
},
methods: {
fetchMessages() {
axios.get('/messages').then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.push(message);
axios.post('/messages', message).then(response => {
console.log(response.data);
});
}
}
});
|
export default [
{
path: '/content',
//可以在打包的时候进行代码分片,并异步加载分片后的代码,此方法在官方中是不建议使用的
// component: resolve => {
// require.ensure([], () => {
// resolve(require('../views/content/Main.vue'))
// })
// },
component: require('../views/content/Main.vue').default,
// component: import('../views/content/Main.vue').default,
children: [
{
path: 'now',
name: 'content-now',
// component: resolve => {
// require.ensure([], () => {
// resolve(require('../views/content/Now.vue'))
// })
// },
component: require('../views/content/Now.vue').default,
// component: import('../views/content/Now.vue').default,
},
{
path: 'future',
name: 'content-future',
component: require('../views/content/Future.vue').default
},
{
path: 'before',
name: 'content-before',
component: require('../views/content/Before.vue').default
}
]
}
] |
const db = require("../models/index");
const Orders_Products = db.sequelize.define(
"Orders_Products",
{
Orders_ProductsID: {
type: db.Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
ProductID: {
type: db.Sequelize.INTEGER,
allowNull: false,
},
OrderID: {
type: db.Sequelize.INTEGER,
allowNull: false,
},
Quantity: {
type: db.Sequelize.INTEGER,
allowNull: true,
},
},
{
tableName: "Orders_Products",
timestamps: false,
}
);
module.exports = Orders_Products;
|
$(document).ready(function(){
$.localScroll({
queue:true,
duration:1000,
hash:true
});
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
// Initiale Naviklassen vergeben
$('header:first').addClass($('header nav li:first-child a').attr('class'));
$('header nav li:first-child a').addClass('active');
$(window).scroll(function () {
var inviewid = $("section:in-viewport:first").attr('id');
// Beim scrollen die sichtbare Klasse der Navigation geben
waitForFinalEvent(function(){
$('header:first').removeClass().addClass(inviewid);
$('header nav a').removeClass('active');
$('header nav a.'+ inviewid).addClass('active');
}, 50, "asideWidth");
});
});
|
'use strict';
angular
.module('playgroundApp')
.controller(
'SignupCtrl',
[
'$scope',
'$location',
'UserService',
function ($scope, $location, UserService) {
$scope.user = {
username: "test",
email: "test@test.com",
password: "test"
};
$scope.error = null;
$scope.submitted = false;
$scope.register = function(form) {
$scope.error = null;
$scope.submitted = true;
if(form.$valid) {
UserService
.save(
$scope.user,
function(data) {
// Przekieruj do widoku logowania
$location.path('/login');
},
function(err) {
$scope.submitted = false;
$scope.error = err.data;
}
);
}
};
}
]
);
|
import {System} from 'gml-system';
import 'gml-polyfills';
import {version, author, name, description} from '../../package.json';
const system = System({
ua: window.navigator.userAgent,
config: { name, version, author, description }
});
window.system = system;
const statements = {};
const folders = require.context("./statements/", true, /.js/);
folders.keys().forEach((filename) => {
statements[filename.replace('./', '').replace('.js', '')] = folders(filename).default;
});
const gosFolders = require.context("./components/", true, /.index\.js/);
const Gos = gosFolders.keys().map((filename) => {
const name = filename.substr(2, filename.lastIndexOf('/') - 2);
return { name, init: gosFolders(filename).default };
});
(async function () {
const thread = system.createThread(() => Object.create({ statements, gos: {} }));
thread.execute('set-up-environment');
await thread.execute('create-store');
await thread.execute(async function () {
const gos = {};
const locale = await system.locale('/localization/static.json');
await locale.load('/localization/globalize/it.json');
await locale.load('/localization/system/it.json');
this.locale = locale;
for (let index = 0; index < Gos.length; index++) {
gos[Gos[index].name] = await Gos[index].init({ locale, system, thread, gos });
}
thread.inject({ gos });
});
thread.execute('set-up-navigation');
await thread.execute('load-resources');
thread.execute(function ({ gos }) {
document.getElementById('header').appendChild(gos.header.get());
document.getElementById('menu').appendChild(gos.menuHeader.get());
document.getElementById('menu').appendChild(gos.menuItems.get());
});
thread.execute(function () {
return system.navigateTo(this.redirectUrl);
});
})();
|
{ location:
{ _url:
{ protocol: 'http:',
slashes: true,
auth: null,
host: 'widget.tippebannere.no',
port: null,
hostname: 'widget.tippebannere.no',
hash: null,
search: null,
query: null,
pathname: '/v3/2.0/Frontbox.aspx',
path: '/v3/2.0/Frontbox.aspx',
href: 'http://widget.tippebannere.no/v3/2.0/Frontbox.aspx' },
_window:
{ location: [Circular],
history: [Object],
addEventListener: [Function],
removeEventListener: [Function],
dispatchEvent: [Function],
raise: [Function],
setTimeout: [Function],
setInterval: [Function],
clearInterval: [Function: stopTimer],
clearTimeout: [Function: stopTimer],
__stopAllTimers: [Function: stopAllTimers],
run: [Function],
getGlobal: [Function],
dispose: [Function],
top: [Object],
parent: [Object],
self: [Circular],
frames: [Circular],
window: [Circular],
document: [Object],
_frame: [Function] } },
history:
{ _states: [ [Object] ],
_index: 0,
_window:
{ location: [Object],
history: [Circular],
addEventListener: [Function],
removeEventListener: [Function],
dispatchEvent: [Function],
raise: [Function],
setTimeout: [Function],
setInterval: [Function],
clearInterval: [Function: stopTimer],
clearTimeout: [Function: stopTimer],
__stopAllTimers: [Function: stopAllTimers],
run: [Function],
getGlobal: [Function],
dispose: [Function],
top: [Object],
parent: [Object],
self: [Circular],
frames: [Circular],
window: [Circular],
document: [Object],
_frame: [Function] },
_location: { _url: [Object], _window: [Object] } },
addEventListener: [Function],
removeEventListener: [Function],
dispatchEvent: [Function],
raise: [Function],
setTimeout: [Function],
setInterval: [Function],
clearInterval: [Function: stopTimer],
clearTimeout: [Function: stopTimer],
__stopAllTimers: [Function: stopAllTimers],
run: [Function],
getGlobal: [Function],
dispose: [Function],
top:
{ '0': [Getter],
location: { _url: [Object], _window: [Object] },
history:
{ _states: [Object],
_index: 0,
_window: [Object],
_location: [Object] },
addEventListener: [Function],
removeEventListener: [Function],
dispatchEvent: [Function],
raise: [Function],
setTimeout: [Function],
setInterval: [Function],
clearInterval: [Function: stopTimer],
clearTimeout: [Function: stopTimer],
__stopAllTimers: [Function: stopAllTimers],
run: [Function],
getGlobal: [Function],
dispose: [Function],
top: [Circular],
parent: [Circular],
self: [Circular],
frames: [Circular],
window: [Circular],
document:
{ _childNodes: [Object],
_ownerDocument: [Circular],
_attributes: [Object],
_nodeName: '#document',
_childrenList: null,
_version: 7867,
_nodeValue: null,
_parentNode: null,
_memoizedQueries: [Object],
_readonly: false,
_tagName: '#document',
_contentType: 'text/html',
_doctype: [Object],
_implementation: [Object],
_documentElement: [Object],
_ids: [Object],
_attached: true,
_referrer: undefined,
_cookie: undefined,
_cookieDomain: '127.0.0.1',
_URL: 'http://www.ba.no/?ads=placeholder',
_documentRoot: 'http://www.ba.no',
_queue: [Object],
readyState: 'complete',
location: [Object],
_listeners: [Object],
_parentWindow: [Circular],
errors: [Object],
_nwmatcher: [Object] },
_frame: [Function],
_length: 1,
constructor: [Function: DOMWindow],
length: 1,
close: [Function],
getComputedStyle: [Function],
console:
{ log: [Function],
info: [Function],
warn: [Function],
error: [Function],
_window: [Object] },
navigator:
{ userAgent: [Getter],
appName: [Getter],
platform: [Getter],
appVersion: [Getter],
noUI: true,
cookieEnabled: [Getter] },
XMLHttpRequest: [Function],
name: 'nodejs',
innerWidth: 1024,
innerHeight: 768,
outerWidth: 1024,
outerHeight: 768,
pageXOffset: 0,
pageYOffset: 0,
screenX: 0,
screenY: 0,
screenLeft: 0,
screenTop: 0,
scrollX: 0,
scrollY: 0,
scrollTop: 0,
scrollLeft: 0,
alert: [Function],
blur: [Function],
confirm: [Function],
createPopup: [Function],
focus: [Function],
moveBy: [Function],
moveTo: [Function],
open: [Function],
print: [Function],
prompt: [Function],
resizeBy: [Function],
resizeTo: [Function],
scroll: [Function],
scrollBy: [Function],
scrollTo: [Function],
screen: { width: 0, height: 0 },
Image: [Function],
Int8Array: [Function: Int8Array],
Int16Array: [Function: Int16Array],
Int32Array: [Function: Int32Array],
Float32Array: [Function: Float32Array],
Float64Array: [Function: Float64Array],
Uint8Array: [Function: Uint8Array],
Uint8ClampedArray: [Function: Uint8ClampedArray],
Uint16Array: [Function: Uint16Array],
Uint32Array: [Function: Uint32Array],
ArrayBuffer: [Function: ArrayBuffer],
NodeFilter:
{ [Function]
acceptNode: [Function],
SHOW_ALL: 4294967295,
SHOW_ELEMENT: 1,
SHOW_ATTRIBUTE: 2,
SHOW_TEXT: 4,
SHOW_CDATA_SECTION: 8,
SHOW_ENTITY_REFERENCE: 16,
SHOW_ENTITY: 32,
SHOW_PROCESSING_INSTRUCTION: 64,
SHOW_COMMENT: 128,
SHOW_DOCUMENT: 256,
SHOW_DOCUMENT_TYPE: 512,
SHOW_DOCUMENT_FRAGMENT: 1024,
SHOW_NOTATION: 2048,
FILTER_ACCEPT: 1,
FILTER_REJECT: 2,
FILTER_SKIP: 3 },
_parser: undefined,
_parsingMode: 'auto',
_augmented: true,
languageProcessors: { javascript: [Function] },
resourceLoader:
{ load: [Function],
enqueue: [Function],
baseUrl: [Function],
resolve: [Function],
download: [Function],
readFile: [Function] },
HTMLCollection: [Function: HTMLCollection],
HTMLOptionsCollection: [Function: HTMLCollection],
HTMLDocument: [Function: HTMLDocument],
HTMLElement: { [Function] _init: undefined },
HTMLFormElement: { [Function] _init: undefined },
HTMLLinkElement: { [Function] _init: [Function] },
HTMLMetaElement: { [Function] _init: undefined },
HTMLHtmlElement: { [Function] _init: undefined },
HTMLHeadElement: { [Function] _init: undefined },
HTMLTitleElement: { [Function] _init: undefined },
HTMLBaseElement: { [Function] _init: undefined },
HTMLIsIndexElement: { [Function] _init: undefined },
HTMLStyleElement: { [Function] _init: [Function] },
HTMLBodyElement: { [Function] _init: undefined },
HTMLSelectElement: { [Function] _init: undefined },
HTMLOptGroupElement: { [Function] _init: undefined },
HTMLOptionElement: { [Function] _init: undefined },
HTMLInputElement: { [Function] _init: [Function] },
HTMLTextAreaElement: { [Function] _init: undefined },
HTMLButtonElement: { [Function] _init: undefined },
HTMLLabelElement: { [Function] _init: undefined },
HTMLFieldSetElement: { [Function] _init: undefined },
HTMLLegendElement: { [Function] _init: undefined },
HTMLUListElement: { [Function] _init: undefined },
HTMLOListElement: { [Function] _init: undefined },
HTMLDListElement: { [Function] _init: undefined },
HTMLDirectoryElement: { [Function] _init: undefined },
HTMLMenuElement: { [Function] _init: undefined },
HTMLLIElement: { [Function] _init: undefined },
HTMLCanvasElement: { [Function] _init: undefined },
HTMLDivElement: { [Function] _init: undefined },
HTMLParagraphElement: { [Function] _init: undefined },
HTMLHeadingElement: { [Function] _init: undefined },
HTMLQuoteElement: { [Function] _init: undefined },
HTMLPreElement: { [Function] _init: undefined },
HTMLBRElement: { [Function] _init: undefined },
HTMLBaseFontElement: { [Function] _init: undefined },
HTMLFontElement: { [Function] _init: undefined },
HTMLHRElement: { [Function] _init: undefined },
HTMLModElement: { [Function] _init: undefined },
HTMLAnchorElement: { [Function] _init: undefined },
HTMLImageElement: { [Function] _init: undefined },
HTMLObjectElement: { [Function] _init: undefined },
HTMLParamElement: { [Function] _init: undefined },
HTMLAppletElement: { [Function] _init: undefined },
HTMLMapElement: { [Function] _init: undefined },
HTMLAreaElement: { [Function] _init: undefined },
HTMLScriptElement: { [Function] _init: [Function] },
HTMLTableElement: { [Function] _init: undefined },
HTMLTableCaptionElement: { [Function] _init: undefined },
HTMLTableColElement: { [Function] _init: undefined },
HTMLTableSectionElement: { [Function] _init: undefined },
HTMLTableRowElement: { [Function] _init: undefined },
HTMLTableCellElement: { [Function] _init: undefined },
HTMLFrameSetElement: { [Function] _init: undefined },
HTMLFrameElement: { [Function] _init: [Function] },
HTMLIFrameElement: { [Function] _init: undefined },
INVALID_STATE_ERR: 11,
SYNTAX_ERR: 12,
INVALID_MODIFICATION_ERR: 13,
NAMESPACE_ERR: 14,
INVALID_ACCESS_ERR: 15,
StyleSheet: [Function: StyleSheet],
MediaList: [Function: MediaList],
CSSStyleSheet: [Function: CSSStyleSheet],
CSSRule:
{ [Function: CSSRule]
STYLE_RULE: 1,
IMPORT_RULE: 3,
MEDIA_RULE: 4,
FONT_FACE_RULE: 5,
PAGE_RULE: 6,
WEBKIT_KEYFRAMES_RULE: 8,
WEBKIT_KEYFRAME_RULE: 9 },
CSSStyleRule: { [Function: CSSStyleRule] parse: [Function] },
CSSMediaRule: [Function: CSSMediaRule],
CSSImportRule: [Function: CSSImportRule],
CSSStyleDeclaration: [Function: CSSStyleDeclaration],
StyleSheetList: [Function],
mapper: [Function],
memoizeQuery: [Function],
mapDOMNodes: [Function],
visitTree: [Function],
markTreeReadonly: [Function],
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10,
exceptionMessages:
{ '1': 'Index size error',
'2': 'DOMString size error',
'3': 'Hierarchy request error',
'4': 'Wrong document',
'5': 'Invalid character',
'6': 'No data allowed',
'7': 'No modification allowed',
'8': 'Not found',
'9': 'Not supported',
'10': 'Attribute in use',
NAMESPACE_ERR: 'Invalid namespace' },
DOMException:
{ [Function]
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10 },
NodeList: [Function: NodeList],
DOMImplementation: [Function: DOMImplementation],
Node:
{ [Function: Node]
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12,
DOCUMENT_POSITION_DISCONNECTED: 1,
DOCUMENT_POSITION_PRECEDING: 2,
DOCUMENT_POSITION_FOLLOWING: 4,
DOCUMENT_POSITION_CONTAINS: 8,
DOCUMENT_POSITION_CONTAINED_BY: 16,
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32 },
NamedNodeMap: [Function: NamedNodeMap],
AttributeList: [Function: AttributeList],
NotationNodeMap: [Function: NotationNodeMap],
EntityNodeMap: [Function: EntityNodeMap],
Element: [Function: Element],
memoizeQueryType: 11,
DocumentFragment: [Function: DocumentFragment],
ProcessingInstruction: [Function: ProcessingInstruction],
Document: [Function: Document],
CharacterData: [Function: CharacterData],
Attr: [Function: Attr],
Text: [Function: Text],
Comment: [Function: Comment],
CDATASection: [Function: CDATASection],
DocumentType: [Function: DocumentType],
Notation: [Function: Notation],
Entity: [Function: Entity],
EntityReference: [Function: EntityReference] },
parent:
{ '0': [Getter],
location: { _url: [Object], _window: [Object] },
history:
{ _states: [Object],
_index: 0,
_window: [Object],
_location: [Object] },
addEventListener: [Function],
removeEventListener: [Function],
dispatchEvent: [Function],
raise: [Function],
setTimeout: [Function],
setInterval: [Function],
clearInterval: [Function: stopTimer],
clearTimeout: [Function: stopTimer],
__stopAllTimers: [Function: stopAllTimers],
run: [Function],
getGlobal: [Function],
dispose: [Function],
top: [Circular],
parent: [Circular],
self: [Circular],
frames: [Circular],
window: [Circular],
document:
{ _childNodes: [Object],
_ownerDocument: [Circular],
_attributes: [Object],
_nodeName: '#document',
_childrenList: null,
_version: 7867,
_nodeValue: null,
_parentNode: null,
_memoizedQueries: [Object],
_readonly: false,
_tagName: '#document',
_contentType: 'text/html',
_doctype: [Object],
_implementation: [Object],
_documentElement: [Object],
_ids: [Object],
_attached: true,
_referrer: undefined,
_cookie: undefined,
_cookieDomain: '127.0.0.1',
_URL: 'http://www.ba.no/?ads=placeholder',
_documentRoot: 'http://www.ba.no',
_queue: [Object],
readyState: 'complete',
location: [Object],
_listeners: [Object],
_parentWindow: [Circular],
errors: [Object],
_nwmatcher: [Object] },
_frame: [Function],
_length: 1,
constructor: [Function: DOMWindow],
length: 1,
close: [Function],
getComputedStyle: [Function],
console:
{ log: [Function],
info: [Function],
warn: [Function],
error: [Function],
_window: [Object] },
navigator:
{ userAgent: [Getter],
appName: [Getter],
platform: [Getter],
appVersion: [Getter],
noUI: true,
cookieEnabled: [Getter] },
XMLHttpRequest: [Function],
name: 'nodejs',
innerWidth: 1024,
innerHeight: 768,
outerWidth: 1024,
outerHeight: 768,
pageXOffset: 0,
pageYOffset: 0,
screenX: 0,
screenY: 0,
screenLeft: 0,
screenTop: 0,
scrollX: 0,
scrollY: 0,
scrollTop: 0,
scrollLeft: 0,
alert: [Function],
blur: [Function],
confirm: [Function],
createPopup: [Function],
focus: [Function],
moveBy: [Function],
moveTo: [Function],
open: [Function],
print: [Function],
prompt: [Function],
resizeBy: [Function],
resizeTo: [Function],
scroll: [Function],
scrollBy: [Function],
scrollTo: [Function],
screen: { width: 0, height: 0 },
Image: [Function],
Int8Array: [Function: Int8Array],
Int16Array: [Function: Int16Array],
Int32Array: [Function: Int32Array],
Float32Array: [Function: Float32Array],
Float64Array: [Function: Float64Array],
Uint8Array: [Function: Uint8Array],
Uint8ClampedArray: [Function: Uint8ClampedArray],
Uint16Array: [Function: Uint16Array],
Uint32Array: [Function: Uint32Array],
ArrayBuffer: [Function: ArrayBuffer],
NodeFilter:
{ [Function]
acceptNode: [Function],
SHOW_ALL: 4294967295,
SHOW_ELEMENT: 1,
SHOW_ATTRIBUTE: 2,
SHOW_TEXT: 4,
SHOW_CDATA_SECTION: 8,
SHOW_ENTITY_REFERENCE: 16,
SHOW_ENTITY: 32,
SHOW_PROCESSING_INSTRUCTION: 64,
SHOW_COMMENT: 128,
SHOW_DOCUMENT: 256,
SHOW_DOCUMENT_TYPE: 512,
SHOW_DOCUMENT_FRAGMENT: 1024,
SHOW_NOTATION: 2048,
FILTER_ACCEPT: 1,
FILTER_REJECT: 2,
FILTER_SKIP: 3 },
_parser: undefined,
_parsingMode: 'auto',
_augmented: true,
languageProcessors: { javascript: [Function] },
resourceLoader:
{ load: [Function],
enqueue: [Function],
baseUrl: [Function],
resolve: [Function],
download: [Function],
readFile: [Function] },
HTMLCollection: [Function: HTMLCollection],
HTMLOptionsCollection: [Function: HTMLCollection],
HTMLDocument: [Function: HTMLDocument],
HTMLElement: { [Function] _init: undefined },
HTMLFormElement: { [Function] _init: undefined },
HTMLLinkElement: { [Function] _init: [Function] },
HTMLMetaElement: { [Function] _init: undefined },
HTMLHtmlElement: { [Function] _init: undefined },
HTMLHeadElement: { [Function] _init: undefined },
HTMLTitleElement: { [Function] _init: undefined },
HTMLBaseElement: { [Function] _init: undefined },
HTMLIsIndexElement: { [Function] _init: undefined },
HTMLStyleElement: { [Function] _init: [Function] },
HTMLBodyElement: { [Function] _init: undefined },
HTMLSelectElement: { [Function] _init: undefined },
HTMLOptGroupElement: { [Function] _init: undefined },
HTMLOptionElement: { [Function] _init: undefined },
HTMLInputElement: { [Function] _init: [Function] },
HTMLTextAreaElement: { [Function] _init: undefined },
HTMLButtonElement: { [Function] _init: undefined },
HTMLLabelElement: { [Function] _init: undefined },
HTMLFieldSetElement: { [Function] _init: undefined },
HTMLLegendElement: { [Function] _init: undefined },
HTMLUListElement: { [Function] _init: undefined },
HTMLOListElement: { [Function] _init: undefined },
HTMLDListElement: { [Function] _init: undefined },
HTMLDirectoryElement: { [Function] _init: undefined },
HTMLMenuElement: { [Function] _init: undefined },
HTMLLIElement: { [Function] _init: undefined },
HTMLCanvasElement: { [Function] _init: undefined },
HTMLDivElement: { [Function] _init: undefined },
HTMLParagraphElement: { [Function] _init: undefined },
HTMLHeadingElement: { [Function] _init: undefined },
HTMLQuoteElement: { [Function] _init: undefined },
HTMLPreElement: { [Function] _init: undefined },
HTMLBRElement: { [Function] _init: undefined },
HTMLBaseFontElement: { [Function] _init: undefined },
HTMLFontElement: { [Function] _init: undefined },
HTMLHRElement: { [Function] _init: undefined },
HTMLModElement: { [Function] _init: undefined },
HTMLAnchorElement: { [Function] _init: undefined },
HTMLImageElement: { [Function] _init: undefined },
HTMLObjectElement: { [Function] _init: undefined },
HTMLParamElement: { [Function] _init: undefined },
HTMLAppletElement: { [Function] _init: undefined },
HTMLMapElement: { [Function] _init: undefined },
HTMLAreaElement: { [Function] _init: undefined },
HTMLScriptElement: { [Function] _init: [Function] },
HTMLTableElement: { [Function] _init: undefined },
HTMLTableCaptionElement: { [Function] _init: undefined },
HTMLTableColElement: { [Function] _init: undefined },
HTMLTableSectionElement: { [Function] _init: undefined },
HTMLTableRowElement: { [Function] _init: undefined },
HTMLTableCellElement: { [Function] _init: undefined },
HTMLFrameSetElement: { [Function] _init: undefined },
HTMLFrameElement: { [Function] _init: [Function] },
HTMLIFrameElement: { [Function] _init: undefined },
INVALID_STATE_ERR: 11,
SYNTAX_ERR: 12,
INVALID_MODIFICATION_ERR: 13,
NAMESPACE_ERR: 14,
INVALID_ACCESS_ERR: 15,
StyleSheet: [Function: StyleSheet],
MediaList: [Function: MediaList],
CSSStyleSheet: [Function: CSSStyleSheet],
CSSRule:
{ [Function: CSSRule]
STYLE_RULE: 1,
IMPORT_RULE: 3,
MEDIA_RULE: 4,
FONT_FACE_RULE: 5,
PAGE_RULE: 6,
WEBKIT_KEYFRAMES_RULE: 8,
WEBKIT_KEYFRAME_RULE: 9 },
CSSStyleRule: { [Function: CSSStyleRule] parse: [Function] },
CSSMediaRule: [Function: CSSMediaRule],
CSSImportRule: [Function: CSSImportRule],
CSSStyleDeclaration: [Function: CSSStyleDeclaration],
StyleSheetList: [Function],
mapper: [Function],
memoizeQuery: [Function],
mapDOMNodes: [Function],
visitTree: [Function],
markTreeReadonly: [Function],
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10,
exceptionMessages:
{ '1': 'Index size error',
'2': 'DOMString size error',
'3': 'Hierarchy request error',
'4': 'Wrong document',
'5': 'Invalid character',
'6': 'No data allowed',
'7': 'No modification allowed',
'8': 'Not found',
'9': 'Not supported',
'10': 'Attribute in use',
NAMESPACE_ERR: 'Invalid namespace' },
DOMException:
{ [Function]
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10 },
NodeList: [Function: NodeList],
DOMImplementation: [Function: DOMImplementation],
Node:
{ [Function: Node]
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12,
DOCUMENT_POSITION_DISCONNECTED: 1,
DOCUMENT_POSITION_PRECEDING: 2,
DOCUMENT_POSITION_FOLLOWING: 4,
DOCUMENT_POSITION_CONTAINS: 8,
DOCUMENT_POSITION_CONTAINED_BY: 16,
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32 },
NamedNodeMap: [Function: NamedNodeMap],
AttributeList: [Function: AttributeList],
NotationNodeMap: [Function: NotationNodeMap],
EntityNodeMap: [Function: EntityNodeMap],
Element: [Function: Element],
memoizeQueryType: 11,
DocumentFragment: [Function: DocumentFragment],
ProcessingInstruction: [Function: ProcessingInstruction],
Document: [Function: Document],
CharacterData: [Function: CharacterData],
Attr: [Function: Attr],
Text: [Function: Text],
Comment: [Function: Comment],
CDATASection: [Function: CDATASection],
DocumentType: [Function: DocumentType],
Notation: [Function: Notation],
Entity: [Function: Entity],
EntityReference: [Function: EntityReference] },
self: [Circular],
frames: [Circular],
window: [Circular],
document:
{ _childNodes: {},
_ownerDocument: [Circular],
_attributes:
{ _ownerDocument: '#document',
_parentNode: [Circular],
_readonly: false,
'_$ns_to_attrs': {},
'_$name_to_attrs': {},
length: 0 },
_nodeName: '#document',
_childrenList: null,
_version: 0,
_nodeValue: null,
_parentNode: null,
_memoizedQueries: {},
_readonly: false,
_tagName: '#document',
_contentType: 'text/html',
_doctype: undefined,
_implementation: { _ownerDocument: undefined, _features: [Object] },
_documentElement: null,
_ids: {},
_attached: true,
_referrer: undefined,
_cookie: undefined,
_cookieDomain: '127.0.0.1',
_URL: 'http://widget.tippebannere.no/v3/2.0/Frontbox.aspx',
_documentRoot: 'http://widget.tippebannere.no/v3/2.0',
_queue: { paused: false },
readyState: 'loading',
location: { _url: [Object], _window: [Object] },
_listeners: { load: [Object] },
_parentWindow: [Circular] },
_frame: [Function],
constructor: [Function: DOMWindow],
_length: 0,
length: 0,
close: [Function],
getComputedStyle: [Function],
console:
{ log: [Function],
info: [Function],
warn: [Function],
error: [Function],
_window:
{ location: [Object],
history: [Object],
addEventListener: [Function],
removeEventListener: [Function],
dispatchEvent: [Function],
raise: [Function],
setTimeout: [Function],
setInterval: [Function],
clearInterval: [Function: stopTimer],
clearTimeout: [Function: stopTimer],
__stopAllTimers: [Function: stopAllTimers],
run: [Function],
getGlobal: [Function],
dispose: [Function],
top: [Object],
parent: [Object],
self: [Circular],
frames: [Circular],
window: [Circular],
document: [Object],
_frame: [Function] } },
navigator:
{ userAgent: [Getter],
appName: [Getter],
platform: [Getter],
appVersion: [Getter],
noUI: true,
cookieEnabled: [Getter] },
XMLHttpRequest: [Function],
name: 'nodejs',
innerWidth: 1024,
innerHeight: 768,
outerWidth: 1024,
outerHeight: 768,
pageXOffset: 0,
pageYOffset: 0,
screenX: 0,
screenY: 0,
screenLeft: 0,
screenTop: 0,
scrollX: 0,
scrollY: 0,
scrollTop: 0,
scrollLeft: 0,
alert: [Function],
blur: [Function],
confirm: [Function],
createPopup: [Function],
focus: [Function],
moveBy: [Function],
moveTo: [Function],
open: [Function],
print: [Function],
prompt: [Function],
resizeBy: [Function],
resizeTo: [Function],
scroll: [Function],
scrollBy: [Function],
scrollTo: [Function],
screen: { width: 0, height: 0 },
Image: [Function],
Int8Array: [Function: Int8Array],
Int16Array: [Function: Int16Array],
Int32Array: [Function: Int32Array],
Float32Array: [Function: Float32Array],
Float64Array: [Function: Float64Array],
Uint8Array: [Function: Uint8Array],
Uint8ClampedArray: [Function: Uint8ClampedArray],
Uint16Array: [Function: Uint16Array],
Uint32Array: [Function: Uint32Array],
ArrayBuffer: [Function: ArrayBuffer],
NodeFilter:
{ [Function]
acceptNode: [Function],
SHOW_ALL: 4294967295,
SHOW_ELEMENT: 1,
SHOW_ATTRIBUTE: 2,
SHOW_TEXT: 4,
SHOW_CDATA_SECTION: 8,
SHOW_ENTITY_REFERENCE: 16,
SHOW_ENTITY: 32,
SHOW_PROCESSING_INSTRUCTION: 64,
SHOW_COMMENT: 128,
SHOW_DOCUMENT: 256,
SHOW_DOCUMENT_TYPE: 512,
SHOW_DOCUMENT_FRAGMENT: 1024,
SHOW_NOTATION: 2048,
FILTER_ACCEPT: 1,
FILTER_REJECT: 2,
FILTER_SKIP: 3 },
_parser: undefined,
_parsingMode: 'auto',
_augmented: true,
languageProcessors: { javascript: [Function] },
resourceLoader:
{ load: [Function],
enqueue: [Function],
baseUrl: [Function],
resolve: [Function],
download: [Function],
readFile: [Function] },
HTMLCollection: [Function: HTMLCollection],
HTMLOptionsCollection: [Function: HTMLCollection],
HTMLDocument: [Function: HTMLDocument],
HTMLElement: { [Function] _init: undefined },
HTMLFormElement: { [Function] _init: undefined },
HTMLLinkElement: { [Function] _init: [Function] },
HTMLMetaElement: { [Function] _init: undefined },
HTMLHtmlElement: { [Function] _init: undefined },
HTMLHeadElement: { [Function] _init: undefined },
HTMLTitleElement: { [Function] _init: undefined },
HTMLBaseElement: { [Function] _init: undefined },
HTMLIsIndexElement: { [Function] _init: undefined },
HTMLStyleElement: { [Function] _init: [Function] },
HTMLBodyElement: { [Function] _init: undefined },
HTMLSelectElement: { [Function] _init: undefined },
HTMLOptGroupElement: { [Function] _init: undefined },
HTMLOptionElement: { [Function] _init: undefined },
HTMLInputElement: { [Function] _init: [Function] },
HTMLTextAreaElement: { [Function] _init: undefined },
HTMLButtonElement: { [Function] _init: undefined },
HTMLLabelElement: { [Function] _init: undefined },
HTMLFieldSetElement: { [Function] _init: undefined },
HTMLLegendElement: { [Function] _init: undefined },
HTMLUListElement: { [Function] _init: undefined },
HTMLOListElement: { [Function] _init: undefined },
HTMLDListElement: { [Function] _init: undefined },
HTMLDirectoryElement: { [Function] _init: undefined },
HTMLMenuElement: { [Function] _init: undefined },
HTMLLIElement: { [Function] _init: undefined },
HTMLCanvasElement: { [Function] _init: undefined },
HTMLDivElement: { [Function] _init: undefined },
HTMLParagraphElement: { [Function] _init: undefined },
HTMLHeadingElement: { [Function] _init: undefined },
HTMLQuoteElement: { [Function] _init: undefined },
HTMLPreElement: { [Function] _init: undefined },
HTMLBRElement: { [Function] _init: undefined },
HTMLBaseFontElement: { [Function] _init: undefined },
HTMLFontElement: { [Function] _init: undefined },
HTMLHRElement: { [Function] _init: undefined },
HTMLModElement: { [Function] _init: undefined },
HTMLAnchorElement: { [Function] _init: undefined },
HTMLImageElement: { [Function] _init: undefined },
HTMLObjectElement: { [Function] _init: undefined },
HTMLParamElement: { [Function] _init: undefined },
HTMLAppletElement: { [Function] _init: undefined },
HTMLMapElement: { [Function] _init: undefined },
HTMLAreaElement: { [Function] _init: undefined },
HTMLScriptElement: { [Function] _init: [Function] },
HTMLTableElement: { [Function] _init: undefined },
HTMLTableCaptionElement: { [Function] _init: undefined },
HTMLTableColElement: { [Function] _init: undefined },
HTMLTableSectionElement: { [Function] _init: undefined },
HTMLTableRowElement: { [Function] _init: undefined },
HTMLTableCellElement: { [Function] _init: undefined },
HTMLFrameSetElement: { [Function] _init: undefined },
HTMLFrameElement: { [Function] _init: [Function] },
HTMLIFrameElement: { [Function] _init: undefined },
INVALID_STATE_ERR: 11,
SYNTAX_ERR: 12,
INVALID_MODIFICATION_ERR: 13,
NAMESPACE_ERR: 14,
INVALID_ACCESS_ERR: 15,
StyleSheet: [Function: StyleSheet],
MediaList: [Function: MediaList],
CSSStyleSheet: [Function: CSSStyleSheet],
CSSRule:
{ [Function: CSSRule]
STYLE_RULE: 1,
IMPORT_RULE: 3,
MEDIA_RULE: 4,
FONT_FACE_RULE: 5,
PAGE_RULE: 6,
WEBKIT_KEYFRAMES_RULE: 8,
WEBKIT_KEYFRAME_RULE: 9 },
CSSStyleRule: { [Function: CSSStyleRule] parse: [Function] },
CSSMediaRule: [Function: CSSMediaRule],
CSSImportRule: [Function: CSSImportRule],
CSSStyleDeclaration: [Function: CSSStyleDeclaration],
StyleSheetList: [Function],
mapper: [Function],
memoizeQuery: [Function],
mapDOMNodes: [Function],
visitTree: [Function],
markTreeReadonly: [Function],
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10,
exceptionMessages:
{ '1': 'Index size error',
'2': 'DOMString size error',
'3': 'Hierarchy request error',
'4': 'Wrong document',
'5': 'Invalid character',
'6': 'No data allowed',
'7': 'No modification allowed',
'8': 'Not found',
'9': 'Not supported',
'10': 'Attribute in use',
NAMESPACE_ERR: 'Invalid namespace' },
DOMException:
{ [Function]
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10 },
NodeList: [Function: NodeList],
DOMImplementation: [Function: DOMImplementation],
Node:
{ [Function: Node]
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12,
DOCUMENT_POSITION_DISCONNECTED: 1,
DOCUMENT_POSITION_PRECEDING: 2,
DOCUMENT_POSITION_FOLLOWING: 4,
DOCUMENT_POSITION_CONTAINS: 8,
DOCUMENT_POSITION_CONTAINED_BY: 16,
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32 },
NamedNodeMap: [Function: NamedNodeMap],
AttributeList: [Function: AttributeList],
NotationNodeMap: [Function: NotationNodeMap],
EntityNodeMap: [Function: EntityNodeMap],
Element: [Function: Element],
memoizeQueryType: 11,
DocumentFragment: [Function: DocumentFragment],
ProcessingInstruction: [Function: ProcessingInstruction],
Document: [Function: Document],
CharacterData: [Function: CharacterData],
Attr: [Function: Attr],
Text: [Function: Text],
Comment: [Function: Comment],
CDATASection: [Function: CDATASection],
DocumentType: [Function: DocumentType],
Notation: [Function: Notation],
Entity: [Function: Entity],
EntityReference: [Function: EntityReference] }
|
const { expect } = require("chai");
const knex = require("knex");
const { test } = require("mocha");
const supertest = require("supertest");
const app = require("../src/app");
const { makePostsArr } = require("./test-helpers");
const testHelpers = require("./test-helpers");
describe("Posts Endpoints", function () {
let db;
let authToken;
before("make knex instance", () => {
db = knex({
client: "pg",
connection: process.env.TEST_DATABASE_URL,
});
return app.set("db", db);
});
afterEach("cleanup", () =>
db.raw("TRUNCATE TABLE users, posts RESTART IDENTITY CASCADE")
);
beforeEach("register and login", () => {
let user = {
email: "testuser@test.com",
username: "testuser1",
password: "P@ssword1234",
};
return supertest(app)
.post("/api/users")
.send(user)
.then((res) => {
return supertest(app)
.post("/api/auth/login")
.send(user)
.then((res2) => {
authToken = res2.body.authToken;
});
});
});
const testUsers = testHelpers.makeUsersArr();
const testPosts = testHelpers.makePostsArr();
beforeEach("insert users", () => {
return db.into("users").insert(testUsers);
});
beforeEach("insert posts", () => {
return db.into("posts").insert(testPosts);
});
it(`responds with 200 and an empty list`, () => {
return db.raw("TRUNCATE TABLE posts RESTART IDENTITY CASCADE").then(() => {
return supertest(app)
.get("/api/feed")
.set("Authorization", `Bearer ${authToken}`)
.expect(200, []);
});
});
it(`responds with 200 and one post`, () => {
return supertest(app)
.get("/api/feed")
.set("Authorization", `Bearer ${authToken}`)
.expect(200)
.then((res) => {
expect(res.body).to.be.an("array");
expect(res.body.content).to.eql(testPosts.content);
});
});
it("creates a post and responds with 201 and the object", () => {
const newPost = {
content: "test1",
};
return supertest(app)
.post("/api/feed")
.send(newPost)
.set("Authorization", `Bearer ${authToken}`)
.expect(201)
.expect((res) => {
expect(res.body.content).to.eql(newPost.content);
expect(res.headers.location).to.eql(`/feed`);
})
.then((postRes) => {
/*return supertest(app)
.get(`/api/movies/${postRes.body.id}`)
.set("Authorization", `Bearer ${authToken}`)
.expect(postRes.body);*/
return true;
});
});
it("responds with 204 and removes the post", () => {
const idToRemove = 2;
const expectedPosts = testPosts.filter((post) => post.id !== idToRemove);
return supertest(app)
.delete(`/api/dashboard`)
.send({ post_id: idToRemove })
.set("Authorization", `Bearer ${authToken}`)
.expect(204);
});
});
|
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link as RouterLink } from 'react-router-dom';
import { makeStyles } from '@material-ui/styles';
import {
Card,
CardContent,
CardMedia,
Typography,
Divider,
Link,
Avatar,
Button,
Box,
CircularProgress
} from '@material-ui/core';
import clsx from 'clsx';
import LockIcon from '@material-ui/icons/Lock';
import Grid from '@material-ui/core/Grid';
import { Page } from 'components';
import gradients from 'utils/gradients';
// import { LoginForm, CreatePasswordForm, ForgotPassword } from './components';
import ModalCustom from 'components/ModalCustom';
import {getJobDetailsPost} from 'actions'
const useStyles = makeStyles(theme => ({
root: {
height: '100%',
display: 'flex',
alignItems: 'center',
// justifyContent: 'center',
// paddingLeft:'50px',
padding: theme.spacing(6, 10),
[theme.breakpoints.down('xs')]: {
alignItems: 'initial',
padding: theme.spacing(2),
}
},
routebackground: {
background: 'url(/images/login-bg.jpg) no-repeat',
backgroundSize: 'cover',
backgroundPosition: '50% 26%',
[theme.breakpoints.down('sm')]: {
backgroundPosition: '90% 26%',
}
},
loader: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: '100%',
height: '100%'
},
spinner: {
textAlign: 'center'
},
title: {
fontSize: 16,
},
jobCard:{
height:'200px',
display:'flex',
alignItems:'center',
padding:'0 16px',
textAlign:'center',
},
card: {
// width: theme.breakpoints.values.md,
maxWidth: '100%',
width:'75%',
overflow: 'unset',
// display: 'flex',
position: 'relative',
backgroundColor: 'transparent',
boxShadow: 'none',
'& > *': {
flexGrow: 1,
flexBasis: '85%',
width: '85%',
[theme.breakpoints.down('xs')]: {
flexBasis: '100%',
width: '100%'
}
},
[theme.breakpoints.down('xs')]: {
flexDirection: 'column'
}
},
media: {
position: 'relative',
borderTopRightRadius: 4,
borderBottomRightRadius: 4,
padding: theme.spacing(2.5),
color: theme.palette.white,
display: 'flex',
paddingBottom: '70px',
backgroundColor: '#0001197d',
flexDirection: 'column',
// justifyContent: 'flex-end',
marginBottom: '15px',
[theme.breakpoints.down('xs')]: {
order: '1',
padding: '5px 20px 15px 20px',
}
},
mediaTitle: {
marginBottom: '5px'
},
divider2: {
margin: theme.spacing(1, 0),
backgroundColor: '#b3b3b3'
},
subtitle2: {
color: '#ffffffe6',
marginBottom:'14px',
},
}));
const ValidateRoute = (props) => {
const classes = useStyles();
const dispatch = useDispatch();
const { match, history } = props;
const { clientID, jobCode } = match.params;
const clientName = clientID ? clientID : '';
const userName = jobCode ? jobCode : ''
useEffect(() => {
let mounted = true;
if (mounted) {
const params = {
ClientSuffix : clientID ? clientID : '',
JobCode : jobCode ? jobCode : ''
}
dispatch(getJobDetailsPost(params));
}
return () => {
mounted = false;
};
}, []);
const jobDetails = useSelector(
state => state.auth.jobDetails
);
const allState = useSelector(
state => state.auth
);
if (clientName.split('').length > 0 && userName.split('').length > 0) {
if(jobDetails.status){
history.push('/auth/login')
}
}
// if (clientName == undefined || userName == undefined || jobDetails.companyName == null) {
// setShowLoader(false)
// setIsPathInvalid(true)
// }
console.log("clientID", clientID);
console.log('jobCode',jobCode);
return (
<Page className={clsx(classes.root, classes.routePage, { [classes.routebackground]: !allState.isLoading })} title="ReRoute">
{allState.isLoading && <Box className={classes.loader} component="div">
<CircularProgress size={80} className={classes.spinner} />
</Box>}
<Card className={classes.card}>
{clientID == undefined && jobCode == undefined && allState.isLoading == false && allState.isNotValidPath && <CardMedia className={classes.media} title="Cover">
<Typography
color="inherit"
className={classes.mediaTitle}
variant="h3"
gutterBottom>
Welcome to Applicant Center.
</Typography>
{/* <Typography color="inherit" variant="h5">
{jobDetails.jobTitle}
</Typography> */}
<Divider className={classes.divider2} />
<Typography
className={classes.subtitle2}
color="inherit"
variant="subtitle1">
As the trucking industry continues to struggle with a growing shortage of drivers, J.J. Keller, Inc has developed a new tech-oriented recruitment solution to attract drivers.
</Typography>
<Typography
className={classes.subtitle2}
color="inherit"
variant="subtitle1">
CDL class A over-the-road drivers are probably the hardest drivers to find right now and there is a need to hire qualified drivers in quick time.
</Typography>
<Typography
className={classes.subtitle2}
color="inherit"
variant="subtitle1">
Applicant Center is a hiring solution for recruiting experienced and qualified CDL drivers. This is based on compliance related to cities or states, in hiring of professional drivers. In a nutshell, a Compliance based Hiring Applicant Center for drivers.
</Typography>
</CardMedia>}
{clientID && jobCode == undefined && allState.isLoading == false && allState.isNotValidPath && <CardMedia className={classes.media} title="Cover">
<Typography
color="inherit"
className={classes.mediaTitle}
variant="h3"
gutterBottom>
Hello!
</Typography>
<Divider className={classes.divider2} />
<Typography
className={classes.subtitle2}
color="inherit"
variant="subtitle1">
Something is not right. If you are looking for a job details, you will need to access it with a correct URL
</Typography>
</CardMedia>}
{clientID && jobCode && allState.isLoading == false && allState.isNotValidPath && <CardMedia className={classes.media} title="Cover">
<Typography
color="inherit"
className={classes.mediaTitle}
variant="h3"
gutterBottom>
Hello!
</Typography>
<Divider className={classes.divider2} />
<Typography
className={classes.subtitle2}
color="inherit"
variant="subtitle1">
This job posting is not currently open to applicants.
</Typography>
</CardMedia>}
</Card>
{/* {allState.isNotValidPath && <Card className={classes.jobCard}>
<CardContent>
<Typography className={classes.title} color="textSecondary" variant='h5' component="h5" gutterBottom>
This job posting is not currently open to applicants.
</Typography>
</CardContent>
</Card>} */}
</Page>
);
};
export default ValidateRoute;
|
const express = require("express");
const cors = require("cors");
const bcrypt = require("bcrypt-nodejs");
const login = require("./controllers/loginHandler").loginHandler;
const register = require("./controllers/registrationHandler");
const {
patientInsertionHandler,
patientRetriever,
patientRetrieveByDoctorAppointed,
patientRetrieveByTheirNames
} = require("./controllers/patientHandler");
const updateDetails = require("./controllers/detailsUpdater");
const {allRetriever} = require('./controllers/allRetrieveHandler');
const pg = require("knex")({
client: "pg",
connection: {
host: "127.0.0.1",
user: "sourav",
password: "sourav",
database: "HospitalManagementSystem"
}
});
const PORT = process.env.PORT || 4000;
const app = express();
app.use(cors()); //Middleware to make connection between http and https protocols
app.use(express.json()); //Using middleware to preprocess the received data for a more relevant data
app.post("/login", (req, res) => {
login(req, res, pg, bcrypt);
});
app.post("/register", (req, res) => {
register.registrationHandler(req, res, pg, bcrypt);
});
app.post("/insert_patient", (req, res) => {
patientInsertionHandler(req, res, pg);
});
app.get("/get_patients", (req, res) => {
patientRetriever(res, pg);
});
app.post("/get_patient_by_name", (req, res) => {
patientRetrieveByTheirNames(res, pg, req.body.name);
});
app.post("/get_patient_by_doctor_appointed", (req, res) => {
patientRetrieveByDoctorAppointed(res, pg, req.body.doctorName);
});
app.put("/patient_details", (req, res) => {
updateDetails.patientDetailUpdater(req, res);
});
app.put("/user_details", (req, res) => {
updateDetails.userDetailUpdater(req, res);
});
app.get('/retrieve', (req, res)=>{
allRetriever(res, pg, req.body.position);
})
app.listen(PORT, () => {
console.log(`Server is running at PORT ${PORT}`);
}); |
const localStore = {}
const isLocalStorageAccessible = (() => {
let isStorageAccessible
return function () {
if (!isStorageAccessible) {
isStorageAccessible = !!(window && window.localStorage)
}
return isStorageAccessible
}
})()
function readLocalStorage (key) {
try {
if (
isLocalStorageAccessible() &&
window.localStorage[key] &&
window.localStorage[key] !== 'undefined'
) {
return window.localStorage[key]
} else if (localStore[key]) {
return localStore[key]
}
return null
} catch (e) {
return null
}
}
function writeLocalStorage (key, value) {
try {
localStore[key] = value
return isLocalStorageAccessible() && window.localStorage.setItem(key, value)
} catch (e) {
return null
}
}
function deleteLocalStorage (key) {
try {
if (localStore[key]) {
delete localStore[key]
}
return (
isLocalStorageAccessible() &&
key &&
delete window.localStorage.removeItem(key)
)
} catch (e) {
return null
}
}
function getFromLocalStorage (key) {
let offline = readLocalStorage('data')
try {
offline = JSON.parse(offline) || {}
} catch (e) {
offline = {}
}
return offline[key]
}
function addToLocalStorage (key, data) {
let offline = readLocalStorage('data')
try {
offline = JSON.parse(offline) || {}
} catch (e) {
offline = {}
}
offline[key] = data
writeLocalStorage('data', JSON.stringify(offline))
}
|
import React from 'react';
import { Media, Button } from 'reactstrap';
export default class Product extends React.Component {
render() {
const { product } = this.props;
const baseUrl = '/images/';
return (
<Media>
<Media left top>
<Media object src={baseUrl + product.img + ".jpg"} alt={product.alt} />
</Media>
<Media body>
<Media heading>
{product.name}
</Media>
<p>{product.description}</p>
<p><Button color="success">Add to Cart</Button></p>
</Media>
</Media>
);
}
} |
var leftHalf = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY",
width: "screenSizeX/2",
height: "screenSizeY"
});
var rightHalf = slate.operation("move", {
x: "screenOriginX+screenSizeX/2",
y: "screenOriginY",
width: "screenSizeX/2",
height: "screenSizeY"
});
var topThird = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY",
width: "screenSizeX",
height: "screenSizeY/3"
});
var middleThird = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY+screenSizeY/3",
width: "screenSizeX",
height: "screenSizeY/3"
});
var bottomThird = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY+(screenSizeY*(2/3))",
width: "screenSizeX",
height: "screenSizeY/3"
});
var topHalf = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY",
width: "screenSizeX",
height: "screenSizeY/2"
});
var bottomHalf = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY+screenSizeY/2",
width: "screenSizeX",
height: "screenSizeY/2"
});
var full = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY",
width: "screenSizeX",
height: "screenSizeY"
});
var fullDubble = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY",
width: "screenSizeX*2",
height: "screenSizeY"
});
var topLeft = S.op("corner", {
"direction": "top-left",
"width": "screenSizeX/2",
"height": "screenSizeY/2"
});
var topLeftShort = S.op("corner", {
"direction": "top-left",
"width": "screenSizeX/2",
"height": "screenSizeY*0.40"
});
var topRight = S.op("corner", {
"direction": "top-right",
"width": "screenSizeX/2",
"height": "screenSizeY/2"
});
var bottomLeft = S.op("corner", {
"direction": "bottom-left",
"width": "screenSizeX/2",
"height": "screenSizeY/2"
});
var bottomLeftTall = S.op("corner", {
"direction": "bottom-left",
"width": "screenSizeX/2",
"height": "screenSizeY*0.6"
});
var bottomRight = S.op("corner", {
"direction": "bottom-right",
"width": "screenSizeX/2",
"height": "screenSizeY/2"
});
var moveScreen0 = slate.operation("throw", {
screen: "0"
});
var moveScreen1 = slate.operation("throw", {
screen: "1"
});
var moveScreen2 = slate.operation("throw", {
screen: "2"
});
var moveScreen3 = slate.operation("throw", {
screen: "3"
});
var moveScreen4 = slate.operation("throw", {
screen: "4"
});
var moveScreen5 = slate.operation("throw", {
screen: "5"
});
function googleChromeLayout(windowObject) {
var title = windowObject.title();
slate.log(title);
if (title !== undefined && title.match(/^Grafana.+$/)) {
windowObject.doOperation(moveScreen0);
windowObject.doOperation(full);
} else if (title !== undefined && title == "Postman") {
//do nothing
} else {
windowObject.doOperation(moveScreen1);
windowObject.doOperation(full);
}
}
slate.config("orderScreensLeftToRight", true);
var screen0Top = slate.operation("move", {
x: "screenOriginX-5",
y: "screenOriginY",
width: "screenSizeX-5",
height: "screenSizeY/2",
screen: "0"
});
var screen0Bottom = slate.operation("move", {
x: "screenOriginX-5",
y: "screenOriginY+screenSizeY/2",
width: "screenSizeX-5",
height: "screenSizeY/2",
screen: "0"
});
var screen3Full = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY",
width: "screenSizeX",
height: "screenSizeY",
screen: "3"
});
var screen4Full = slate.operation("move", {
x: "screenOriginX",
y: "screenOriginY",
width: "screenSizeX",
height: "screenSizeY",
screen: "4"
});
var threeMonitorLayout = slate.layout("threeMonitor", {
"Slack": {
"operations": [function(wo) {
wo.doOperation(moveScreen0);
wo.doOperation(topLeftShort);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Microsoft Outlook": {
"operations": [function(wo) {
wo.doOperation(moveScreen0);
wo.doOperation(bottomLeftTall);
}],
"main-first": true,
"ignore-fail": false,
"repeat": true
},
"Google Play Music Desktop Player": {
"operations": [function(wo) {
wo.doOperation(moveScreen0);
wo.doOperation(bottomRight);
}],
"main-first": true,
"ignore-fail": false,
"repeat": true
},
"VMware Fusion": {
"operations": [function(wo) {
wo.doOperation(moveScreen1);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Google Chrome": {
"operations": [googleChromeLayout],
"repeat": true,
"ignore-fail": true
},
"Firefox": {
"operations": [function(wo) {
wo.doOperation(moveScreen1);
wo.doOperation(full);
}],
"repeat": true,
"ignore-fail": true
},
"PyCharm Community Edition": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(topHalf);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"WebStorm": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(topHalf);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Emacs": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(topHalf);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"iTerm2": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(bottomHalf);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
}
});
var fourMonitorLayout = slate.layout("fourMonitor", {
"Slack": {
"operations": [function(wo) {
wo.doOperation(moveScreen0);
wo.doOperation(topLeftShort);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Microsoft Outlook": {
"operations": [function(wo) {
wo.doOperation(moveScreen0);
wo.doOperation(bottomLeftTall);
}],
"main-first": true,
"ignore-fail": false,
"repeat": true
},
"Google Play Music Desktop Player": {
"operations": [function(wo) {
wo.doOperation(moveScreen0);
wo.doOperation(bottomRight);
}],
"main-first": true,
"ignore-fail": false,
"repeat": true
},
"VMware Fusion": {
"operations": [function(wo) {
wo.doOperation(moveScreen1);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Google Chrome": {
"operations": [googleChromeLayout],
"repeat": true,
"ignore-fail": true
},
"Firefox": {
"operations": [function(wo) {
wo.doOperation(moveScreen0);
wo.doOperation(full);
}],
"repeat": true,
"ignore-fail": true
},
"PyCharm Community Edition": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"WebStorm": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Xcode": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Android Studio": {
"operations": [function(wo) {
wo.doOperation(moveScreen2);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"Emacs": {
"operations": [function(wo) {
wo.doOperation(moveScreen3);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
},
"iTerm2": {
"operations": [function(wo) {
wo.doOperation(moveScreen1);
wo.doOperation(full);
}],
"main-first": true,
"ignore-fail": true,
"repeat": true
}
});
slate.bind("f:ctrl,cmd", fullDubble)
slate.bind("a:ctrl,alt,cmd", function(wo){
if (slate.screenCount() == 3) {
slate.operation("layout", {
name: threeMonitorLayout
}).run();
}
if (slate.screenCount() == 4) {
slate.operation("layout", {
name: fourMonitorLayout
}).run();
}
});
slate.default(3, threeMonitorLayout);
if (slate.screenCount() == 3) {
slate.operation("layout", {
name: threeMonitorLayout
}).run();
}
if (slate.screenCount() == 4) {
slate.operation("layout", {
name: fourMonitorLayout
}).run();
}
slate.log("screen count " + slate.screenCount());
slate.eachScreen(function(screenObject) {
slate.log(screenObject.id() + " " + JSON.stringify(screenObject.rect()));
});
|
const express = require('express');
const router = express.Router();
const { completeUserProfile, isUserExist, addToCart, findUser, adduserLocation, summaTestWA, userOrderPayment, removeFromCart, getUserData, getAllProductInCart, getallproductDataFromCart, userOrdernow, showUserOrders } = require('../controllers/user');
router.post('/user/create/profile', completeUserProfile);
router.post('/user/create/showOrder', showUserOrders);
router.post('/user/exist', isUserExist);
router.post('/user/getalldata', getUserData);
router.post('/user/findUserData', findUser);
router.post('/user/adduserlocation', adduserLocation);
router.post('/user/:rasauserId/createprofile');
// router.post('/user/:rasauserId/showOrder', showUserOrders);
router.post('/test/trigger', summaTestWA)
// Here we handle Cart and Orders
router.post('/user/addtocart/:userId', addToCart);
router.post('/user/removefromcart/:userId', removeFromCart);
router.get('/user/:userId/getallproductfromcart', getAllProductInCart);
router.get('/user/:userId/getallproductdatafromcart', getallproductDataFromCart);
router.post('/user/:userId/ordernow', userOrdernow);
router.post('/user/:userId/orderpayment/:orderId', userOrderPayment);
module.exports = router; |
/*
Elasticity:
1 - elastic
2 - firm
3 - rigid
Texture:
1 - rough
2 - semi-smooth
3 - smooth
Temperature:
1 - cold
2 - warm
3 - hot
Solidity:
1 - liquid
2 - gel
3 - solid
*/
function Element() {
// Init main variables
this.name;
this.elasticity;
this.texture;
this.temperature;
this.solidity;
this.allPropertiesArr = [];
this.x;
this.y;
this.width = 50;
this.height = 50;
this.velX = 0;
this.velY = 0;
this.accelX = 0;
this.accelY = 0;
this.isHovered = false;
this.formula;
this.sound;
this.color ='rgb(0,0,0)';
this.hitTest = function(hitX,hitY) {
if (hitX > this.x && hitX < this.x + this.width && hitY > this.y && hitY < this.y + this.height) {
return true;
}
return false;
};
this.draw = function() {
ctx.save();
ctx.fillStyle = 'rgb(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ')';
ctx.fillRect(this.x, this.y, this.width, this.height);
// Draw element symbol
ctx.fillStyle = '#c6c9b1';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Element symbol consists of first two characters of element name
var symbol = this.name.match(/.{1,2}/g)[0];
ctx.font = fontSmallHeading;
ctx.strokeStyle = '#000';
ctx.lineWidth = 3;
ctx.strokeText(symbol, this.x + this.width / 2 , this.y + this.height / 2);
ctx.fillText(symbol, this.x + this.width / 2 , this.y + this.height / 2);
ctx.restore();
if (this.isHovered) {
this.drawInformation();
}
};
this.setAllPropertiesArr = function() {
// Create an array of all properties for this element
this.allPropertiesArr = [
{
name: 'elasticity',
value: this.elasticity,
description: elementManager.getPropertyDescription('elasticity', this.elasticity)
},
{
name: 'texture',
value: this.texture,
description: elementManager.getPropertyDescription('texture', this.texture)
},
{
name: 'temperature',
value: this.temperature,
description: elementManager.getPropertyDescription('temperature', this.temperature)
},
{
name: 'solidity',
value: this.solidity,
description: elementManager.getPropertyDescription('solidity', this.solidity)
}
];
};
this.drawInformation = function() {
var inMixingPalette = mixingPalette.hitTest(this.x, this.y);
var x;
var y;
if (!inMixingPalette) {
x = this.x + this.width + 5;
y = this.y;
ctx.textAlign = "left";
}
else {
x = mixingPalette.x - 5;
y = this.y;
ctx.textAlign = "right";
}
ctx.save();
ctx.textBaseline = 'middle';
ctx.font = fontTiny;
ctx.fillStyle = 'rgb(' + this.color.r + ',' + this.color.g + ',' + this.color.b +')';
ctx.fillText(this.name, x, y);
y += 13;
ctx.fillStyle = '#ccc';
for (var i = 0; i < this.allPropertiesArr.length; i++) {
var property = this.allPropertiesArr[i];
var description;
if (this.name !== 'Antemanium') {
description = property.description;
}
else {
description = 'N/A';
}
ctx.fillText(property.name + ': ' + description, x, y);
y += 13;
}
ctx.restore();
};
};
function Helper() {
// Init main variables
this.radius = 25;
this.color;
this.name;
this.property;
this.x;
this.y;
this.parentX;
this.parentY;
this.allPropertiesArr;
this.sound;
this.hitTest = function(hitX,hitY) {
var dx = this.x - hitX;
var dy = this.y - hitY;
return(dx*dx + dy*dy < this.radius*this.radius);
};
this.draw = function() {
ctx.save();
ctx.fillStyle = 'rgb(' + this.color.r + ',' + this.color.g + ',' + this.color.b +')';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.closePath();
ctx.fill();
ctx.fillStyle = 'rgba(0,0,0,0.3)';
var symbol = this.name.match(/.{1,2}/g)[0];
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.font = fontSmallHeading;
ctx.fillText(symbol, this.x, this.y);
ctx.restore();
if (this.isHovered) {
this.drawInformation();
}
};
this.drawInformation = function() {
var x = 622;
var y = canvas.height - 250;
ctx.save();
ctx.textAlign = "right";
ctx.textBaseline = 'middle';
ctx.font = fontTiny;
ctx.fillStyle = '#c6c9b1';
ctx.fillText(this.name, x, y);
ctx.restore();
};
};
// Main element manager
function ElementManager() {
// Create the helpers
this.createHelperElements = function() {
var helperCount = 2;
var x = 565;
var y = canvas.height - 105;
var radius = 15;
for (var i = 0; i < helperCount; i++) {
this.createHelper('Liquifier', x, y, radius);
x += radius * 2 + 3;
}
x = 565;
y -= 35;
for (var i = 0; i < helperCount; i++) {
this.createHelper('Cooler', x, y, radius);
x += radius * 2 + 3;
}
x = 565;
y -= 35;
for (var i = 0; i < helperCount; i++) {
this.createHelper('Smoother', x, y, radius);
x += radius * 2 + 3;
}
x = 565;
y -= 35;
for (var i = 0; i < helperCount; i++) {
this.createHelper('Elasticizer', x, y, radius);
x += radius * 2 + 3;
}
};
this.createHelper = function(name, x, y, radius) {
switch (name) {
case 'Liquifier':
var helper = new Helper();
helper.name = 'Liquifier';
helper.radius = radius;
helper.formula = [{count: 1, symbol: 'Li'}];
helper.property = {name: 'solidity', value: -0.25};
helper.isHelper = true;
helper.color = {
r: 122,
g: 122,
b: 122
};
helper.x = x + radius;
helper.y = y - radius;
helper.parentX = x + radius;
helper.parentY = y - radius;
helperElementsArr.push(helper);
break;
case 'Cooler':
var helper = new Helper();
helper.name = 'Cooler';
helper.radius = radius;
helper.formula = [{count: 1, symbol: 'Co'}];
helper.property = {name: 'temperature', value: -0.25};
helper.isHelper = true;
helper.color = {
r: 145,
g: 145,
b: 145
};
helper.x = x + radius;
helper.y = y - radius;
helper.parentX = x + radius;
helper.parentY = y - radius;
helperElementsArr.push(helper);
break;
case 'Smoother':
var helper = new Helper();
helper.name = 'Smoother';
helper.radius = radius;
helper.formula = [{count: 1, symbol: 'Sm'}];
helper.property = {name: 'texture', value: -0.25};
helper.isHelper = true;
helper.color = {
r: 189,
g: 189,
b: 189
};
helper.x = x + radius;
helper.y = y - radius;
helper.parentX = x + radius;
helper.parentY = y - radius;
helperElementsArr.push(helper);
break;
case 'Elasticizer':
var helper = new Helper();
helper.name = 'Elasticizer';
helper.radius = radius;
helper.formula = [{count: 1, symbol: 'El'}];
helper.property = {name: 'elasticity', value: -0.25};
helper.isHelper = true;
helper.color = {
r: 219,
g: 219,
b: 219
};
helper.x = x + radius;
helper.y = y - radius;
helper.parentX = x + radius;
helper.parentY = y - radius;
helperElementsArr.push(helper);
break;
}
var soundSrc = jsfxr([2,0.02,0.11,0.35,0.32,0.91,,-0.02,,0.04,0.14,-0.88,0.63,,-0.56,,-0.28,0.06,1,,,,,0.5]);
helper.sound = new Audio();
helper.sound.src = soundSrc;
};
// Restock all the helper elements
this.restockHelperElements = function() {
// There should be 2 of each element
var reqHelpers = 2;
// Get all liquifiers
var liquifierHelperArr = this.getHelpers('Liquifier');
// Subtract # of liquifiers from required helpers
var helpersNeeded = reqHelpers - liquifierHelperArr.length;
var radius = 15;
// For each helper needed, spawn a new liquifier
for (var i = 0; i < helpersNeeded; i++) {
var y = canvas.height - 105;
this.createHelper('Liquifier', 0, 0, radius);
}
// Again, get all the liquifiers (including newly spawned ones)
liquifierHelperArr = this.getHelpers('Liquifier');
// Draw each liquifier
var x = 580;
var y = canvas.height - 120;
for (var i = 0; i < liquifierHelperArr.length; i++) {
var helper = liquifierHelperArr[i];
helper.x = x;
helper.y = y;
helper.parentX = x;
helper.parentY = y;
x += radius * 2 + 3;
}
// Continue to do the same for the other helpers
var coolerHelperArr = this.getHelpers('Cooler');
helpersNeeded = reqHelpers - coolerHelperArr.length;
for (var i = 0; i < helpersNeeded; i++) {
this.createHelper('Cooler', 0, 0, radius);
}
coolerHelperArr = this.getHelpers('Cooler');
x = 580;
y -= 35;
for (var i = 0; i < coolerHelperArr.length; i++) {
var helper = coolerHelperArr[i];
helper.x = x;
helper.y = y;
helper.parentX = x;
helper.parentY = y;
x += radius * 2 + 3;
}
var smootherHelperArr = this.getHelpers('Smoother');
helpersNeeded = reqHelpers - smootherHelperArr.length;
for (var i = 0; i < helpersNeeded; i++) {
this.createHelper('Smoother', 0, 0, radius);
}
smootherHelperArr = this.getHelpers('Smoother');
x = 580;
y -= 35;
for (var i = 0; i < smootherHelperArr.length; i++) {
var helper = smootherHelperArr[i];
helper.x = x;
helper.y = y;
helper.parentX = x;
helper.parentY = y;
x += radius * 2 + 3;
}
var elasticizerHelperArr = this.getHelpers('Elasticizer');
helpersNeeded = reqHelpers - elasticizerHelperArr.length;
for (var i = 0; i < helpersNeeded; i++) {
this.createHelper('Elasticizer', 0, 0, radius);
}
elasticizerHelperArr = this.getHelpers('Elasticizer');
x = 580;
y -= 35;
for (var i = 0; i < elasticizerHelperArr.length; i++) {
var helper = elasticizerHelperArr[i];
helper.x = x;
helper.y = y;
helper.parentX = x;
helper.parentY = y;
x += radius * 2 + 3;
}
};
this.mixHelper = function(helper) {
// If this is NOT the first element being placed in the container...
// if (mixedElementsArr.length === 2) {
// Calculate the new formula
var formula = container.calcFormula(mixedElementsArr[0], helper);
// Combine the elements
var combinedElement = this.combineElements(mixedElementsArr[0], helper);
// Empty the container
// container.empty();
// Assign formula to combined element
combinedElement.formula = formula;
// Push combined element to container
// mixedElementsArr.push(combinedElement);
// }
// Calculate formula string
container.calcFormulaStr();
// Mix helper elements
// Loop through all properties of the mixed element in the container
for (var i = 0; i < mixedElementsArr[0].allPropertiesArr.length; i++) {
var property = mixedElementsArr[0].allPropertiesArr[i];
// If the property name matches the property name of the helper...
if (helper.property.name === property.name) {
// Add helper's value for that property to existing property value
mixedElementsArr[0][helper.property.name] += helper.property.value;
// If it ends up > 1, set to 1. If it ends up < 0, set to 0.
if (mixedElementsArr[0][helper.property.name] > 1) {
mixedElementsArr[0][helper.property.name] = 1;
}
else if (mixedElementsArr[0][helper.property.name] < -1) {
mixedElementsArr[0][helper.property.name] = -1;
}
// Set the properties
mixedElementsArr[0].setAllPropertiesArr();
}
}
// Remove this helper from the array of helpers as it is used up
helperElementsArr = utility.removeFromArray(helper, helperElementsArr);
};
// Get all helpers of a certain name
this.getHelpers = function(name) {
// Init array of specified helpers
var helperArr = [];
// Loop through array of all existing helpers
for (var i = 0; i < helperElementsArr.length; i++) {
// If helper name matches the specified name, add it to array
if (helperElementsArr[i].name === name) {
helperArr.push(helperElementsArr[i]);
}
}
return helperArr;
};
this.createBaseElements = function() {
// Create Toughinium
var element = new Element();
element.name = 'Toughinium';
element.formula = [{count: 1, symbol: 'To'}];
element.elasticity = 1;
element.texture = 0;
element.temperature = 0;
element.solidity = 0;
var soundSrc = jsfxr([2,0.02,0.11,0.35,0.32,0.77,,,,,,-0.4,0.63,,-0.56,,,,1,,,,,0.5]);
element.sound = new Audio();
element.sound.src = soundSrc;
element.color = {
r: 85,
g: 0,
b: 196
}
baseElementsArr.push(element);
// Create Roghitinam
element = new Element();
element.name = 'Roghitinam';
element.formula = [{count: 1, symbol: 'Ro'}];
element.elasticity = 0;
element.texture = 1;
element.temperature = 0;
element.solidity = 0;
element.color = {
r: 91,
g: 209,
b: 232
}
baseElementsArr.push(element);
// Create Heatonium
element = new Element();
element.name = 'Heatoinium';
element.formula = [{count: 1, symbol: 'He'}];
element.elasticity = 0;
element.texture = 0;
element.temperature = 1;
element.solidity = 0;
element.color = {
r: 232,
g: 0,
b: 43
}
baseElementsArr.push(element);
// Create Solidantium
element = new Element();
element.name = 'Solidantium';
element.formula = [{count: 1, symbol: 'So'}];
element.elasticity = 0;
element.texture = 0;
element.temperature = 0;
element.solidity = 1;
element.color = {
r: 227,
g: 16,
b: 235
}
baseElementsArr.push(element);
// Create Antemanium
element = new Element();
element.name = 'Antemanium';
element.formula = [{count: 1, symbol: 'An'}];
element.color = {
r: 115,
g: 222,
b: 0
}
baseElementsArr.push(element);
// Position the elements depending on game mode
// If main, they are positioned vertically along left side of canvas
if (gameMode === 'main') {
var x = 25;
var y = (canvas.height / 2) - ((25 * 5) + (40 * 4)) / 2;
var size = 25;
var margin = 40;
}
// Otherwise (meaning in menu) they are positioned horizontally with instructions
else {
var x = 10;
var y = 300;
var size = 25;
var margin = 40;
}
// Loop through all the elements and position based on the above
for (var i = 0; i < baseElementsArr.length; i++) {
element = baseElementsArr[i];
element.x = x;
element.y = y;
if (gameMode === 'main') {
y += size + margin;
element.setAllPropertiesArr();
}
else {
x += size + margin;
}
}
};
// Spawn a new element of a certain name
this.spawnNewElement = function(name) {
var element = new Element();
switch (name) {
case 'Toughinium':
element.name = 'Toughinium';
element.formula = [{count: 1, symbol: 'To'}];
element.elasticity = 1;
element.texture = 0;
element.temperature = 0;
element.solidity = 0;
var soundSrc = jsfxr([2,0.02,0.11,0.35,0.32,0.52,,0.1599,,0.04,0.14,0.4599,0.63,,-0.56,,-0.28,0.06,1,,,,,0.5]);
element.sound = new Audio();
element.sound.src = soundSrc;
element.color = {
r: 85,
g: 0,
b: 196
}
break;
case 'Roghitinam':
element.name = 'Roghitinam';
element.formula = [{count: 1, symbol: 'Ro'}];
element.elasticity = 0;
element.texture = 1;
element.temperature = 0;
element.solidity = 0;
var soundSrc = jsfxr([2,0.02,0.11,0.35,0.32,0.48,,0.1599,,0.04,0.14,-0.26,0.63,,-0.56,,-0.28,0.06,1,,,,,0.5]);
element.sound = new Audio();
element.sound.src = soundSrc;
element.color = {
r: 91,
g: 209,
b: 232
}
break;
case 'Heatoinium':
element.name = 'Heatoinium';
element.formula = [{count: 1, symbol: 'He'}];
element.elasticity = 0;
element.texture = 0;
element.temperature = 1;
element.solidity = 0;
var soundSrc = jsfxr([2,0.02,0.11,0.35,0.32,0.72,,0.1599,,0.04,0.14,-0.3199,0.63,,-0.56,,-0.28,0.48,1,,,,,0.5]);
element.sound = new Audio();
element.sound.src = soundSrc;
element.color = {
r: 232,
g: 0,
b: 43
}
break;
case 'Solidantium':
element.name = 'Solidantium';
element.formula = [{count: 1, symbol: 'So'}];
element.elasticity = 0;
element.texture = 0;
element.temperature = 0;
element.solidity = 1;
var soundSrc = jsfxr([2,0.02,0.11,0.35,0.32,0.44,,0.1599,,0.04,0.14,0.4399,0.63,,-0.56,,-0.28,0.06,1,,,,,0.5]);
element.sound = new Audio();
element.sound.src = soundSrc;
element.color = {
r: 227,
g: 16,
b: 235
}
break;
case 'Antemanium':
element.name = 'Antemanium';
element.formula = [{count: 1, symbol: 'An'}];
element.elasticity = -1;
element.texture = -1;
element.temperature = -1;
element.solidity = -1;
var soundSrc = jsfxr([2,0.02,0.11,0.35,0.32,0.29,,0.1599,,0.04,0.14,0.4399,0.63,,-0.56,,-0.28,0.06,1,,,,,0.5]);
element.sound = new Audio();
element.sound.src = soundSrc;
element.color = {
r: 115,
g: 222,
b: 0
}
break;
};
// Create array of properties for element
element.allPropertiesArr = [
{
name: 'elasticity',
value: element.elasticity,
description: this.getPropertyDescription('elasticity', element.elasticity)
},
{
name: 'texture',
value: element.texture,
description: this.getPropertyDescription('texture', element.texture)
},
{
name: 'temperature',
value: element.temperature,
description: this.getPropertyDescription('temperature', element.temperature)
},
{
name: 'solidity',
value: element.solidity,
description: this.getPropertyDescription('solidity', element.solidity)
}
];
return element;
};
// Stir the elements
this.stirElements = function() {
container.volume = 100;
container.flushing = false;
// If this is NOT the first element being placed in the container...
if (mixedElementsArr.length === 2) {
// Calculate the new formula
var formula = container.calcFormula(mixedElementsArr[0], mixedElementsArr[1]);
// Combine the elements
var combinedElement = this.combineElements(mixedElementsArr[0], mixedElementsArr[1]);
// Empty the container
container.empty();
// Assign formula to combined element
combinedElement.formula = formula;
// Push combined element to container
mixedElementsArr.push(combinedElement);
}
// Calculate formula string
container.calcFormulaStr();
initBubbles();
};
// Combine two elements
this.combineElements = function(element1, element2) {
var name1 = element1.name
var name2 = element2.name;
// Get first 3 chars of first element name
var namePart1 = name1.match(/.{1,3}/g)[0];
// Split 2nd element name into sets of 3 chars
var name2Split = name2.match(/.{1,3}/g);
var namePart2 = "";
// Loop through all sets of 3 chars except the first from second element name & create second part of name
for (var i = 1; i < name2Split.length; i++) {
var string = name2Split[i];
namePart2 += string;
}
var name = namePart1 + namePart2;
// Create new element
var combinedElement = new Element();
combinedElement.name = name;
// Set all the properties for the new element
if (element1.name !== 'Antemanium' && element2.name !== 'Antemanium') {
combinedElement.elasticity = (element1.elasticity + element2.elasticity) / 2;
combinedElement.texture = (element1.texture + element2.texture) / 2;
combinedElement.temperature = (element1.temperature + element2.temperature) / 2;
combinedElement.solidity = (element1.solidity + element2.solidity) / 2;
}
else {
combinedElement.elasticity = (element1.elasticity * element2.elasticity);
combinedElement.texture = (element1.texture * element2.texture);
combinedElement.temperature = (element1.temperature * element2.temperature);
combinedElement.solidity = (element1.solidity * element2.solidity);
}
combinedElement.setAllPropertiesArr();
// Combine colors of the two combined elements into a new color
var newColor = {
r: Math.round(0.5 * element1.color.r + 0.5 * element2.color.r),
g: Math.round(0.5 * element1.color.g + 0.5 * element2.color.g),
b: Math.round(0.5 * element1.color.b + 0.5 * element2.color.b)
};
// Assign new color to combined element
combinedElement.color = newColor;
combinedElement.sound = element1.sound;
return combinedElement;
};
// Assign descriptions to each property value
this.getPropertyDescription = function(propertyName, value) {
switch (propertyName) {
case 'elasticity':
switch (true) {
case value >= 0.5:
return 'Rigid';
case value > -0.5:
return 'Firm';
default:
return 'Elastic';
}
break;
case 'texture':
switch (true) {
case value >= 0.5:
return 'Rough';
case value > -0.5:
return 'Semi-rough';
default:
return 'Smooth';
}
break;
case 'temperature':
switch (true) {
case value >= 0.5:
return 'Hot';
case value > -0.5:
return 'Warm';
default:
return 'Cold';
}
break;
case 'solidity':
switch (true) {
case value >= 0.5:
return 'Solid';
case value > -0.5:
return 'Gel';
default:
return 'Liquid';
}
break;
}
}
};
// These are just for visual effect - other than that they do nothing.
function Bubble() {
this.x = container.x;
this.y = container.y;
this.parentX = this.x;
this.parentY = this.y;
this.radius;
this.color;
this.floatSpeedX;
this.floatSpeedY;
this.alpha = 1;
this.init = function() {
this.floatSpeedX = utility.randomFromTo(-10,10);
this.floatSpeedX = this.floatSpeedX / 25;
this.floatSpeedY = utility.randomFromTo(5,10) / 25;
this.radius = utility.randomFromTo(5,15);
this.y = container.y - container.radius + this.radius;
this.parentY = this.y;
}
this.setColor = function() {
var mixedElement = mixedElementsArr[0];
this.color = mixedElement.color;
}
this.draw = function() {
if (this.alpha <= 0.01) {
utility.removeFromArray(this, bubblesArr);
}
else {
if (this.color) {
if (!container.flushing) {
if (this.x < container.x - container.radius / 2 ||
this.x > container.x + container.radius / 2) {
this.alpha -= 0.03;
}
if (this.y < container.y - container.height) {
this.alpha -= 0.03;
}
}
this.x += this.floatSpeedX;
this.y -= this.floatSpeedY;
ctx.fillStyle = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.alpha + ')';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.closePath();
ctx.fill();
}
}
}
}; |
const express = require('express');
const router = express.Router();
const UserController = require('./../controllers/UserController');
const PhoneController = require('./../controllers/PhoneController');
const AuthController = require('./../controllers/AuthController');
const ReportController = require('../controllers/ReportController');
const SpecialistController = require('../controllers/SpecialistController');
const RatingController = require('../controllers/RatingController');
const TypeAdvisoriesController = require('../controllers/TypeAdvisoriesController');
const BankingHistoryController = require('../controllers/BankingHistoryController');
const DoctorController = require('../controllers/DoctorController');
const PatientsController = require('../controllers/PatientsController');
const ChatsHistoryController = require('../controllers/ChatsHistoryController');
const PaymentsHistoryController = require('../controllers/PaymentsHistoryController');
const UploadImageController = require('../controllers/UploadImageController');
const NotificationController = require('../controllers/NotificationController');
const BankController = require('../controllers/BankController');
const IntroduceAndRuleController = require('../controllers/IntroduceAndRuleController');
const ReportConversationController = require('../controllers/ReportConversationController');
const VideoCallHistoryController = require('../controllers/VideoCallHistoryController');
const passport = require('passport');
const path = require('path');
require('./../middleware/passport')(passport);
/* GET home page. */
router.get('/', function (req, res, next) {
res.json({
status: 'success',
message: 'Your doctor api',
data: {
'version_number': 'v1.0.0',
},
});
});
//Auth controller
router.post('/auth/register', AuthController.register);
router.post('/auth/login', AuthController.login);
router.post('/auth/logout', AuthController.logout);
//User controllerss
router.get('/users', passport.authenticate('jwt', {
session: false,
}), UserController.get);
router.put('/users', passport.authenticate('jwt', {
session: false,
}), UserController.update);
router.put('/users/update-user', passport.authenticate('jwt', {
session: false,
}), UserController.updateUser);
router.put('/users/changePassword', passport.authenticate('jwt', {
session: false,
}), UserController.changePassword);
router.get('/users/forgotPassword/:phoneNumber', UserController.forgotPassword);
router.delete('/users', passport.authenticate('jwt', {
session: false,
}), UserController.remove);
router.get('/users/detail/:userId', passport.authenticate('jwt', {
session: false,
}), UserController.getUserById);
router.delete('/users/:userId', passport.authenticate('jwt', {
session: false,
}), UserController.deleteUserById);
router.get('/users/get-all-user', passport.authenticate('jwt', {
session: false,
}), UserController.getAllUser);
// Introduce and Rule
router.post('/IntroduceAndRule', IntroduceAndRuleController.create);
router.get('/IntroduceAndRule', IntroduceAndRuleController.get);
//Phone
router.post('/phone/sms', PhoneController.sendPhoneVerifyCode);
router.post('/phone/verify', PhoneController.verifyPhoneVerifyCode);
//--------------- Report
router.post('/reports', passport.authenticate('jwt', {
session: false,
}), ReportController.create);
router.get('/reports/get-list-report-doctor', passport.authenticate('jwt', {
session: false,
}), ReportController.get);
router.put('/reports/update-report-doctor/:id', passport.authenticate('jwt', {
session: false,
}), ReportController.updateReportDoctorProcessing);
//--------------- Specialist
router.post('/specialists', SpecialistController.create);
router.get('/specialists/get-all-specialist', passport.authenticate('jwt', {
session: false,
}), SpecialistController.getAllSpecialist);
router.get('/specialists/getListSpecialist', SpecialistController.getListSpecialist);
router.get('/specialists/getDetailSpecialist/:specialistId', SpecialistController.getDetailSpecialist);
router.put('/specialists/:id', passport.authenticate('jwt', {
session: false,
}), SpecialistController.update);
router.delete('/specialists', passport.authenticate('jwt', {
session: false,
}), SpecialistController.remove);
router.delete('/specialists/:id', passport.authenticate('jwt', {
session: false,
}), SpecialistController.deleteById);
//--------------- Rating
router.post('/ratings', passport.authenticate('jwt', {
session: false,
}), RatingController.create);
router.get('/ratings/:doctorId', passport.authenticate('jwt', {
session: false,
}), RatingController.getCommentAndRating);
router.get('/ratings/countPatientRatingForDoctor/:doctorId', passport.authenticate('jwt', {
session: false,
}), RatingController.countPatientRatingForDoctor);
//--------------- Type_advisories
router.post('/typeadvisorys', passport.authenticate('jwt', {
session: false,
}), TypeAdvisoriesController.create);
router.get('/typeadvisorys/getAllTypeAdvisories', passport.authenticate('jwt', {
session: false,
}), TypeAdvisoriesController.getAllTypeAdvisories);
router.get('/typeadvisorys/getTypeAdvisoriesById/:id', passport.authenticate('jwt', {
session: false,
}), TypeAdvisoriesController.getTypeAdvisoriesById);
router.put('/typeadvisorys/:typeId', passport.authenticate('jwt', {
session: false,
}), TypeAdvisoriesController.update);
router.delete('/typeadvisorys', passport.authenticate('jwt', {
session: false,
}), TypeAdvisoriesController.remove);
router.delete('/typeadvisorys/:typeId', passport.authenticate('jwt', {
session: false,
}), TypeAdvisoriesController.deleteById);
//---------------Banking_history
router.post('/bankinghistorys/doctorWithdrawal', passport.authenticate('jwt', {
session: false,
}), BankingHistoryController.doctorWithdrawal);
router.post('/bankinghistorys/checkCodeVerify', BankingHistoryController.checkCodeVerify);
router.get('/bankinghistorys/getHistoryBanking/:userId', passport.authenticate('jwt', {
session: false,
}), BankingHistoryController.getHistoryBanking);
router.get('/bankinghistorys/get-detail-banking/:id',passport.authenticate('jwt', {
session: false,
}), BankingHistoryController.getDetailHistoryById);
router.put('/bankinghistorys/handleBankingHistory/:id', passport.authenticate('jwt', {
session: false,
}),BankingHistoryController.handleBankingHistory);
router.get('/bankinghistorys/get-list-banking-pending', passport.authenticate('jwt', {
session: false,
}),BankingHistoryController.getListBankingPendingVerify);
router.delete('/bankinghistorys/:id', passport.authenticate('jwt', {
session: false,
}), BankingHistoryController.removeLogic);
router.get('/bankinghistorys', passport.authenticate('jwt', {
session: false,
}), BankingHistoryController.getAllBanking);
//---------------Doctor
router.post('/doctors', DoctorController.registerDoctor);
router.get('/doctors', passport.authenticate('jwt', {
session: false,
}), DoctorController.getDoctor);
router.get('/doctors/getInformationDoctorById/:doctorId', passport.authenticate('jwt', {
session: false,
}), DoctorController.getInformationDoctorById);
router.get('/doctors/getListSpecialistDoctor', passport.authenticate('jwt', {
session: false,
}), DoctorController.getListSpecialistDoctor);
router.get('/doctors/getDoctorRankingBySpecialist/:specialistId', passport.authenticate('jwt', {
session: false,
}), DoctorController.getDoctorRankingBySpecialist);
router.get('/doctors/getDetailDoctor/:doctorId', passport.authenticate('jwt', {
session: false,
}), DoctorController.getDetailDoctor);
router.put('/doctors', passport.authenticate('jwt', {
session: false,
}), DoctorController.update);
router.delete('/doctors', passport.authenticate('jwt', {
session: false,
}), DoctorController.remove);
router.get('/doctors/getListDoctorPending', passport.authenticate('jwt', {
session: false,
}), DoctorController.getListDoctorPending);
router.put('/doctors/confirmInforDoctor', passport.authenticate('jwt', {
session: false,
}), DoctorController.confirmInforDoctor);
router.get('/doctors/doctors-by-specialist', DoctorController.getDoctorsBySpecialist);
//-----------Patient
router.post('/patients', passport.authenticate('jwt', {
session: false,
}), PatientsController.create);
router.get('/patients/getPatients', passport.authenticate('jwt', {
session: false,
}), PatientsController.getPatients);
router.get('/patients/getInformationPatientById/:patientId', passport.authenticate('jwt', {
session: false,
}), PatientsController.getInformationPatientById);
router.get('/patients/getListFavoriteDoctor/:patientId', passport.authenticate('jwt', {
session: false,
}), PatientsController.getListFavoriteDoctor);
router.get('/patients/getListIDFavoriteDoctor/:patientId', passport.authenticate('jwt', {
session: false,
}), PatientsController.getListIDFavoriteDoctor);
router.put('/patients', passport.authenticate('jwt', {
session: false,
}), PatientsController.update);
router.put('/patients/addFavoriteDoctor', passport.authenticate('jwt', {
session: false,
}), PatientsController.addFavoriteDoctor);
router.put('/patients/removeFavoriteDoctor', passport.authenticate('jwt', {
session: false,
}), PatientsController.removeFavoriteDoctor);
router.delete('/patients', passport.authenticate('jwt', {
session: false,
}), PatientsController.remove);
//-----------ChatsHistory
router.post('/chatshistorys', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.create);
router.put('/chatshistorys', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.updateRecord);
router.get('/chatshistorys/getAllConversationByPatient/:patientId', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.getAllConversationByPatient);
router.get('/chatshistorys/getAllConversationByDoctor/:doctorId', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.getAllConversationByDoctor);
router.get('/chatshistorys/getConversationByID/:id', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.getConversationByID);
router.get('/chatshistorys/getListConversationPending/:patientId', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.getListConversationPending);
router.post('/chatshistorys/checkDoctorReply', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.checkDoctorReply);
router.post('/chatshistorys/checkStatusChatsHistory', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.checkStatusChatsHistory);
router.get('/chatshistorys/doctorDenyRequestChat/:id', passport.authenticate('jwt', {
session: false,
}), ChatsHistoryController.doctorDenyRequestChat);
//----------PaymentHistory
router.post('/paymentshistorys', passport.authenticate('jwt', {
session: false,
}), PaymentsHistoryController.create);
router.get('/paymentshistorys/getPaymentHistoryByUser/:userID', passport.authenticate('jwt', {
session: false,
}), PaymentsHistoryController.getPaymentHistoryByUser);
// uploadImage
router.post('/uploadImageChat', UploadImageController.upload);
// test insert notification
router.post('/notifications', NotificationController.create);
router.get('/notifications/getAllNotificationByUser/:receiverId', passport.authenticate('jwt', {
session: false,
}), NotificationController.getAllNotificationByUser);
/// ReportConversationController
router.post('/reportConversations', passport.authenticate('jwt', {
session: false,
}), ReportConversationController.createReportConveration);
router.put('/reportConversations/update-report-conversation', passport.authenticate('jwt', {
session: false,
}), ReportConversationController.updateReportConversationProcessing);
router.get('/reportConversations/get-list-report-conversation', passport.authenticate('jwt', {
session: false,
}), ReportConversationController.getListReport);
router.get('/reportConversations/get-detail-report-conversation', passport.authenticate('jwt', {
session: false,
}), ReportConversationController.getDetailReport);
router.get('/reportConversations/:reportId', passport.authenticate('jwt', {
session: false,
}), ReportConversationController.getReportById);
router.put('/reportConversations/reportPunish', passport.authenticate('jwt', {
session: false,
}), ReportConversationController.reportPunish);
//
router.post('/banks',passport.authenticate('jwt', {
session: false
}), BankController.create);
router.get('/banks',passport.authenticate('jwt', {
session: false
}), BankController.get);
///////// video call history
router.get('/videcallhistories/getHistoryVideoCallPatient/:patientId',passport.authenticate('jwt', {
session: false
}), VideoCallHistoryController.getHistoryVideoCallPatient);
router.get('/videcallhistories/getHistoryVideoCallDoctor/:doctorId',passport.authenticate('jwt', {
session: false
}), VideoCallHistoryController.getHistoryVideoCallDoctor);
router.get('/videcallhistories/:id',passport.authenticate('jwt', {
session: false
}), VideoCallHistoryController.getById);
router.get('/download/:file(*)',(req, res) => {
const file = req.params.file;
const fileLocation = path.join('../../../../tmp/videos',file);
console.log(fileLocation);
res.download(fileLocation, file);
});
module.exports = router;
|
function runTest()
{
FBTest.openNewTab(basePath + "commandLine/4209/issue4209.html", function(win)
{
FBTest.openFirebug(function()
{
FBTest.enableConsolePanel(function(win)
{
var config = {tagName: "a", classes: "objectLink objectLink-object"};
FBTest.waitForDisplayedElement("console", config, function(row)
{
FBTest.compare(/Object\s*{\s*obj={...}}/, row.textContent,
"The result must match");
FBTest.testDone();
});
FBTest.clickToolbarButton(null, "fbConsoleClear");
FBTest.executeCommand("var a = {obj: {prop: 1}}; a;");
});
});
});
}
|
var bolognese = document.getElementById("bolognese");
var baked = document.getElementById("baked");
// var avocado = document.getElementById("avocado");
// var roasted = document.getElementById("roasted");
// var half = document.getElementById("half");
// var mushroom = document.getElementById("mushroom");
// var aglio = document.getElementById("aglio");
// var sumatran = document.getElementById("sumatran");
// var ginger = document.getElementById("ginger");
// var random = document.getElementById("random");
// var food = document.getElementById('food').value;
// var dishh;
// if(food =='Fixed Rate'){
// rate_value = document.getElementById('avocado').value;
// }else if(rates =='Variable Rate'){
// rate_value = document.getElementById('roasted').value;
// }else if(rates =='Multi Rate'){
// rate_value = document.getElementById('r3').value;
// }
// document.getElementById('results').innerHTML = rate_value;
var output = document.querySelector('#output');
var results = document.querySelector('#results');
function displayI(xx){
output.innerText = xx ;
}
function displayR(xx){
results.innerText = xx ;
}
var state = 0
var invalid = "Input Invalid, choose dish again"
var bolog = "choose ingredients.. \n tomatoes / ginger / minced meat / salt / butter / fettuccine"
var baked = "choose ingredients.. \n salmon / lemon / minced meat / ginger / / pepper / salt / butter"
var avocado = "choose ingredients.. \n milk / avocado / tomatoes / minced meat / sugar"
var roasted = "choose ingredients.. \n cashew nuts / salt / rocks / minced meat / cumin / salt"
var half = "choose ingredients.. \n water / salt / rocks / eggs / sugar / salt "
var mushroom = "choose ingredients.. \n water / glutinous rice / couscous / eggs / mushroom / pessimon "
var aglio = "choose ingredients.. \n water / glutinous rice / spaghetti / eggs / garlic / red pepper flakes "
var sumatran = "choose ingredients.. \n beef / lime leaves / galangal / rempah / chilli "
var ginger = "choose ingredients.. \n seasame oil / garlic / pork / beehoon / chilli / ginger "
var correct = "Congrats, you are a master chef! or so you think.."
var sure = "Are you sure"
// console.log("choose 5 ingredients..\nmacaroni/lemon/tomatoes/ginger/minced meat/pepper/salt")
// document.querySelector('bolognese').addEventListener('click', function(event){
// console
// })
// "milk"||"avocado"||"tomatoes"||"minced meat"||"sugar"
// "cashew nuts"||"salt"||"rocks"||"minced meat"||"cumin"||"salt"
// "water"||"salt"||"rocks"||"eggs"||"sugar"||"salt "
// "glutinous rice"||"water"||"couscous"||"eggs"||"mushroom"||"pessimon "
// "water"||"glutinous rice"||"spaghetti"||"eggs"||"garlic"||"red pepper flakes "
// "beef"||"lime leaves"||"galangal"||"rempah"||"chilli"
// "seasame oil"||"garlic"||"pork"||"beehoon"||"chilli"||"ginger "
// var input2 = document.querySelector('#input2').value
// console.log(input2)
document.querySelector('#input2').addEventListener('change', function(event){
if(state==1){
var currentInput = event.target.value;
console.log(currentInput)
if(currentInput === "tomatoes"||"ginger"||"minced meat"||"salt"||"butter"||"fettuccine"){
displayR(correct)
}
else if(currentInput === "salmon"||"lemon"||"minced meat"||"ginger"||"pepper"||"salt"||"butter"){
displayR(baked)
}
else if(currentInput === "Avocado"){
displayR(avocado)
}
else if(currentInput === "Roasted"){
displayR(roasted )
}
else if(currentInput === "Half"){
displayR(half)
}
else if(currentInput === "Mushroom"){
displayR(mushroom)
}
else if(currentInput === "Aglio"){
displayR(aglio)
}
else if(currentInput === "Sumatran"){
displayR(sumatran)
}
else if(currentInput === "Ginger"){
displayR(ginger)
}
else{
displayR("are you sure")
}
}
else{
displayR(invalid)
}
})
document.querySelector('#input').addEventListener('change', function(event){
var currentInput = event.target.value;
//-------------------------------------------------------------------------------------BOLOG
if(state === 0 ){
if(currentInput === "Bolognese"){
displayI(bolog)
state = 1
}
//-------------------------------------------------------------------------------------BAKED
else if(currentInput === "Baked"){
displayI(baked)
state = 1
}
//-------------------------------------------------------------------------------------AVOCADO
else if(currentInput === "Avocado"){
displayI(avocado)
state = 1
}
//-------------------------------------------------------------------------------------ROASTED
else if(currentInput === "Roasted"){
displayI(roasted)
state = 1
}
//-------------------------------------------------------------------------------------HALF
else if(currentInput === "Half"){
displayI(half)
state = 1
}
//-------------------------------------------------------------------------------------MUSHROOM
else if(currentInput === "Mushroom"){
displayI(mushroom)
state = 1
}
//-------------------------------------------------------------------------------------AGLIO
else if(currentInput === "Aglio"){
displayI(aglio)
state = 1
}
//-------------------------------------------------------------------------------------SUMATRAN
else if(currentInput === "Sumatran"){
displayI(sumatran)
state = 1
}
//-------------------------------------------------------------------------------------GINGER
else if(currentInput === "Ginger"){
displayI(ginger)
state = 1
}
else{displayI(invalid)
}
}
else{displayI(invalid)
}
})
// -------------------- function confirm() {
// var x = document.getElementById("baked");
// if (x.style.display === "none") {
// x.style.display = "block";
// } else {
// x.style.display = "none";
// }
// }
// ------------------(Math.random()*1) for select one randomly
|
import moxios from 'moxios'
const {
__httpClient__,
updateClient,
getAsync,
postAsync,
putAsync,
deleteAsync
} = jest.requireActual('..')
describe('Api', () => {
const data = {
firstName: 'Dimitri',
lastName: 'Kurashvili'
}
const responseData = {
id: 1,
first_name: 'Dimitri',
last_name: 'Kurashvili'
}
function assertSuccessfulResponse(resp) {
expect(resp.isSuccess).toBe(true)
expect(resp.data.data).toEqual({
id: 1,
firstName: 'Dimitri',
lastName: 'Kurashvili'
})
}
beforeEach(() => {
moxios.install(__httpClient__())
})
afterEach(() => {
moxios.uninstall(__httpClient__())
updateClient()
})
test('updateClient', () => {
updateClient({
baseUrl: 'https://my.server/api',
httpHeaders: {
authorization: 'token'
}
})
const client = __httpClient__()
expect(client.defaults.timeout).toBe(10000)
expect(client.defaults.headers.authorization).toBe('token')
expect(client.defaults.baseURL).toBe('https://my.server/api')
})
test('getAsync', async () => {
let request
moxios.wait(async () => {
request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: {
data: responseData
}
})
})
const resp = await getAsync('/profiles/1')
expect(request.config.url).toBe('/profiles/1')
expect(request.config.method).toBe('get')
assertSuccessfulResponse(resp)
})
test('postAsync', async () => {
let request
moxios.wait(async () => {
request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: {
data: responseData
}
})
})
const resp = await postAsync('/profiles', data)
expect(request.config.url).toBe('/profiles')
expect(request.config.method).toBe('post')
expect(JSON.parse(request.config.data)).toEqual({
first_name: 'Dimitri',
last_name: 'Kurashvili'
})
assertSuccessfulResponse(resp)
})
test('putAsync', async () => {
let request
moxios.wait(async () => {
request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: {
data: responseData
}
})
})
const resp = await putAsync('/profiles/1', data)
expect(request.config.url).toBe('/profiles/1')
expect(request.config.method).toBe('put')
expect(JSON.parse(request.config.data)).toEqual({
first_name: 'Dimitri',
last_name: 'Kurashvili'
})
assertSuccessfulResponse(resp)
})
test('deleteAsync', async () => {
let request
moxios.wait(async () => {
request = moxios.requests.mostRecent()
request.respondWith({
status: 200,
response: {
data: {
ok: true
}
}
})
})
const resp = await deleteAsync('/profiles/1')
expect(request.config.url).toBe('/profiles/1')
expect(request.config.method).toBe('delete')
expect(request.config.data).toBe(undefined)
expect(resp.isSuccess).toBe(true)
})
})
|
angular
.module('app')
.controller('aboutCtrl', ['$scope','Friends', function($scope, Friends) {
$scope.title = "About";
$scope.friends = Friends.get();
$scope.items = ['a', 'b', 'c'];
}]);
|
"use strict"
class DocMerger {
constructor(combinedDoc, doc, pathProcessor) {
this.combinedDoc = combinedDoc
this.doc = doc
this.pathProcessor = pathProcessor
}
mergeDoc() {
if (this.combinedDoc) {
const newDoc = this.newDocAfterRenamingSchemaReferences()
this.updatePathsInCombinedDoc(newDoc.paths)
} else {
this.combinedDoc = this.doc
}
return this.combinedDoc
}
newDocAfterRenamingSchemaReferences() {
const renamedSchemas = this.getRenamedSchemas()
if (renamedSchemas.length > 0) {
const docJson = JSON.stringify(this.doc);
const schemaRef = (name) => "\"#/components/schemas/" + name.replace(/\//g, "~1") + "\""
const newDocJson = renamedSchemas.reduce((accumulator, currentValue) => {
return replaceAll(
accumulator,
schemaRef(currentValue.oldName),
schemaRef(currentValue.newName))
}, docJson)
const newDoc = JSON.parse(newDocJson)
this.updateSchemasInCombinedDoc(newDoc.components.schemas, renamedSchemas)
return newDoc
} else {
return this.doc
}
}
updatePathsInCombinedDoc(paths) {
for (let path in paths) {
const path2 = (this.pathProcessor) ?
this.pathProcessor(this.combinedDoc, path, this.doc.info.title) :
path
this.combinedDoc.paths[path2] = paths[path]
}
}
getRenamedSchemas() {
if (!this.doc.components || !this.doc.components.schemas) return []
const newName = (oldName) => (oldName + "_" + this.doc.info.title)
.replace(new RegExp("\\s", "g"), "_")
return Object.keys(this.doc.components.schemas).map(schema => {
return {
"oldName": schema,
"newName": newName(schema)
}
})
}
updateSchemasInCombinedDoc(schemas, renamedSchemas) {
for (let schema in schemas) {
const renamedSchema = this.renamedSchemaName(schema, renamedSchemas)
this.combinedDoc.components.schemas[renamedSchema] = schemas[schema]
}
}
renamedSchemaName(schema, renamedSchemas) {
const filteredSchemas = renamedSchemas.filter(function (val, index, arr) {
return val.oldName == schema
})
return (filteredSchemas.length == 1) ? filteredSchemas[0].newName : null
}
}
function replaceAll(str, a, b) {
return str.split(a).join(b)
}
module.exports = {
// pathProcessor is needed in scenarios where you want to replace the path
// /v1/appointments/ with /appointments
// while merging it into combined doc
// if not provided, same path will be used
"mergeDoc": function (combinedDoc, doc, pathProcessor) {
const docMerger = new DocMerger(combinedDoc, doc, pathProcessor)
return docMerger.mergeDoc()
}
} |
import React from "react"
import { Map, TileLayer, Marker } from "react-leaflet"
// import { icon } from "leaflet"
import { css } from "@emotion/core"
import "leaflet/dist/leaflet.css"
export default ({ position }) => (
<Map
center={position}
zoom={15}
css={css`
@media screen and (max-width: 943px) {
height: 280px;
}
`}
>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={position}
// icon={icon({
// iconUrl: "/icon/markerIcon.png",
// iconSize: [25, 34],
// iconAnchor: [13, 34],
// })}
></Marker>
</Map>
)
|
import { put } from "redux-saga/effects";
import { failureList, successList } from "Reducers/people";
import create from "Services/api";
const api = create("people");
export function* getPeople() {
try {
const response = yield api.getAll({});
if (response.ok) {
const { results } = response.data;
yield put(successList(results));
} else {
yield put(failureList(response.originalError));
}
} catch (e) {
yield put(failureList(e));
}
}
|
function ApiError( message, status, errors ){
this.message = message;
this.status = status;
this.errors = errors || [];
}
ApiError.create = function( err, status ){
if( err instanceof ApiError ){
return err;
} else if( Array.isArray( err ) ){
return new ApiError( 'Multiple Errors', err.status || status, err );
}
return new ApiError( err.message || err, err.status || status );
}
module.exports = ApiError;
|
const config = require("../config/db.config.js");
const Sequelize = require("sequelize");
const db = {};
const sequelize = new Sequelize(config.DB, config.USER, config.PASSWORD, {
host: config.HOST,
dialect: config.dialect,
operatorsAliases: 0,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false,
},
},
pool: {
max: config.pool.max,
min: config.pool.min,
acquire: config.pool.acquire,
idle: config.pool.idle,
},
});
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.user = require("../models/user.model.js")(sequelize, Sequelize);
db.marker = require("../models/marker.model.js")(sequelize, Sequelize);
db.event = require("../models/event.model.js")(sequelize, Sequelize);
db.todo = require("../models/todo.model.js")(sequelize, Sequelize);
db.habit = require("../models/habit.model.js")(sequelize, Sequelize);
db.marker.belongsTo(db.user);
db.event.belongsTo(db.user);
db.todo.belongsTo(db.user);
db.habit.belongsTo(db.user);
module.exports = db;
|
/* APIs.js */
var i = 0, treeview;
$(function () {
$("#sampleProperties").ejPropertiesPanel();
var treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
});
// Client side APIs
function onExpandAll(args) {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model) {
if (args.isChecked)
treeview.expandAll();
else
treeview.collapseAll();
}
}
function onCheckAll(args) {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model) {
if (args.isChecked)
treeview.checkAll();
else
treeview.unCheckAll();
}
}
function onExpand() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model)
treeview.expandNode(treeview.getSelectedNode());
}
function onCollapse() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model)
treeview.collapseNode(treeview.getSelectedNode());
}
function onCheck() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model)
treeview.checkNode(treeview.getSelectedNode());
}
function onUncheck() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model)
treeview.uncheckNode(treeview.getSelectedNode());
}
function onEnable() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model) {
var node = $("#LayoutSection_ControlsSection_treeview").find('.e-node-disable');
treeview.enableNode(node[0]);
}
}
function onDisable() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model)
treeview.disableNode(treeview.getSelectedNode());
}
function onAddNew() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model) {
treeview.addNode("Item" + i, treeview.getSelectedNode());
i++;
}
}
function onRemoveNode() {
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
if (treeview.model)
treeview.removeNode(treeview.getSelectedNode());
}
function onDestoryRestore(args) {
i = 0;
if (args.isChecked) {
$("button[id^='btn']").attr('disabled', 'disabled');
$("input[id^='btn']").ejToggleButton("disable")
treeview.destroy();
}
else {
$("#LayoutSection_ControlsSection_treeview").ejTreeView(
{
showCheckbox: true,
allowEditing: true
});
$("button[id^='btn']").removeAttr('disabled');
$("input[id^='btn']").ejToggleButton("enable")
treeview = $("#LayoutSection_ControlsSection_treeview").data("ejTreeView");
}
} |
import {component} from '@reduct/component';
import propTypes from '@reduct/nitpick';
import lighten from 'lightness';
import {loadJs} from './../Utilities/';
const dependencies = [
'https://www.amcharts.com/lib/3/amcharts.js',
'https://www.amcharts.com/lib/3/serial.js',
'https://www.amcharts.com/lib/3/themes/light.js',
'https://www.amcharts.com/lib/3/gantt.js'
];
const themeColor = '#26224C';
const config = {
type: 'gantt',
theme: 'light',
period: 'YYYY',
dataDateFormat: 'YYYY-MM',
columnWidth: 0.65,
precision: 1,
graph: {
fillAlphas: 1,
balloonText: '<b>[[task]]</b>: [[open]]-[[value]]'
},
rotate: true,
categoryField: 'version',
segmentsField: 'segments',
colorField: 'color',
startDateField: 'start',
endDateField: 'end',
valueScrollbar: {
autoGridCount: true,
color: '#555555'
},
chartCursor: {
cursorColor: themeColor,
valueBalloonsEnabled: false,
cursorAlpha: 0,
valueLineAlpha: 0.5,
valueLineBalloonEnabled: true,
valueLineEnabled: true,
zoomable: false,
valueZoomable: true
},
export: {
enabled: true,
divId: 'exportContainer',
position: 'bottom-right',
fileName: 'typo3-support-times',
menu: ['PNG', 'PDF', 'SVG']
}
};
@component({
dataSelector: propTypes.string.isRequired
})
export default class AmChart {
constructor() {
// Hence AmCharts relies on element id's, we generate a random one.
this.el.setAttribute('id', `amChart__${Math.random() * 1000}`);
this.loadDependencies()
.then(() => this.initializeGlobals())
.then(() => this.render());
}
getDefaultProps() {
return {
dataSelector: '[data-json]'
};
}
loadDependencies() {
return new Promise(resolve => {
dependencies.reduce((prev, cur) => {
const isLast = cur === dependencies[dependencies.length - 1];
return prev.then(() => loadJs(cur)).then(() => {
if (isLast) {
resolve();
}
});
}, Promise.resolve());
});
}
initializeGlobals() {
// AmCharts isn't published on npm, thus we load it via their CDN and setup the global - Yeah...
try {
window.AmCharts.useUTC = true;
} catch (e) {}
return Promise.resolve();
}
render() {
const dataProvider = this.parseData();
const today = new Date();
window.AmCharts.makeChart(this.el.getAttribute('id'), Object.assign({}, config, {
valueAxis: {
type: 'date',
autoGridCount: false,
gridCount: 24,
guides: [{
value: today,
toValue: today,
lineAlpha: 1,
lineThickness: 1,
inside: true,
labelRotation: 90,
label: 'Today',
above: true
}]
},
dataProvider
}));
}
parseData() {
const data = JSON.parse(this.find(this.props.dataSelector).innerHTML);
// To reduce the places where colors are defined, especially in the data itself,
// we automatically set colors for the chart depending on the index of the segment.
return data.map(obj => {
return Object.assign({}, obj, {
segments: obj.segments.map((segment, index) => {
const color = lighten(themeColor, index * 10);
return Object.assign({}, segment, {
color
});
})
});
});
}
}
|
import React, { useState, useEffect, useRef } from 'react';
import { useDrag } from 'react-use-gesture';
import PropTypes from 'prop-types';
import Icon from '../icon';
export const BottomSheet = (props) => {
const [show, setShow] = useState(props.show);
const [active, setActive] = useState(false);
const [heightChange, setHeightChange] = useState(0);
const [height, setHeight] = useState(global.window ? window.innerWidth < 600 ? 60 : 100 : 60);
const [touchAction, setTouchAction] = useState(false);
const [stylingSheet, setStylingSheet] = useState('rounded-t-2xl');
const [stylingContent, setStylingContent] = useState('overflow-y-hidden sm:overflow-y-scroll');
const sheetView = `fixed bottom-0 max-w-600px w-full pb-8 bg-white z-50 ${stylingSheet}`;
const contentView = `${stylingContent} w-full h-full flex flex-col sm:mt-4`;
const sheet = useRef (null);
const content = useRef (null);
useEffect(() => {
setShow(props.show);
}, [props.show]);
useEffect(() => {
show ? (document.body.style.overflow = 'hidden') : (document.body.style.overflow = 'unset');
}, [show]);
const setClose = props.close;
const bind = useDrag(({ active, last, movement: [, my] }) => {
setActive(active);
const changePercentage = -(my / window.innerHeight) * 100;
if (active === true && height === 60) {
setHeightChange(height + changePercentage);
} else if (active === true && height === 100) {
if (changePercentage < 0 && content.current?.scrollTop === 0) {
setHeightChange(height + changePercentage);
setTouchAction(false);
} else if (changePercentage > 0) {
setHeightChange(100);
setTouchAction(true);
} else setHeightChange(100);
}
if (last) {
if (height === 60) {
if (changePercentage > 20) {
setHeight(100);
setStylingContent('overflow-auto');
setStylingSheet('rounded-none');
setTouchAction(true);
} else if (changePercentage < -20) {
setClose();
}
}
if (height === 100) {
if (changePercentage < -20) {
setHeight(60);
setStylingContent('overflow-hidden');
setStylingSheet('rounded-t-2xl');
}
}
}
});
const handleClickOverlay = (e) => {
e.stopPropagation();
};
const closeOverlay = () => {
setClose();
setShow(false);
};
return (
<div>
{show ? (
<div
className="fixed top-0 w-full h-full max-w-600px mx-auto bg-nero bg-opacity-75 left-1/2 z-40"
onClick={closeOverlay}
style={{ transform: 'translateX(-50%)', transition: `${active ? '' : 'opacity 0.5s'}` }}
data-cy={'bottomsheet'}
>
<div
onClick={handleClickOverlay}
className={sheetView}
{...bind()}
style={{ touchAction: 'none', height: `${active ? heightChange : height}%` }}
ref={sheet}
>
<div className="w-10 mx-auto mt-2 mb-6 bg-nobel h-1 rounded-3xl sm:hidden" />
<div
className='absolute top-0 right-0 transform -translate-x-4 translate-y-4 cursor-pointer tablet:hidden xxs:hidden mini:hidden'
onClick={closeOverlay}
data-cy={'bottomsheet-close'}
>
<Icon
color='zambesi'
name='close'
/>
</div>
<div
className={contentView}
ref={content}
style={{ touchAction: `${touchAction ? 'auto' : 'none'}` }}
>
{props.children}
{stylingContent === 'overflow-auto' ? <div className="w-full h-4 bg-transparent sticky bottom-0" /> : null}
</div>
</div>
</div>
) : null}
</div>
);
};
BottomSheet.propTypes ={
show: PropTypes.bool,
children: PropTypes.node,
close: PropTypes.any,
}
BottomSheet.defaultProps = {
show: false
};
export default BottomSheet;
|
window.onload = function(){
const background = document.getElementsByTagName("background");
const order = document.getElementsByClassName("order");
const box = document.getElementsByClassName("ourcontacts");
// const container = document.getElementsByClassName("ourcontacts_container");
// const change = document.getElementsByClassName("change");
for(let i = 0; i < order.length; i++){
order[i].addEventListener('click', function(){
box[0].classList.toggle('inactive');
background[0].classList.toggle('active');
// container[0].classList.toggle('inactive');
// change[0].addEventListener('click', toggleWorkers);
// change[1].addEventListener('click', toggleWorkers);
});
}
background[0].addEventListener('click', function(){
box[0].classList.toggle('inactive');
background[0].classList.toggle('active');
// container[0].classList.add('inactive');
// container[1].classList.add('inactive');
});
// if(!box[0].classList.contains('inactive'))
// body[0].addEventListener('click', function(){
// box[0].classList.add('inactive');
// });
// function toggleWorkers(){
// container[0].classList.toggle('inactive');
// container[1].classList.toggle('inactive');
// }
}; |
import React from "react";
import {NavLink, Redirect, Route} from "react-router-dom";
import css from "./dialogs.module.css"
import {draftMessageActionCreator, sendMessageActionCreator} from "../../redux/dialogs-reducer";
import Login from "../component/auth";
import {Field, reduxForm} from "redux-form";
const MessageForm =(props)=>{
return<form onSubmit={props.handleSubmit}>
<Field component='textarea'
name='newMessageBody'
placeholder='Send Message'
className={css.textMessage}
//onChange={()=>{props.draft()}}
></Field>
<button>Send message</button>
</form>
}
function Dialogs (props) {
let getRef = React.createRef();
const send =(value)=>{
//let sendMessage = sendMessageActionCreator(id, getRef.current.value);
let sendMessage = value.newMessageBody
console.log(sendMessage)
props.sendMSG(1,sendMessage)
}
const draft =(id=1)=>{
let sendDraft = draftMessageActionCreator(id, getRef.current.value)
props.draftMSG(sendDraft)
}
const test =(value)=>{
alert(value.newMessageBody)
}
debugger
return <div className={css.body}>
<ul className={css.friends}>
{props.dialogs.friends.map(fr=><li><NavLink to={`/dialogs/${fr.userId}`}>{fr.name}</NavLink></li>)}
</ul>
<div className={css.messages}>
{props.dialogs.messages.map(di=>
<div>
<Route path={`/dialogs/${di.userId}`} render={
()=><p>{di.mess}</p>
}>
</Route>
</div>)
}
<div className={css.textSend}>
{props.dialogs.draft.map(dr=><Route path={`/dialogs/${dr.userId}`} render={
()=><MessageReduxForm
onSubmit={send}
/>
/*<div>
<textarea onChange={()=>{draft(dr.userId)}}
value={dr.draftMess}
className={css.textMessage}
ref={getRef}></textarea>
<button onClick={()=>{send(dr.userId)}} className={css.bottom}>Send message</button>
</div>*/
} />
)}
</div>
</div>
</div>
}
const MessageReduxForm = reduxForm({form: 'messageForm'})(MessageForm)
export default Dialogs; |
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
const CANVAS_HEIGHT = canvas.height;
const CANVAS_WIDTH = canvas.width;
let drawBB = false;
let worldObjects = [];
let worldBullets = [];
let animations = [];
let enemies = [];
let player;
let gameloop;
function circleCollidingWithRectangle(circle, rect, dx, dy) {
let hori_dist = Math.abs(circle.center.x - rect.center.x + dx);
let vert_dist = Math.abs(circle.center.y - rect.center.y + dy);
if (hori_dist > (rect.width/2 + circle.radius)) return false;
if (vert_dist > (rect.height/2 + circle.radius)) return false;
if (hori_dist <= (rect.width/2)) return true;
if (vert_dist <= (rect.height/2)) return true;
let cornerDistance_sq =
((hori_dist - rect.width / 2) ** 2) +
((vert_dist - rect.height / 2) ** 2);
return (cornerDistance_sq < (circle.radius ** 2));
}
function circleCollidingWithCirlce(circle1, circle2, dx, dy) {
let sq_dist = ((circle1.center.x - circle2.center.x + dx) ** 2) + ((circle1.center.y - circle2.center.y + dy) ** 2);
return (sq_dist < ((circle1.radius + circle2.radius) ** 2));
}
function possibleObjectCollision(obj1, obj2, dx, dy) {
if (obj1.bb_min.x - obj2.bb_max.x + dx >= 0) return false; // obj1 is right of obj2 if > 0
if (obj1.bb_min.y - obj2.bb_max.y + dy >= 0) return false; // obj1 is under obj2 if > 0
if (obj1.bb_max.x - obj2.bb_min.x + dx <= 0) return false; // obj1 is left of obj2 if > 0
if (obj1.bb_max.y - obj2.bb_min.y + dy <= 0) return false; // obj1 is above obj2 if > 0
return true;
}
function isColliding(obj1, obj2, dx, dy) {
if (obj1 instanceof Rectangle) {
if (obj2 instanceof Rectangle) {
return possibleObjectCollision(obj1, obj2, dx, dy);
} else {
return circleCollidingWithRectangle(obj2, obj1, dx, dy);
}
} else if (obj1 instanceof Circle) {
if (obj2 instanceof Rectangle) {
return circleCollidingWithRectangle(obj1, obj2, dx, dy);
} else {
return circleCollidingWithCirlce(obj1, obj2, dx, dy);
}
}
}
function checkCollision(obj1, obj2, dx, dy) {
return possibleObjectCollision(obj1, obj2, dx, dy) && isColliding(obj1, obj2, dx, dy);
}
function outsideCanvas(obj) {
if (obj.bb_min.x > CANVAS_WIDTH / 2) return true;
if (obj.bb_min.y > CANVAS_HEIGHT / 2) return true;
if (obj.bb_max.x < -CANVAS_WIDTH / 2) return true;
if (obj.bb_max.y < -CANVAS_HEIGHT / 2) return true;
return false;
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
}
class Line {
constructor(x1, y1, x2, y2, color) {
this.p1 = new Point(x1, y1);
this.p2 = new Point(x2, y2);
this.color = color;
this.length = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
}
move(dx, dy) {
this.p1.move(dx, dy);
this.p2.move(dx, dy);
}
draw() {
ctx.strokeStyle = this.color;
ctx.beginPath();
ctx.moveTo(this.p1.x + CANVAS_WIDTH / 2, this.p1.y + CANVAS_HEIGHT / 2);
ctx.lineTo(this.p2.x + CANVAS_WIDTH / 2, this.p2.y + CANVAS_HEIGHT / 2);
ctx.stroke();
}
}
class Rectangle {
constructor(x, y, width, height, color) {
this.center = new Point(x, y);
this.bb_min = new Point(x - width / 2, y - height / 2);
this.bb_max = new Point(x + width / 2, y + height / 2);
this.width = width;
this.height = height;
this.color = color;
}
move(dx, dy) {
this.center.move(dx, dy);
this.bb_min.move(dx, dy);
this.bb_max.move(dx, dy);
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.bb_min.x + CANVAS_WIDTH / 2, this.bb_min.y + CANVAS_HEIGHT / 2, this.width, this.height);
if (drawBB) {
ctx.strokeStyle = "black";
ctx.strokeRect(this.bb_min.x + CANVAS_WIDTH / 2, this.bb_min.y + CANVAS_HEIGHT / 2, this.width, this.height);
}
}
}
class Circle {
constructor(x, y, radius, color) {
this.radius = radius;
this.color = color;
this.center = new Point(x, y);
this.bb_min = new Point(x - radius, y - radius);
this.bb_max = new Point(x + radius, y + radius);
}
move(dx, dy) {
this.center.move(dx, dy);
this.bb_min.move(dx, dy);
this.bb_max.move(dx, dy);
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.center.x + CANVAS_WIDTH / 2, this.center.y + CANVAS_HEIGHT / 2, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
if (drawBB) {
ctx.strokeStyle = "black";
ctx.strokeRect(this.bb_min.x + CANVAS_WIDTH / 2, this.bb_min.y + CANVAS_HEIGHT / 2, this.bb_max.x - this.bb_min.x, this.bb_max.y - this.bb_min.y);
}
}
}
class Bullet extends Circle {
constructor(x, y, dx, dy, radius, direction, speed, color) {
super(x, y, radius, color);
this.speed = speed;
this.dx = dx;
this.dy = dy;
this.direction = direction;
}
}
class Gun extends Line {
constructor(x1, y1, x2, y2, direction, color) {
super(x1, y1, x2, y2, color);
this.firerate = 10;
this.magCapacity = 10;
this.direction = direction;
this.magCount = this.magCapacity;
this.lastShot = performance.now() - 1000;
}
reload() {
this.magCount = this.magCapacity;
}
isLoaded() {
return (this.magCount > 0);
}
rotate(v) {
this.direction += v;
this.p2.x = this.length * Math.cos(this.direction);
this.p2.y = this.length * Math.sin(this.direction);
}
tryShoot(dx, dy) {
if (performance.now() - this.lastShot > (1000 / this.firerate) && this.isLoaded()) {
this.shoot(dx, dy);
}
}
shoot(dx, dy) {
worldBullets.push(new Bullet(this.p2.x, this.p2.y, dx, dy, 3, this.direction, 7, "black"));
this.magCount -= 1;
this.lastShot = performance.now();
}
}
class CrossHair {
constructor(x1, y1, x2, y2, direction) {
this.direction = direction;
this.body = new Circle(x2, y2, 5, "red");
this.line = new Line(x1, y1, x2, y2, "red");
}
rotate(v) {
this.direction += v;
let new_x = this.line.length * Math.cos(this.direction);
let new_y = this.line.length * Math.sin(this.direction);
this.body.move(new_x - this.body.center.x, new_y - this.body.center.y);
this.line.p2.x = new_x;
this.line.p2.y = new_y;
}
move(dx, dy) {
this.line.move(dx,dy);
this.body.move(dx,dy);
}
draw() {
this.line.draw();
this.body.draw();
}
}
class Character {
constructor(direction, speed, rotationSpeed, health) {
this.direction = direction;
this.speed = speed;
this.health = health;
this.rotationSpeed = rotationSpeed;
this.body = new Circle(0, 0, 10, "green");
this.gun = new Gun(0, 0, 20, 0, direction, "red");
}
rotate(v) {
this.direction += v;
this.gun.rotate(v);
}
draw() {
this.body.draw();
this.gun.draw();
}
}
class Player extends Character {
constructor(direction, speed, rotationSpeed, health) {
super(direction, speed, rotationSpeed, health);
this.dx = 0;
this.dy = 0;
}
setDX(new_dx) {
this.dx = new_dx;
}
setDY(new_dy) {
this.dy = new_dy;
}
getDX() {
return this.dx;
}
getDY() {
return this.dy;
}
update() {
this.dx = 0;
this.dy = 0;
for (const k of keys) {
if (!k.pressed) {
continue;
}
var key = k.key;
if (key == 'w') { // forward
this.dx += this.speed * Math.cos(this.direction);
this.dy += this.speed * Math.sin(this.direction);
} else if (key == 'd') { // right
this.dx += this.speed * Math.cos(this.direction + Math.PI / 2);
this.dy += this.speed * Math.sin(this.direction + Math.PI / 2);
} else if (key == 's') { // backwards
this.dx -= this.speed * Math.cos(this.direction);
this.dy -= this.speed * Math.sin(this.direction);
} else if (key == 'a') { // left
this.dx += this.speed * Math.cos(this.direction - Math.PI / 2);
this.dy += this.speed * Math.sin(this.direction - Math.PI / 2);
} else if (key == "r") { // reload
this.gun.reload();
} else if (key == "ArrowRight") { // rotate clockwise
this.rotate(this.rotationSpeed);
} else if (key == "ArrowLeft") { // rotate counter clockwise
this.rotate(-this.rotationSpeed);
} else if (key == " ") { // space, shoot
this.gun.tryShoot(this.dx, this.dy);
}
}
}
}
class ExplosionAnimation {
constructor(x, y, duration, speed) {
this.shape = new Circle(x,y,2,"red");
this.duration = duration;
this.growSpeed = speed;
this.start = performance.now();
}
isDone() {
return (performance.now() - this.start > this.duration);
}
update(dx, dy) {
this.shape = new Circle(this.shape.center.x - dx, this.shape.center.y -dy, this.shape.radius + 1, this.shape.color);
if((performance.now() - this.start)/this.duration > 0.7) this.shape.color = "yellow";
}
draw() {
this.shape.draw();
}
}
const keys = [
{ key: "w", pressed: false },
{ key: "s", pressed: false },
{ key: "a", pressed: false },
{ key: "d", pressed: false },
{ key: "r", pressed: false },
{ key: "ArrowRight", pressed: false },
{ key: "ArrowLeft", pressed: false },
{ key: " ", pressed: false },
];
function keydown(e) {
switch (e.key) {
case "w":
keys[0].pressed = true;
break;
case "s":
keys[1].pressed = true;
break;
case "a":
keys[2].pressed = true;
break;
case "d":
keys[3].pressed = true;
break;
case "r":
keys[4].pressed = true;
break;
case "ArrowRight":
keys[5].pressed = true;
break;
case "ArrowLeft":
keys[6].pressed = true;
break;
case " ":
keys[7].pressed = true;
break;
default:
break;
}
}
function keyup(e) {
switch (e.key) {
case "w":
keys[0].pressed = false;
break;
case "s":
keys[1].pressed = false;
break;
case "a":
keys[2].pressed = false;
break;
case "d":
keys[3].pressed = false;
break;
case "r":
keys[4].pressed = false;
break;
case "ArrowRight":
keys[5].pressed = false;
break;
case "ArrowLeft":
keys[6].pressed = false;
break;
case " ":
keys[7].pressed = false;
break;
default:
break;
}
}
function checkPlayerCollision() {
for (const obj of worldObjects) {
if(checkCollision(player.body, obj, player.getDX(), player.getDY())) {
player.setDX(0);
player.setDY(0);
break;
}
}
}
function updateObjects() {
const dx = player.getDX();
const dy = player.getDY();
if(dx == 0 && dy == 0) return;
for (obj of worldObjects) {
obj.move(-dx, -dy);
}
}
function updateBullets() {
let newBullets = [];
const player_dx = player.getDX();
const player_dy = player.getDY();
while(worldBullets.length > 0) {
let b = worldBullets.pop();
const bullet_dx = Math.cos(b.direction) * b.speed + b.dx;
const bullet_dy = Math.sin(b.direction) * b.speed + b.dy;
b.move(-player_dx, -player_dy);
if(outsideCanvas(b)) continue;
let collision = false;
for(const obj of worldObjects) {
if(checkCollision(b, obj, 0, 0)) {
animations.push(new ExplosionAnimation(b.center.x, b.center.y, 200, 1));
collision = true;
break;
}
}
if(collision) continue;
b.move(bullet_dx, bullet_dy);
newBullets.push(b);
}
worldBullets = newBullets;
}
function updateAnimations() {
let newAnimations = [];
const player_dx = player.getDX();
const player_dy = player.getDY();
while(animations.length > 0) {
let a = animations.pop();
if(a.isDone()) {
continue;
}
a.update(player_dx, player_dy);
newAnimations.push(a);
}
animations = newAnimations;
}
function updateWorld() {
updateObjects();
updateBullets();
updateAnimations();
}
function clearCanvas() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
}
function drawWorld() {
for (const obj of worldObjects) {
obj.draw();
}
for (const b of worldBullets) {
b.draw();
}
for (const a of animations) {
a.shape.draw();
}
player.draw();
for(const p of enemies) p.draw();
}
function updateBulletCount() {
let txt = "Bullets x " + player.gun.magCount;
if(player.magCount > 0) {
document.getElementById("bullets").innerText = txt;
} else {
document.getElementById("bullets").innerText = txt + ("\nRELOAD (r)");
}
}
function init_world() {
var recta = new Rectangle(150, 150, 40, 20, "red");
var circa = new Circle(100, -120, 50, "grey");
worldObjects.push(recta);
worldObjects.push(circa);
worldObjects.push(new Rectangle(-300, 0, 300, 300, "blue"));
player = new Player(0, 3, 0.1, 100);
drawWorld();
}
function startGame() {
window.addEventListener("keydown", keydown);
window.addEventListener("keyup", keyup);
init_world();
gameloop = setInterval(gameLoop, 20); // // set game update frequency
}
function gameLoop() {
player.update();
checkPlayerCollision();
updateWorld();
clearCanvas();
updateBulletCount();
drawWorld();
}
startGame();
|
$(function() {
var main = $("main"),
fName,
message,
pictureURL,
rankURL,
currency,
amount,
lName,
phone,
tumbD,
tumbU,
messageID,
dealID,
id,
cells = 0,
body = $("body"),
del = $(".delete"),
detail = $(".details");
$("li").eq(1).addClass("underLine");
function deleteAll() {
$.ajax({
type: "GET",
url: "../../includes/action.php?",
data: {
action: "deleteAllMessages",
dealID:dealID,
amount:amount,
buyerID:pictureURL
},
dataType: 'text',
success: function (data) {
}
});
}
function deleteRow() {
$.ajax({
type: "GET",
url: "../../includes/action.php?",
data: {
action: "deleteMessage",
messageID: messageID
},
dataType: 'text',
success: function (data) {
}
});
}
function dealsInfo() {
var userMes = $("#userMessege");
userMes.append(
"<section id='profilePic'>" +
"<section id='rank'></section>" +
"<section id='tumbU'><p></p></section>" +
"<section id='tumbD'><p></ptumbR></section>" +
"</section>" +
"<section><p id='name'></p></section>" +
"<section><p id='phone'></p></section>" +
"<section><p id='message'></p></section>" +
"<section></section>" +
"<section></section>"
);
var sec = userMes.find("> section"),
tumbUp = $("#tumbU"),
tumbDown = $("#tumbD");
sec.eq(0).css('background-image', 'url('+"../../images/users/"+pictureURL+".png"+')');
$("#rank").css('background-image', 'url('+rankURL+')');
tumbUp.css('background-image', 'url("../../images/graphics/tumbUp.png")');
tumbDown.css('background-image', 'url("../../images/graphics/tumbDown.png")');
tumbUp.find("p").html(tumbU);
tumbDown.find("p").html(tumbD);
$("#name").html(fName + " " + lName);
$("#phone").html(phone);
$("#message").html(message);
sec.eq(4).css('background-image', 'url('+"../../images/buttons/btBack.png"+')');
sec.eq(5).css('background-image', 'url('+"../../images/buttons/btOK.png"+')');
sec.eq(4).click(function () {
$("#userMessege").remove();
$("#coverBlack").remove();
});
sec.eq(5).click(function () {
deleteAll();
userMes.empty();
userMes.append(
"<div id='exit'></div>" +
"<section id='confirmed'></section>" +
"<p id='confirmedMessage'>העסקה אושרה בהצלחה</p>"
);
$("#confirmed").css('background-image', 'url('+"../../images/graphics/confirmed.png"+')');
$("#exit").click(function () {
$("#userMessege").remove();
$("#coverBlack").remove();
});
});
}
function createRow(){
main.append("<section class='row'>"+
"<section class='cell'></section>" +
"<section class='cell'><p>"+fName+"</p></section>" +
"<section class='cell'></section>" +
"<section class='cell'><p>"+message+"</p></section>" +
"<section class='cell'><p>"+amount+currency+"</p></section>" +
"<section class='cell delete'></section>" +
"<section class='cell details'></section>" +
"</section>"
);
var cell = $(".cell");
cell.eq(cells).parent().data({lName:lName,phone:phone,tumbU:tumbU,tumbD:tumbD,fName:fName,dealID:dealID,
message:message,pictureURL:pictureURL,rankURL:rankURL,amount:amount,currency:currency,messageID:messageID});
cell.eq(cells).css('background-image', 'url('+"../../images/users/"+pictureURL+".png"+')');
cells+=2;
cell.eq(cells).css('background-image', 'url('+rankURL+')');
cells+=5;
}
function loadMessages() {
$.ajax({
type: "GET",
url: "../../includes/action.php?",
data:{
action: "getMessages",
id: id
},
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
fName = element.user_name;
message = element.messages_message;
pictureURL = element.user_id;
rankURL = "../../images/ranks/rank"+element.user_rank+".png";
currency = element.messages_currency;
amount = element.messages_amount;
phone = element.user_phone;
tumbD = element.user_tumb_d;
tumbU = element.user_tumb_u;
lName = element.user_last_name;
messageID = element.messages_id;
dealID = element.messages_deals_id;
createRow();
});
del = $(".delete");
del.click(function () {
messageID = $(this).parent().data('messageID');
deleteRow();
if(cells>7)
cells = cells -7;
$(this).parent().remove();
});
detail = $(".details");
detail.click(function () {
fName = $(this).parent().data('fName');
currency = $(this).parent().data('currency');
message = $(this).parent().data('message');
pictureURL = $(this).parent().data('pictureURL');
rankURL = $(this).parent().data('rankURL');
amount = $(this).parent().data('amount');
phone = $(this).parent().data('phone');
tumbD = $(this).parent().data('tumbD');
tumbU = $(this).parent().data('tumbU');
lName = $(this).parent().data('lName');
dealID = $(this).parent().data('dealID');
body.append("<div id='coverBlack'></div>");
body.append("<div id='userMessege'><div id='exit'></div></div>");
dealsInfo();
$("#exit").click(function () {
$("#userMessege").remove();
$("#coverBlack").remove();
});
$("#coverBlack").click(function () {
$("#userMessege").remove();
$("#coverBlack").remove();
});
});
},
error: function (data) {
console.log("something went wrong");
}
});
}
function getID() {
$.ajax({
type: "GET",
url: "../../includes/session.php?",
data:{
action: "getUserId"
},
dataType: 'json',
success: function (data) {
id = data.id;
id = id.user_id;
loadMessages();
}
});
}
getID();
}); |
(function(){
'use strict';
angular.module('app')
.controller('CreateCustomerModalCtrl', CreateCustomerModalCtrl);
CreateCustomerModalCtrl.$inject = ["$scope","$uibModalInstance", "$location", "$window", "omsUtilService"];
function CreateCustomerModalCtrl($scope, $uibModalInstance, $location, $window, omsUtilService){
$scope.forms = {};
$scope.cNumber = /^[a-zA-Z]+[a-zA-Z0-9._]{0,9}$/;
$scope.addCustomerId = function(customerId){
if($scope.forms.createCustomerForm.$valid){
$uibModalInstance.close(customerId);
}else{
var form = $scope.forms.createCustomerForm;
omsUtilService.setErrorFields(form);
}
};
$scope.cancelCstModal = function(){
$uibModalInstance.dismiss();
};
}
}())
|
var potions ={
"Healing":
{effect:"This potion’s red liquid glimmers when agitated. Drink to regain 2d4 + 2 hitpoints.",
value:25
},
"Animal Friendship":
{effect:"When you drink this potion, you can cast the animal friendship spell (save DC 13) for 1 hour at will. Agitating this muddy liquid brings little bits into view: a fish scale, a hummingbird tongue, a cat claw, or a squirrel hair.",
value:50
},
"Fire Breath":
{effect:"After drinking this potion, you can use a bonus action to exhale fire at a target within 30 feet of you. The target must make a DC 13 Dexterity saving throw, taking 4d6 fire damage on a sailed save, or half as much damage on a successful one. The effect ends after you exhale the fire three times or when 1 hour has passed. The potion's orange liquid flickers, and smoke fills the top of the container and wafts out whenever it is opened.",
value:100
},
"Giant Strength":
{effect:"When you drink this potion, your Strength score changes to 25 for 1 hour. The potion has no effect on you if your Strength is equal to or greater than that score. This potion’s transparent liquid has floating in it a sliver of fingernail from a giant of the appropriate type. The potion of frost giant strength and the potion of stone giant strength have the same effect.",
value:100
},
"Growth":
{effect:"When you drink this potion, you gain the “enlarge” effect of the enlarge/reduce spell for 1d4 hours (no concentration required). The red in the potion’s liquid continuously expands from a tiny bead to color the clear liquid around it and then contracts. Shaking the bottle fails to interrupt this process.",
value:50
},
"Greater Healing":
{effect:"This potion’s red liquid glimmers when agitated. Drink to regain 4d4+4 hitpoints.",
value:50
}
"Finn's Cure-All":
{effect:"This potion removes effects such as charm, petrification, curses (including attunement to a cursed magic item), any reduction to the target's ability scores, or an effect reducing the target's hit point maximum",
value:500
},
"Glibness":
{effect:"For one hour, when you make a Charisma check, you can replace the number you roll with a 15. Additionally, no matter what you say, magic that would determine if you are telling the truth indicates that you are being truthful.",
value:100
},
"Poison":
{effect:"This concoction looks, smells, and tastes like a potion of healing or other beneficial potion. However, it is actually poison masked by illusion magic. An identify spell reveals its true nature.If you drink it, you take 3d6 poison damage, and you must succeed on a DC 13 Constitution saving throw or be poisoned. At the start of each of your turns while you are poisoned in this way, you take 3d6 poison damage. At the end of each of your turns, you can repeat the saving throw. On a successful save, the poison damage you take on your subsequent turns decreases by 1d6. The poison ends when the damage decreases to 0.",
value:50
},
"Fire Resistance":
{effect:"When you drink this potion, you gain resistance to fire damage for 1 hour.",
value:50
},
"Cold Resistance":
{effect:"When you drink this potion, you gain resistance to cold damage for 1 hour.",
value:50
},
"Force Resistance":
{effect:"When you drink this potion, you gain resistance to force damage for 1 hour.",
value:50
},
"Lightning Resistance":
{effect:"When you drink this potion, you gain resistance to lightning damage for 1 hour.",
value:50
},
"Necrotic Resistance":
{effect:"When you drink this potion, you gain resistance to necrotic damage for 1 hour.",
value:50
},
"Poison Resistance":
{effect:"When you drink this potion, you gain resistance to poison damage for 1 hour.",
value:50
},
"Psychic Resistance":
{effect:"When you drink this potion, you gain resistance to psychic damage for 1 hour.",
value:50
},
"Radiant Resistance":
{effect:"When you drink this potion, you gain resistance to radiant damage for 1 hour.",
value:50
},
"Thunder Resistance":
{effect:"When you drink this potion, you gain resistance to thunder damage for 1 hour.",
value:50
},
"Love":
{effect:"The next time you see a creature within 10 minutes after drinking this philter, you become charmed by that creature for 1 hour. If the creature is of a species and gender you are normally attracted to, you regard it as your true love while you are charmed. This potion’s rose-hued, effervescent liquid contains one easy-to-miss bubble shaped like a heart.",
value:100
},
"Clairvoyance":
{effect:"When you drink this potion, you gain the effect of the clairvoyance spell. An eyeball bobs in this yellowish liquid but vanishes when the potion is opened.",
value:250
},
"Diminution":
{effect:"When you drink this potion, you gain the “reduce” effect of the enlarge/reduce spell for 1d4 hours (no concentration required). The red in the potion’s liquid continuously contracts to a tiny bead and then expands to color the clear liquid around it. Shaking the bottle fails to interrupt this process.",
value:250
},
"Superior Healing":
{effect:"This potion’s red liquid glimmers when agitated. Drink to regain 8d4 + 8 hitpoints.",
value:250
},
"Heroism":
{effect:"For 1 hour after drinking it, you gain 10 temporary hit points that last for 1 hour. For the same duration, you are under the effect of the bless spell, which means whenever you makes an attack roll or a saving throw before the spell ends, you can roll a d4 and add the number rolled to the attack roll or saving throw. This blue potion bubbles and steams as if boiling.",
value:250
},
"Invulnerability":
{effect:"Drink to regain 2d4 + 2 hitpoints.",
value:1000
},
"Mind Reading":
{effect:"When you drink this potion, you gain the effect of the detect thoughts spell (save DC 13). The potion’s dense, purple liquid has an ovoid cloud of pink floating in it.",
value:250
},
"Flying":
{effect:"When you drink this potion, you gain a flying speed equal to your walking speed for 1 hour and can hover. If you’re in the air when the potion wears off, you fall unless you have some other means of staying aloft. This potion’s clear liquid floats at the top of its container and has cloudy white impurities drifting in it.",
value:1000
},
"Invisibility":
{effect:"This potion’s container looks empty but feels as though it holds liquid. When you drink it, you become invisible for 1 hour. Anything you wear or carry is invisible with you. The effect ends early if you attack or cast a spell.",
value:5000
},
"Longevity":
{effect:"Drink to regain 2d4 + 2 hitpoints.",
value:10000
},
"Speed":
{effect:"When you drink this potion, for one minute your speed is doubled, you gain a +2 bonus to AC, you have advantage on Dexterity saving throws, and you gain an additional action on each of its turns. That action can be used only to take the Attack (one weapon attack only), Dash, Disengage, Hide, or Use an Object action. When the effect ends, you can’t move or take actions until after your next turn, as a wave of lethargy sweeps over you. The potion’s yellow fluid is streaked with black and swirls on its own.",
value:1000
},
"Vitality": {effect:"Drink to regain 2d4 + 2 hitpoints.",
value:1000
},
"Supreme Healing":
{effect:"This potion’s red liquid glimmers when agitated. Drink to regain 10d4 + 20 hitpoints.",
value:1000
}
"Water Breathing":
{effect:"You can breathe underwater for 1 hour after drinking this potion. Its cloudy green fluid smells of the sea and has a jellyfish-like bubble floating in it.",
value:100
}
}
|
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import * as serviceWorker from './serviceWorker'
import AuthService from "./services/authService";
if (localStorage.token) {
AuthService.setToken(localStorage.token)
}
ReactDOM.render(<App />, document.getElementById('root'))
serviceWorker.unregister()
|
var instruction_8c =
[
[ "CLASSMANAGER_SERV", "instruction_8c.html#a5c7b181a46e1bf752e98109ae790381f", null ],
[ "doCLInit", "instruction_8c.html#a7d9d7f8ad882f517712edf151f60d439", null ],
[ "doInstruction", "instruction_8c.html#af8cd4f0201364dedd1ced41896652716", null ],
[ "doInstructionArray", "instruction_8c.html#accb9f059d39002d21edf45e666a9a952", null ],
[ "doInstructionInvoke", "instruction_8c.html#a6b5e2bb68ef29ecb17db6c2fd6180510", null ],
[ "doInstructionShift", "instruction_8c.html#a248b0cb7412e90840ef10076855117aa", null ],
[ "doInvokespecial", "instruction_8c.html#a14f6e846df2b700a7f8688870f05fd6b", null ],
[ "doInvokestatic", "instruction_8c.html#a600193b4ea48cdd9cb4a8f31beb4c8c0", null ],
[ "doNew", "instruction_8c.html#abdd1a98f02e976b2dc0174a11f0e8a2e", null ],
[ "getFieldIndex", "instruction_8c.html#a0155279c0e01d3f722dc6c12f0742c60", null ],
[ "instr_getstatic", "instruction_8c.html#a5d7cac5b58d408bc1421d07b57933f06", null ],
[ "instr_invokeVirtual", "instruction_8c.html#a2f0e0d9790ff283dd93e0876c1888fdd", null ],
[ "instr_lookUpSwitch", "instruction_8c.html#a2b715427caf2a6d0415740a2fe6165a2", null ],
[ "instr_putstatic", "instruction_8c.html#a87e40a30a4a27b586ba7105e2a673d6a", null ],
[ "instr_tableSwitch", "instruction_8c.html#ac8464154dce876cfa320c67561671fc5", null ],
[ "printBin", "instruction_8c.html#a2680b61bdd1322b80561f039dbf37ef9", null ],
[ "printStack", "instruction_8c.html#a74e2ea2a50e8a1921a62a0d9e1192869", null ]
]; |
import { PROMPT_TRACK, NO_MATCH } from '../actions';
export const responseStatus = (state = { error: false }, action) => {
switch (action.type) {
case PROMPT_TRACK:
return {
...state,
error: false,
};
case NO_MATCH:
return {
...state,
error: 'The is no match for this query',
};
default:
return state;
}
};
|
import logo from './logo.svg';
import './App.css';
import { useDispatch, useSelector } from 'react-redux';
import { addCustomerAction } from './store/customersReducer'
import { removeCustomerAction } from './store/customersReducer'
import {addCashAction} from './store/cashReducer'
import {getCashAction} from './store/cashReducer'
import { fetchCustomers } from './store/acyncActions/customer';
function App() {
const dispatch = useDispatch()
const cash = useSelector(state => state.cash.cash)
const customers = useSelector(state => state.customers.customers)
// Функции для добавления и снятия денег из нашего состояния
const addCash = () => {
dispatch(addCashAction(5))
}
const getCash = () => {
dispatch(getCashAction(5))
}
// Функции для добавления и удаления клиентов
const addCustomer = (name) => {
const customer = {
name,
id: Date.now()
}
dispatch(addCustomerAction(customer))
}
const removeCustomer = customer => {
dispatch(removeCustomerAction(customer.id))
}
return (
<div className="content">
<p>{cash}</p>
<div className="buttons">
<button onClick={() => addCash()}>Добавить денег</button>
<button onClick={() => getCash()}>Уменьшить денег</button>
<button onClick={() => addCustomer(prompt())}>Добавить клиента</button>
<button onClick={() => dispatch(fetchCustomers())}>Получить клиентов из базы</button>
</div>
{customers.length > 0 ?
<ul>
{customers.map(customer => (
<li key={customer.id} onClick={() => removeCustomer(customer)}>{customer.name}</li>
))}
</ul>
:
<div>
Клиенты отсутствуют
</div>
}
</div>
)
}
export default App;
|
var ForumPost = {
reply : function(obj){
if(jQuery(".reply-to-this-thread a").attr("active")=="true"){
return;
}else{
var html = '<div class="reply-post-container"><textarea id="reply" name="text" placeholder="write your reply here..."></textarea>';
html += '<div class="submit-reply" ><button class="cancel" onclick="ForumPost.cancel();return false;">Cancel</button><button class="submit-post">Submit</button></div>';
html += '</div><br style="clear:both"/>';
jQuery(".reply-thread-container form").append(html);
jQuery(".reply-to-this-thread a").attr("active","true");
}
},
cancel : function(obj){
jQuery(".reply-to-this-thread a").attr("active","false");
jQuery(".reply-thread-container form").html("");
},
replyToThisPost : function(id,obj){
if(jQuery(obj).attr("active")=="false"){
var html = '<div class="reply-post-container"><textarea name="text" placeholder="write your reply here..."></textarea>';
html += '<div class="submit-reply" ><button class="cancel" onclick="ForumPost.cancelReplyToThisPost('+id+');return false;">Cancel</button><button class="submit-post">Submit</button></div>';
html += '</div><br style="clear:both"/>';
jQuery("#reply-specfic-post-container-"+id+" form").append(html);
jQuery(obj).attr("active","true");
}else{
return;
}
},
cancelReplyToThisPost : function(id){
jQuery("#reply-specfic-post-container-"+id).next().find("a").attr("active","false");
jQuery("#reply-specfic-post-container-"+id+ " form").html("");
},
submitThreadReply : function(){
return false;
},
submitReplyToPost : function(){
},
loadMorePost : function(){
var html = jQuery("#post-dummy").html();
var count = jQuery(".post").length;
html = html.replace("{{name}}","Sepiroth");
html = html.replace("{{post_number}}","#10");
html = html.replace("{{posted_on}}","2 February 2014 - 6:40PM");
html = html.replace("{{location}}","Philippines");
html = html.replace("{{number_of_posts}}","100");
html = html.replace("{{like_count}}","100");
html = html.replace("{{dislike_count}}","5");
html = html.replace("{{post_text}}","Lorem ipsum dolor lit. Dolor Lit..");
html = html.replace(/{{param_id}}/g,++count);
var li = jQuery('<li class="post" style="display:none">');
li.html(html);
jQuery(".post-list").append(li);
li.fadeIn(500);
},
bindLikeButton : function(){
jQuery(".like").click(function(){
var like_url = jQuery(this).attr("href");
var comment_id = jQuery(this).attr("comment_id");
jQuery.ajax({
url : like_url,
success : function(response){
jQuery("#likes_of_this_comment_"+comment_id).html(response.trim());
}
});
return false;
})
},
bindUnLikeButton : function(){
jQuery(".unlike").click(function(){
var like_url = jQuery(this).attr("href");
var comment_id = jQuery(this).attr("comment_id");
jQuery.ajax({
url : like_url,
success : function(response){
jQuery("#likes_of_this_comment_"+comment_id).html(response.trim());
}
});
return false;
})
},
bindResponseButton : function(){
jQuery(".post").click(function(){
jQuery(".report-popup").removeClass("active");
});
jQuery(".report").click(function(){
if(jQuery(this).next().hasClass("active")){
jQuery(this).next().removeClass("active");
}else{
jQuery(".report-popup").removeClass("active");
jQuery(this).next().addClass("active");
}
return false;
})
},
bindSettingButton : function(){
jQuery(".fdata").click(function(){
jQuery(".settings-popup").removeClass("active");
});
jQuery(".thread-settings").click(function(){
if(jQuery(this).next().hasClass("active")){
console.log(jQuery(this).next());
jQuery(this).next().removeClass("active");
}else{
jQuery(".settings-popup").removeClass("active");
jQuery(this).next().addClass("active");
}
return false;
})
},
reportAs : function(obj,comment_id,type){
var like_url = "http://[Url.DomainName]/forum/report/"+comment_id+"/"+type;
jQuery.ajax({
url : like_url,
success : function(response){
console.log(response);
jQuery(obj).parent().removeClass("active");
//jQuery("#likes_of_this_comment_"+comment_id).html(response.trim());
}
});
},
deleteComment : function(comment_id){
var delete_url = "http://[Url.DomainName]/forum/delete/"+comment_id;
window.location.href = delete_url;
},
threadActions : function(thread_id,actions){
switch(actions){
case 'enable' : { var url = "http://[Url.DomainName]/forum/EnabledThread/"+thread_id; window.location.href = url; }break;
case 'block' : { var url = "http://[Url.DomainName]/forum/BlockedThread/"+thread_id; window.location.href = url; }break;
case 'delete' : { var url = "http://[Url.DomainName]/forum/DeleteThread/"+thread_id; window.location.href = url; }break;
case 'pinned' : { var url = "http://[Url.DomainName]/forum/PinnedThread/"+thread_id; window.location.href = url; }break;
case 'makeprio' : { var url = "http://[Url.DomainName]/forum/PrioThread/"+thread_id; window.location.href = url; }break;
case 'edit' : {
var old_value = jQuery('.thread-description blockquote').html();
jQuery(".thread-description blockquote").hide();
var textarea = jQuery('<textarea id="thread-description" class="input-data">');
var button_html = '<div class="edit-comment-button"><a href="#" onclick="ForumPost.cancelUpdateComment('+thread_id+');return false;">Cancel</a>';
button_html += ' | <a href="#" onclick="ForumPost.updateComment('+thread_id+');return false;">Update</a></div>';
textarea.html(old_value);
var div = jQuery('<div id="edit-comment-container">');
div.append(textarea);
div.append(button_html);
jQuery('.thread-description').append(div);
}break;
}
},
updateComment : function(thread_id){
var url = "http://[Url.DomainName]/forum/edit/"+thread_id;
console.log(url);
jQuery.post( url, { text: jQuery("#thread-description").val() }).done(
function( data ) {
window.location.href = "http://[Url.DomainName]/forum/thread/"+thread_id;
});
},
cancelUpdateComment : function(){
jQuery("#edit-comment-container").remove();
jQuery(".thread-description blockquote").css('display','block');
},
}
|
import styled from 'styled-components';
const Container = styled.section`
margin: 0 0 0 0;
display: -webkit-flex; /_ Safari _/
display: flex;
flex-direction: column;
`;
export default Container; |
var images = [
"images/google_clone.png",
"images/streetfighter.png",
"images/shopping_list.png",
"images/hot_or_cold.png",
"images/quiz.png",
"images/stackerAJAX.png",
"images/apihack.png"
];
var links = [
"http://scompton.github.io/google-clone/",
"http://scompton.github.io/jquery-streetfighter/",
"http://scompton.github.io/shopping-list/",
"http://scompton.github.io/hot-or-cold-starter/",
"http://scompton.github.io/quizapp/",
"http://scompton.github.io/stackerAJAX/",
"http://scompton.github.io/apihack/"
];
var imageNumber = 0;
var imageLength = images.length-1;
function changeImage(num) {
console.log(num);
imageNumber = imageNumber+num;
if (imageNumber>imageLength) {
imageNumber = 0;
}
if (imageNumber<0) {
imageNumber = imageLength;
}
$("#ss").attr("src",images[imageNumber]);
$("#imageLink").attr("href",links[imageNumber]);
}
$(document).ready(function() {
setInterval("changeImage(1)",2500);
$('#prev').click(function(e) {
changeImage(-1);
e.preventDefault();
});
$('#next').click(function(e) {
changeImage(1);
e.preventDefault();
});
});
|
require('app-module-path').addPath(__dirname);
const express = require('express');
const config = require('config');
const passport = require('passport');
const events = require('events');
let eventEmitter = new events.EventEmitter();
function startApp() {
let app = express();
require('bootstrap/express')(app, config);
require('bootstrap/passport')(app, passport, config);
require('controllers/index')(app, config);
app.listen(app.get('port'), function () {
console.log('Server listening to port %d', app.get('port'));
});
};
require('bootstrap/db')(config, eventEmitter);
eventEmitter.on('db-connection-established', function () {
startApp();
}); |
import React,{useState} from 'react';
import {View,StyleSheet, TextInput,Alert} from 'react-native';
import CircleButton from '../components/CircleButton';
import KeyboardSafeView from '../components/KeyboardSafeView';
import firebase from 'firebase';
import { translateErrors } from '../utils';
export default function MemoCreateScreen(props){
const { navigation }=props;
const [bodyText,setBodyText] = useState('');
function handlePress(){
const {currentUser} = firebase.auth();
const db=firebase.firestore();
const ref =db.collection(`users/${currentUser.uid}/memos`);
ref.add({bodyText,updatedAt:new Date(),}).then(()=>{
navigation.goBack();
})
.catch((error)=>{
const errorMsg=translateErrors(error.code);
Alert.alert(errorMsg.title,errorMsg.description)});
}
return (
<KeyboardSafeView style={styles.container}>
<View style={styles.inputContainer}>
<TextInput
value={bodyText}
multiline
style={styles.input}
onChangeText={(text)=>{setBodyText(text);}}
autoFocus />
</View>
<CircleButton name="check" onPress={handlePress}/>
</KeyboardSafeView>
);
}
const styles = StyleSheet.create({
container: {
flex:1,
},
inputContainer:{
paddingHorizontal:27,
paddingVertical:32,
flex:1
},
input:{
flex:1,
textAlignVertical:'top',
fontSize:16,
lineHeight:24,
}
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import Dancer from './Dancer.jsx';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import dummyPeople from '../../../database-mongo/dummyPeople.js'
class Dancers extends React.Component {
constructor(props) {
super(props);
this.state = {
dancers: [
{
id: 0,
name: 'Shi Hao Hong',
profilePic: 'https://s3-us-west-1.amazonaws.com/dancin/shi-hao-hong.jpg',
currentTeam: 'HR Duo',
previousTeam: 'Chaotic 3',
currentJob: 'Technical Mentor at Hack Reactor',
rating: 5.0,
choreoSong: 'Location - Khalid',
choreoLink:'https://www.youtube.com/watch?v=4_pg4pkopuk',
choreoId: '4_pg4pkopuk',
},
{
id: 1,
name: 'Dylan Qian',
profilePic: 'https://s3-us-west-1.amazonaws.com/dancin/dylan-qian.jpg',
currentTeam: 'HR Duo',
previousTeam: 'Ascension',
currentJob: 'Student at Hack Reactor',
rating: 5.0,
choreoSong: "Can't Stop The Feeling - Justin Timberlake",
choreoLink: 'https://www.youtube.com/watch?v=dX53hWaYNd8',
choreoId: 'dX53hWaYNd8',
},
]
}
}
render() {
console.log(this.state.dancers)
return (
<div>
<div className="featurette">
<div className="featurette-inner text-center">
<form role="form" className="search">
<h3 className="no-margin-top h1">Dancers</h3>
<div className="input-group input-group-lg">
<input type="search" className="form-control" />
<span className="input-group-btn">
<button className="btn btn-danger" type="button">Search</button>
</span>
</div>
</form>
</div>
</div>
<div>
{this.state.dancers.map((dancer)=> <Dancer dancer = {dancer} key = {dancer.id}/>)}
</div>
<div>
</div>
</div>
)
}
}
export default Dancers |
var url = 'http://localhost:8080';
var app = angular.module("myApp", ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: "myCtrl"
})
.when('/etl', {
templateUrl: 'etl.html',
controller: "myCtrl"
})
.when('/produkty', {
templateUrl: 'produkty.html',
controller: "myCtrl"
})
.when('/opinie', {
templateUrl: 'opinie.html',
controller: "myCtrl"
})
.when('/baza', {
templateUrl: 'czysc.html',
controller: "myCtrl"
});
}]);
app.controller("myCtrl", function($scope, $http, $location) {
$scope.start = function() {
$location.path("/");
}
$scope.extract = function() {
$('#etlDiv').hide();
$('#extractDiv').hide();
$('#transformDiv').hide();
$('#loadDiv').hide();
var productCode = $scope.productCode;
if (productCode == null || productCode == "") {
$('#noCodeModal').modal('show');
} else {
$('#waitingModal').modal('show');
$http.get(url + '/extract/' + productCode)
.then(function successCallback(response) {
$('#waitingModal').modal('hide');
$('#extractDiv').show();
$scope.product = response.data.product;
$scope.pagesNumber = response.data.reviewsPagesNumber;
$scope.reviewsNumber = response.data.reviewsNumber;
$('#transform').attr('disabled', false);
}, function errorCallback(response) {
$('#waitingModal').modal('hide');
$('#wrongCodeModal').modal('show');
});
}
}
$scope.transform = function() {
$('#extractDiv').hide();
$('#transform').attr('disabled', true);
$('#load').attr('disabled', false);
$('#waitingModal').modal('show');
$http.get(url + '/transform')
.then(function successCallback(response) {
$('#transformDiv').show();
$scope.productRecords = response.data.productRecords;
$scope.reviewRecords = response.data.reviewRecords;
$('#waitingModal').modal('hide');
}, function errorCallback(response) {
alert("Coś poszło nie tak");
});
}
$scope.load = function() {
$('#transformDiv').hide();
$('#load').attr('disabled', true);
$('#extract').attr('disabled', false);
$('#waitingModal').modal('show');
$http.get(url + '/load')
.then(function successCallback(response) {
$('#loadDiv').show();
$scope.newProductsNumber = response.data.newProductRecordsNumber;
$scope.newReviewsNumber = response.data.newReviewRecordsNumber;
$scope.newAdvantagesNumber = response.data.newAdvantagesRecordsNumber;
$scope.newDisadvantagesNumber = response.data.newDisadvantagesRecordsNumber;
$('#waitingModal').modal('hide');
}, function errorCallback(response) {
$('#waitingModal').modal('hide');
alert("Coś poszło nie tak");
});
document.getElementById('productCode').disabled = false;
}
$scope.etl = function() {
$('#transform').attr('disabled', true);
$('#load').attr('disabled', true);
$('#etlDiv').hide();
$('#extractDiv').hide();
$('#transformDiv').hide();
$('#loadDiv').hide();
var productCode = $scope.productCode;
if (productCode == null || productCode == "") {
$('#noCodeModal').modal('show');
} else {
$('#waitingModal').modal('show');
$http.get(url + '/etl/' + productCode)
.then(function successCallback(response) {
$('#waitingModal').modal('hide');
$('#etlDiv').show();
$scope.product = response.data.product;
$scope.pagesNumber = response.data.reviewsPagesNumber;
$scope.reviewsNumber = response.data.reviewsNumber;
$scope.productRecords = response.data.productRecords;
$scope.reviewRecords = response.data.reviewRecords;
$scope.newProductsNumber = response.data.newProductRecordsNumber;
$scope.newReviewsNumber = response.data.newReviewRecordsNumber;
$scope.newAdvantagesNumber = response.data.newAdvantagesRecordsNumber;
$scope.newDisadvantagesNumber = response.data.newDisadvantagesRecordsNumber;
}, function errorCallback(response) {
$('#waitingModal').modal('hide');
$('#wrongCodeModal').modal('show');
});
}
}
$scope.getProducts = function() {
$http.get(url + '/products')
.then(function successCallback(response) {
$scope.products = response.data;
if($scope.products !== ""){
var down = document.getElementById('downAll');
if(down != null){
down.style.display = "block";
}
}
}, function errorCallback(response) {
alert("Coś poszło nie tak");
});
}
$scope.getReviews = function() {
var productCode = $('#productChoice').find(":selected").val();
$http.get(url + '/reviews/' + productCode)
.then(function successCallback(response) {
if (response.data.length == 0) {
$('#noReviewsModal').modal('show');
} else {
$scope.productReviews = response.data;
}
}, function errorCallback(response) {
alert("Coś poszło nie tak");
});
}
$scope.clear = function() {
var option = $("input[type='radio'][name='clearRadios']:checked").val();
if(option == "all"){
$scope.records = "rekordy";
} else if(option == "reviewsOnly") {
$scope.records = "opinie";
}
$('#confirmationModal').modal('show');
}
$scope.clearDB = function() {
$('#confirmationModal').modal('hide');
var option = $("input[type='radio'][name='clearRadios']:checked").val();
if (option == "all") {
$http.get(url + '/delete/all')
.then(function successCallback(response) {
var info = "Liczba usuniętych produktów: " + response.data.deletedProductsNumber + '<br>' + "Liczba usuniętych opinii: " + response.data.deletedReviewsNumber;
console.log(info);
$('#deleteModalBody').html(info);
$('#deleteModal').modal('show');
}, function errorCallback(response) {
alert("Coś poszło nie tak");
});
}
if (option == "reviewsOnly") {
$http.get(url + '/delete/reviews')
.then(function successCallback(response) {
$('#deleteModalBody').html("Liczba usuniętych opinii: " + response.data.deletedReviewsNumber);
$('#deleteModal').modal('show');
}, function errorCallback(response) {
alert("Coś poszło nie tak");
});
}
}
$scope.downloadAllCSV = function() {
$('#waitingModal').modal('show');
$http.get(url + '/generateCSV')
.then(function successCallback(response) {
var cont = response.data.fileContent;
var name = response.data.fileName;
download(name, "csv", cont);
$('#waitingModal').modal('hide');
}, function errorCallback(response) {
$('#waitingModal').modal('hide');
alert("Coś poszło nie tak");
});
}
$scope.downloadCSV = function(code) {
$('#waitingModal').modal('show');
$http.get(url + '/generateCSV/' + code)
.then(function successCallback(response) {
var cont = response.data.fileContent;
var name = response.data.fileName;
download(name, "csv", cont);
$('#waitingModal').modal('hide');
}, function errorCallback(response) {
$('#waitingModal').modal('hide');
alert("Coś poszło nie tak");
});
}
$scope.downloadTXT = function(code) {
$('#waitingModal').modal('show');
$http.get(url + '/generateTXT/' + code)
.then(function successCallback(response) {
var cont = response.data.fileContent;
var name = response.data.fileName;
download(name, "plain", cont);
$('#waitingModal').modal('hide');
}, function errorCallback(response) {
$('#waitingModal').modal('hide');
alert("Coś poszło nie tak");
});
}
$scope.downloadAllTXT = function() {
$('#waitingModal').modal('show');
$http.get(url + '/generateTXT')
.then(function successCallback(response) {
var cont = response.data.fileContent;
var name = response.data.fileName;
download(name, "plain", cont);
$('#waitingModal').modal('hide');
}, function errorCallback(response) {
$('#waitingModal').modal('hide');
alert("Coś poszło nie tak");
});
}
function download(filename, type, text) {
var downloader = document.createElement('a');
/* WARTO ZAZNACZYC ZE PLIKI GENEROWANE SA Z KODOWANIEM utf-8 */
downloader.setAttribute('href', 'data:text/' + type + ';charset=utf-8,' + encodeURIComponent(text));
downloader.setAttribute('download', filename);
downloader.style.display = 'none';
document.body.appendChild(downloader);
downloader.click();
document.body.removeChild(downloader);
}
}); |
'use strict'
var React = require('react-native');
var {
AppRegistry,
View,
Text,
StyleSheet,
Navigator,
Platform,
BackAndroid,
} = React;
/**
* 对Navigator的封装控件
*/
var NavAndroid = React.createClass({
componentWillMount:function() {
if (Platform.OS === 'android') {
BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
}
},
componentWillUnmount:function() {
if (Platform.OS === 'android') {
BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid);
}
},
onBackAndroid :function(){
const nav = this.navigator;
console.log('nav:'+nav);
const routers = nav.getCurrentRoutes();
if (routers.length > 1) {
nav.pop();
return true;
}
return false;
},
render: function() {
return (
<Navigator
ref={nav => { this.navigator = nav; }}
style={styles.flex}
initialRoute={{
name:'',
component:this.props.component,
// index:0,
}}
renderScene={(route, navigator) => {
const Component = route.component;
return (
<View style ={{flex:1}}>
<Component {...route.passProps} navigator={navigator} route = {route}/>
</View>
);
}}
/>
);
},
});
var styles = StyleSheet.create({
flex:{
flex:1,
},
});
module.exports = NavAndroid;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.