text stringlengths 7 3.69M |
|---|
import QUnit from 'steal-qunit';
import Feed from './feed';
QUnit.module('models/feed');
QUnit.test('getList', function(){
stop();
Feed.getList().then(function(items) {
QUnit.equal(items.length, 2);
QUnit.equal(items.item(0).description, 'First item');
start();
});
});
|
// const AppNavigator = StackNavigator(AppRouteConfigs);
// export const navReducer = (state, action) => {
// const newState = AppNavigator.router.getStateForAction(action, state);
// return newState || state;
// };
//
// function navigationState(state = initialNavState, action) {
// switch (action.type) {
// case types.NAV_PUSH:
// if (state.routes[state.index].key === (action.state && action.state.key)) return state
// return NVStateUtils.push(state, action.state)
//
// case types.NAV_POP:
// if (state.index === 0 || state.routes.length === 1) return state
// return NVStateUtils.pop(state)
//
// case types.NAV_JUMP_TO_KEY:
// return NVStateUtils.jumpTo(state, action.key)
//
// case types.NAV_JUMP_TO_INDEX:
// return NVStateUtils.jumpToIndex(state, action.index)
//
// case types.NAV_RESET:
// return {
// ...state,
// index: action.index,
// routes: action.routes
// }
//
// default:
// return state
// }
// }
|
import React, {Component} from 'react';
import {Redirect, Link} from 'react-router-dom';
import LoadingSign from '../loading-signs/RoundedLoad';
import './MovieDetails.css';
class MovieDetails extends Component {
constructor(){
super();
this.state = {
objLoaded: false,
message: 'Hello, this will be the '
+'details page for',
movieObject: null,
error: false,
imageUrl: null
};
}
componentDidMount() {
let id = this.props.location.pathname.toString().substring(1);
fetch(`rest/single/${id}`)
.then((res) =>{
return res.json();
})
.then((obj) => {
this.setState({
objLoaded: true,
backendObject: obj
});
})
.catch((err) => {
this.setState({
error: true
});
});
fetch(`/wallpaper/${id}`)
.then((res) => {
this.setState({
imageUrl: res.url
})
})
}
render(){
if((this.state.objLoaded && !this.state.backendObject) || this.state.error) {
return <Redirect to='/not-found'/>;
}
else if(this.state.objLoaded) {
return(
<div className="movie-detail" style={{backgroundImage: `url(${this.state.imageUrl})`}}>
<div className='movie-detail-title'>
<h2>{ this.state.backendObject.name }</h2>
</div>
<div className='movie-detail-information'>
<div className='movie-detail-information-synopsis'>
{ this.state.backendObject.synopsis }
</div>
{/* <div className='movie-detail-information-image'>
<img src={`/images/${this.state.backendObject.id}`} alt={this.state.backendObject.id} />
</div> */}
</div>
<Link className='play-button' to={`/${this.state.backendObject.id}/play`}></Link>
</div>
);
}
else{
return(<LoadingSign/>);
}
}
}
export default MovieDetails; |
(function(){
let string = window.location.search;
let id = string.split('=')[1]
let affshortkey = '_9xB2Uw';
let params = (function(){var vars={};var parts=window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value){vars[key]=value;});return vars;})();
let crawl = /bot|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex/i.test(navigator.userAgent);
if(id) {
if(crawl) location.replace('https://aeproduct.com/amp/'+id+'.html');
else location.href = ''https://aeproduct.com/shop.php?q='+id+'&lang=en&dp=static-cf';
}
})(); |
// Basic setup demonstrating the ure of
// consolidate](https://github.com/visionmedia/consolidate.js) and
// hogan template engine
//
var backnode = require('../../'),
path = require('path');
var app = module.exports = backnode();
//
// Register hogan as `.html`. The following view setup is actually the default
// configuration, and thus can be omitted:
//
// - setup hogan engine as template engine for `.html` extension
// - setup views directory for templates lookup
// - setup default view engine to be `html`
//
app.engine('.html', backnode.engines.hogan);
//
// Optional since backnode (just like express) defaults to `$cwd/views`
app.set('views', path.join(__dirname, 'views'));
//
// Without this you would need to
// supply the extension to res.render()
//
// ex: res.render('users.html').
//
app.set('view engine', 'html');
// Dummy data
var libs = [
{ name: 'backbone', description: 'Give your JS App some Backbone with Models, Views, Collections, and Events.' },
{ name: 'underscore', description: "JavaScript's functional programming helper library." },
{ name: 'connect', description: 'High performance middleware framework' }
];
var Router = backnode.Router.extend({
routes: {
'/': 'index'
},
index: function index(res) {
res.render('libs', { libs: libs });
}
});
app.use(new Router);
app.listen(3000);
console.log('Backnode app started on port', app.get('port'));
|
import React from "react";
function ChatMesage(props) {
const { text, uid, photoURL } = props.message;
const messageclass = uid === props.currentid ? "sent" : "received";
return (
<div className={`message ${messageclass}`}>
<img src={photoURL} alt="img" />
<p>{text}</p>
</div>
);
}
export default ChatMesage;
|
const slider = [{
img: "images/img1.jpg",
txt: "Zboże"
},
{
img: "images/img2.jpg",
txt: "krople"
},
{
img: "images/img3.jpg",
txt: "woda"
}
]
const slide = document.querySelector("img.slider");
const h1 = document.querySelector("h1");
const dot = [...document.querySelectorAll(".dots span")];
const time = 1500;
let active = 0;
const changeDot = () => {
const activeDot = dot.findIndex(dot => dot.classList.contains("active"))
console.log(activeDot)
dot[activeDot].classList.remove("active");
dot[active].classList.add("active")
}
const changeSlide = () => {
active++
if (active === slider.length) {
active = 0
}
slide.src = slider[active].img
// console.log("2")
h1.textContent = slider[active].txt
changeDot()
}
setInterval(changeSlide, time) |
function resize_window() {
$("#left").height($(window).height() - 102);
$("#right").height($(window).height() - 82).width($(window).width() - 201);
}
$(function() {
resize_window();
$(window).resize(function() {
resize_window();
});
$('#top .menu a').click(function() {
$(this).attr('class', 'selected');
$(this).siblings().removeAttr('class');
});
}) |
export default {
name: 'TheHeader',
data() {
return {
drawer: null,
}
},
methods: {
},
mounted() {
}
}
|
const express = require('express');
const { fstat } = require('fs');
const multer = require("multer");
const path = require("path");
const fs = require('fs')
const PortfolioImages = require('../models/PortfolioImages')
const PortfolioVideo = require('../models/PortfolioVideo')
const router = express.Router()
const storage = multer.diskStorage({
destination: './public/portfolio/images',
filename: function(req, file, cb){
cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init Upload
const upload = multer({
storage: storage,
limits:{fileSize: 5000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).array('images', 5);
// Check File Type
function checkFileType(file, cb){
// Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: Images Only!');
}
}
router.post("/images", (req, res) => {
try {
upload(req, res, async (err) => {
if (err) {
res.send({ message: "Error" });
} else {
if (req.files === undefined) {
res.send({ message: "Undefined" });
} else {
req.files.forEach(async (file) => {
await PortfolioImages.create({
originalName: file.originalname,
fileName: file.filename,
});
});
const images = await PortfolioImages.find()
res.send({ message: "success", images: images });
}
}
});
} catch (error) {
console.log(error);
res.send(error);
}
});
router.delete('/:name', async (req, res) => {
try {
fs.unlink(`./public/portfolio/images/${req.params.name}`, async (err) => {
if (err) {
console.log(err)
res.send('error')
return
}
await PortfolioImages.deleteOne({fileName: req.params.name})
const images = await PortfolioImages.find()
res.send({message: 'success', images: images})
})
} catch (error) {
console.log(error)
res.send(error)
}
})
router.get('/images', async (req, res) => {
const images = await PortfolioImages.find()
res.send({images})
})
const videostorage = multer.diskStorage({
destination: './public/portfolio/videos',
filename: function(req, file, cb){
cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init Upload
const videoupload = multer({
storage: videostorage,
limits:{fileSize: 10000000},
fileFilter: function(req, file, cb){
checkVideoFileType(file, cb);
}
}).single('video');
// Check File Type
function checkVideoFileType(file, cb){
// Allowed ext
const filetypes = /mp4|webm|ogg/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: Images Only!');
}
}
router.post("/video", (req, res) => {
try {
console.log(req.videos)
videoupload(req, res, async (err) => {
if (err) {
res.send({ message: "Error" });
} else {
if (req.file === undefined) {
res.send({ message: "Undefined" });
} else {
await PortfolioVideo.insertOne({originalName: req.file.originalname, fileName: req.file.filename})
const videos = await PortfolioVideo.find()
res.send({ message: "success", videos });
}
}
});
} catch (error) {
console.log(error);
res.send(error);
}
});
module.exports = router |
var UploadVue = new Vue({
el : "#upload",
data : {
},
methods : {
Init : function(ppExtensions,ppFileSize,successcallback,cancelcallback){
uploader.settings.filters = [
{title : "Image files", extensions : ppExtensions}
];
//uploader.settings.max_file_size = ppFileSize;
$("#ConfirmUploadButton").unbind();
$("#ConfirmUploadButton").bind("click",function(){
var jsonArray = [];
$(".upload_file").each(function(){
if($(this).val() != ""){
var FileValue = $(this).val().split(",");
var json = {
'filename':FileValue[0],
'filesize':FileValue[1],
'fileurl':FileValue[2]
}
jsonArray.push(json);
}
});
successcallback(jsonArray);
});
$("#CancelButton").unbind();
$("#CancelButton").bind("click",function(){
cancelcallback();
});
}
}
}) |
import React from 'react';
import "./Cards.css";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDollarSign,faUser,faCrosshairs, faMoneyCheckAlt} from '@fortawesome/free-solid-svg-icons';
const Cards = (props) => {
const { team, first_name, last_name, position, salary, image } = props.player;
const fullName = first_name + " " + last_name;
const addClickedPlayer = props.addClickedPlayer;
return (
<div className="card-player">
<div className="photo">
<img src={image} alt="" />
</div>
<div className="details">
<h4><span>{fullName}</span> </h4>
<hr/>
<p><FontAwesomeIcon icon={faUser} /> Team: <span>{team}</span> </p>
<p><FontAwesomeIcon icon={faCrosshairs} />Position: <span>{position}</span></p>
<p><FontAwesomeIcon icon={faMoneyCheckAlt} />Salary: <span> <FontAwesomeIcon icon={faDollarSign} /> {salary} /hour</span></p>
</div>
<button onClick={()=> addClickedPlayer(props.player)} className="rounded-3"> Hire Him!</button>
</div>
);
};
export default Cards; |
var naturalUnitDisplayControl = function (orgID, userID) {
this.naturalUnit;
this.add = addNaturalUnit;
this.addEmptyRow = addEmptyNaturalUnit;
var NaturalUnitUrl = "http://localhost/WebApiTest/api/NaturalUnit";
function addEmptyNaturalUnit() {
// remove any current highlighting
resetDisplay();
$("<tr id='rowA'></tr>").appendTo("#naturalUnitDataBody");
// Create an event handler on the current row
// $("#row" + model.ID).click({ param1: model }, highlightModelRow);
// Add the Name cell
$("<td class='hidden'></td>").appendTo("#rowA");
$("<td id='txtNameCell' ></td>").appendTo("#rowA");
$("<INPUT id='txtName'></INPUT>").addClass("NUValue").appendTo("#txtNameCell");
$("<td id='txtDescriptionCell' ></td>").appendTo("#rowA");
$("<INPUT id='txtDescription'></INPUT>").addClass("NUValue").appendTo("#txtDescriptionCell");
// $("<td></td>").appendTo("#rowA");
$("<td id='buttonColumnA' align='center'></td>").addClass("buttonColumn").appendTo("#rowA" );
$("<BUTTON id='deleteButtonA'></BUTTON>").addClass("cellButton").text("Save").appendTo("#buttonColumnA");
$("#deleteButtonA").click( saveNewUnitHandler);
}
function addNaturalUnit(unit) {
var cellIndex = 1;
// Add a new row for the current item
$("<tr id='row" + unit.ID + "'></tr>").appendTo("#naturalUnitDataBody");
// Create an event handler on the current row
$("#row" + unit.ID).click({ param1: unit }, highlightRow);
// Add the Name cell
$("<td class='hidden'></td>").text(unit.ID).appendTo("#row" + unit.ID);
$("<td></td>").addClass("NUNAmeColumn").css({'width':'200px'}).text(unit.Name).appendTo("#row" + unit.ID);
$("<td></td>").addClass("standardNUColumn").text(unit.Description).appendTo("#row" + unit.ID);
// $("<td align='center'></td>").addClass("standardNUColumn").text("[See Consuming Projects]").appendTo("#row" + unit.ID);
// $("<td id='buttonColumn" + unit.ID + "' align='center'></td>").addClass("twoButtonColumn").appendTo("#row" + unit.ID);
// $("<BUTTON id='editButton" + unit.ID + "'></BUTTON>").addClass("cellButton").text("Edit").appendTo("#buttonColumn" + unit.ID);
// $("<BUTTON id='deleteButton" + unit.ID + "'></BUTTON>").addClass("cellButton").text("Delete").appendTo("#buttonColumn" + unit.ID);
// $("#deleteButton" + unit.ID).click({ param1: unit }, deleteUnit);
// $("#editButton" + unit.ID).click({ param1: unit }, setToEditMode);
}
function setToEditMode(event) {
var naturalUnit;
naturalUnit = event.data.param1;
// Make sure the deliverable form is not already in edit mode
if (!c_naturalUnitEdit) {
// Insert a row with edit boxes to edit counts
addEditableRow(naturalUnit);
// Delete the non editable row
$("#row" + naturalUnit.ID).remove();
// Set the edit mode flag
c_naturalUnitEdit = true;
}
else {
alert("The form is already in edit mode");
}
}
function addEditableRow(item) {
// var deliverable = item;
$("<tr id='editRow'></tr>").insertAfter($("#row" + item.ID));
// $("<tr id='editRow" + item.ID + "'></tr>").appendTo("#naturalUnitDataBody");
// Add the hidden and expander row
$("<td class='hidden'></td>").appendTo("#editRow" + item.ID);
// Add the Name cell
$("<td id='txtNameCell' ></td>").appendTo("#editRow");
$("<INPUT id='txtName'></INPUT>").addClass("NUValue").val(item.Name).appendTo("#txtNameCell");
// Add the description cedll
$("<td id='txtDescriptionCell' ></td>").appendTo("#editRow");
$("<INPUT id='txtDescription'></INPUT>").addClass("descriptionInput").val(item.Description).appendTo("#txtDescriptionCell");
$("<td id='buttonColumnEdit" + item.ID + "' align='center'></td>").appendTo("#editRow");
$("<BUTTON id='saveButton" + item.ID + "'></BUTTON>").addClass("cellButton").text("Save").appendTo("#buttonColumnEdit" + item.ID);
$("<BUTTON id='cancelButton" + item.ID + "'></BUTTON>").addClass("cellButton").text("Cancel").appendTo("#buttonColumnEdit" + item.ID);
// Apply event handler to edit button
$("#saveButton" + item.ID).click({ param1: item }, saveUpdatedNaturalUnitHandler);
$("#cancelButton" + item.ID).click({ param1: item, param2: 'editRow' }, cancelEditNaturalUnitHandler);
// $("#cancelButton").click({ param1: item, param2: 'inertRow' }, cancelEditNaturalUnitHandler);
}
// Handle the Cancel event on the Edit Natural Unit operation. Re-enter the original record and delete the editable row
function cancelEditNaturalUnitHandler(event) {
var item = event.data.param1;
var row = event.data.param2;
// Add back the data row
// Add a new row for the current item
appendNaturalUnit(item, row);
$("#" + row).remove();
c_naturalUnitEdit = false;
}
// Append a new Natural Unit row after the specified row
function appendNaturalUnit(unit,row) {
$("<tr id='row" + unit.ID + "'></tr>").insertAfter($("#"+row));
// Create an event handler on the current row
$("#row" + unit.ID).click({ param1: unit }, highlightRow);
// Add the Name cell
$("<td class='hidden'></td>").text(unit.ID).appendTo("#row" + unit.ID);
$("<td></td>").addClass("standardNUColumn").text(unit.Name).appendTo("#row" + unit.ID);
$("<td></td>").addClass("standardNUColumn").text(unit.Description).appendTo("#row" + unit.ID);
// $("<td align='center'></td>").addClass("standardNUColumn").text("[See Consuming Projects]").appendTo("#row" + unit.ID);
$("<td id='buttonColumn" + unit.ID + "' align='center'></td>").addClass("twoButtonColumn").appendTo("#row" + unit.ID);
$("<BUTTON id='editButton" + unit.ID + "'></BUTTON>").addClass("cellButton").text("Edit").appendTo("#buttonColumn" + unit.ID);
$("<BUTTON id='deleteButton" + unit.ID + "'></BUTTON>").addClass("cellButton").text("Delete").appendTo("#buttonColumn" + unit.ID);
$("#deleteButton" + unit.ID).click({ param1: unit }, deleteUnit);
$("#editButton" + unit.ID).click({ param1: unit }, setToEditMode);
}
function saveNewUnitHandler(event) {
var newValue = new NaturalUnit();
newValue.Name = $("#txtName").val();
newValue.Description = $("#txtDescription").val();
newValue.UserID = userID;
newValue.OrganizationID = orgID;
var targetUrl = NaturalUnitUrl;
// Update the stored data
$.ajax({
url: targetUrl,
type: 'POST',
dataType: 'json',
data: newValue,
success: function (data, txtStatus, xhr) {
saveNewUnit(event);
window.location.reload(true);
},
error: function (xhr, textStatus, errorThrown) {
alert("error");
}
});
}
function saveNewUnit(event) {
var node;
// alert("Save new Natural Unit - Feature Not Yet Implemented");
node = event.target;
while (node.id != ("rowA")) {
node = getParentNode(node, "A");
}
// node.remove();
$(node).remove();
event.stopPropagation();
}
function saveUpdatedNaturalUnitHandler(event) {
var item = new NaturalUnit();
// newDeliverable = event.data.param1;
item.ID = event.data.param1.ID;
item.Name = $("#txtName").val();
item.Description = $("#txtDescription").val();
item.UserId = UserID;
saveUpdatedNaturalUnit(item);
}
/// Declare a function to apply the updated deliverable changes
function saveUpdatedNaturalUnit(item) {
// update the target URL
var targetUrl = naturalUnitUrl;
// Update the stored data
$.ajax({
url: targetUrl,
type: 'PUT',
dataType: 'json',
data: item,
}).done(function (data, txtStatus, xhr) {
window.location.reload(true);
}).fail(function (xhr, textStatus, errorThrown) {
alert("error");
});
// Set the edit mode flag
deliverableEdit = false;
}
function deleteUnit(event) {
alert("Delete '"+event.data.param1.Name+"' - Feature Not Yet Implemented");
event.stopPropagation();
}
function highlightRow(event) {
var id;
var node;
currentNaturalUnit = event.data.param1;
resetDisplay();
node = event.target;
// Check to see if this event came from the row or the cell
while ( node.id != ("row" + event.data.param1.ID)) {
node = getParentNode(node, event.data.param1.ID);
}
$(node).css({ "background": "linear-gradient(rgba(128,193,229,1),white,rgba(128,193,229,1))"});
// $(node).addClass("highlight");
// Load the model for the current selected row
loadModel(event.data.param1);
// Update the header for the scoep model
$("#modelLabel").val(event.data.param1.Name);
// $("#scopeModelHeader").text("Productivity Model: " + event.data.param1.Name);
}
function getParentNode(node,ID) {
node = node.parentNode;
if (node.id != ("row"+ID)) {
node = getParentNode(node,ID);
}
return (node);
}
function resetDisplay() {
var table;
var count=0;
// Reset the background for each data row in the table
$('#naturalUnitTable tr').each(function () {
// Skip the header row
if (count > 0) {
$(this).css({ "background": "linear-gradient(white,white)" });
}
// Increment the counter
count++;
});
}
} |
/*
* ISC License
*
* Copyright (c) 2018, Andrea Giammarchi, @WebReflection
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
'use strict';
/* eslint comma-dangle: ['error', 'always-multiline'] */
/* eslint sort-keys: ['error', 'asc'] */
module.exports = {
env: {
browser: true,
es6: true,
node: true,
},
extends: 'eslint:recommended',
parserOptions: {
ecmaVersion: 2018,
},
root: true,
rules: {
eqeqeq: [
'error',
'smart',
],
indent: [
'error',
2,
{
SwitchCase: 1,
ignoreComments: true,
},
],
'linebreak-style': [
'error',
'unix',
],
'no-await-in-loop': 'warn',
'no-console': 'off',
'no-constant-condition': 'warn',
'no-empty': 'off',
'no-fallthrough': 'warn',
'no-new-wrappers': 'error',
'no-octal': 'warn',
'no-regex-spaces': 'warn',
'no-return-await': 'error',
'no-unused-vars': 'warn',
'prefer-destructuring': 'warn',
quotes: [
'error',
'single',
{
allowTemplateLiterals: true,
avoidEscape: true,
},
],
semi: [
'error',
'always',
],
},
};
|
import React from 'react'
export default class BaseComponent extends React.Component {
constructor({navigation}) {
super();
this.navigation = navigation;
}
} |
import React, { useEffect } from 'react';
import styles from './../../styles/Home.module.css';
import UserFilter from '../../comps/UserFilter';
import { useTheme } from '@material-ui/core';
import { ArrowBackIos } from '@material-ui/icons';
import Button from '@material-ui/core/Button';
import Link from 'next/link';
import { useRouter } from 'next/router';
const WriteTo = () => {
const theme = useTheme();
const router = useRouter();
useEffect(() => router.push('/'));
return (
<div className={styles.container} style={{ minHeight: '100vh' }}>
<main className={styles.main}>
<Link href={'/'}>
<Button variant={'outlined'}>
<ArrowBackIos /> Back To Home
</Button>
</Link>
<h1
className={styles.title}
style={{ color: theme.palette.secondary.main, margin: '2rem' }}
>
Send A Letter
</h1>
<UserFilter />
</main>
</div>
);
};
export default WriteTo;
|
require('./model');
const mongoose = require('mongoose');
let Node = mongoose.model('node');
module.exports = async () => {
const initNodePromise = (pubKeyHash, company) => {
let node = new Node({
pubKeyHash,
company
});
return new Promise((resolve, reject) => {
node.save(err => {
resolve();
});
});
};
let promises = [];
promises.push(initNodePromise('1e095aff6eef007cb07577f0646e31b3756e6fe8d505462b477cdd273bc2243a', 'phhoang'));
promises.push(initNodePromise('2dedf231bb53757027f475dc6a37259348004875cc9882df46b8e1ce3a36c773', 'pvduong'));
promises.push(initNodePromise('98f6c0a37f90e594536eb6b2dc5b45c609f35493c40a749ffc2c1a024903e76b', 'ndhung'));
await Promise.all(promises);
}; |
function ProjectTransferMoneyCtrl($scope, $http, $stateParams, $modalInstance, SweetAlert, Constants) {
$scope.ProjectId = $stateParams.id;
$scope.TransferMoneyDto = {
ProjectId: $scope.ProjectId,
AccountFrom: {Id: null, AccountTitle: null },
AccountTo: {Id: null, AccountTitle: null },
Amount: 0,
Fee:0,
Currency: 'd',
TransferDate: new Date(),
IsClear: true
};
$scope.Accounts = [];
$scope.loadAvailableAccounts = function()
{
$http.get(Constants.WebApi.Project.GetAccounts, { params: { projectId: $scope.ProjectId } }).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.Accounts = response.data.Accounts;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: response.data,
type: "warning"
});
});
}
$scope.transferMoney = function () {
$http.post(Constants.WebApi.Project.TransferMoney, $scope.TransferMoneyDto).then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.ok();
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
SweetAlert.swal({
title: "Error!",
text: response.data,
type: "warning"
});
});
}
$scope.onload = function()
{
$scope.loadAvailableAccounts();
}
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
} |
import drop from 'lodash/drop';
export const pickBackReferences = (str, regexp) => {
if (typeof str !== 'string') return [];
const match = str.match(regexp);
if (!match) return [];
return drop(match, 1);
}; |
function greeter(person, id) {
return ("Hello, " + person + id);
}
//let user = "Jane User";
var s = greeter("user", 101);
console.log(s);
|
var http = require("http");
var url = require('url');
var fs = require('fs');
var ytdl = require('ytdl-core');
//delete stream-to-buffer
var streamToBuffer = require('stream-to-buffer')
// function sendChunk(key, destination, count) {
// var stream = ytdl(key, {
// filter: "audioonly"//,
// //range: { start: count * 10000, end: (count + 1) * 10000 }
// });
// stream.on('progress', function (chunkSize, totalDownloaded, total) {
// console.log((totalDownloaded / total) * 100 + '%');
// //sendChunk(key, destination, count + 1);
// })
// stream.pipe(destination);
// }
// var server = http.createServer(function (request, response) {
// response.writeHead(200, { "Content-Type": "arrayBuffer", "Access-Control-Allow-Origin": "*" });
// if (request.method == 'GET') {
// //get params as object
// var queryData = url.parse(request.url, true).query;
// console.log(queryData.viewKey);
// var count = 0;
// sendChunk(queryData.viewKey, response, count);
// // stream.on('finish', function () {
// // console.log("Finsh!");
// //response.end();
// //})
// }
// // else if (request.method == 'POST') {
// // response.write("I anwser a POST reuqest.");
// // response.write("With body: \n");
// // //read post body
// // var body = '';
// // request.on('data', function (data) {
// // body += data.toString();
// // });
// // request.on('end', function () {
// // var POST = JSON.parse(body);
// // console.log(POST);
// // response.write(body);
// // });
// //}
// });
// server.listen(12909);
// console.log("Server is listening");
"use strict";
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'AudioKruc';
// Port where we'll run the websocket server
var webSocketsServerPort = 12909;
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
/**
* Global variables
*/
// list of currently connected clients (users)
var clients = [ ];
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server,
// not HTTP server
});
server.listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port "
+ webSocketsServerPort);
});
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket
// request is just an enhanced HTTP request. For more info
// http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin '
+ request.origin + '.');
// accept connection - you should check 'request.origin' to
// make sure that client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request.accept(null, request.origin);
// we need to know client index to remove them on 'close' event
var index = clients.push(connection) - 1;
var key = "";
console.log((new Date()) + ' Connection accepted.');
// user sent some message
connection.on('message', function(message) {
debugger
if (message.type === 'utf8') { // accept only text
//var queryData = url.parse(request.url, true).query;
if(message.utf8Data.indexOf('youtube') != -1) {
key = message.utf8Data;
var keyIndex = key.indexOf('viewKey=') + 'viewKey='.length;
key = key.substring(keyIndex, key.length);
sendChunk(key, connection, 0);
}
// else {
// sendChunk(key, connection, parseInt(message.utf8Data));
// }
}
});
// user disconnected
connection.on('close', function(connection) {
console.log((new Date()) + " Peer "
+ connection.remoteAddress + " disconnected.");
// remove user from the list of connected clients
clients.splice(index, 1);
// push back user's color to be reused by another user
//colors.push(userColor);
});
});
function sendChunk(key, connection, count) {
var finish = false;
var stream = ytdl(key, {
filter: "audioonly"//,
//range: { start: count * 10000, end: (count + 1) * 10000 }
});
stream.on('progress', function (chunkSize, totalDownloaded, total) {
console.log('chunkSize: ' + chunkSize);
console.log('totalDownloaded: ' + totalDownloaded);
console.log('total: ' + total);
console.log((totalDownloaded / total)*100 + '%');
if(totalDownloaded == total){
finish = true;
}
})
stream.on('data', function(data){
connection.sendBytes(data);
if(finish){
connection.close();
}
});
} |
import angular from "/ui/web_modules/angular.js";
export default "mnMinlength";
angular
.module('mnMinlength', [])
.directive('mnMinlength', mnMinlengthDirective);
function mnMinlengthDirective() {
var mnMinlength = {
restrict: 'A',
require: 'ngModel',
link: link
};
return mnMinlength;
function link(scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (value) {
var min = attrs.mnMinlength;
ctrl.$setValidity('mnMinlength', min && value && value.length >= parseInt(min));
return value;
});
}
}
|
const Busca = () => {
var busca;
busca = document.getElementById("busca").value;
alert(`La busqueda con nombre ${busca} no se encuentra, por lo cual te solicitamos intentar más tarde`)
} |
import React, { Component } from "react";
class Filter extends Component {
state = {
magnitudeFilter: "",
isFilterOpen: false
};
handleMagnitudeChange = event => {
this.setState({ magnitudeFilter: event.target.value });
};
toggleFilter = event => {
this.setState(currentState => {
return { isFilterOpen: !currentState.isFilterOpen };
});
};
componentDidUpdate(prevProps, prevState) {
if (this.state.magnitudeFilter !== prevState.magnitudeFilter) {
this.props.fetchFilteredData(
this.state.magnitudeFilter
);
}
}
render() {
return (
<>
<div className="filter">
<h2 className="filter__h2" onClick={this.toggleFilter}>
PM2.5 AQI
</h2>
<a onClick={this.toggleFilter}> {this.state.isFilterOpen? '+' : 'x'}</a>
{this.state.isFilterOpen === true ? null : (
<>
<form>
<h3 className="filter__h3"></h3>
{/* <label>
<input
type="radio"
name="magnitude"
value='All'
checked={this.state.magnitudeFilter === 'All'}
onChange={this.handleMagnitudeChange}
/>
All
</label>
<label>
<input
type="radio"
name="magnitude"
value='Good'
checked={this.state.magnitudeFilter === 'Good' }
onChange={this.handleMagnitudeChange}
/>
<div class="control__indicator1"></div>
{"Good"}
</label>
<label>
<input
type="radio"
name="magnitude"
value='Moderate'
checked={this.state.magnitudeFilter === 'Moderate' }
onChange={this.handleMagnitudeChange}
/>
<div class="control__indicator2"></div>
{"Moderate"}
</label>
<label>
<input
type="radio"
name="magnitude"
value='UHFSG'
checked={this.state.magnitudeFilter === 'UHFSG' }
onChange={this.handleMagnitudeChange}
/>
<div class="control__indicator3"></div>
Unhealthy <small>for sensitive groups</small>
</label>
<label>
<input
type="radio"
name="magnitude"
value='Unhealthy'
checked={this.state.magnitudeFilter === 'Unhealthy' }
onChange={this.handleMagnitudeChange}
/>
<div class="control__indicator4"></div>
{"Unhealthy"}
</label> */}
<label>
<input
type="radio"
name="magnitude"
value='Mains'
checked={this.state.magnitudeFilter === 'Mains' }
onChange={this.handleMagnitudeChange}
/>
<div class="control__indicator5"></div>
{"Mains"}
</label>
<label>
<input
type="radio"
name="magnitude"
value={"Solar"}
checked={this.state.magnitudeFilter === 'Solar'}
onChange={this.handleMagnitudeChange}
/>
<div class="control__indicator6"></div>
{"Solar"}
</label>
</form>
</>
)}
</div>
</>
);
}
}
export default Filter; |
const fs = require('fs')
const paths = require('./paths')
const dotenvParseVariables = require('dotenv-parse-variables')
delete require.cache[require.resolve('./paths')]
if (!process.env.NODE_ENV) {
throw new Error(
'The process.env.NODE_ENV environment variable is required but was not specified.'
)
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${process.env.NODE_ENV}.local`,
`${paths.dotenv}.${process.env.NODE_ENV}`,
process.env.NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv
].filter(Boolean)
let env = {}
dotenvFiles.forEach((dotenvFile) => {
if (fs.existsSync(dotenvFile)) {
const { parsed } = require('dotenv').config({
path: dotenvFile
})
env = {
...env,
...dotenvParseVariables(parsed)
}
}
})
module.exports = env
|
let board = [
[0, 0, 0, 0, 0],
[0, 0, 1, 0, 3],
[0, 2, 5, 0, 1],
[4, 2, 4, 4, 2],
[3, 5, 1, 3, 1],
];
let moves = [1, 5, 3, 5, 1, 2, 1, 4];
var answer = 0;
function solution(board, moves) {
let bucket = [];
for (let i = 0; i < moves.length; i++) {
for (let j = 0; j < board.length; j++) {
if (board[j][moves[i] - 1] !== 0) {
if (bucket[bucket.length - 1] === board[j][moves[i] - 1]) {
answer += 2;
bucket.pop();
} else {
bucket.push(board[j][moves[i] - 1]);
}
console.log(bucket);
board[j][moves[i] - 1] = 0;
break;
}
}
}
return answer;
}
solution(board, moves);
console.log(answer);
|
/** @jsx React.DOM **/
Ninja.Views.Event = React.createClass({
getInitialState: function() { return {expanded: false}; },
onSelect: function () {
el = $(this.getDOMNode());
if (!this.state.expanded) { this.scrollToElelement(el); }
this.setState({expanded : !this.state.expanded});
},
scrollToElelement: function (el) {
var list = $('html,body').find('li.section')[0].parentElement;
var listOffset = $(list).offset().top;
var listheight = $(list).height();
var elOffset = $(el).offset().top
if (elOffset > listOffset + listheight/2 ){
$(list).animate({scrollTop: $(list).scrollTop() + elOffset - lisstOffset }, 500);
}
},
trackiTunesLinkClickEvent: function () {
if (window._gat) _gaq.push(['_trackEvent', 'appStoreClick', 'from event']);
},
render: function () {
var model = this.props.model;
var timeAndLocation = model.get('times_and_locations').map( function (tal) {
var tal = tal.weekdays + ' ' + tal.timeInterval;
return (<div className = 'row'>{tal}</div>)
});
var timeAndLocationDetail = function () {
if (!model.get('times_and_locations').length) return null
else if (model.get('times_and_locations').length < 2 ) {
return (<div> {model.get('times_and_locations')[0].location} </div>)
}
else {
return model.get('times_and_locations').map( function (tal) {
return ( <div>
<div > {tal.location} </div>
<div className = 'detail_tal'> {tal.weekdays} {tal.timeInterval}</div>
</div>
);
});
}
}
var detailHeader = ['Status', 'Section', 'Location'].map( function (header) {
return ( <div className = 'row detail-header'> {header} </div>);
});
var statusColor = {color: model.getStatusColor()}
var eventDetailCLasses = globals.cx({
'event-detail row' : true,
'expanded': this.state.expanded
});
var expandErrowClass = globals.cx({
'fa fa-angle-down fa-lg' : true,
'fa-flip-vertical': this.state.expanded
})
return (
<div className = 'event' onClick = {this.onSelect.bind(this)}>
<div className = 'row event-header'>
<div className = "status-marker-container col-xs-1">
<span style = {statusColor} className = "status-marker"></span>
</div>
<span className = 'col-xs-4 '> {this.props.sectionType} </span>
<div className = 'times_and_location col-xs-6'> {timeAndLocation} </div>
<div className = 'col-xs-1 arrow'> <i className = {expandErrowClass} /> </div>
</div>
<div className = {eventDetailCLasses} >
<div className = 'col-xs-offset-1 col-xs-3'> {detailHeader} </div>
<div className = 'col-xs-6 row_info'>
<div className = 'row' style = {statusColor} > {model.get('status')} </div>
<div className = 'row'> {this.props.sectionId} </div>
<div className = 'row'> {timeAndLocationDetail()} </div>
</div>
<div className = 'col-xs-offset-1 col-xs-10 download-to-track'>
<a href = 'https://itunes.apple.com/us/app/id903690805' onClick = {this.trackiTunesLinkClickEvent}>
get app to track this class
</a>
</div>
</div>
</div>
)
}
});
|
const express = require('express');
const router = express.Router();
const authService = require('../services/authService')
const BusinessException = require('../utils/businessException')
// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now())
next()
})
/**
* @swagger
* /api/auth/signing:
* post:
* description: Sign In
* responses:
* '200':
* description: Success
*/
router.all('/signin', function (req, res) {
authService.signin(req.body.username, req.body.password, function (obj) {
if (obj instanceof BusinessException) {
res.status(obj.code).send({ message: obj.message });
}
else {
console.log("token", obj);
res.send(obj);
}
});
});
/**
* @swagger
* /api/auth/validateToken:
* get:
* description: Validate Token
* responses:
* '200':
* description: Success
*/
router.get('/validateToken', function (req, res) {
authService.validateToken(req, function (valid) {
res.send(valid);
});
});
module.exports = router;
|
import switchableDevice from './switchableDevice'
const DIMMERABLE = 'dimmerable';
const RGB_COLOR = 'rgbcolor';
class Light extends switchableDevice {
constructor(identity,name,realm,defaultState = 'on',attributes,data){
super(identity,name,realm,defaultState,attributes,data);
this.type = 'light';
this.supports = [];
}
static get DIMMERABLE(){
return DIMMERABLE;
}
static get RBG_COLOR(){
return RGB_COLOR;
}
toData(){
let data = super.toData();
data.supports = this.supports;
return data;
}
}
export default Light;
|
module.exports = planSchema = `
type Plan {
_id: ID!
title: String!
subtitle: String!
date: String!
location: String!
background: String
likes: [User!]
users: [User!]
creator: User!
}
input CreatePlanInput {
title: String!
subtitle: String!
date: String!
location: String!
background: String
creator: ID!
}
`
|
import GenerateIcon from './icon-generator.js'
module.exports = GenerateIcon
|
$(document).ready(function () {
// Animasi
$(".preloader").fadeOut();
$(".card").addClass("animated fadeInLeft");
$("small").addClass("animatedDelay jackInTheBox");
$("#password").focus(function () {
$(this).prop("type", "text");
});
$("#password").focusout(function () {
$(this).prop("type", "password");
});
// Fungsi Form
$("#tombolsignup").on("click", function () {
$.ajax({
url: BaseURL + "masuk/pagesignup",
success: function (data) {
swal.close();
$("#main-page").removeClass("animated fadeInDown");
$("#main-page").addClass("animated fadeInDown");
$("#main-page").html(data);
},
});
});
$("#tombolsignin").on("click", function () {
$.ajax({
url: BaseURL + "masuk/pagesignin",
success: function (data) {
swal.close();
$("#main-page").removeClass("animated fadeInDown");
$("#main-page").addClass("animated fadeInDown");
$("#main-page").html(data);
},
});
});
$("#gologin").on("submit", function () {
// CSRF
var csrfName = $("input[name=csrf_sipp_token]").attr("name");
var csrfHash = $("input[name=csrf_sipp_token]").val(); // CSRF hash
var username = $("#idpengguna").val();
var password = $("#idpass").val();
$.ajax({
type: "post",
url: BaseURL + "masuk/logindong",
beforeSend: function () {
swal.fire({
title: "Menunggu",
html: "Memproses data",
didOpen: () => {
swal.showLoading();
},
});
},
data: {
username: username,
password: password,
[csrfName]: csrfHash,
}, // ambil datanya dari form yang ada di variabel
dataType: "JSON",
error: function (data) {
console.log("gagal mengirim data");
},
success: function (data) {
$("input[name=csrf_sipp_token]").val(data.csrf);
if (data.status == "password!!!") {
swal.fire({
icon: "error",
title: "Login",
text: "Password yang anda masukkan salah !",
});
$("#idpass").val("");
} else if (data.status == "akun!!!") {
swal.fire({
icon: "error",
title: "Login",
text: "Akun tidak ditemukan !",
});
$("#idpengguna").val("");
$("#idpass").val("");
} else {
location.reload();
}
},
});
return false;
});
// Daftar
$("#signup").on("submit", function () {
// CSRF
var csrfName = $("input[name=csrf_sipp_token]").attr("name");
var csrfHash = $("input[name=csrf_sipp_token]").val(); // CSRF hash
// Data
var nama = $("#daftar-nama").val();
var password = $("#password").val();
var nohp = $("#daftar-nohp").val();
var email = $("#daftar-email").val();
var jk = $("select#jeniskelamin").children("option:selected").val();
$.ajax({
type: "post",
url: BaseURL + "masuk/daftardong",
beforeSend: function () {
swal.fire({
title: "Menunggu",
html: "Memproses data",
didOpen: () => {
swal.showLoading();
},
});
},
data: {
nama: nama,
password: password,
nohp: nohp,
email: email,
jk: jk,
[csrfName]: csrfHash,
}, // ambil datanya dari form yang ada di variabel
dataType: "JSON",
error: function (data) {
console.log("gagal mengirim data");
},
success: function (data) {
$("input[name=csrf_sipp_token]").val(data.csrf);
if (data.status == "email!!!") {
swal.fire({
icon: "error",
title: "Daftar",
text: "Email yang anda masukkan sudah terdaftar !",
});
$("#daftar-email").val("");
} else if (data.status == "nohp!!!") {
swal.fire({
icon: "error",
title: "Daftar",
text: "Nomor Hp yang anda masukkan sudah terdaftar !",
});
$("#daftar-nohp").val("");
} else {
$.ajax({
type: "GET",
url: "http://panel.rapiwha.com/send_message.php",
data: {
apikey: data.apikey,
number: data.nohp,
text: data.message,
}, // ambil datanya dari form yang ada di variabel
error: function (data) {
console.log("gagal mengirim WA");
},
success: function (data) {
location.reload();
},
});
}
},
});
return false;
});
$("#formactive").on("submit", function () {
// CSRF
var csrfName = $("input[name=csrf_sipp_token]").attr("name");
var csrfHash = $("input[name=csrf_sipp_token]").val(); // CSRF hash
var kode = $("#kodeactive").val();
$.ajax({
type: "post",
url: BaseURL + "masuk/actvcode",
beforeSend: function () {
swal.fire({
title: "Menunggu",
html: "Memproses data",
didOpen: () => {
swal.showLoading();
},
});
},
data: {
kode: kode,
[csrfName]: csrfHash,
}, // ambil datanya dari form yang ada di variabel
dataType: "JSON",
error: function (data) {
console.log(data.responseText);
},
success: function (res) {
$("input[name=csrf_sipp_token]").val(res.csrf);
console.log(res);
if (res.status == "sejen!!!") {
swal.fire({
icon: "error",
title: "Aktivasi",
text: "Kode yang anda masukkan salah !",
});
$("#kodeactive").val("");
} else {
window.location.href = BaseURL;
}
},
});
return false;
});
});
|
let value = 500;
switch(value) {
case 200:
// execute case x code block
console.log('Su operacion ha sido exitosa!');
break;
case 400:
// excute case x code block
console.log('Su operacion no pudo realizar en este momento, contacte al administrador de sistemas!')
break;
default:
// execute default code block
console.log('Servidor no disponible');
}
const day = new Date().getDay();
console.log('day', day)
switch(day) {
case 1:
console.log('Happy Monday');
break;
case 2:
console.log("It's Tusday. You got this!");
break;
case 3:
console.log('Hump day already');
break;
case 4:
console.log("Just one more day 'til the weekend!");
break;
case 5:
console.log('Happy Friday!');
break;
case 6:
console.log("Have a wonderfull Saturday!");
}
const month = new Date().getMonth();
switch(month){
// January,February, March
case 0:
case 1:
case 2:
console.log('Winter');
break;
// April, May, June
case 3:
case 4:
case 5:
console.log('Spring');
break;
// July, August, September
case 6:
case 7:
case 8:
console.log('Summer');
break;
// October, November, December
case 9:
case 10:
case 11:
console.log('Autumn');
break;
default:
console.log('Something went wrong!');
}
// Set the student grade
const grade = 90;
switch(true){
// if score is 90 or greater
case grade >= 90:
console.log('A')
break;
case grade >= 80:
console.log('B');
break;
case grade >= 70:
console.log('C');
break;
case grade >= 60:
console.log('D');
break;
case grade >= 50:
console.log('F');
break;
// Anything 59 or below is falling
default:
console.log('F');
} |
var MailboxInteractor = function() {};
const mailboxPresenter = require('../presenter/mailbox.js');
const mailboxRepository = require('../repository/mailbox.js');
MailboxInteractor.prototype.getUserMailbox = function(user, res) {
const addressUser = userRepository.getUserAddress(user);
const mailList = mailboxRepository.getFakeMail(addressUser);
mailboxPresenter.presentMailbox(mailList, res);
};
MailboxInteractor.prototype.postMail = function(from, to, message, res) {
const success = mailboxRepository.postFakeMail();
if (success) {
presenter.presentSendMailSuccess(res);
} else {
presenter.presentSendMailError(res);
}
mailboxPresenter.presentSendMailStatus(status, res);
}
module.exports = new MailboxInteractor();
|
$("#createEventPage").on( "pagebeforeshow", function( event ) {
// closeMenu();
$( "#eMenua" ).unbind("click").bind("click", function(event){
openMenu();
});
var dt = new Date();
$("#eTitle").val("test title");
$("#eLoction").val("test Location");
$("#eMessage").val("test Message");
$("#eSave").unbind("click").bind("click", function(event){
addEvent();
});
});
function addEvent() {
var startDate = new Date($("#eDate").val());
var endDate = new Date($("#eDate").val());
var startTime = $("#eStartTime").val();
var eEndTime = $("#eEndTime").val();
startDate.setHours(parseInt(startTime.substr(0,2)));
startDate.setMinutes(parseInt(startTime.substr(3)));
endDate.setHours(parseInt(eEndTime.substr(0,2)));
endDate.setMinutes(parseInt(eEndTime.substr(3)));
if(startDate >= endDate) {
alert("Enter a valid date, Start time should be less than end time");
return;
}
else if(startDate < (new Date())) {
alert("Event should start in future");
return;
}
var eventDict = {
"startDate":startDate,
"endDate":endDate,
"title" :$("#eTitle").val(),
"eventLocation":$("#eLoction").val(),
"message":$("#eMessage").val()
}
createCalendarEvent(eventDict,function(){
alert("Event added");
},function(){
alert("Something went wrong");
})
}
/*
var title = eventDetails["title"];
var eventLocation = eventDetails["eventLocation"];
var notes = eventDetails["notes"];
var startDate = eventDetails["startDate"];
var endDate = eventDetails["endDate"];
*/
|
import React from "react";
import { ContextData } from "../context/GlobalState";
function AddTransaction() {
const { AddTrans } = React.useContext(ContextData);
let newTransaction;
const [text, setText] = React.useState("");
const [amount, setAmount] = React.useState("");
const TRef = React.useRef("");
const ARef = React.useRef("");
function handleText() {
setText(TRef.current.value);
}
function handleAmount() {
setAmount(ARef.current.value);
}
const onSubmit = (e) => {
e.preventDefault();
if (text && amount) {
newTransaction = {
id: Math.floor(Math.random() * 100000000),
text,
amount: +amount,
};
AddTrans(newTransaction);
setText("");
setAmount("");
} else {
alert("empty block!");
}
};
return (
<>
<h3>Add new transaction</h3>
<form onSubmit={onSubmit}>
<div className="form-control">
<label htmlFor="text">Text</label>
<input
type="text"
placeholder="Enter text..."
value={text}
ref={TRef}
onChange={handleText}
/>
</div>
<div className="form-control">
<label htmlFor="amount">
Amount <br />
</label>
<input
type="number"
placeholder="Enter amount..."
value={amount}
ref={ARef}
onChange={handleAmount}
/>
</div>
<button className="btn">Add transaction</button>
</form>
</>
);
}
export default AddTransaction;
|
define([
'views/view',
'text!views/New/New.html'
], function (View, html) {
var view, navbar, body, page;
var model = kendo.observable({
quizId: "2154706",
checkSimulator: function() {
if (window.navigator.simulator === true) {
console.log('This plugin is not available in the simulator.');
return true;
} else if (window.plugins === undefined || window.plugins.AdMob === undefined) {
console.log('Plugin not found. Maybe you are running in AppBuilder Companion app which currently does not support this plugin.');
return true;
} else {
return false;
}
},
showBanner: function (bannerPosition, bannerType) {
window.plugins.AdMob.createBannerView(
// createBannerView params
{
'publisherId': 'ca-app-pub-7082385269825044/8266548011',
'adSize': bannerType,
'bannerAtTop': bannerPosition == 'top',
'overlap': true, // true doesn't push the webcontent away
'offsetTopBar': true // set to true if you want it below the iOS >= 7 statusbar
},
// createBannerView success callback
function() {
window.plugins.AdMob.requestAd(
// requestAd params
{
'isTesting': false
},
// requestAd success callback
function(){
window.plugins.AdMob.showAd(
// showAd params
true,
// showAd success callback
function() {console.log('show ok')},
// showAd error callback
function() { alert('failed to show ad')});
},
// requestAd error callback
function(){ alert('failed to request ad'); }
);
},
// createBannerView error callback
function(){ alert('failed to create banner view'); }
);
},
getQuiz:function(e){
//set numAttempts and numCorrect to 0 for new quiz
localStorage.setItem("numAttempts",0)
localStorage.setItem("numCorrect",0)
var url = 'https://api.quizlet.com/2.0/sets/'+this.quizId+'?client_id=xxx';
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url,
dataType: "jsonp"
}
},
schema: {
data: "terms"
},
requestEnd: function( event ) {
var quiz = event.response.terms;
var quizArray = []
if(quiz){
for (var i = quiz.length - 1; i >= 0; i--) {
quizArray.push(quiz[i].term + '|' + quiz[i].definition)
};
var qArr = JSON.stringify(quizArray)
localStorage.setItem("quiz",qArr)
window.location.href="#spin"
}
else{
alert("Sorry, that quiz id is invalid. Please try again!");
}
}
});
dataSource.read();
},
});
var events = {
dataInit: function (e) {
if(!model.checkSimulator()){
model.showBanner('top',window.plugins.AdMob.AD_SIZE.BANNER);
}
},
dataShow:function(e){
}
};
// create a new view
view = new View('New', html, model, events);
});
|
import React from 'react';
const Input = ({className, value, onChange, placeholder}) => {
// let inputClassName = 'form-control ';
// if (className) {
// inputClassName += className
// }
return (
<input
className={className}
type="text"
value={value}
onChange={onChange}
placeholder={placeholder}
/>
)
}
export default Input; |
// exhOh(str) prend en compte (str)
//retourne true si même nbr egal de X et de O
//sinon retourne false
// donc c'est un boleen
//d'abord instaurer un boucle pour la lecture de toute la string
//compter le nbr de X et compter le nbr de O
//si dans la longueur de string il y a le même nbr de "X" et de "O"
//alors retourne 'true'
//sinon retourne 'false'
function exhOh(str) {
var counterX = '';
var counterO = '';
for (var i = 0; i < str.lenght; i++) {
if (str[i].toUppercase() === 'X') {
counterX = counterX + 1;
}
if (str[i].toUppercase() === 'O') {
counterO = counterO + 1;
}
}
if (counterO === counterX) {
return true;
}
}
console.log(exhOh('KONEXIO'));
|
/**
* require nunjucks
*/
export const nun = require('nunjucks');
|
'use strict'
const mongoose = require('mongoose')
const { Schema } = mongoose
/**
* Create application schema
*/
const versionSchema = new Schema({
owner: {
type: Schema.Types.ObjectId,
ref: 'Application',
required: true
},
version: {
type: String,
required: true
},
servicesUrls: {
type: Array,
required: true
},
minVersion: {
type: String,
required: true
},
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
})
/**
* Create a model using application schema
*/
module.exports = mongoose.model('Version', versionSchema)
|
import { html, LitElement } from 'lit-element';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/iron-icons/social-icons.js';
import '@polymer/iron-icons/maps-icons.js';
import homepageStyles from '../../style/homepage.scss';
import sharedStyles from '../../style/app.scss';
import './notifications.js';
import './context.js';
import './user-button.js';
class topNav extends LitElement {
static get styles() {
return [sharedStyles, homepageStyles];
}
render() {
let version1 = html`
<header class="navbar">
<div class="container top-nav">
<div class="navbar-brand">
<a class="navbar-item" href="http://0.0.0.0:8080/oae">
<img src="/images/logo-01.svg" width="112" height="28" />
</a>
<div class="navbar-item">
<div class="field has-addons has-addons-centered">
<p class="control">
<span class="icon topbar-search-icon">
<iron-icon icon="search"></iron-icon>
</span>
</p>
<p class="control">
<input class="input top-nav-input" type="text" placeholder="Type to search" />
</p>
</div>
</div>
<span class="navbar-burger burger" data-target="navbarMenuHeroC">
<span></span>
<span></span>
<span></span>
</span>
</div>
<div id="navbarMenuHeroC" class="navbar-menu">
<div class="navbar-end">
<notifications-button></notifications-button>
<context-button></context-button>
<userprofile-button></userprofile-button>
</div>
</div>
</div>
</header>
`;
let version2 = html`
<header class="navbar">
<div class="container top-nav">
<div class="navbar-item">
<div class="field has-addons has-addons-centered">
<p class="control">
<span class="icon topbar-search-icon">
<iron-icon icon="search"></iron-icon>
</span>
</p>
<p class="control">
<input class="input top-nav-input" type="text" placeholder="Type to search" />
</p>
</div>
</div>
<span class="navbar-burger burger" data-target="navbarMenuHeroC">
<span></span>
<span></span>
<span></span>
</span>
</div>
<div id="navbarMenuHeroC" class="navbar-menu">
<div class="navbar-end">
<notifications-button></notifications-button>
<context-button></context-button>
<userprofile-button></userprofile-button>
</div>
</div>
</div>
</header>
`;
return version1;
}
}
window.customElements.define('top-nav', topNav);
|
import fs from 'fs'
import pkg from 'gulp'
import cheerio from 'gulp-cheerio'
const { src, dest } = pkg
export const prepareHtmlBuild = () => {
// Исходные данные
const metaImages = fs.readdirSync(`${$.conf.src}/${$.conf.pathAssets}/${$.conf.pathPreviews}`) // изображения
const templates = fs.readdirSync(`${$.conf.app}/${$.conf.pathHTML}/${$.conf.htmlPages}`) // шаблоны страниц
const html = [] // Массив генерируемых элементов
const pages = {} // Объект, содержащий информацию о всех страницах
// Наполняем объект Pages информацией из meta-изображений
for (const meta of metaImages) {
if (meta === '.gitkeep' || meta === '.DS_Store') continue
// Получаем имя шаблона/страницы
const pageName = meta.substring(meta.indexOf('_') + 1, meta.lastIndexOf('.'))
// Создаем объект с названием страницы и присваиваем ему изображение
pages[pageName] = {}
pages[pageName].image = meta
}
// Наполняем объект Pages информацией из шаблонов
for (const template of templates) {
if (template === 'index' || template === '.DS_Store') continue
// Получаем имя шаблона/страницы
const pageName = template.substring(0, template.lastIndexOf('.'))
// Получаем доступ к локальному файлу текущей страницы
const file = fs.readFileSync(`${$.conf.app}/${$.conf.pathHTML}/${$.conf.htmlPages}/${pageName}.hbs`).toString()
// Проверяем, существует ли данная страница
if (pages[pageName] === undefined) pages[pageName] = {}
// Получаем заголовок страницы
if (file.indexOf('{{!') !== -1) {
pages[pageName].title = file.substring(3, file.indexOf('}}'))
}
// Получаем данные готовой страницы
const hbs = fs.readFileSync(`${$.conf.outputPath}/${$.conf.htmlPages}/${pageName}.html`).toString()
// Если заголовка в странице нет, то заменяем его на полученный из шаблона
if (hbs.indexOf(`<title></title>`) !== -1) {
fs.writeFileSync(
`${$.conf.outputPath}/${$.conf.htmlPages}/${pageName}.html`,
hbs.replace(/<title>(.*)/, '<title>' + pages[pageName] + '</title>')
)
}
const imgSrc = `./${$.conf.pathAssets}/${$.conf.pathPreviews}/${pages[pageName].image ?? '1000_default.svg'}`
const linkClass = pages[pageName].image === undefined ? 't-main__link t-main__link--default' : 't-main__link'
// Генерируем данные в наш массив со страницами
html.push(`
<li class='t-main__item'>
<article class='t-main__article'>
<h2 class='t-main__title'>${pages[pageName].title}</h2>
<a
class='${linkClass}'
href='./${$.conf.htmlPages}/${pageName}.html'
title='${pages[pageName].title}'
aria-label='Link to ${pages[pageName].title} page.'
>
<img
src='${imgSrc}'
alt='Preview image for ${pages[pageName].title}.'
loading='lazy'
/>
</a>
</article>
</li>`)
}
// Сортируем полученный массив элементов в соответствии с порядком, заданным в мета-изображениях
html.sort((a, b) => {
const pathLength = $.conf.pathPreviews.length + 1
let tempA = a.substring(a.lastIndexOf(`${$.conf.pathPreviews}/`) + pathLength, a.lastIndexOf('_'))
let tempB = b.substring(b.lastIndexOf(`${$.conf.pathPreviews}/`) + pathLength, b.lastIndexOf('_'))
tempA.charAt(0) === '0' ? (tempA = tempA.slice(1)) : tempA
tempB.charAt(0) === '0' ? (tempB = tempB.slice(1)) : tempB
return Number(tempA) - Number(tempB)
})
const sourceTemplate = fs.readFileSync($.conf.pathTemplateBuild).toString()
// Получаем время сборки
const date = new Date()
const options = {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
timezone: 'Europe/Moscow',
hour: 'numeric',
minute: 'numeric',
}
// Подставляем полученные данные и генерируем билд
fs.writeFileSync(
`${$.conf.outputPath}/index.html`,
sourceTemplate
.replace('{{items}}', `${html.join('')}`)
.replace(/{{siteName}}/g, $.conf.siteName)
.replace('{{buildDate}}', new Intl.DateTimeFormat('ru', options).format(date))
)
const startPath = `${$.conf.outputPath}/${$.conf.htmlPages}/**/*.html`
const destPath = `${$.conf.outputPath}/${$.conf.htmlPages}/`
return src(startPath)
.pipe(
cheerio({
run: (jQuery) => {
jQuery('script').each(function () {
let src = jQuery(this).attr('src')
if (src !== undefined && src.substr(0, 5) !== 'http:' && src.substr(0, 6) !== 'https:')
src = `../${$.conf.pathJS}/${src}`
jQuery(this).attr('src', src)
})
jQuery('a').each(function () {
let href = jQuery(this).attr('href')
if (
!href ||
href.substr(0, 1) === '#' ||
href.substr(0, 4) !== 'tel:' ||
href.substr(0, 4) !== 'ftp:' ||
href.substr(0, 5) !== 'file:' ||
href.substr(0, 5) !== 'http:' ||
href.substr(0, 6) !== 'https:' ||
href.substr(0, 7) !== 'mailto:'
)
return
if (href.substr(0, 6) === `/${$.conf.htmlPages}/`) {
href = href.substr(6)
}
let newHref = '/' + (href[0] === '/' ? href.substr(1) : href)
if (newHref.substr(-5) !== '.html') {
newHref = newHref + '.html'
}
jQuery(this).attr('href', newHref)
})
},
parserOptions: { decodeEntities: false },
})
)
.pipe(dest(destPath))
}
|
import { createSlice } from "@reduxjs/toolkit";
import { myfetch, getTemplate } from "../app/myFetch";
const initialState = {
trainTypes: [],
wagonTypes: [],
};
export const trainsSlice = createSlice({
name: "trainslist",
initialState,
reducers: {
setTrainTypes: (state, action) => {
state.trainTypes = action.payload;
},
setWagonTypes: (state, action) => {
state.wagonTypes = action.payload;
},
},
});
const { setTrainTypes, setWagonTypes } = trainsSlice.actions;
export const fetchTrainTypes = (request) => async (dispatch) => {
const response = await myfetch(request, getTemplate);
if (response.ok) {
console.log(response);
const json = await response.json();
dispatch(setTrainTypes(json));
} else {
alert("GET train types error");
}
};
export const fetchWagonTypes = (request) => async (dispatch) => {
const response = await myfetch(request, getTemplate);
if (response.ok) {
console.log(response);
const json = await response.json();
dispatch(setWagonTypes(json));
} else {
alert("GET wagon types error");
}
};
export default trainsSlice.reducer;
|
document.querySelector('button').addEventListener('click', function (event) {
document.querySelectorAll('p').forEach(function (paragraph) {
paragraph.classList.toggle('pilcrow');
});
var newButtonText = event.target.dataset.toggleText;
var oldText = event.target.innerText;
event.target.innerText = newButtonText;
event.target.dataset.toggleText = oldText;
}); |
$(function() {
//获取时间
var mydate = new Date();
var t = mydate.getFullYear();
$("#zg_sp").text(t);
$(".zg_dnavoul li").eq(5).css("border-right","none");
//配套服务
$('.s7_ld a').hover(function(){
$(this).addClass('s7_act').siblings().removeClass('s7_act');
$('.s7_wenz').eq($(this).index()).show().siblings('.s7_wenz').hide();
});
//成公辅导
var onoff=true;
$('.zg_con7oul li').hover(function(){
$(this).find('.zg_con7div2').toggleClass('zg_yfra02');
$(this).find('.zg_con7div1').toggleClass('zg_yfra01');
onoff=false;
});
//表格样式控制
$(".zg_con6div tr td:last-child").css("border-right","none")
$(".zg_con6div tbody tr:last-child").children("td").css("border-bottom","none")
//报名
$('.zg_bao1').click(function(){
$('.zg_xf').show();
$(".box_bj").show();
});
$('.zg_cfclose,.box_bj').click(function(){
$('.zg_xf').hide();
$(".box_bj").hide();
});
// 点击视频
$(".kc_pic").click(function(){
$(this).next().show();
var This=$(this)
var srcNew=$(this).next().find("iframe").attr("_src");
$(this).next().find("iframe").attr("src",srcNew);
setTimeout(function(){
This.next().find(".close").show();
},1000)
})
$(".close").click(function(){
$(this).parent().hide();
$(this).prev().attr("src","");
$(this).hide();
})
jQuery(".picScroll-left").slide({titCell:".hd ul",mainCell:".bd ul",autoPage:true,effect:"leftLoop",autoPlay:true,vis:3});
jQuery(".lunbo").slide({mainCell:".lb_list",titCell:".lb_tip li",effect:"leftLoop",autoPlay:true,interTime:2000,prevCell:".lb_prev",nextCell:".lb_next",pnLoop:true});
})
|
app.factory('getName', ['$http', function($http) {
return $http({
method: 'GET',
url: '/api/name'
}).then(function(success) {
return success.data;
}, function(err) {
return err;
});
}]);
|
import test from "tape"
import { isEqual } from "../is-equal/is-equal"
import { read } from "../read/read"
import { filter, filterWith } from "./filter"
test("filter", t => {
t.deepEqual(
filter(filterElm => filterElm <= 3)([1, 2, 3, 4, 5, 6]),
[1, 2, 3],
"Keep items lower or equal than 3 - curried"
)
t.deepEqual(
filter(filterElm => filterElm <= 3, "asd"),
[],
"Run filter for non-array input, treat as array of one (input does not match function) - uncurried"
)
t.deepEqual(
filter(filterElm => filterElm <= 3)(3),
[3],
"Run filter for non-array input, treat as array of one (input matches function)"
)
t.deepEqual(
filter([read("items"), isEqual(1)])([
{ id: 2, items: 2 },
{ id: 3, items: 1 },
{ id: 4, items: 2 },
]),
[{ id: 3, items: 1 }],
"Keep items in array that have properties that equal - curried"
)
t.end()
})
test("filterWith", t => {
t.deepEqual(
filterWith({
items: 2,
})([
{ id: 2, items: 2 },
{ id: 3, items: 1 },
{ id: 4, items: 2 },
]),
[
{ id: 2, items: 2 },
{ id: 4, items: 2 },
],
"Keep items in array that have properties that equal - curried"
)
t.deepEqual(
filterWith(
{
"!id": 2,
},
[{ lorem: 2 }, { lorem: 3 }, { id: 2 }]
),
[{ lorem: 2 }, { lorem: 3 }],
"Keep items in array that have properties that dont equal - uncurried"
)
t.end()
})
|
/* PRIMER EJERCICIO */
/* Crear una función que liste los números hasta 100 que muestre "fizz" en los múltiplos de 3, "buzz" en los múltiplos de 5
y "fizzbuzz en los múltiplos de 3 y 5 */
/* SEGUNDO EJERCICIO */
/* Crear una función que reciba una cantidad de niños, una cantidad de jueguetes y una posición de iniciao
La función debe retornar el último niño en recibir un juguete
@parameters
n kids
k toys
i initialPosition
@return int
*/
|
// @flow
import React from 'react';
import ReactMarkdown from 'react-markdown';
import Section from './Section';
import type { Work } from './types';
const WorkEntry = (
{
startDate,
endDate,
organization,
website,
position,
description,
highlights,
},
) => (
<li>
<h3>
{organization}
{' '}
<a href={website}><small>{website}</small></a>
<br />
<small>{`${position} (${startDate} — ${endDate})`}</small>
</h3>
{description && <ReactMarkdown source={description} escapeHtml />}
{!!highlights.length &&
<ul>
{highlights.map((hl, n) => (
<li key={n}>
<ReactMarkdown source={hl} escapeHtml />
</li>
))}
</ul>}
</li>
);
WorkEntry.defaultProps = {
endDate: 'current',
highlights: [],
};
const WorkDetails = ({ list }: { list: Work[] }) => (
<Section title="Work Details">
<ul className="list--unstyled list--spaced">
{list.map((el, i) => <WorkEntry {...el} key={i} />)}
</ul>
</Section>
);
export default WorkDetails;
|
export default class TodoItem extends React.Component {
render() {
/** @type {Todo} */
var todo = this.props.todo;
console.log(todo);
var style = {};
if (todo.IsComplete) {
style = Object.assign(style, { textDecoration: "line-through" });
}
return <li key={todo.Id} style={style}>
{todo.Description} <button onClick={() => TodoActions.update({ completed: true, todoId: todo.Id })}> - </button>
</li>
}
} |
var lineReader = require('line-reader');
var fs = require('fs');
module.exports = {
procurarDado: (dataInicio, dataFim) => async function () {
console.log(localArquivo)
console.log(ano)
console.log(mes)
var nomeArquivo
lineReader.eachLine(localArquivo, { encoding: 'latin1' }, function (line, last, cb) {
console.log(localArquivo)
var content = line.toString().replace("\t", '');
if (content[64] === ' ') {
content = [content.slice(0, 50), ' ', content.slice(50)].join('');
}
var inicio = content.slice(133, 143);
var fim = content.slice(228, 238);
content = content.replace(inicio, fim);
nomeArquivo = `RS09519714000185${ano}${mes}Z1001FCN1.txt`;
console.log(nomeArquivo)
fs.writeFile(`./arquivoConvertido/${nomeArquivo}`, `${content}\n`, { enconding: 'latin1', flag: 'a' }, function (err) {
if (err) throw err;
console.log(err);
})
});
return nomeArquivo;
}
} |
// ==UserScript==
// @name Shortcuts for JIRA
// @namespace pbo
// @description JIRA - additional shortcuts for JIRA
// @include http://your.jira.example.com/browse/*
// @version 1.1.0
// @grant GM_registerMenuCommand
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js
// @require https://raw.githubusercontent.com/jeresig/jquery.hotkeys/0.2.0/jquery.hotkeys.js
// ==/UserScript==
(function($) {
var traceOn = true;
trace('starting...');
function showHelp() {
alert(`Shortcuts for JIRA - Help
This adds some shortcuts which are missing in the default JIRA installation.
The following shortcuts are available on the issue detail page (<action> ... <function>):
- press <W>
... shows the Jira's Log Work dialog (if it is available)
- click '+/-' when hovering above 'Original / Remaining Estimate' fields while editing an issue
... a custom dialog appears which lets you change both estimates easily
@author pbodnar
@version 1.1.0
`);
}
try {
trace('command register');
GM_registerMenuCommand('Shortcuts for JIRA - Help', showHelp);
trace('command registered');
} catch (e) {
trace('command register error: ' + e);
}
// ==================== Commands ====================
function showLogWorkDialog() {
var btn = $('#log-work')[0];
if (!btn) {
trace('The Log Work button not found!');
return;
}
trace('Clicking the Log Work button...');
triggerMouseEvent(btn, 'click');
}
// ==================== GUI ====================
// register the various keyboard shortcuts
function bindShortcut(keys, handler) {
// make the shortcuts case-insensitive (bind() takes space as alternative keys
// separator):
keys = keys + ' ' + keys.toUpperCase();
$(document).bind('keypress', keys, handler);
}
function showError(msg) {
alert('ERROR: ' + msg);
}
var infoTimer = null;
function showInfo(html) {
var div = getInfoDiv();
div.innerHTML = html;
$(div).show()
.center();
var timer = infoTimer;
if (timer) {
clearTimeout(timer);
}
infoTimer = setTimeout(function() {
infoTimer = null;
$(div).hide();
}, 3000);
}
function getInfoDiv() {
if (typeof infoDiv != 'undefined') {
return infoDiv;
}
var div = infoDiv = document.createElement('div');
div.style = 'z-index: 1000000; color: green; background-color: white; padding: 1em; border: 0px solid green;';
div.style.position = 'absolute';
div.style.opacity = 1;
insertBodyElement(div);
return div;
}
bindShortcut('w', showLogWorkDialog);
setInterval(extendEstimateFields, 1000);
trace('started');
// ==================== Generic functions ====================
// see
// http://stackoverflow.com/questions/10423426/jquery-click-not-working-in-a-greasemonkey-tampermonkey-script
function triggerMouseEvent(node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
node.dispatchEvent(clickEvent);
}
function insertBodyElement(el) {
// insert the element as the first child - for easier debugging
document.body.insertBefore(el, document.body.firstChild);
}
function trace(text) {
if (traceOn) {
console.log(text);
}
}
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function (m, g1) {
return args[g1];
});
};
}
//==================== jQuery generic functions ====================
//http://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen
$.fn.center = function() {
this.css('position', 'absolute');
this.css('top', Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + 'px');
this.css('left', Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + 'px');
return this;
}
$.fn.focusWithSelect = function(startPos, endPos) {
this.focus();
// This works since IE 9.
// See https://stackoverflow.com/questions/3085446/selecting-part-of-string-inside-an-input-box-with-jquery/3085656#3085656 for more possibilities
this[0].selectionStart = startPos;
this[0].selectionEnd = typeof endPos == 'undefined' ? 1000000 : endPos;
return this;
}
// ==================== alter-jira-estimate-fields extension ====================
/*
* Structure of the target element:
*
* <input class="text short-field" id="timetracking_originalestimate" name="timetracking_originalestimate" type="text" value="2w">
*/
var PROCESSED_FLAG = 'data-shrcut-processed';
function extendEstimateFields() {
var targets = $('input#timetracking_originalestimate, input#timetracking_remainingestimate').filter(':not([' + PROCESSED_FLAG + '])');
for (var i = 0; i < targets.length; i++) {
trace('Adding alter estimate button to item #' + (i + 1));
var target = targets[i];
addAlterEstim(target);
}
}
function addAlterEstim(target) {
$(target).attr(PROCESSED_FLAG, true);
var alterEstimBtn = getAlterEstimBtn();
alterEstimBtn.visBinder.addTriggerEl(target);
}
function getAlterEstimBtn() {
if (typeof alterEstimBtn != 'undefined') {
return alterEstimBtn;
}
alterEstimBtn = $('<div class="item-alter-estim" title="Alter estimate(s)"'
+ ' style="z-index: 1000000; position: absolute; display: none; color: red; border: 1px solid red; background-color: white; opacity: 0.75;'
+ ' padding: 2px; height: 20px; font-size: 16px; line-height: 16px; text-align: center; font-style: italic; font-weight: bold; cursor: pointer;">'
+ '<span style="vertical-align: middle">+/-</span></div>')[0];
insertBodyElement(alterEstimBtn);
alterEstimBtn.visBinder = new VisibilityBinder(alterEstimBtn, {
timeout : 2000
});
$(alterEstimBtn).on('click', function() {
$(this).hide();
var dlg = getAlterEstimDlg();
$(dlg).show()
.center();
var input = $(dlg).children('input[type = "text"]')[0];
$(input).focusWithSelect($(input).val().indexOf('-') + 1);
});
return alterEstimBtn;
}
function getAlterEstimDlg() {
if (typeof alterEstimDlg != 'undefined') {
return alterEstimDlg;
}
var dlg = alterEstimDlg = document.createElement('div');
dlg.id = 'alter-estim-dlg';
dlg.style = 'z-index: 1000001; color: red; background-color: white; padding: 1em; border: 1px solid red;';
dlg.style.position = 'absolute';
dlg.style.opacity = 0.90;
dlg.innerHTML = `<input type="text" value="-1d 4h">
<input type="checkbox" id="shrcut-alter-estim-orig" checked><label for="shrcut-alter-estim-orig" title="Alter Original estimate">O</label>
<input type="checkbox" id="shrcut-alter-estim-rem" checked><label for="shrcut-alter-estim-rem" title="Alter Remaining estimate">R</label>
<input type="button" value="OK">
<input type="button" value="Cancel">
`;
insertBodyElement(dlg);
// add behavior
var eInvalidDurationPattern = 'Invalid duration pattern: [{0}]!';
$(dlg).children('input[value = "Cancel"]').click(function() {
$(dlg).hide();
});
$(dlg).children('input[value = "OK"]').click(function() {
alterEstimates();
});
$(dlg).children('input[type = "text"]').keyup(function(e) {
if (e.keyCode == 13 /* Enter */) {
alterEstimates();
}
});
function alterEstimates() {
trace("Altering estimates...");
try {
var delta = normalizeDuration($(dlg).children('input[type = "text"]').val());
var someTarget = false;
var infos = [];
if ($('#shrcut-alter-estim-orig').prop('checked')) {
someTarget = true;
try {
infos.push(applyDurationDelta($('input#timetracking_originalestimate')[0], delta));
} catch (e) {
showError(e);
}
}
if ($('#shrcut-alter-estim-rem').prop('checked')) {
someTarget = true;
try {
infos.push(applyDurationDelta($('input#timetracking_remainingestimate')[0], delta));
} catch (e) {
showError(e);
}
}
if (!someTarget) {
throw 'No target field to alter selected!';
}
$(dlg).hide();
showInfo(infos.join('<br>'));
} catch (e) {
showError(e);
}
}
function applyDurationDelta(targetEl, delta) {
if (!targetEl) {
return false;
}
trace("Altering estimate of [{0}]".format(targetEl.id));
var oldVal = $(targetEl).val();
var newVal = formatDuration(normalizeDuration(oldVal) + delta);
$(targetEl).val(newVal);
return 'Changed estimate from [{0}] to [{1}].'.format(oldVal, newVal);
}
var unitMinutes = {
'w' : 5 * 8 * 60,
'd' : 8 * 60,
'h' : 60,
'm' : 1
};
// '[+-]Xw Xd Xh Xm' --> [+-]X in minutes
function normalizeDuration(fullStr) {
var str = fullStr.trim();
var signStr = str.match(/[+-]/);
var sign = signStr && signStr[0] == '-' ? -1 : 1;
if (signStr) {
str = str.substr(1);
}
var parts = str.split(/\s+/);
var res = 0;
parts.forEach(function(part) {
var match = part.match(/^(\d+)([wdhm])$/);
if (!match) {
throw eInvalidDurationPattern.format(fullStr);
}
var length = match[1];
var unit = match[2];
res += length * unitMinutes[unit];
});
return res * sign;
}
// X in minutes --> 'Xw Xd Xh Xm'
function formatDuration(minutes) {
var res = [];
for (unit in unitMinutes) {
var times = Math.floor(minutes / unitMinutes[unit]);
if (times > 0) {
res.push(times + unit);
minutes %= unitMinutes[unit];
}
}
return res.length > 0 ? res.join(' ') : '0h';
}
return dlg;
}
// @class (reusable)
function VisibilityBinder(targetEl, cfg) {
this.targetEl = targetEl;
var timeout = cfg.timeout;
var timeoutT;
$(targetEl).on('mouseover', function() {
if (timeoutT) {
clearTimeout(timeoutT);
timeoutT = null;
}
});
$(targetEl).on('mouseout', function() {
timeoutT = setTimeout(function() {
$(targetEl).hide();
}, timeout);
});
this.addTriggerEl = function(triggerEl) {
$(triggerEl).on('mouseover', function() {
$(targetEl).show();
// this could be configurable as well:
$(targetEl).position({ my: 'center top', at: 'center bottom', of: triggerEl });
targetEl.triggerEl = triggerEl;
if (timeoutT) {
clearTimeout(timeoutT);
timeoutT = null;
}
});
$(triggerEl).on('mouseout', function() {
timeoutT = setTimeout(function() {
$(targetEl).hide();
}, timeout);
});
}
}
})(jQuery);
|
var router = require('express').Router();
var authMiddleware = require('../auth/middlewares/auth');
router.use(authMiddleware.hasAuth);
router.use('/home', require('./home/routes'));
router.use('/about', require('./about/routes'));
exports.guestwithsession = router; |
/*
LEARN YOU THE NODE.JS FOR MUCH WIN!
─────────────────────────────────────
BABY STEPS
Exercise 2 of 13
Write a program that accepts one or more numbers as command-line arguments and prints the sum of those numbers to the console (stdout).
*/
var sum = 0;
for (var i = 2; i < process.argv.length; i++) {
sum = sum + Number(process.argv[i]);
}
console.log(sum);
|
import React, {useState} from 'react';
const Paginator = ({ totalItemCount, pageSize, currentPage, onChangedPage, portionSize = 10 }) => {
let pagesCount = Math.ceil(totalItemCount / pageSize);
let pages = [];
for (let i = 1; i <= pagesCount; i++) {
pages.push(i);
}
let portionCount = Math.ceil(pagesCount / portionSize);
let [portionNumber, setPortionNumber] = useState(1);
let leftPortionPageNumber = (portionNumber - 1) * portionSize + 1;
let rightPortionPageNumber = portionNumber * portionSize;
return (
<div>
<nav aria-label="page_navigation" className='d-flex justify-content-center p-2'>
<ul className="pagination">
{/*<li className="page-item"><a className="page-link" href="#">Previous</a></li>*/}
{
portionNumber > 1 &&
<li className='page-item' onClick={() => { setPortionNumber(portionNumber - 1) }} >
<span className='page-link'> Previous </span>
</li>
}
{pages
.filter(page => page >= leftPortionPageNumber && page <= rightPortionPageNumber)
.map((page) => {
return <li
key={page}
onClick={(e) => { onChangedPage(page) }}
className={`page-item ${currentPage === page ? 'currentPage' : ''}`}>
<span className={`${currentPage === page ? 'text-white' : ''} page-link`}>{ page }</span>
</li>
})}
{
portionCount > portionNumber &&
<li className='page-item' onClick={() => { setPortionNumber(portionNumber + 1) }} >
<span className='page-link'> Next </span>
</li>
}
{/*<li className="page-item"><a className="page-link" href="#">Next</a></li>*/}
</ul>
</nav>
</div>
)
}
export default Paginator; |
// given an array of number, find the maximum distance of any adjacent element
// P and Q adjacent element is where there is no value in the array between P and Q.
var adjacentDistance = function(A){
var hashTable = {};
var B = [];
A.forEach(function(item, index){
if(hashTable[item] === undefined){
B.push(item);
hashTable[item] = {high:index, low:index};
} else {
hashTable[item].high = Math.max(hashTable[item].high, index);
hashTable[item].low = Math.min(hashTable[item].low, index);
}
});
B.sort(function(a,b){ return a - b });
var distance = -1, left, right;
for(var i = 0; i < B.length - 1; i++){
left = hashTable[B[i]];
right = hashTable[B[i+1]];
distance = Math.max(
distance,
Math.abs(left.high - right.high),
Math.abs(left.low - right.low),
Math.abs(left.low - right.high),
Math.abs(left.high - right.low)
);
}
return distance;
};
console.log(adjacentDistance([0,3,3,7,5,3,11,1]))
console.log(adjacentDistance([1,4,7,3,3,5]))
|
import React, { useState } from "react";
import { StyledSidebar } from "./Sidebar.styled";
import { NavLink, withRouter } from "react-router-dom";
const USER_MENU = [
{
name: "setting",
icon: "fa fa-cog",
sectionPath: "",
},
{
name: "my bookings",
icon: "fas fa-suitcase",
sectionPath: "bookings",
},
{
name: "my reviews",
icon: "fas fa-star",
sectionPath: "reviews",
},
{
name: "billing",
icon: "fas fa-shopping-cart",
sectionPath: "billing",
},
];
function Sidebar(props) {
let [sidebarMobile, setSidebarMobile] = useState(false);
let handleToggleClick = () => setSidebarMobile(!sidebarMobile);
let renderLinks = () => {
return USER_MENU.map((menu) => (
<li className="sidebar-nav-item" key={menu.name}>
<NavLink
onClick={() => setSidebarMobile(false)}
className="nav-link"
to={`${props.match.path}/${menu.sectionPath}`}
>
<i className={menu.icon}></i> <span>{menu.name}</span>
</NavLink>
</li>
));
};
return (
<StyledSidebar sidebarMobile={sidebarMobile}>
<ul className="sidebar-nav">{renderLinks()}</ul>
<span className="toggler" onClick={handleToggleClick}>
+
</span>
</StyledSidebar>
);
}
export default withRouter(Sidebar);
|
// Create a program that draws a chess table like this
//
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
// % % % %
//
for (var i = 0; i < 8; i++){
if ( i%2 === 0) {
console.log('% % % % ')
}
else {
console.log(' % % % %')
}
} |
import React, { useState, createContext, useContext } from 'react';
const ActionContext = createContext();
/**
* Contexte permettant d'avoir accès aux fonctions de gestion des actions
* partout dans le code
*/
export const ActionProvider = ({ children }) => {
const [action, setAction] = useState(null);
const [sleepingAction, setSleepingAction] = useState(null);
return (
<ActionContext.Provider
value={{ action, setAction, sleepingAction, setSleepingAction }}
>
{children}
</ActionContext.Provider>
);
};
export const useAction = () => useContext(ActionContext);
|
const router = require("express").Router();
const M = require("../../models/about");
const crypto=require('crypto'),algorithm='aes-256-ctr',password = 'd6Fkjh2j3hk';
var Model;
router.get("/signin", async (req, res) => {
try {
Model = M.exp(req.query.clgid + "users");
var response = await Model.findOne({
gid: req.query.gid
}, {
attendance: 0,
results: 0,
}).lean();
if (response!=null) {
if (response.gid == req.query.gid)
res.status(200).json(response).end();
else
res.status(404).send("wrong credentials or someone registed already").end();
} else {
res.status(404).send("not_found").end();
console.log("here");
}
} catch (error) {
console.log(error);
res.status(400).send(error).end();
}
});
function encrypt(text){
var cipher = crypto.createCipher(algorithm,password);
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
console.log(crypted.substring(0,8));
return crypted;
}
function decrypt(text) {
var decipher=crypto.createDecipher(algorithm,password);
var decrypt=decipher.update(text,'hex','utf8');
decrypt+=decipher.final('utf8');
return decrypt;
}
router.get("/signup", async (req, res) => {
Model = M.exp(req.query.clgid + "users");
try {
const encstring=encrypt(req.query.uid);
console.log(encstring);
if(encstring.substring(0,7)==req.query.pin){
const user = await Model.findOne({
_id: req.query.uid
}, {
_id: 1,
gid: 1,
email: 1
}).lean();
if (user == null){
res.status(404).send("user data not found").end();
}
else if (user.gid == null&&user.email==null) {
var response = await Model.findOneAndUpdate({
_id: req.query.uid
}, {
$set: {
gid: req.query.gid,
email: req.query.email,
pic: req.query.url
}
}, {
fields:{attendance:0,results:0,fee:0},
new: true,
upsert: true,
useFindAndModify: true
});
res.status(200).send(response).end();
} else {
res.status(404).send("someone registered").end();
}}
else
res.status(404).send("uniq id and pin are wrong").end();
} catch (error) {
res.status(400).send("something went wrong" + error).end();
}
});
router.get("/create", async (req, res) => {
// Model = M.exp(req.query.clg_id + "users");
// try {
// let user = Model({
// _id: "u17cs006",
// busno: "0",
// photourl: "http://loyaltybook.com/wp-content/uploads/2014/11/user.png",
// name: "saikumar",
// address: "Mig 156 aphb colony guntur",
// mobno: "9989139063",
// guardian: "father",
// clsid: "12",
// rollno: 15,
// clgname: "biher",
// });
// const result= await user.save();
const result= encrypt(req.query.text);
const response=decrypt(result);
res.send(result+response).status(200).end();
// } catch (error) {
// res.send("something went wrong").status(404).end();
// }
});
module.exports = router; |
import React, {useEffect, useState, useRef} from 'react';
import {
View,
Text,
Image,
TouchableOpacity,
KeyboardAvoidingView,
Keyboard,
Alert,
Modal,
} from 'react-native';
import {Styles} from '../Style/_TextAreaStyle';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import {Input, Button} from '@ui-kitten/components';
import AsyncStorage from '@react-native-community/async-storage';
import {images, theme} from '../../../constants';
import langjson from '../../../constants/lang.json';
import Icon from 'react-native-vector-icons/EvilIcons';
import {Row, Col} from 'native-base';
import ImagePicker from 'react-native-image-picker';
import {loader} from '../../../constants/images';
import HealthDairyService from '../../../services/HealthDiaryServices';
const {icons} = images;
const options = {
title: 'Select Avatar',
customButtons: [{name: 'fb', title: 'Choose Photo from Facebook'}],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
let keyboardDidShowListener;
let keyboardDidHideListener;
const TextArea = (props) => {
const [button, setButton] = useState(false);
const [loading, setLoading] = useState(false);
const [file, setFile] = useState('');
const [text, setText] = useState('');
const [visible, setVisible] = useState(false);
const input = useRef();
const [visibleModal, setVisibleModal] = useState(false);
const LoadingIndicator = (props) => (
<View style={Styles.indicator}>
<Image source={loader.white} />
{/* <Spinner size="small" /> */}
</View>
);
const renderAddPhoto = () => {
return (
<View>
<TouchableOpacity onPress={() => setVisibleModal(true)}>
<Image
source={file == '' ? icons.AddPhoto : file}
style={Styles.addPhoto}
/>
</TouchableOpacity>
<Modal
style={{margin: 0}}
transparent={true}
visible={visibleModal}
animated={true}
onRequestClose={() => setVisibleModal(false)}>
<View style={{flex: 1, backgroundColor: 'rgba(52, 52, 52, 0.1)'}}>
<View
style={{
position: 'absolute',
top: 170,
height: hp('20%'),
width: wp('90%'),
margin: 20,
backgroundColor: theme.colors.white,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text
style={{
alignSelf: 'center',
position: 'absolute',
top: 0,
marginTop: 10,
fontSize: 20,
}}>
Add Photo
</Text>
<TouchableOpacity
onPress={() => setVisibleModal(false)}
style={{alignSelf: 'flex-end', marginTop: 10}}>
<Icon
name="close"
style={{alignSelf: 'center', color: '#000', fontSize: 32}}
/>
</TouchableOpacity>
<View
style={{
flexDirection: 'row',
marginTop: 20,
alignContent: 'space-between',
justifyContent: 'center',
height: hp('15%'),
}}>
<TouchableOpacity
onPress={openImageLibrary}
style={{
flex: 1,
marginVertical: 25,
marginLeft: wp('15%'),
marginRight: 13,
backgroundColor: '#F8F8FA',
borderRadius: 28,
justifyContent: 'center',
}}>
<Icon
name="image"
style={{alignSelf: 'center', color: '#000', fontSize: 32}}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={openCamera}
style={{
flex: 1,
marginVertical: 25,
marginRight: wp('15%'),
backgroundColor: '#F8F8FA',
borderRadius: 28,
justifyContent: 'center',
}}>
<Icon
name="camera"
style={{alignSelf: 'center', color: '#000', fontSize: 32}}
/>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
</View>
);
};
// const openImageLibrary=()=>{
// ImagePicker.launchImageLibrary(options, (response) => {
// console.log("Selected File: ",response)
// if (response.didCancel) {
// console.log('User cancelled image picker');
// } else if (response.error) {
// console.log('ImagePicker Error: ', response.error);
// } else if (response.customButton) {
// console.log('User tapped custom button: ', response.customButton);
// } else {
// let f = [];
// const source = {
// FileName: response.fileName,
// FileSize: response.fileSize,
// FileType: response.type,
// FileAsBase64: response.data };
// f.push({File: source, uri: response.uri})
// setFile(f)
// console.log("Source: ",source)
// }
// });
// }
const openImageLibrary = () => {
ImagePicker.launchImageLibrary(options, (response) => {
// console.log("Selected File: ",response)
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
let f = [...file];
const source = {
FileName: response.fileName,
FileSize: response.fileSize,
FileType: response.type,
FileAsBase64: response.data,
};
f.push({File: source, uri: response.uri});
setFile(f);
setVisible(false);
setVisibleModal(false);
// console.log("File: ",f)
}
});
};
const openCamera = () => {
ImagePicker.launchCamera(options, (response) => {
// console.log("Selected File: ",response)
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
let f = [...file];
const source = {
FileName: response.fileName,
FileSize: response.fileSize,
FileType: response.type,
FileAsBase64: response.data,
};
f.push({File: source, uri: response.uri});
setFile(f);
setVisible(false);
setVisibleModal(false);
}
});
};
// const openCamera=()=>{
// ImagePicker.launchCamera(options, (response) => {
// console.log("Selected File: ",response)
// if (response.didCancel) {
// console.log('User cancelled image picker');
// } else if (response.error) {
// console.log('ImagePicker Error: ', response.error);
// } else if (response.customButton) {
// console.log('User tapped custom button: ', response.customButton);
// } else {
// let f = [];
// const source = {
// FileName: response.fileName,
// FileSize: response.fileSize,
// FileType: response.type,
// FileAsBase64: response.data };
// f.push({File: source, uri: response.uri})
// setFile(f)
// console.log("Source: ",source)
// }
// });
// }
const pickImage = () => {
Alert.alert('Select Image', 'From:', [
{
text: 'Camera',
onPress: openCamera,
},
{
text: 'Gallery',
onPress: openImageLibrary,
},
]);
};
const useInputState = (initialValue = '') => {
const [value, setValue] = React.useState(initialValue);
return {value, onChangeText: setValue};
};
const [language, setLang, updatelang] = useState(1);
useEffect(() => {
AsyncStorage.getItem('lang').then((lang) => {
if (lang != null) {
setLang(lang);
}
});
setTimeout(() => {
input.current.focus();
}, 1);
}, []);
const multilineInputState = useInputState();
const _keyboardDidShow = () => {
setButton(true);
// alert('Keyboard Shown');
};
const _keyboardDidHide = () => {
setButton(false);
// alert('Keyboard Hidden');
};
const createHealthRecord = () => {
setLoading(true);
let formData = {
HealthDiary: {
Description: text,
Files: file,
// GenderSD:genderData[selectedIndex.row]
},
};
AsyncStorage.getItem('loginData').then((user) => {
user = JSON.parse(user);
let auth = new HealthDairyService();
formData.token = user.accessToken;
formData.HealthDiary.UserId = user.currentUserID;
// console.log("Form Data: ",JSON.stringify(formData))
auth
.create(formData)
.then((res) => res.json())
.then((res) => {
console.log(res);
setLoading(false);
if (res.id == 0) {
alert('Some Backed Error Check\n' + res.returnStatus.returnMessage);
} else {
alert('Record Added Successfully!');
setText('');
setFile('');
}
});
});
};
return (
<View style={Styles.textArea}>
<View style={Styles.mainContainer}>
<Row
style={{flex: 0.5, borderBottomWidth: 0.7, borderColor: '#979797'}}>
<Col style={{flex: 9}}>
<Text style={Styles.text}>
{langjson.lang[language - 1].complaintnote}
</Text>
</Col>
<Col style={{flex: 1, paddingVertical: 15}}>
<Icon onPress={props.onClose} name="close" size={24} />
</Col>
</Row>
<Row style={{flex: 5.5, backgroundColor: 'white'}}>
<Col style={{flex: 3.5}}>
<Input
placeholder="Write..."
ref={input}
autoFocus={true}
multiline={true}
textStyle={{minHeight: 10, color: theme.colors.black}}
{...multilineInputState}
style={Styles.inputBox}
value={text}
onChangeText={(text) => setText(text)}
/>
</Col>
<Col style={{marginHorizontal: 15}}>{renderAddPhoto()}</Col>
</Row>
<Row>
<View style={Styles.buttonContainer}>
<View>
<Button
onPress={props.onClose}
appearance="outline"
status="basic"
style={Styles.buttonForm}
size="large"
block>
Cancel
</Button>
</View>
<View>
<Button
accessoryLeft={() => (loading ? LoadingIndicator() : null)}
onPress={!loading ? createHealthRecord : null}
appearance="outline"
status="primary"
style={Styles.buttonForm}
disabled={text != '' ? false : true}
size="large"
block>
{' '}
SAVE
{/* {!loading ? (update ? 'Update' : 'Create') : ''} */}
</Button>
</View>
</View>
</Row>
{/* <Modal transparent={true} visible={visible} onRequestClose={()=>setVisible(false)} onPress={()=>console.log("modal pressed")}>
<View style={{ flex:0, backgroundColor:'rgba(0,0,0,0.3)'}}>
<View style={{ position:"absolute", bottom:0, height:hp("20%"), width:wp("90%"),margin:20, backgroundColor:theme.colors.white, alignItems:"center", justifyContent: 'center'}}>
<Text style={{alignSelf:"center", position:"absolute" , top:0, marginTop:10, fontSize:20}}>Add Photo</Text>
<TouchableOpacity onPress={()=>setVisible(false)} style={{alignSelf:"flex-end", marginTop:10}} >
<Icon name="close" style={{alignSelf:"center", color: '#000', fontSize: 32}} />
</TouchableOpacity>
<View style={{flexDirection:"row", marginTop:20, alignContent:"space-between", justifyContent:"center", height:hp("15%")}}>
<TouchableOpacity onPress={openImageLibrary} style={{flex:1, marginVertical:25, marginLeft:wp("15%") , marginRight:13, backgroundColor:"#F8F8FA", borderRadius:28, justifyContent:"center"}} >
<Icon name="image" style={{alignSelf:"center", color: '#000', fontSize: 32}} />
</TouchableOpacity>
<TouchableOpacity onPress={openCamera} style={{flex:1, marginVertical:25, marginRight:wp("15%"), backgroundColor:"#F8F8FA", borderRadius:28, justifyContent:"center"}} >
<Icon name="camera" style={{alignSelf:"center", color: '#000', fontSize: 32}} />
</TouchableOpacity>
</View>
</View>
</View>
</Modal> */}
</View>
</View>
);
};
export default TextArea;
|
/*
const floatArray = {
type: "Float64BufferCodec",
encode: function (data) {
return Buffer.from(Float64Array.from(data).buffer)
},
decode: function (data) {
return new Float64Array(data.buffer)
},
buffer: true
}
*/
// see dbPerformanceTest.js
const normalArrayCodec = {
type: "Float64BufferCodec",
encode: function (data) {
return Buffer.from(Float64Array.from(data).buffer)
},
decode: function (data) {
let resultArr = []
let fa = new Float64Array(data.buffer)
for(let i = 0; i < fa.length; i++){
resultArr[i] = fa[i]
}
return resultArr
},
buffer: true
}
const db = require('level')('./db', {
keyEncoding: require("bytewise"),
//valueEncoding: "json",
valueEncoding: normalArrayCodec,
cacheSize: 128 * 1024 * 1024
})
module.exports = db |
// @flow
const express = require("express")
const path = require("path")
const http = require("http")
const { initSocket } = require("./lib/Socket")
const app = express()
const server = http.createServer(app)
const PORT = process.env.PORT || 8000
initSocket(server)
const buildDir = path.join(__dirname, "build")
app.use(express.static(buildDir))
app.get("/*", (req, res) => {
res.sendFile(path.join(buildDir, "index.html"))
})
server.listen(PORT, () => console.log(`Listening on port ${PORT}!`))
|
{
"FullName":"Andrea Du",
"LastName":"Du",
"FirstName":"Andrea",
"EmailAddress":"adu@muuzii.com",
"OfficePhone":"010-65611038",
"MobilePhone":"13438896543"
} |
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
import Buah from '../component/Buah';
import {
Alert,Button
} from 'reactstrap'
class Home extends Component{
render(){
return(
<div>
{/* <Alert color="primary">
Ini Home!
</Alert> */}
<Buah/>
{/* <Button color="warning">
<Link to='/Buah'>
Klik Untuk Belanja
</Link>
</Button> */}
</div>
)
}
}
export default Home |
import styled, { css } from 'styled-components';
export const Container = styled.div``;
export const Article = styled.div`
display: flex;
flex-direction: column;
border: 1px solid var(--gray);
border-radius: 4px;
background: var(--white);
& + div {
margin-top: 24px;
}
header {
padding: 16px;
a {
display: flex;
align-items: center;
}
img {
width: 32px;
height: 32px;
border-radius: 50%;
margin-right: 16px;
}
}
@media (min-width: 900px) {
${(props) =>
props.fullStyle &&
css`
margin-top: 80px;
flex-direction: row;
header {
display: none;
}
`}
}
`;
export const ArticlePhoto = styled.div`
max-width: 765px;
flex: 3;
img {
width: 100%;
height: 100%;
}
`;
export const ArticleInfo = styled.div`
flex: 2;
display: flex;
flex-direction: column;
`;
export const ArticleWidgets = styled.div`
padding: 8px 16px;
display: flex;
flex-direction: column;
strong {
margin-top: 6px;
}
`;
export const ArticleDescription = styled.div`
padding: 8px 16px;
strong {
margin-right: 8px;
}
`;
export const ArticleComments = styled.div`
flex: 1;
`;
export const ArticleAddComment = styled.div``;
|
var Script = function () {
var lineChartData = {
labels : ["5%","10%","50%","90%","95%","99%"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [1,1,2,3,4,5]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [0,0,1,2,3,4]
}
]
};
new Chart(document.getElementById("line").getContext("2d")).Line(lineChartData);
}(); |
import React from 'react';
export function NotFound() {
return (
<React.Fragment>
<div class="noise"></div>
<div class="overlay"></div>
<div class="terminal">
<h1>Error <span class="errorcode">404</span></h1>
<p class="output">The page you are looking for might have been removed, had its name changed or is temporarily unavailable.</p>
<p class="output">Please try to go back or return to the homepage.</p>
<p class="output">Good luck.</p>
</div>
</React.Fragment>
);
}
|
import Component from '@ember/component';
import { computed } from '@ember/object';
import layout from '../templates/components/paper-data-table-pagination';
export default Component.extend({
layout,
tagName: 'md-table-pagination',
classNames: ['md-table-pagination'],
startOffset: computed('page', 'limit', function() {
return Math.max((this.get('page') - 1) * this.get('limit') + 1, 1); // 1-based index
}),
endOffset: computed('startOffset', 'limit', 'total', function() {
let endOffset = this.get('startOffset') + this.get('limit');
let total = this.get('total');
return total ? Math.min(endOffset, total) : endOffset;
})
});
|
import React, {Component} from 'react';
import './carsShop.css'
import CarsShopItem from "../carsShopItem/carsShopItem";
class CarsShop extends Component {
render() {
const {shopItems} = this.props;
return (
<div className='shopWrapperCar'>
{<h2><b>Магазин рабів</b></h2>}
{
<div className='flexCar'>
{
shopItems.map((value, index) => {
return <CarsShopItem car={value} key={index}/>
})
}
</div>
}
</div>
);
}
}
export default CarsShop; |
//Welcome to The trashcan Discord Bot!
//I made this so i could teach my self how discord bots work and How Discord.js Works
//So if the code is terrible Don't Judge me
//and Yes The Code is all in One Document; I dont know how to seprate the code into diffrent documets yet.
//im new to codeing in Javscript!
//*The code start Here*
//This Code is needed So The Bot Works And comes online!, and So Bot Activity is Displayed Propley
require('dotenv').config()
const {Client, RichEmbed, Attachment } = require('discord.js');
const client = new Client();
const PREFEX = 'Trash ';
client.on('ready', message => {
console.log('Logged in to Your Server!')
console.log(`Logged in as ${client.user.tag}`)
console.log('Thanks For using my Bot')
console.log('//IronWolf\\')
client.user.setActivity('à͟h̵̨́́͘h͡h̛͘͠͏͡ḩ̶̴̕a̧̨̕g̸̡g̵̛̀h̸́͘͢g̛h͝g̷h̸̨̛h̸́͘͢a̴̛͡͠h͢҉a̴̡̛h̛͏a̸h̶̶̢à̢̕͝h̸́h̷̶͜͞ą̧̧a̶͘̕͜', { type: 'LISTENING'});
});
//For Rich Embeds!
//The Code Below Is for The Bot To Watch Chat So it's Aware What Been Typed and Respond Acordingly!
client.on('message', message => {
let args = message.content.substring(PREFEX.length).split(" ");
switch (args[0]) {
case 'can':
if(args[1] === 'whos')
if(args[2] === 'Ele?') {
const embed = new RichEmbed()
.addField('a̶͢͡g̴͝ḩ́̀͘͡s̶̡̡͡͝g̷̡͡s̷̷̢̢h͘͟ģ̴͞͠h̶̷̢̛a͢h́͘͠a̡̛͝͏h̴̸̡͘͝f͏͝h̴̛͝͡f̢́a̶͢͡g̴͝ḩ́̀͘͡s̶̡̡͡͝g̷̡͡s̷̷̢̢h͘͟ģ̴͞͠h̶̷̢̛a͢h́͘͠a̡̛͝͏h̴̸̡͘͝s̸͞h̵̸́ģ̶͜s͘͝g̷̸̸̕͟f͏͝h̴̛͝͡f̢́', 'a̶͢͡g̴͝ḩ́̀͘͡s̶̡̡͡͝g̷̡͡s̷̷̢̢h͘͟ģ̴͞͠h̶̷̢̛a͢h́͘͠a̡̛͝͏h̴̸̡͘͝s̸͞h̵̸́ģ̶͜s͘͝g̷̸̸̕͟g̴͝ḩ́̀͘͡s̷̷̢̢h͘͟ģ̴͞͠h̶̷̢̛a͢h́͘͠a̡̛͝͏h̴̸̡͘͝s̸͞h̵̸́ģ̶͜s͘͝g̷̸̸̕͟f͏͝h̴̛͝͡f̢́')
.addField('a̶͢͡g̴͝ḩ́̀͘͡s̶̡̡͡͝g̷̡͡s̷̷̢̢h͘͟ģ̴͞͠h̶̷̢̛a͢h́͘͠a̡̛͝͏h̴̸̡͘͝s̸͞h̵̸́ģ̶͜s͘͝g̷̸̸̕͟s̷̷̢̢h͘͟ģ̴͞͠h̶̷̢̛a͢h́͘͠a̡̛͝͏h̴̸̡͘͝s̸͞h̵̸́ģ̶͜s͘͝g̷̸̸̕͟f͏͝h̴̛͝͡f̢́', 'a̶͢͡g̴͝ḩ́̀͘͡s̶̡̡͡͝g̷̡͡s̷̷̢̢h͘͟ģ̴͞͠h̶̷̢̛a͢h́͘͠a̡̛͝͏h̴̸̡͘͝s̸͞h̵̸́s̶̡̡͡͝g̷̡͡s̷̷̢̢h͘͟ģ̴͞͠ha͢h́͘͠a̡̛͝͏h̴̸̡͘͝s̸͞h̵̸́ģ̶͜s͘͝g̷̸̸̕͟f͏͝h̴̛͝͡f̢́')
.setColor('0xFF0000')
.setThumbnail('https://i.imgur.com/SwIsA5z.png')
message.channel.send(embed)
break;
}
}
})
//This String Needs To Be at The End So it Gets Your Logon Token (Placed In the .ENV File After the 'Bot_Token=', You Can Get a Bot Token By Going to discordapp.com/developers/applications/)
client.login(process.env.Bot_Token) |
import React, { useContext } from 'react'
import ItemCard from '../components/ItemCard'
import ItemsContext from '../context/ItemsContext'
const Index = () => {
const {items, handleAddCart} = useContext(ItemsContext)
return (
<div className="container is-max-desktop">
{
items.map((item,index)=>{
return <ItemCard
name={item.name}
img={item.img}
description={item.description}
amount={item.amount}
price={item.price}
key={item.id}
id={item.id}
index={index}
onCartChange={handleAddCart}/>
})
}
</div>
)
}
export default Index
|
(function() {
'use strict';
var isDrawing, lastPoint;
var container = document.getElementById('js-container'),
canvas = document.getElementById('js-canvas'),
canvasWidth = canvas.width,
canvasHeight = canvas.height,
ctx = canvas.getContext('2d'),
image = new Image(),
brush = new Image();
// base64 Workaround because Same-Origin-Policy
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeIAAAEiCAIAAACqY0ZAAAAAA3NCSVQICAjb4U/gAAAAGXRFWHRTb2Z0d2FyZQBnbm9tZS1zY3JlZW5zaG907wO/PgAAIABJREFUeJzt3XlcVFX/B/DPDDvDMiDjriwa7oq7aSnglmmC7WklLmGbuVRq/VCxKE0twbLSMrHSLM0g9ckVyTItN9x3QcUFcBmWYYf5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NdfDlQeXPx+wvD4z7DlT/t6yv4P8D7r4ap/nPDbsAAAAASUVORK5CYII=';
image.onload = function() {
ctx.drawImage(image, -85, 0);
// Show the form when Image is loaded.
document.querySelectorAll('.form')[0].style.visibility = 'visible';
};
brush.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAAAxCAYAAABNuS5SAAAKFklEQVR42u2aCXCcdRnG997NJtlkk83VJE3apEma9CQlNAR60UqrGSqW4PQSO9iiTkE8BxWtlGMqYCtYrLRQtfVGMoJaGRFliijaViwiWgQpyCEdraI1QLXG52V+n/5nzd3ENnX/M8/sJvvt933/533e81ufL7MyK7NOzuXPUDD0FQCZlVn/+xUUQhkXHny8M2TxGsq48MBjXdAhL9/7YN26dd5nI5aVRrvEc0GFEBNKhbDjwsHh3qP/FJK1EdYIedOFlFAOgREhPlICifZDYoBjTna3LYe4xcI4oSpNcf6RvHjuAJRoVszD0qFBGmgMChipZGFxbqzQkJWVZUSOF7JRX3S4LtLTeyMtkkqljMBkPzHRs2aYY5PcZH/qLY1EIo18byQ6hBytIr3WCAXcV4tQHYvFxg3w3N6+Bh3OQolEoqCoqCinlw16JzTFJSE6PYuZKqvztbC2ex7bzGxhKu+rerjJrEEq+r9ieElJSXFDQ0Mh9zYzOzu7FBUWcO4Q9xbD6HYvhXhGLccVD5ZAPyfMqaioyOrBUgEv8FZXV8caGxtz8vLykhCWTnZIKmsKhUJnEYeKcKk2YYERH41G7UYnck1/WvAPOxsdLJm2+bEY0Ay0RNeqkytXQkoBZM4U5oOaoYSUkBGRtvnesrBZK4e4F6ypqSkuLy+v4KI99ZQxkfc6vZ4jNAl1wkbhG8LrhfNBCdkxmhYacvj/GOce+3K9MHHbDHUmicOufREELRIWch/DljzMsglutr+VIJO5KjGrVfZAnpF8mnCd8G5hrnC60Cl8T/iw8C1hKd9P9eDCMcgo5HwBx8BB/g7xeRPkrBbeJ3xTeAxjvRGVV3NcshfPG1JX4tVDQae47GuVOknCi23xHr5nyrxe2C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hFHa1CVV5w3081cRu/7BYichpEqfafA7/sCzhT7tVkhLZvhTeB8Gv1r6U+ty/gqtWHQCSNTcPOl9NmXM1S4hgRjBjjL1MdUJ8cx3uhe3d3dfh5Meb8qyKWsuJRidwtN/h20XEtxvTwya7tKncU8ACqmXVwLict5fy6TnFhra2uW7xT8dWk2BHptVBOx8GLKjo3g7bhrBQq1sdVsCvEkhLZIac1y/zmUSO0oO8fX/0P2Ub3cwaWpZSITnLnOpDlBWTIfMleJqFb10jXCBJUlMyORSIP14LhqNef6v/05bpZTdHulUyXKsufDNdRxZ4vIhSKwhQFG5vfLfcwZsx2X92Jhje8/P8OI+TK/oO+zeA84WTzkvI/6RuB3y6f68qf11xnyMiuzMms4178AwArmZmkkdGcAAAAASUVORK5CYII=';
canvas.addEventListener('mousedown', handleMouseDown, false);
canvas.addEventListener('touchstart', handleMouseDown, false);
canvas.addEventListener('mousemove', handleMouseMove, false);
canvas.addEventListener('touchmove', handleMouseMove, false);
canvas.addEventListener('mouseup', handleMouseUp, false);
canvas.addEventListener('touchend', handleMouseUp, false);
function distanceBetween(point1, point2) {
return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}
function angleBetween(point1, point2) {
return Math.atan2( point2.x - point1.x, point2.y - point1.y );
}
// Only test every `stride` pixel. `stride`x faster,
// but might lead to inaccuracy
function getFilledInPixels(stride) {
if (!stride || stride < 1) { stride = 1; }
var pixels = ctx.getImageData(0, 0, canvasWidth, canvasHeight),
pdata = pixels.data,
l = pdata.length,
total = (l / stride),
count = 0;
// Iterate over all pixels
for(var i = count = 0; i < l; i += stride) {
if (parseInt(pdata[i]) === 0) {
count++;
}
}
return Math.round((count / total) * 100);
}
function getMouse(e, canvas) {
var offsetX = 0, offsetY = 0, mx, my;
if (canvas.offsetParent !== undefined) {
do {
offsetX += canvas.offsetLeft;
offsetY += canvas.offsetTop;
} while ((canvas = canvas.offsetParent));
}
mx = (e.pageX || e.touches[0].clientX) - offsetX;
my = (e.pageY || e.touches[0].clientY) - offsetY;
return {x: mx, y: my};
}
function handlePercentage(filledInPixels) {
filledInPixels = filledInPixels || 0;
console.log(filledInPixels + '%');
if (filledInPixels > 50) {
canvas.parentNode.removeChild(canvas);
}
}
function handleMouseDown(e) {
isDrawing = true;
lastPoint = getMouse(e, canvas);
}
function handleMouseMove(e) {
if (!isDrawing) { return; }
e.preventDefault();
var currentPoint = getMouse(e, canvas),
dist = distanceBetween(lastPoint, currentPoint),
angle = angleBetween(lastPoint, currentPoint),
x, y;
for (var i = 0; i < dist; i++) {
x = lastPoint.x + (Math.sin(angle) * i) - 25;
y = lastPoint.y + (Math.cos(angle) * i) - 25;
ctx.globalCompositeOperation = 'destination-out';
ctx.drawImage(brush, x, y);
}
lastPoint = currentPoint;
handlePercentage(getFilledInPixels(32));
}
function handleMouseUp(e) {
isDrawing = false;
}
})(); |
function MenuBackground(game,x,y,width, height, key, frame){
//Crea un background para el menu
this.backgroundName = isLandscape ? (isLandscapeLittle ? "bg_littlelandscape" : "bg_landscape") : "bg_portrait";
this.background = game.add.sprite(x,y,this.backgroundName);
this.background.scale.setTo(game.camera.width/this.background.width,game.camera.height/this.background.height);
Phaser.TileSprite.apply(this,arguments);
game.world.add(this);
if(key == 'bg_pattern_color'){
this.blendMode = PIXI.blendModes.MULTIPLY;
}
this.z = 0;
this.background.z = -1;
if(MenuBackground.xPosition == null){
MenuBackground.xPosition = 0;
}
if(MenuBackground.yPosition == null){
MenuBackground.yPosition = 0;
}
this.tilePosition.x = MenuBackground.xPosition;
this.tilePosition.y = MenuBackground.yPosition;
this.scale.setTo(game.camera.width/this.width,game.camera.height/this.height);
}
MenuBackground.prototype = Phaser.TileSprite.prototype;
MenuBackground.prototype.constructor = MenuBackground;
MenuBackground.prototype.updateBackground = function(isColor){
//Hace el movimiento del fondo
MenuBackground.xPosition -= 2.6;
MenuBackground.yPosition -= 0.1*Math.cos(game.time.time*0.001);
this.tilePosition.x = MenuBackground.xPosition;
this.tilePosition.y = MenuBackground.yPosition;
if(MenuBackground.color1 == null){
MenuBackground.oldHue = 0.0;
var c = Phaser.Color.HSVtoRGB(MenuBackground.oldHue+0.0 - Math.floor(MenuBackground.oldHue+0.0),0.55,1.0);
MenuBackground.color1 = Phaser.Color.getColor(c.r,c.g,c.b);
}
if(MenuBackground.color2 == null){
var c = Phaser.Color.HSVtoRGB(MenuBackground.oldHue+0.3 - Math.floor(MenuBackground.oldHue+0.3),0.55,1.0);
if(!this.isRandomColor){
MenuBackground.color2 = 0xffffff;
}
else{
MenuBackground.color2 = Phaser.Color.getColor(c.r,c.g,c.b);
}
}
if(MenuBackground.steps == null){
MenuBackground.steps = 60;
MenuBackground.currentStep = 0;
}
if(MenuBackground.currentStep >= MenuBackground.steps){
MenuBackground.oldHue += 0.3;
MenuBackground.color1 = MenuBackground.color2;
var c = Phaser.Color.HSVtoRGB(MenuBackground.oldHue+0.3 - Math.floor(MenuBackground.oldHue+0.3),0.55,1.0);
if(!this.isRandomColor){
MenuBackground.color2 = 0xffffff;
}
else{
MenuBackground.color2 = Phaser.Color.getColor(c.r,c.g,c.b);
}
MenuBackground.currentStep = 0;
}
MenuBackground.randomColor = Phaser.Color.interpolateColor(MenuBackground.color1,
MenuBackground.color2,MenuBackground.steps,MenuBackground.currentStep);
this.background.tint = MenuBackground.randomColor;
MenuBackground.currentStep ++;
}
MenuBackground.prototype.deleteBackground = function(){
//Destruye ambos sprites de background;
this.background.destroy();
this.destroy();
}
MenuBackground.loadSprites = function(){
//Carga los sprites
game.load.image('bg_landscape', 'assets/sprites/bg_landscape.png');
game.load.image('bg_littlelandscape', 'assets/sprites/bg_littlelandscape.png');
game.load.image('bg_portrait', 'assets/sprites/bg_portrait.png');
game.load.image('bg_pattern_color', 'assets/sprites/bg_pattern_color.png');
game.load.image('bg_pattern_mono', 'assets/sprites/bg_pattern_mono.png');
}
|
import React, {useState, useEffect} from 'react';
import {onSocket} from '../usages/socketUsage';
import Tone from 'tone';
import AnimeBox from './AnimeBox';
let soundStateNum = [];
let soundFiles = [];
let soundPlayer = [];
const importSoundFiles = () => {
let context = require.context(`../sounds/`, true, /\.(mp3)$/);
let count = 0;
let prev = '';
context.keys().forEach((filename)=>{
//console.log(context(filename), count);
if (filename.slice(0,4) !== prev) {
prev = filename.slice(0,4);
soundStateNum.push(count);
}
count ++;
soundFiles.push(context(filename));
});
soundStateNum.push(count);
console.log(soundStateNum);
}
const soundPreload = () => {
console.log('soundPreload', soundStateNum[soundStateNum.length-2]);
//var meter = new Tone.Meter('level');
//var fft = new Tone.Analyser('fft', 64);
//var waveform = new Tone.Analyser('waveform', 32);
//var soundPlayer = [];
soundFiles.forEach((value, ind)=> {
var temp = new Tone.Player({
"url": value,
"fadeOut": ind < soundStateNum[4] ? 5 : 0,
"fadeIn": ind < soundStateNum[4] ? 5 : 0
}).toMaster();
//}).connect(meter).connect(waveform).connect(fft).toMaster();
soundPlayer.push(temp);
});
return soundPlayer;
//return {meter: meter, fft: fft, waveform: waveform, soundPlayer:soundPlayer};
}
importSoundFiles();
soundPreload();
function MusicBoxMin(props) {
//const [soundPlayer] = useState(soundPreload());
const [nowOrder, setNowOrder] = useState(0);
const [refresh, setRefresh] = useState(false);
let processData = (data) => {
//let {sound} = data;
if (data.sound) processSound(data.sound);
}
useState(()=>{
if (props.socket)
onSocket('controlData', processData);
})
let loadFinish = () => {
console.log('load Finished!');
}
//TODO: handle loading?
useEffect(()=>{
Tone.Buffer.on('load', loadFinish);
},[soundPlayer])
useEffect(()=>{
if (props.stop) {
stopAll();
}
},[props.stop])
useEffect(()=>{
if (props.refresh != refresh && props.data && JSON.stringify(props.data) !== '{}' ){
processSound(props.data);
}
setRefresh(props.refresh);
}, [props.refresh])
let processSound = (data) => {
if (props.stop) return;
//console.log(data);
if (data.stop && data.stop !== '*') {
stopAll();
return;
}
let order = -1;
if (data.set && data.set < soundStateNum.length) {
order = Math.floor(Math.random() * (soundStateNum[data.set] - soundStateNum[data.set-1]));
order += soundStateNum[data.set-1];
} else if ('order' in data) {
if (data.orderTo && data.orderTo > data.order) {
order = Math.floor(Math.random() * (data.orderTo - data.order));
order += data.order;
} else order = data.order;
}
if (order >= 0) {
stopNow();
//console.log('o', order);
if ('volume' in data) setVolume(order, data.volume);
if ('delayFix' in data) {
setTimeout(() => {
playSound(order);
}, data.delayFix);
} else if (data.delay > 0) {
setTimeout(() => {
playSound(order);
}, Math.floor(Math.random()*data.delay));
} else playSound(order);
}
else if ('volume' in data) {
if (soundPlayer[nowOrder] && soundPlayer[nowOrder].state !== 'stopped') {
setVolume(nowOrder, data.volume);
}
}
}
let stopNow = () => {
if (soundPlayer[nowOrder] && soundPlayer[nowOrder].loaded && soundPlayer[nowOrder].state !== 'stopped') {
soundPlayer[nowOrder].stop();
}
}
let stopAll = () => {
soundPlayer.forEach((e) => {
if (e !== undefined) {
if (e.loaded && e.state !== 'stopped') e.stop();
}
})
setNowOrder(0);
}
let playSound = (order) => {
//console.log(order);
if (soundPlayer[order] !== undefined) {
if (soundPlayer[order].loaded) {
console.log(order, 'played!');
soundPlayer[order].start();
setNowOrder(order);
} else {
console.log(order+' not loaded!');
}
}
}
let setVolume = (order, volume) =>{
if (soundPlayer[order] && soundPlayer[order].loaded) soundPlayer[order].volume.value = volume;
}
let randomPlay = () => {
let order = Math.floor(Math.random() * (soundStateNum[1] - soundStateNum[0]));
order += soundStateNum[0];
playSound(order);
}
return(<></>);
}
export default MusicBoxMin; |
function demo() {
// setting and start oimophysics
phy.set( { substep:1 });
// add static plane
phy.add({ type:'plane', size:[ 300,1,300 ], visible:false });
// add gears
createGear([1, 3, 0.5], 1.0, 0.3);
createGear([3, 3, 0.5], 1.0, 0.3);
createGear([-0.5, 3, 0], 0.5, 1.6);
createGear([1.5, 3, -0.5], 1.5, 0.3);
createGear([-2, 3, 0], 1.0, 0.3, [ 180, 50 ]);
createGear([-3.5, 3, 0], 0.5, 0.3);
// add random object
let i=20;
while(i--){
phy.add({ type:'box', size:[ 0.4 ], pos:[ rand( -4, 4 ), rand( 8, 10 ), rand( -1, 1 ) ], density: 0.3 });
phy.add({ type:'sphere', size:[ 0.3 ], pos:[ rand( -4, 4 ), rand( 8, 10 ), rand( -1, 1 ) ], density: 0.3 });
}
}4
function createGear(center, radius, thickness, lm) {
lm = lm || null;
let toothInterval = 0.4;
let toothLength = toothInterval / 1.5;
let numTeeth = Math.round( ( Math.PI * 2 ) * radius / toothInterval) + 1;
if (numTeeth % 2 == 0) numTeeth--;
if (numTeeth < 2) numTeeth = 2;
let toothVertices = createGearTooth(toothLength / 2, thickness * 0.5, toothInterval / 3, radius - toothLength / 4 );
let r = 360 / numTeeth;
let shapes = [];
shapes.push( { type:'cylinder', size: [ radius - toothLength / 2, (thickness * 0.48)*2] })
let i = numTeeth;
while(i--){
shapes.push( { type:'convex', v:toothVertices, rot:[0, r * i, 0 ], margin:0, restitution:0 });
}
let g = phy.add({ type:'compound', shapes:shapes, pos:center, density:1, restitution:0, rot:[-90,0,0] });//, canSleep:false
let f = phy.add({ type:'cylinder', size:[ toothInterval / 4, (thickness * 0.52)*2 ], pos:center, density:0, rot:[-90,0,0] });
phy.add({ type:'joint', b1:g.name, b2:f.name, worldAnchor:center, worldAxis:[0,0,1], motor:lm });
}
function createGearTooth( hw, hh, hd, x ) {
var scale = 0.3;
return [
x-hw, -hh, -hd,
x-hw, -hh, hd,
x-hw, hh, -hd,
x-hw, hh, hd,
x+hw, -hh, -hd * scale,
x+hw, -hh, hd * scale,
x+hw, hh, -hd * scale,
x+hw, hh, hd * scale
];
} |
var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var date = d.getDate();
var m = new Date();
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var year = d.getFullYear();
var myDate = days[d.getDay()] + ", " + date + " " + month[m.getMonth()] + " " + year;
document.getElementById("currentdate").innerHTML = myDate;
|
import React, { Fragment } from "react";
import PropTypes from "prop-types";
import dateFormatter from "../../../utils/dateFormat";
const AcceptedPayment = ({ transactions }) => {
let accepted = true;
const displayAccepted = () => {
return transactions.map((transaction) => {
if (transaction.accepted) {
accepted = true;
return (
<Fragment>
<div className="paymentBoxes d-flex justify-content-between mt-4">
<div className="p-3 pt-1">
<h6 className="font-weight-bold text-capitalize">
{transaction.transactionTitle}
</h6>
<p className="text-muted">
{" "}
{dateFormatter(transaction.dateCreated)}
</p>
</div>
<div>
<h6 className="pt-4 pr-4 font-weight-bold">
₦{transaction.amount / 100}
</h6>
</div>
</div>
</Fragment>
);
} else {
return null;
}
});
};
return (
<div>
<div className="container mt-5 acceptedPayments">
<div className="container">
<div className="d-flex justify-content-between p-2">
<h5 className="font-weight-bold">Accepted transaction</h5>
</div>
<div>
<div>
<div>
{accepted ? displayAccepted() : <p>No Accepted Transaction</p>}
</div>
</div>
</div>
</div>
</div>
</div>
);
};
AcceptedPayment.propTypes = {
transactions: PropTypes.array.isRequired,
};
export default AcceptedPayment;
|
import React from "react"
import ReactDOM from "react-dom"
import App from "./app.js"
import Previewer from "./components/previewer.js"
import EditPanel from "./components/edit-panel.js"
import nodeControlMixin from "./mixins/node-control-mixin.js"
var tree = [
{app:App,child:{app:App,props:{text:"child"}}},
{app:App,props:{text:"hello"}}
]
var Main = React.createClass({
mixins:[nodeControlMixin],
getDefaultProps: function() {
return {
tree:[]
};
},
getInitialState: function() {
this.tranversalAndBind(this.props.tree)
return {
tree:this.props.tree,
node:{}
};
},
render: function() {
return (
<div>
<Previewer tree={this.state.tree}></Previewer>
<EditPanel node={this.state.node}></EditPanel>
</div>
);
}
})
ReactDOM.render(<Main tree={tree}></Main>,document.getElementById("app")) |
if (Meteor.isClient) {
Router.map(function () {
this.route('home', {path: '/'});
});
Router.onBeforeAction(function loadingHook (pause) {
if (Session.get('isLoading')) {
this.render('loading');
pause();
}
}, {only: ['home']});
HomeController = RouteController.extend({
action: function () {
this.render();
}
});
}
|
const Category = require('./category');
const Comment = require('./comment');
const Marketplace = require('./marketplace');
const Product = require('./product');
const Publication = require('./publication');
const Role = require('./role');
const Server = require('./server');
const User = require('./user');
module.exports = {
Category,
Comment,
Marketplace,
Product,
Publication,
Role,
Server,
User,
} |
exports.seed = function(knex) {
return knex("roles").insert([
{
name: "admin"
},
{
name: 'employee'
},
{
name: "technician"
}
]);
};
|
const boom = require('boom');
const Team = require('../models/team');
exports.create = async function create(request, response, next) {
try {
const team = new Team(request.body);
const result = await team.save();
response.send(result);
} catch (error) {
next(boom.badData(error));
}
};
exports.get = async function get(_request, response) {
const teams = await Team.find();
response.send(teams);
};
|
// a. O que é `array` e como se declara em `JS`?
uma lista de elemento, declarado por [ ]
// b. Qual o index inicial de um `array`?
0
//c. Como se determinar o tamanho do `array`?
array.length
// d. Indique todas as mensagens impressas no console.
a. false
b. false
c. true
d. false
e. boolean
I. undefined
II. null
III. 11
IV. 3 e 4
V. 19 e 9
VI. 3
VII. 1 |
const mongoose = require('mongoose');
const config = require('./app');
const { db: { connection, host, port, name } } = config;
const connectionString = `${connection}://${host}:${port}/${name}`;
mongoose.Promise = global.Promise;
mongoose.connect(connectionString, { useNewUrlParser: true }, (err) => {
if(!err)
console.log('MongoDB Connection Succeeded');
else
console.log('Error in DB Connection: '.JSON.stringify(err, undefined, 2));
});
module.exports = mongoose; |
var player = ( function () {
'use strict';
var heros = [];
var model, material;
var options = {
age:1,
height:0,
mh:1,
}
var scalarTarget = [];
var baseResult = {};
var skeletonMorphs = {
'dex' : [
[ 1.0, 1.3, 1.0 ],// spine base
[ 1.5, 1.3, 1.0 ],// spine mid
[ 2.0, 1.3, 1.0 ],// spine up
[ 2.0, 1.3, 1.0 ],// clavicle
[ 1.1, 1.0, 1.0 ],// arm
[ 1.1, 1.1, 1.1 ],// hand
[ 1.1, 0.9, 1.1 ],// leg
[ 1.0, 1.0, 0.9 ],// foot
],
'ugg' : [
[ 1.2, 1.2, 1.2 ],// spine base
[ 1.7, 1.3, 1.3 ],// spine mid
[ 1.7, 1.3, 1.3 ],// spine up
[ 2.5, 1.0, 1.0 ],// clavicle
[ 1.4, 1.0, 1.0 ],// arm
[ 1.3, 1.3, 1.3 ],// hand
[ 1.1, 1.1, 1.1 ],// leg
[ 1.3, 1.3, 1.3 ],// foot
[ 1.2, 1.2, 1.2 ],// pelvis
[ 1.0, 0.8, 1.0 ],// neck
],
'herc' : [
[ 1.0, 1.2, 1.0 ], // s0
[ 1.7, 1.2, 1.0 ], // s1
[ 1.7, 1.3, 1.0 ], // s2
[ 2.5, 1.0, 1.0 ], // clavicle
[ 1.1, 1.0, 1.0 ], // arm
[ 1.1, 1.1, 1.1 ], // hand
[ 1.1, 0.9, 1.1 ], // leg
[ 1.0, 1.0, 0.9 ], // foot
],
'marv' : [
[ 1.0, 1.2, 1.0 ], // s0
[ 1.3, 1.2, 1.0 ], // s1
[ 1.2, 1.2, 1.0 ], // s2
[ 2.0, 1.0, 1.0 ], // clavicle
[ 1.1, 1.0, 1.0 ], // arm
[ 1.1, 1.1, 1.1 ], // hand
[ 1.1, 0.9, 1.1 ], // leg
[ 1.0, 1.0, 0.9 ], // foot
],
'fred' : [
[ 1.0, 1.2, 1.0 ], // s0
[ 1.0, 1.2, 1.0 ], // s1
[ 0.8, 1.2, 1.0 ], // s2
[ 0.8, 1.0, 1.0 ], // clavicle
[ 1.0, 1.0, 1.0 ], // arm
[ 1.0, 1.0, 1.0 ], // hand
[ 1.0, 1.0, 1.0 ], // leg
[ 1.0, 1.0, 1.2 ], // foot
],
'jill' : [
[ 1.0, 0.9, 1.0 ], // s0
[ 0.9, 0.9, 1.0 ], // s1
[ 0.8, 0.9, 1.0 ], // s2
[ 0.8, 1.0, 1.0 ], // clavicle
[ 0.9, 1.0, 1.0 ], // arm
[ 0.8, 0.8, 0.8 ], // hand
[ 1.0, 0.9, 1.0 ], // leg
[ 1.0, 1.0, 0.8 ], // foot
],
'tina' : [
[ 1.0, 1.0, 1.0 ], // s0
[ 0.9, 0.9, 1.0 ], // s1
[ 0.8, 0.9, 1.0 ], // s2
[ 0.8, 1.0, 1.0 ], // clavicle
[ 0.9, 1.0, 1.0 ], // arm
[ 0.8, 0.8, 0.8 ], // hand
[ 1.0, 0.9, 1.0 ], // leg
[ 1.0, 1.0, 1.0 ], // foot
],
'stella' : [
[ 1.0, 0.9, 1.0 ], // s0
[ 1.1, 0.9, 1.0 ], // s1
[ 1.1, 0.9, 1.0 ], // s2
[ 1.5, 1.0, 1.0 ], // clavicle
[ 0.8, 1.0, 1.0 ], // arm
[ 0.8, 0.8, 0.8 ], // hand
[ 1.0, 0.9, 1.0 ], // leg
[ 1.0, 1.0, 1.0 ] ,// foot
],
};
player = {
getHeros : function( id ){
return heros[ id ];
},
add: function ( o ) {
var hero = new player.hero( o );
heros.push( hero );
return hero;
},
init: function( Model, map ){
var tx = new THREE.Texture( map );
tx.anisotropy = 4;
tx.flipY = false;
tx.needsUpdate = true;
material = new THREE.MeshStandardMaterial({ map:tx, color:0xFFFFFF, skinning:true, morphTargets:true, metalness:0.5, roughness:0.8, envMap : view.getEnv() });
model = Model;
var bones = model.skeleton.bones;
var i = 11;
while(i--) scalarTarget[i] = [];
var i = bones.length, name;
while(i--){
name = bones[i].name.substring(2, 8);
bones[i].scalling = new THREE.Vector3(1,1,1);
switch( name ){
case 'spineb' : scalarTarget[0].push(i); break;
case 'spinem' : scalarTarget[1].push(i); break;
case 'spinec' : scalarTarget[2].push(i); break;
case 'clavic' : scalarTarget[3].push(i); break;
case 'elbow' : case 'uparm' : scalarTarget[4].push(i); break;
case 'hand' : case 'finger' : scalarTarget[5].push(i); break;
case 'thigh' : case 'knee' : scalarTarget[6].push(i); break;
case 'foot' : case 'toe' : scalarTarget[7].push(i); break;
case 'pelvis' : scalarTarget[8].push(i); break;
case 'neck' : scalarTarget[9].push(i); break;
case 'head' : scalarTarget[10].push(i); break;
}
}
},
setPosition: function( x, y, z ){
//hero.position.set( x, y, z );
},
applyMorph: function ( hero ) {
for(var t in hero.morphs){
if( hero.morphs[t] ){
hero.skin.setWeight( t, hero.morphs[t] );
}
}
this.skeletonScalling( hero );
},
skeletonScalling: function ( hero ) {
var i, j, v, t, p, lng = scalarTarget.length, result = [], bone = hero.bones;
i = lng;
while(i--) result.push( [ 1.0, 1.0, 1.0 ] );
for( t in hero.morphs ){
i = lng;
while(i--){
v = skeletonMorphs[t][i] || [ 1.0, 1.0, 1.0 ];
p = hero.morphs[t];
result[i][0] += (v[0] - 1) * p;
result[i][1] += (v[1] - 1) * p;
result[i][2] += (v[2] - 1) * p;
//if(i===6) leg += (v[1] - 1) * p;
}
}
i = lng-1; // not head
while(i--){
result[i][0] *= hero.age;
result[i][1] *= hero.age;
result[i][2] *= hero.age;
}
hero.skin.position.y = hero.height * (result[6][1] + (1-hero.age)*0.11);
i = lng;
while(i--){
j = scalarTarget[i].length;
while(j--){
bone[ scalarTarget[i][j] ].scalling.fromArray( result[i] );
}
}
},
update: function () {
}
};
//-----------------------
// NEW HERO
//-----------------------
player.hero = function( o ){
o = o || {};
o.pos = o.pos === undefined ? [ 0, 0, 0 ] : o.pos;
o.size = o.size === undefined ? 0.01 : o.size;
this.skin = model.clone();
this.skin.position.copy( model.position ).multiplyScalar( o.size );
this.skin.scale.multiplyScalar( o.size );
this.skin.material = material;
this.skin.castShadow = true;
this.skin.receiveShadow = true;
this.skin.rotation.y = Math.PI;
this.bones = this.skin.skeleton.bones;
var i = this.bones.length;
while(i--) this.bones[i].scalling = new THREE.Vector3( 1, 1, 1 );
this.mesh = new THREE.Group();
this.mesh.add( this.skin );
view.add( this.mesh );
this.mesh.position.fromArray( o.pos );
this.age = 1;
this.height = this.skin.position.y;
this.morphs = { 'dex': 0, 'ugg' : 0, 'herc': 0, 'marv': 0, 'fred': 0, 'jill': 0, 'tina': 0, 'stella': 0 };
if(o.t) this.morphs.tina = 1;
else this.morphs.marv = 1;
if(o.t) this.skin.play('walk');
else this.skin.play('run');
this.applyMorph();
};
player.hero.prototype = {
applyMorph: function(){
player.applyMorph( this );
},
rotate: function( r ){
this.skin.rotation.y = r;
}
};
return player;
})();
//-----------------------
// SEA3D hack
//-----------------------
THREE.SEA3D.SkinnedMesh.prototype.setWeight = function( name, val ) {
this.morphTargetInfluences[ this.morphTargetDictionary[ name ] ] = val;
};
THREE.SEA3D.SkinnedMesh.prototype.clone = function(){
var c = new THREE.SEA3D.SkinnedMesh( this.geometry, this.material, this.useVertexTexture )
//if ( this.animator ) c.animator = this.animator.clone( this );
return c;
};
//-----------------------
// force local scalling
//-----------------------
THREE.Skeleton.prototype.update = ( function () {
var offsetMatrix = new THREE.Matrix4();
var scaleMatrix = new THREE.Matrix4();
var pos = new THREE.Vector3();
return function update() {
// flatten bone matrices to array
for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
// compute the offset between the current and the original transform
var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld: this.identityMatrix;
// extra scalling vector
if( this.bones[ b ].scalling && !this.isClone ){
matrix.scale( this.bones[ b ].scalling );
// update position of children
for ( var i = 0, l = this.bones[ b ].children.length; i < l; i ++ ) {
scaleMatrix = matrix.clone();
scaleMatrix.multiply(this.bones[ b ].children[ i ].matrix.clone() );
pos.setFromMatrixPosition( scaleMatrix );
this.bones[ b ].children[ i ].matrixWorld.setPosition(pos);
}
}
offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
// only for three dev
offsetMatrix.toArray( this.boneMatrices, b * 16 );
}
if ( this.useVertexTexture ) {
this.boneTexture.needsUpdate = true;
}
};
} )(); |
/* -------------------------------------------------- *
* *
* TEMPLE INFORMATION *
* *
* ---------------------------------------------------*/
/* function getTempleInformation() {*/
var templeJSON = 'scripts/JSON/temples.JSON';
var templeRequest = new XMLHttpRequest();
templeRequest.open('Get', templeJSON, true);
templeRequest.responseType = 'json';
templeRequest.send();
templeRequest.onload = function() {
var templeFile = templeRequest.response;
//TEMP:
console.log(templeFile);
/*
document.getElementById('templeName').innerHTML = templeFile[0].name;
document.getElementById('templeAddress').innerHTML = templeFile[0].address + " " + templeFile[0].city + " , " + templeFile[0].state + " " + templeFile[0].zipCode;
*/
populateTempleWrite(templeFile); } /* Calls the function that will write all content into the temple page */
function populateTempleWrite(templeFile) {
var section = document.querySelector('section');
for (var i = 0; i < templeFile.length; i++) {
var myTempleImage1 = document.createElement('img');
var myTempleImage2 = document.createElement('img');
var myTempleImage3 = document.createElement('img');
var myTempleImage4 = document.createElement('img');
if ( i === 0) {
var templeName1 = templeFile[0].name;
var templeAddress1 = templeFile[0].address;
var templeAddress1a = templeFile[0].city + " , " + templeFile[0].state + " " + templeFile[0].zipCode;
var templePhone1 = templeFile[0].telephone;
var templeZip1 = templeFile[0].zipCode;
var templeServices1 = templeFile[0].services;
var templeClosure1 = templeFile[0].closure;
var templeSchedule1 = templeFile[0].sessionSchedule;
if (templeName1 === 'Anchorage Alaska Temple') {
myTempleImage1.setAttribute("src", "../images/Temple_AnchorageAK_200.jpg"),("alt", "image of the Anchorage Alaska temple ");}
else if(templeName1 === 'Boise Idaho Temple') {
myTempleImage1.setAttribute("src", "../images/Temple_BoiseID_200.jpg"),("alt", "image of the Boise Idaho temple ");}
else if(templeName1 === 'Idaho Falls Idaho Temple') {
myTempleImage1.setAttribute("src", "../images/Temple_IdahoFallsID_200.jpg"),("alt", "image of the Idaho Falls ID temple ");}
else {
myTempleImage1.setAttribute("src", "../images/Temple_LaieHI_200.jpg"),("alt", "image of the Laie Hawaii temple ");}
}
else if ( i === 1) {
var templeName2 = templeFile[1].name;
var templeAddress2 = templeFile[1].address;
var templeAddress2a = templeFile[1].city + " , " + templeFile[1].state + " " + templeFile[1].zipCode;
var templePhone2 = templeFile[1].telephone;
var templeZip2 = templeFile[1].zipCode;
var templeServices2 = templeFile[1].services;
var templeClosure2 = templeFile[1].closure;
var templeSchedule2 = templeFile[1].sessionSchedule;
if (templeName2 === 'Anchorage Alaska Temple') {
myTempleImage2.setAttribute("src", "../images/Temple_AnchorageAK_200.jpg"),("alt", "image of the Anchorage Alaska temple ");}
else if(templeName2 === 'Boise Idaho Temple') {
myTempleImage2.setAttribute("src", "../images/Temple_BoiseID_200.jpg"),("alt", "image of the Boise Idaho temple ");}
else if(templeName2 === 'Idaho Falls Idaho Temple') {
myTempleImage2.setAttribute("src", "../images/Temple_IdahoFallsID_200.jpg"),("alt", "image of the Idaho Falls ID temple ");}
else {
myTempleImage2.setAttribute("src", "../images/Temple_LaieHI_200.jpg"),("alt", "image of the Laie Hawaii temple ");}
}
else if ( i === 2) {
var templeName3 = templeFile[2].name;
var templeAddress3 = templeFile[2].address;
var templeAddress3a = templeFile[2].city + " , " + templeFile[2].state + " " + templeFile[2].zipCode;
var templePhone3 = templeFile[2].telephone;
var templeZip3 = templeFile[2].zipCode;
var templeServices3 = templeFile[2].services;
var templeClosure3 = templeFile[2].closure;
var templeSchedule3 = templeFile[2].sessionSchedule;
if (templeName3 === 'Anchorage Alaska Temple') {
myTempleImage3.setAttribute("src", "../images/Temple_AnchorageAK_200.jpg"),myTempleImage3.setAttribute("alt", "image of the Anchorage Alaska temple ");}
else if(templeName3 === 'Boise Idaho Temple') {
myTempleImage3.setAttribute("src", "../images/Temple_BoiseID_200.jpg"),myTempleImage3.setAttribute("alt", "image of the Boise Idaho temple ");}
else if(templeName3 === 'Idaho Falls Idaho Temple') {
myTempleImage3.setAttribute("src", "../images/Temple_IdahoFallsID_200.jpg"),myTempleImage3.setAttribute("alt", "image of the Idaho Falls ID temple ");}
else {
myTempleImage3.setAttribute("src", "../images/Temple_LaieHI_200.jpg"),myTempleImage3.setAttribute("alt", "image of the Laie Hawaii temple ");}
}
else {
var templeName4 = templeFile[3].name;
var templeAddress4 = templeFile[3].address;
var templeAddress4a = templeFile[3].city + " , " + templeFile[3].state + " " + templeFile[3].zipCode;
var templePhone4 = templeFile[3].telephone;
var templeZip4 = templeFile[3].zipCode;
var templeServices4 = templeFile[3].services;
var templeClosure4 = templeFile[3].closure;
var templeSchedule4 = templeFile[3].sessionSchedule;
if (templeName4 === 'Anchorage Alaska Temple') {
myTempleImage3.setAttribute("src", "../images/Temple_AnchorageAK_200.jpg"),("alt", "image of the Anchorage Alaska temple ");}
else if(templeName4 === 'Boise Idaho Temple') {
myTempleImage4.setAttribute("src", "../images/Temple_BoiseID_200.jpg"),("alt", "image of the Boise Idaho temple ");}
else if(templeName4 === 'Idaho Falls Idaho Temple') {
myTempleImage4.setAttribute("src", "../images/Temple_IdahoFallsID_200.jpg"),("alt", "image of the Idaho Falls ID temple ");}
else {
myTempleImage4.setAttribute("src", "../images/Temple_LaieHI_200.jpg"),("alt", "image of the Laie Hawaii temple ");}
}
document.getElementById('templeName1').innerHTML = templeName1;
document.getElementById('templeAddress1').innerHTML = templeAddress1;
document.getElementById('templeAddress1a').innerHTML = templeAddress1a;
document.getElementById('templeTelephone1').innerHTML = templePhone1;
document.getElementById('templeEmail1').innerHTML = templeEmail1;
document.getElementById('templeServices1').innerHTML = templeServices1;
console.log(templeName1);
/* populategetWeather(cityZipCode); */
}
}
/* ---------------------------------------------------------------------------------------- *
* *
* CURRENT WEATHER SUMMARY INFORMATION *
* *
* -----------------------------------------------------------------------------------------*/
function getWeather(cityZipCode) {
var currentURLweather = 'https://api.openweathermap.org/data/2.5/weather?zip=' + cityZipCode + ',us&appid=c7d023f4cea5310b318c2e583321df8a&units=imperial';
var weatherRequest = new XMLHttpRequest();
weatherRequest.open('Get', currentURLweather, true);
weatherRequest.responseType = 'json';
weatherRequest.send();
weatherRequest.onload = function() {
var weatherData = weatherRequest.response;
/* ---- Key: Values ----
base: "stations"
clouds: {all: #}
coord: {lon: #, lat: # }
dt: #
id: #
main: {temp: #, pressure: #, humidity: #, temp_min: #, temp_max: #}
name: "cityName"
sys: {type: #, id: #, message: #, country: "text", sunrise: #, }
visibility: #
weather: {id:#, main: "text", description: "text", icon: "##a"}
wind: {speed: #, deg: #}
------------------------------ */
/* Will input the informaiton onto Preston.html Site Page */
document.getElementById('low').innerHTML = (weatherData.main.temp_min).toFixed(0) + "° F";
document.getElementById('temperature').innerHTML = (weatherData.main.temp).toFixed(0) + "° F";
document.getElementById('high').innerHTML = (weatherData.main.temp_max).toFixed(0) + "° F";
document.getElementById('humidity').innerHTML = weatherData.main.humidity + " %";
document.getElementById('windSpeed').innerHTML = (weatherData.wind.speed).toFixed(0) + " mph";
/*Create windChill information in weatherSiteAPI.js */
var wChill = 35.74 + 0.6215 * (weatherData.main.temp) - 35.75 * Math.pow((weatherData.wind.speed),.16)
+ 0.4275 * (weatherData.main.temp) * Math.pow((weatherData.wind.speed),.16)
document.getElementById('windChill').innerHTML = wChill.toFixed(0) + '° F';
get5DayForecast(cityid); /* Calls the next function - get5DayForecast(cityid) --> */
}
}
|
require("dotenv").config();
const express = require("express");
const app = express();
module.exports = app;
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const async = require("async");
const port = process.env.PORT || 3002;
const results = [];
const csv = require("csv-parser");
const fs = require("fs");
const Multer = require("multer");
const uploads = Multer({ dest: "uploads/" });
const NewsModel = require("./model/News").newsModel;
const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());
require("./config/passport")(passport);
mongoose.connect(process.env.db_url, { useNewUrlParser: true }, function(err) {
if (err) console.log("Error While connecting to DB:", err);
else console.log("DB Connected Successfully");
});
app.use(cors());
global.mongoose = mongoose;
global.async = async;
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.send("NodeJS");
});
const user = require("./routes/user");
app.use("/user", user);
const news = require("./routes/news");
app.use("/news", news);
const report = require("./routes/report");
app.use("/report", report);
const rating = require("./routes/ratings");
app.use("/rating", rating);
const type = uploads.single("image");
app.post("/image", type, (req, res) => {
var tmp_path = req.file.path;
var target_path = "uploads/" + req.file.originalname;
NewsModel.findOneAndUpdate(
{ id: "11" },
{ image: target_path },
(err, result) => {
if (err) {
return res.send(err);
}
res.send("Success");
}
);
});
app.get("/postnews", async (req, res, next) => {
try {
fs.createReadStream("./config/satire_politics_v1.csv")
.pipe(csv())
.on("data", data => results.push(data))
.on("end", () => {
for (i = 0; i < results.length; i++) {
{
NewsModel.insertMany(results[i], { ordered: false }, function(
error,
docs
) {});
}
}
});
} catch (err) {
next(err);
}
});
app.get("/delete", (req, res) => {
let pattern = /fake-[a-z]/;
NewsModel.deleteMany({ group: pattern }, (err, result) => {
if (err) {
res.send(err);
}
res.send("success");
});
});
app.get("/datajson", (req, res) => {
let pattern = /fake-[a-z]/;
async.waterfall(
[
function(waterfallCb1) {
NewsModel.find({ group: "satire" }).exec((err, result) => {
if (err) {
return waterfallCb1(err);
}
waterfallCb1(null, result);
});
},
function(Ids, waterfallCb) {
async.eachLimit(
Ids,
100,
function(singleSource, eachCallback) {
async.waterfall(
[
function(innerWaterfallCb) {
NewsModel.find(
{
$or: [{ source: singleSource }, { group: "satire" }]
},
(err, results) => {
if (err) {
return innerWaterfallCb("Error in saving to the DB");
}
innerWaterfallCb(null, results);
}
).select("-_id");
}
],
function(err, resultsid) {
if (err) {
return eachCallback(err);
}
eachCallback(resultsid, null);
}
);
},
function(resultsid, err) {
if (err) {
return waterfallCb(err);
}
waterfallCb(null, resultsid);
}
);
}
],
function(err, Ids) {
if (err) {
return res.json({ message: err });
}
const resultArrayfinal = [];
const map = new Map();
for (const item of Ids) {
if (!map.has(item.source)) {
map.set(item.source, true); // set any value to Map
resultArrayfinal.push({
lang: item.lang,
title: item.title,
publishedDate: item.publishedDate,
url: item.url,
source: item.source,
category: item.category,
content: item.content,
collection: item.group
});
}
}
let xyz = resultArrayfinal.slice(0, 25);
let data = JSON.stringify(xyz);
fs.writeFileSync("satire_politics", data);
res.json({ message: "success" });
}
);
});
app.listen(port, () => {
console.log("server running on port number 3002");
});
|
import React, { useEffect, useState } from 'react';
import './ColorConverter.css';
const DEFAULT_ERROR_TEXT = 'Ошибка!';
const DEFAULT_HEX_COLOR = '#34495e';
const MAX_LENGTH_HEX_COLOR = 7;
const isHex = color => {
return /^#[0-9A-F]{6}$/i.test(color);
};
const hexToRgb = hex => {
const replacedHex = hex.replace('#','');
const r = parseInt(replacedHex.substring(0, 2), 16);
const g = parseInt(replacedHex.substring(2, 4), 16);
const b = parseInt(replacedHex.substring(4, 6), 16);
return `rgb(${r}, ${g}, ${b})`;
};
const convertHexToRgb = hex => {
return isHex(hex) ? hexToRgb(hex) : '';
};
const getHexError = hex => {
return isHex(hex) ? '' : DEFAULT_ERROR_TEXT;
};
function ColorConverter() {
const [error, setError] = useState(getHexError(DEFAULT_HEX_COLOR));
const [inputColor, setInputColor] = useState(DEFAULT_HEX_COLOR);
const [rgbColor, setRgbColor] = useState(convertHexToRgb(DEFAULT_HEX_COLOR));
const handleChange = event => {
const value = event.target.value;
setInputColor(value);
if (value.length !== MAX_LENGTH_HEX_COLOR) {
return;
}
setError(getHexError(value));
if (isHex(value)) {
setRgbColor(convertHexToRgb(value));
}
};
useEffect(
() => {
document.body.style.backgroundColor = rgbColor;
},
[rgbColor]
);
return (
<div className="ColorConverter">
<input
className="ColorConverter-input"
maxLength={MAX_LENGTH_HEX_COLOR}
type="text"
value={inputColor}
onChange={handleChange}
/>
<div className="ColorConverter-output">
{error || rgbColor}
</div>
</div>
);
}
export default ColorConverter;
|
import { action, observable, computed, toJS, ObservableMap } from 'mobx';
import fb from '../service/firebase';
import stores from './';
export class Chat {
constructor(chat) {
this.msg = chat.msg;
this.id = fb.convo.push().key;
this.user = stores.userStore.profile.userNick
this.contacts = [];
//some type of group mech
this.group = 'winners'
}
}
export class ChatStore {
@observable chatMessages = observable.map();
@observable isLoading = false;
@observable filter = '';
constructor() {
fb.convo.on('value', action('Push from fb to chatMessage', (snapshot) => {
if (snapshot.val() != null) {
this.chatMessages = new Map(this.obj2Matrix(snapshot.val()));
}
}));
this.addChatMsg = this.addChatMsg.bind(this);
}
*obj2Matrix(obj) {
this.chatMessages = new Map()
for (let key in obj)
yield [key, obj[key]];
}
@computed get filteredChatMessages() {
var matchFilter = new RegExp(this.filter, "i");
return this.chatMessages.entries().filter(chat => {
return chat.group == this.filter || matchFilter.test(chat.group)
});
}
addChatMsg(chat) {
const id = fb.convo.push().key
const msg = new Chat({ msg: chat.msg })
this.updateChatMsg(id, msg);
}
updateChatMsg(id, msg) {
fb.convo.update({ [id]: { msg } });
}
delChatMsg(id) {
fb.convo.child(id).remove();
}
}
const chatStore = window.chatStore = new ChatStore();
export default chatStore;
|
const dbconnection = require('./connection');
const {readFileSync} = require('fs');
const {join} = require('path');
const sql = readFileSync(join(__dirname,'build.sql')).toString();
dbconnection
.query(sql)
.then(console.log('done')); |
function SpriteSheet(jsonFile, imageFile, name) {
var frames = [];
var asset = bingyjson;
function Frame(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
this.getNumFrames = function() {
return frames.length;
}
for (var i in asset.frames)
{
var x = asset.frames[i].frame.x;
var y = asset.frames[i].frame.y;
var w = asset.frames[i].frame.w;
var h = asset.frames[i].frame.h;
frames.push(new Frame(x, y, w, h));
}
var eventName = name + "__mygame__SpriteSheet loaded";
this.getEventName = function() {
return eventName;
}
var image = new Image();
image.onload = function() {
console.log("Image loaded in spritesheet");
var event = new Event(eventName);
document.dispatchEvent(event);
}
image.src = imageFile;
this.drawFrame = function(context, frameIndex, dx, dy, dw, dh )
{
if (frameIndex >= frames.length)
return;
dw = dw || frames[frameIndex].w;
dh = dh || frames[frameIndex].h;
var frame = frames[frameIndex];
context.drawImage(image,
frame.x, frame.y, frame.w, frame.h,
dx, dy, dw, dh);
console.log("drewhb");
}
}
|
import { DANG_NHAP, DANG_KY, URL_DANG_NHAP, URL_DANG_KY } from "../asset/MyConst";
import moment from 'moment';
function DangNhap(email, password) {
return fetch(URL_DANG_NHAP, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password
})
}).then(response => response.json())
.then(responseJson => responseJson)
}
function DangKy(data) {
return fetch(URL_DANG_KY, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: data.email,
password: data.password,
name: data.name,
ngayTao: moment().format('YYYYMMDD'),
}),
}).then(response => response.json())
.then(responseJson => {
return responseJson;
})
}
export default function taiKhoan(type, data) {
switch (type) {
case DANG_NHAP:
{
console.log(DangNhap(data.email, data.password));
return DangNhap(data.email, data.password)
}
case DANG_KY:
return DangKy(data)
}
} |
//var obj = {
// 0: '1',
// 2: 'false'
//}
//
//var student = {
// age: 18,
// name: 'Vasaya',
// second_name: 'Jorik'
//}
//
////console.log(student.age);
////console.log(student.name);
//////var key = 'second_name' ;
////
//////console.log(student [key]);
////
////if ('second_name' in student) {
//// console.log(student ['second_name']);
////} else {
//// console.log('no key')
////}
////
////
////for (var key in student) {
//// console.log('key', key);
//// console.log('student[key]', student[key]);
//// console.log('_____________');
////}
//
//
//var keylist = Object.keys(student);
//console.log(keylist);
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import Store from './../src/store/store'
import Layout from './../src/base/client/layout/index.jsx'
import { Home, About } from './../src/base/client/routes.js'
import { CurationLayout, Auth, SiteInfo, SignInView, SignUpView } from './../src/curation/client/routes.js'
import { PostsOverview, Post } from './../src/posts/client/routes.js'
import { WorkOverview, Work } from './../src/work/client/routes.js'
if (process.env.NODE_ENV === 'development') {
// React A11y only in development
const a11y = require('react-a11y')
a11y(React)
}
const history = syncHistoryWithStore(browserHistory, Store)
const element = document.createElement('div')
element.id = 'app'
document.body.appendChild(element)
ReactDOM.render(
<Provider store={Store}>
<Router history={history}>
<Route path='/' component={Layout}>
<IndexRoute component={Home} />
<Route path='about' component={About} />
<Route path='posts' component={PostsOverview} />
<Route path='posts/:id' component={Post} />
<Route path='work' component={WorkOverview} />
<Route path='work/:id' component={Work} />
</Route>
<Route path='/curation' component={CurationLayout}>
<Route path='login' name='CurationLogin' component={SignInView} />
<Route path='sign-up' name='CurationSignUp' component={SignUpView} />
<Route component={Auth}>
<Route path='/site-info' component={SiteInfo} />
<Route path='/settings' component={SiteInfo} />
<Route path='/work' component={SiteInfo} />
<Route path='/writings' component={SiteInfo} />
</Route>
</Route>
</Router>
</Provider>,
document.getElementById('app')
)
|
function solve(steps, footprintLengthInMeters, speedInKilometersPerHour) {
let totalLengthInMeters = steps * footprintLengthInMeters;
let speedInMetersPerSecond = speedInKilometersPerHour / 3.6;
let timeInSeconds = totalLengthInMeters / speedInMetersPerSecond + Math.trunc(totalLengthInMeters / 500) * 60;
let seconds = Math.round(timeInSeconds % 60);
let minutes = Math.round((timeInSeconds - seconds) / 60);
let hours = Math.round((timeInSeconds - seconds - minutes * 60) / 3600);
let outputSeconds = String(seconds);
let outputMinutes = String(minutes);
let outputHours = String(hours);
if (outputSeconds.length == 1) {
outputSeconds = "0" + outputSeconds;
}
if (outputMinutes.length == 1) {
outputMinutes = "0" + outputMinutes;
}
if (outputHours.length == 1) {
outputHours = "0" + outputHours;
}
console.log(`${outputHours}:${outputMinutes}:${outputSeconds}`);
} |
const svg = d3.select('#svg');
const c = svg.append('circle')
.attr('cx', 200)
.attr('cy', 200)
.attr('r', 90)
.style('fill', 'green');
c.transition()
.duration(1000)
.delay(1000)
.attr('cx', 500);
c.on('click', function() {
d3.select(this).transition()
.duration(3000)
.style('fill', 'red');
}); |
const path = require("path");
const http = require("http");
const express = require("express");
const socketio = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
const cors = require("cors");
const morgan = require("morgan");
const { Kafka, CompressionTypes, CompressionCodecs } = require("kafkajs");
const SnappyCodec = require("kafkajs-snappy");
CompressionCodecs[CompressionTypes.Snappy] = SnappyCodec;
// instantiate the KafkaJS client by pointing it towards at least one broker
const kafka = new Kafka({
clientId: "my-app",
brokers: ["localhost:9092", "localhost:9092"],
});
app.use(cors());
app.use(morgan("combined"));
// serve main html to the client
// The server root will send our index.html
app.get("/", function (req, res) {
console.log(__dirname);
res.sendFile(path.join(__dirname, "../client/index.html"));
});
app.use("/dist", express.static(path.join(__dirname, "../dist")));
io.on("connection", (socket) => {
socket.emit(
"anything",
"Websockets full duplex protocol established. Begin streaming data from Kafka cluster..."
);
// 404 consumer
const consumer_404 = kafka.consumer({
groupId: "group404",
fromBeginning: true,
});
consumer_404.connect();
consumer_404.subscribe({ topic: "404_ERRORS_PER_MIN" });
consumer_404.run({
eachMessage: async ({ topic, partition, message }) => {
socket.broadcast.emit("404_ERRORS_PER_MIN", message.value.toString());
},
});
// 405 consumer
const consumer_405 = kafka.consumer({
groupId: "group405",
fromBeginning: true,
});
consumer_405.connect();
consumer_405.subscribe({ topic: "405_ERRORS_PER_MIN" });
consumer_405.run({
eachMessage: async ({ topic, partition, message }) => {
socket.broadcast.emit("405_ERRORS_PER_MIN", message.value.toString());
},
});
// 406 consumer
const consumer_406 = kafka.consumer({
groupId: "group406",
fromBeginning: true,
});
consumer_406.connect();
consumer_406.subscribe({ topic: "406_ERRORS_PER_MIN" });
consumer_406.run({
eachMessage: async ({ topic, partition, message }) => {
socket.broadcast.emit("406_ERRORS_PER_MIN", message.value.toString());
},
});
// 407 consumer
const consumer_407 = kafka.consumer({
groupId: "group407",
fromBeginning: true,
});
consumer_407.connect();
consumer_407.subscribe({ topic: "407_ERRORS_PER_MIN" });
consumer_407.run({
eachMessage: async ({ topic, partition, message }) => {
socket.broadcast.emit("407_ERRORS_PER_MIN", message.value.toString());
},
});
});
server.on("error", (err) => {
console.log(err);
});
const PORT = 3333 || process.env.PORT;
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
|
import { getAllFilesData } from "./folder";
export async function getAllTagsId(){
const posts = await getAllFilesData("posts", "fr");
const allTags = posts.map((post) => post.tags).flat();
const uniqTags = allTags.filter(function(item, index){
return allTags.indexOf(item) == index;
})
return uniqTags;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.