text stringlengths 7 3.69M |
|---|
const body=document.querySelector('section');
const div=document.createElement('div');
const el = document.createElement('div');
el.classList.add('visualizzaDOT');
div.classList.add('container');
body.appendChild(el);
el.appendChild(div);
document.querySelector('body').classList.add('no-scroll');
const dot1=document.createElement('div');
dot1.classList.add('dot');
dot1.setAttribute('id', 'dot1');
div.appendChild(dot1);
const dot2=document.createElement('div');
dot2.classList.add('dot');
dot2.setAttribute('id', 'dot2');
div.appendChild(dot2);
const dot3=document.createElement('div');
dot3.classList.add('dot');
dot3.setAttribute('id', 'dot3');
div.appendChild(dot3);
setTimeout(removeLoad, 4000, el);
function removeLoad(el){
el.remove();
document.querySelector('body').classList.remove('no-scroll');
}
fetch('products/foto').then(onResponse).then(onJson);
function onResponse(response){
return response.json();
}
function onJson(json){
const foto=json.foto;
for(let f of foto){
fetch('products/stampe/'+f.ID).then(onResponse).then(onJsonStampe);
}
}
function onJsonStampe(promise){
console.log(promise);
const article=document.querySelector('article');
const stampa=promise.foto[0];
const it=document.createElement('div');
it.classList.add('item');
it.dataset.id=stampa.foto;
let gmin=0;
let gmax=0;
if(parseInt(stampa.larghezza)<parseInt(stampa.altezza)){
it.dataset.gmin=parseInt(stampa.larghezza);
}
else {it.dataset.gmin=parseInt(stampa.altezza);}
if(parseInt(stampa.larghezza)<parseInt(stampa.altezza)){
it.dataset.gmax=parseInt(stampa.altezza);
}
else {it.dataset.gmax=parseInt(stampa.larghezza);}
it.dataset.pmin=parseFloat(stampa.prezzo);
it.dataset.pmax=parseFloat(stampa.prezzo);
let c=0;
for(let stmp of promise.foto){
if((parseInt(stmp.larghezza))<(parseInt(stmp.altezza))){
gmin=parseInt(stmp.larghezza);
}
else {gmin=parseInt(stmp.altezza)};
if(gmin<(parseInt(it.dataset.gmin))) {it.dataset.gmin=gmin;}
if((parseInt(stmp.larghezza))<(parseInt(stmp.altezza))){
gmax=parseInt(stmp.altezza);
}
else {gmax=parseInt(stmp.larghezza);}
if(gmax>parseInt(it.dataset.gmax)) {it.dataset.gmax=gmax;}
if(parseFloat(stmp.prezzo)<parseFloat(it.dataset.pmin)) {it.dataset.pmin=parseFloat(stmp.prezzo)}
if(parseFloat(stmp.prezzo)>parseFloat(it.dataset.pmax)) {it.dataset.pmax=parseFloat(stmp.prezzo);}
c++
}
article.appendChild(it);
const newTitle = document.createElement('h1');
newTitle.textContent=stampa.titolo;
it.appendChild(newTitle);
const newDiv = document.createElement('div');
newDiv.style.backgroundImage = "url('"+stampa.file+"')";
newDiv.classList.add('background');
it.appendChild(newDiv);
const newFoto = document.createElement('div');
newFoto.classList.add('foto');
it.appendChild(newFoto);
const bottoni=document.createElement('div');
bottoni.classList.add('interazioni');
newFoto.appendChild(bottoni);
const but1 = document.createElement('img');
but1.classList.add('button1');
but1.src='immagini/info.png';
but1.dataset.id=id=stampa.foto;
but1.addEventListener('click', mostraInfo);
bottoni.appendChild(but1);
const but2 = document.createElement('img');
but2.classList.add('button1');
but2.src='immagini/like.png';
but2.dataset.id=id=stampa.foto;
but2.addEventListener('click', addSalvato);
bottoni.appendChild(but2);
const but3 = document.createElement('img');
but3.classList.add('button1');
but3.src='immagini/carrello.png';
but3.dataset.id=id=stampa.foto;
but3.addEventListener('click', addCarrello);
bottoni.appendChild(but3);
}
function addCarrello(event){
const button=event.currentTarget;
const items=document.querySelectorAll('.item');
for(let item of items){
if(item.dataset.id===button.dataset.id){
fetch('products/stampe/'+item.dataset.id).then(onResponse).then(onJsonSceltaCarrello);
}
}
}
function addSalvato(event){
const button=event.currentTarget;
const items=document.querySelectorAll('.item');
for(let item of items){
if(item.dataset.id===button.dataset.id){
fetch('products/stampe/'+item.dataset.id).then(onResponse).then(onJsonScelta);
}
}
}
function onJsonScelta(promise){
console.log(promise);
const stampe=promise.foto;
const corpo= document.querySelector('article');
const el = document.createElement('div');
const text = document.createElement('div');
el.appendChild(text);
text.classList.add('choice');
el.classList.add('visualizza');
document.body.classList.add('no-scroll');
corpo.appendChild(el);
const info=document.createElement('div');
text.appendChild(info);
info.setAttribute('id', 'datiStampa');
const rece=document.createElement('div');
text.appendChild(rece);
rece.classList.add('dimensioni');
const titolo=document.createElement('strong');
titolo.textContent=stampe[0].titolo;
info.appendChild(titolo);
const autore=document.createElement('em');
autore.textContent=stampe[0].nome+' '+stampe[0].cognome;
info.appendChild(autore);
const data=document.createElement('p');
data.textContent=stampe[0].data_scatto;
info.appendChild(data);
for(let stampa of stampe){
const blocco=document.createElement('label');
blocco.classList.add('dim');
rece.appendChild(blocco);
const input=document.createElement('input');
input.setAttribute('type', 'radio');
input.setAttribute('name', 'dimensioni');
input.setAttribute('id', stampa.ID);
input.setAttribute('value', stampa.ID);
input.addEventListener('click', scelta);
blocco.appendChild(input);
input.style.display='none';
const div=document.createElement('div');
blocco.appendChild(div);
const misure=document.createElement('p');
misure.textContent= stampa.altezza+'cm x '+stampa.larghezza+'cm';
div.appendChild(misure);
const materiale=document.createElement('p');
materiale.textContent= stampa.materiale;
div.appendChild(materiale);
const prezzo=document.createElement('p');
prezzo.textContent= stampa.prezzo+'$';
div.appendChild(prezzo);
}
}
function onJsonSceltaCarrello(promise){
console.log(promise);
const stampe=promise.foto;
const corpo= document.querySelector('article');
const el = document.createElement('div');
const text = document.createElement('div');
el.appendChild(text);
text.classList.add('choice');
el.classList.add('visualizza');
document.body.classList.add('no-scroll');
corpo.appendChild(el);
const info=document.createElement('div');
text.appendChild(info);
info.setAttribute('id', 'datiStampa');
const rece=document.createElement('div');
text.appendChild(rece);
rece.classList.add('dimensioni');
const titolo=document.createElement('strong');
titolo.textContent=stampe[0].titolo;
info.appendChild(titolo);
const autore=document.createElement('em');
autore.textContent=stampe[0].nome+' '+stampe[0].cognome;
info.appendChild(autore);
const data=document.createElement('p');
data.textContent=stampe[0].data_scatto;
info.appendChild(data);
for(let stampa of stampe){
const blocco=document.createElement('label');
blocco.classList.add('dim');
rece.appendChild(blocco);
const input=document.createElement('input');
input.setAttribute('type', 'radio');
input.setAttribute('name', 'dimensioni');
input.setAttribute('id', stampa.ID);
input.setAttribute('value', stampa.ID);
input.addEventListener('click', sceltaCarrello);
blocco.appendChild(input);
input.style.display='none';
const div=document.createElement('div');
blocco.appendChild(div);
const misure=document.createElement('p');
misure.textContent= stampa.altezza+'cm x '+stampa.larghezza+'cm';
div.appendChild(misure);
const materiale=document.createElement('p');
materiale.textContent= stampa.materiale;
div.appendChild(materiale);
const prezzo=document.createElement('p');
prezzo.textContent= stampa.prezzo+'$';
div.appendChild(prezzo);
}
}
function scelta(event){
const button=event.currentTarget;
console.log(button.value);
fetch('products/addSalvato/'+button.value).then(onResponse).then(onJsonSalvato);
}
function sceltaCarrello(event){
const button=event.currentTarget;
console.log(button.value);
fetch('products/addCarrello/'+button.value).then(onResponse).then(onJsonAggiunto);
}
function onJsonAggiunto(promise){
console.log(promise);
const corpo= document.querySelector('.choice');
corpo.innerHTML='';
if(promise.type==='no'){
corpo.style.display='flex';
corpo.style.flexDirection='column';
corpo.style.alignItems='center';
corpo.style.justifyContent='space-around';
corpo.style.textAlign='center';
const message=document.createElement('p');
message.textContent=promise.response;
corpo.appendChild(message);
const buttons=document.createElement('div');
buttons.classList.add('interazioni');
const registrati=document.createElement('a');
registrati.href='registrazione';
registrati.classList.add('linkLog');
buttons.appendChild(registrati);
registrati.innerText='Registrati';
const login=document.createElement('a');
login.href='login';
login.classList.add('linkLog');
login.innerText='Login';
buttons.appendChild(login);
corpo.appendChild(buttons);
document.querySelector('.visualizza').addEventListener('click', nascondiFoto);
}
if(promise.type==='si'){
corpo.style.display='flex';
corpo.style.flexDirection='column';
corpo.style.alignItems='center';
corpo.style.justifyContent='space-around';
corpo.style.textAlign='center';
const message=document.createElement('p');
message.textContent=promise.response;
corpo.appendChild(message);
const buttons=document.createElement('div');
buttons.classList.add('interazioni');
const userArea=document.createElement('a');
userArea.href='userArea';
userArea.classList.add('linkLog');
buttons.appendChild(userArea);
userArea.innerText='Area Personale';
corpo.appendChild(buttons);
document.querySelector('.visualizza').addEventListener('click', nascondiFoto);
}
if(promise.type==='proprietario'){
corpo.style.display='flex';
corpo.style.flexDirection='column';
corpo.style.alignItems='center';
corpo.style.justifyContent='space-around';
corpo.style.textAlign='center';
const message=document.createElement('p');
message.textContent=promise.response;
corpo.appendChild(message);
document.querySelector('.visualizza').addEventListener('click', nascondiFoto);
}
}
function onJsonSalvato(promise){
console.log(promise);
const corpo= document.querySelector('.choice');
corpo.innerHTML='';
if(promise.type==='no'){
corpo.style.display='flex';
corpo.style.flexDirection='column';
corpo.style.alignItems='center';
corpo.style.justifyContent='space-around';
corpo.style.textAlign='center';
const message=document.createElement('p');
message.textContent=promise.response;
corpo.appendChild(message);
const buttons=document.createElement('div');
buttons.classList.add('interazioni');
const registrati=document.createElement('a');
registrati.href='registrazione';
registrati.classList.add('linkLog');
buttons.appendChild(registrati);
registrati.innerText='Registrati';
const login=document.createElement('a');
login.href='login';
login.classList.add('linkLog');
login.innerText='Login';
buttons.appendChild(login);
corpo.appendChild(buttons);
document.querySelector('.visualizza').addEventListener('click', nascondiFoto);
}
if(promise.type==='done'){
corpo.style.display='flex';
corpo.style.flexDirection='column';
corpo.style.alignItems='center';
corpo.style.justifyContent='space-around';
corpo.style.textAlign='center';
const message=document.createElement('p');
message.textContent=promise.response;
corpo.appendChild(message);
document.querySelector('.visualizza').addEventListener('click', nascondiFoto);
}
if(promise.type==='proprietario'){
corpo.style.display='flex';
corpo.style.flexDirection='column';
corpo.style.alignItems='center';
corpo.style.justifyContent='space-around';
corpo.style.textAlign='center';
const message=document.createElement('p');
message.textContent=promise.response;
corpo.appendChild(message);
document.querySelector('.visualizza').addEventListener('click', nascondiFoto);
}
if(promise.type==='si'){
corpo.style.display='flex';
corpo.style.flexDirection='column';
corpo.style.alignItems='center';
corpo.style.justifyContent='space-around';
corpo.style.textAlign='center';
const message=document.createElement('p');
message.textContent=promise.response;
corpo.appendChild(message);
const buttons=document.createElement('div');
buttons.classList.add('interazioni');
const userArea=document.createElement('a');
userArea.href='userArea';
userArea.classList.add('linkLog');
buttons.appendChild(userArea);
userArea.innerText='Area Personale';
corpo.appendChild(buttons);
document.querySelector('.visualizza').addEventListener('click', nascondiFoto);
}
}
function mostraInfo(event){
const button=event.currentTarget;
const items=document.querySelectorAll('.item');
for(let item of items){
if(item.dataset.id===button.dataset.id){
fetch('products/stampe/'+item.dataset.id).then(onResponse).then(onJsonInfo);
}
}
}
function onJsonInfo(promise){
console.log(promise);
const stampe=promise.foto;
const corpo= document.querySelector('article');
const el = document.createElement('div');
const image=document.createElement('img');
image.setAttribute('id', 'fullFoto');
image.src=stampe[0].file;
el.appendChild(image)
const text = document.createElement('div');
el.appendChild(text);
text.setAttribute('id', 'container');
el.classList.add('visualizza');
el.setAttribute('id', 'showMore');
document.body.classList.add('no-scroll');
corpo.appendChild(el);
const info=document.createElement('div');
text.appendChild(info);
info.setAttribute('id', 'datiStampa');
const rece=document.createElement('div');
text.appendChild(rece);
rece.setAttribute('id', 'recensioni');
const titolo=document.createElement('strong');
titolo.textContent=stampe[0].titolo;
info.appendChild(titolo);
const autore=document.createElement('em');
autore.textContent=stampe[0].nome+' '+stampe[0].cognome;
info.appendChild(autore);
const data=document.createElement('p');
data.textContent=stampe[0].data_scatto;
info.appendChild(data);
const descrizione=document.createElement('p');
descrizione.textContent=stampe[0].descrizione;
info.appendChild(descrizione);
const misure=document.createElement('p');
misure.textContent='Dimensioni disponibili: ';
const materiali=document.createElement('p');
materiali.textContent='Materiali disponibili: ';
const prezzo=stampe[0].prezzo;
for(let stampa of stampe){
misure.textContent=misure.textContent+' '+stampa.altezza+'cm x '+stampa.larghezza+'cm ';
materiali.textContent=materiali.textContent+' '+stampa.materiale+' ';
if(stampa.prezzo<prezzo){
prezzo=stampa.prezzo;
}
}
const valore=document.createElement('p');
valore.textContent="A partire da: "+prezzo+'$';
info.appendChild(misure);
info.appendChild(materiali);
info.appendChild(valore);
el.addEventListener('click', nascondiFoto);
fetch('products/recensioni/'+stampe[0].foto).then(onResponse).then(onJsonRecensioni);
}
function nascondiFoto(event){
const item=event.currentTarget;
item.remove();
document.body.classList.remove('no-scroll');
}
function onJsonRecensioni(json){
console.log(json);
const recensioni=json.items;
const blocco=document.getElementById('recensioni');
if(recensioni.length==0){
const noRec=document.createElement('strong');
noRec.textContent='Non sono state ancora create recensioni per questa foto.';
noRec.style.fontSize='36px';
blocco.appendChild(noRec);
}
else{
for(let item of recensioni){
const block=document.createElement('div');
block.classList.add('block');
blocco.appendChild(block);
const dati = document.createElement('div');
dati.classList.add('list');
block.appendChild(dati);
const titolo=document.createElement('p');
titolo.textContent= item.utente;
titolo.classList.add('descrizione');
const materiale=document.createElement('p');
materiale.textContent='Materiale: '+item.materiale;
materiale.classList.add('descrizione');
const misure=document.createElement('p');
misure.textContent="Dimensioni: "+item.altezza + "cm x " + item.larghezza + "cm";
misure.classList.add('descrizione');
dati.appendChild(titolo);
dati.appendChild(materiale);
dati.appendChild(misure);
const recensione = document.createElement('div');
block.appendChild(recensione);
const stelle=document.createElement('div');
recensione.appendChild(stelle);
stelle.setAttribute('id', 'ratings');
for(let i=0; i<item.voto; i++){
const star=document.createElement('img');
star.src='immagini/filledstar.png';
stelle.appendChild(star);
}
const area=document.createElement('div');
recensione.appendChild(area);
area.classList.add('testoRec');
area.innerText=item.testo;
}
}
}
function find(){
const barra = document.getElementById('barra');
const key=barra.value.toUpperCase();
const item = document.getElementsByClassName('item');
for(let it=0; it< item.length; it++){
let nome=item[it].querySelector('h1');
if(nome){
let txt = nome.textContent;
if(txt.toUpperCase().indexOf(key)>-1){
item[it].style.display='';
}
else{
item[it].style.display='none';
}
}
}
}
const filtrigmin=document.querySelectorAll('#gmin p');
for(let filtro of filtrigmin){
filtro.addEventListener('click', filtroGMin);
}
function filtroGMin(event){
const gmin=event.currentTarget;
const valore = parseInt(gmin.dataset.gmin);
const items=document.querySelectorAll('.item');
console.log(valore);
for(let item of items){
item.classList.remove('hidden');
if((parseInt(item.dataset.gmax)<valore)) {
item.classList.add('hidden');
}
}
}
const filtrigmax=document.querySelectorAll('#gmax p');
for(let filtro of filtrigmax){
filtro.addEventListener('click', filtroGMax);
}
function filtroGMax(event){
const gmax=event.currentTarget;
const valore = parseInt(gmax.dataset.gmax);
const items=document.querySelectorAll('.item');
for(let item of items){
item.classList.remove('hidden');
if((parseInt(item.dataset.gmax)>valore)||(parseInt(item.dataset.gmin)>valore)){
item.classList.add('hidden');
}
}
}
const filtripmin=document.querySelectorAll('#pmin p');
for(let filtro of filtripmin){
filtro.addEventListener('click', filtroPMin);
}
function filtroPMin(event){
const gmin=event.currentTarget;
const valore = parseInt(gmin.dataset.pmin);
const items=document.querySelectorAll('.item');
console.log(valore);
for(let item of items){
item.classList.remove('hidden');
if((parseInt(item.dataset.pmax)<valore)) {
item.classList.add('hidden');
}
}
}
const filtripmax=document.querySelectorAll('#pmax p');
for(let filtro of filtripmax){
filtro.addEventListener('click', filtroPMax);
}
function filtroPMax(event){
const gmax=event.currentTarget;
const valore = parseInt(gmax.dataset.pmax);
const items=document.querySelectorAll('.item');
for(let item of items){
item.classList.remove('hidden');
if((parseInt(item.dataset.pmax)>valore)||(parseInt(item.dataset.pmin)>valore)){
item.classList.add('hidden');
}
}
}
|
import styled from 'styled-components';
export const Container = styled.div`
background-color: #fff;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
position: relative;
padding: 20px;
width: 250px;
height: 310px;
padding-bottom: 70px;
h1, h2, h3, button {
margin: 5px;
}
h3 {
margin-top: 10px;
font-size: 13px;
text-transform: uppercase;
}
h1 {
font-size: 20px;
}
h2 {
font-size: 13px;
span {
position: relative;
&:before {
content: "____";
position: absolute;
left: -0.1em;
bottom: 0.42em;
}
}
}
button {
background-color: #eff2fb;
border: none;
color: #212121;
padding: 5px 15px 6px;
border-radius: 20px;
cursor: pointer;
}
`;
export const Image = styled.img`
box-shadow: 0px 5px 10px 0px rgba(0,0,0,0.2);
border-radius: 10px;
position: relative;
min-height: 200px;
width: 200px;
transition: all 300ms ease;
&:hover {
border: 20px solid black;
}
`;
|
import React from "react";
import { Image as PdfImage } from "@react-pdf/renderer";
import extract from "../../styles/compose";
const Image = ({ className, src }) => {
return (
<PdfImage
style={extract("view " + (className ? className : ""))}
src={src}
/>
);
};
export default Image;
|
import { ScaledSheet } from 'react-native-size-matters';
import { spacing } from '../../styles/spacing';
const styles = ScaledSheet.create({
// inputLabelStyle: {
flatliststyle:{
marginTop: 40
},
slotView:{
flexDirection: 'row',
justifyContent: 'space-between',
margin: spacing.MARGIN_12,
padding: spacing.PADDING_10,
borderWidth: 2,
borderColor: 'black',
backgroundColor: '#ADD8E6',
height:spacing.HEIGHT_74
},
freeView:{
backgroundColor: 'green',
height: spacing.HEIGHT_45,
width: spacing.WIDTH_55,
flexDirection:'row'
},
textFreeSlot:{
color: 'white',
marginLeft: spacing.MARGIN_14,
// flexDirection: 'row'
},
bookedSlot:{
color: 'white',
padding: 5
},
bookedView:{
backgroundColor: 'red',
height: spacing.HEIGHT_35,
width: spacing.WIDTH_55
},
textMainViews:{
justifyContent:'center',
alignItems:'center',
marginTop:20
},
slotTimeText:{
color:'black',
fontWeight:'700',
fontSize:20
}
});
export default styles |
import React from 'react'
import PropTypes from 'prop-types'
import { Svg, HiddenText } from './styled'
const CoffeeDrip = ({
attributionId,
attributionText,
isAnimating,
inScene,
}) => (
<Svg
aria-labelledby={attributionId}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 125"
isAnimating={isAnimating}
inScene={inScene}
>
<path d="M 0 0 L 0 125" />
<HiddenText id={attributionId}>{attributionText}</HiddenText>
</Svg>
)
CoffeeDrip.propTypes = {
attributionId: PropTypes.string,
attributionText: PropTypes.string,
isAnimating: PropTypes.bool,
}
CoffeeDrip.defaultProps = {
attributionId: 'coffee-drip-attribution',
attributionText: 'Coffee Drip',
isAnimating: false,
}
export default CoffeeDrip
|
//A function is a piece of code that can be run many times, usually by its name
//can you make this a polygon?
function square(side) {
repeat(4, function () {
forward(side);
right(90);
});
}
function demo() {
hideTurtle();
colour(0,0,255,1);
for(s = 100; s > 0; s -= 10) {
square(s);
right(36);
}
}
//type "demo()" below this line, and hit "Run Code" (or ctl-m)
|
//utils
import React from 'react';
import Modal from 'react-modal';
import * as MaterialDesign from 'react-icons/lib/md';
//components
import NoteModalContainer from '../modals/note_modal_container';
class NoteTools extends React.Component {
constructor(props) {
super(props);
this.state = {
editModalOpen: false,
deleteModalOpen: false
};
this.openEditModal = this.openEditModal.bind(this);
this.closeEditModal = this.closeEditModal.bind(this);
this.openDeleteModal = this.openDeleteModal.bind(this);
this.closeDeleteModal = this.closeDeleteModal.bind(this);
}
openEditModal() {
this.setState({ editModalOpen: true });
}
closeEditModal() {
this.setState({ editModalOpen: false });
}
//open and close for delete modal
openDeleteModal() {
this.setState({ deleteModalOpen: true });
}
closeDeleteModal() {
this.setState({ deleteModalOpen: false });
}
render() {
return (
<div className='note-tools'>
<MaterialDesign.MdCreate
className='note-tools-icon'
onClick={this.openEditModal} />
<Modal
isOpen={this.state.editModalOpen}
onRequestClose={this.closeEditModal}
overlayClassName={
{
base: "root-modal-container",
afterOpen: "root-modal-container",
beforeClose: "root-modal-container"
}
}
className={
{
base: "override-content-default",
afterOpen: "override-content-default",
beforeClose: "override-content-default"
}
}>
<NoteModalContainer
closeModal={this.closeEditModal}
note={this.props.note}
modalAction="edit"
/>
</Modal>
<MaterialDesign.MdDelete
className='note-tools-icon'
onClick={this.openDeleteModal} />
<Modal
isOpen={this.state.deleteModalOpen}
onRequestClose={this.closeDeleteModal}
overlayClassName={
{
base: "root-modal-container",
afterOpen: "root-modal-container",
beforeClose: "root-modal-container"
}
}
className={
{
base: "override-content-default",
afterOpen: "override-content-default",
beforeClose: "override-content-default"
}
}>
<NoteModalContainer
closeModal={this.closeDeleteModal}
note={this.props.note}
modalAction="delete"
/>
</Modal>
</div>
);
}
}
export default NoteTools; |
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
var varToggleCampaign = true;
elems.forEach(function(html) {
var switchery = new Switchery(html);
});
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-bottom-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "700",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
function toggleCampaign(campaign_id) {
var status = $("#campaign-"+campaign_id).is(":checked");
var rpid = $("#tv_id").text();
$("#campaign-"+campaign_id).parent().attr('data-hasData',status);
$.ajax({
type: 'POST', // http method
url: '/toggle-campaign/'+rpid+'/'+campaign_id+'/'+status,
success: function (data) {
console.log(data);
if (data.success) {
toastr.success("Updated");
}else {
toastr.warning("Failed to update. Please try again.");
}
},
error: function (data) {
toastr.warning("Failed to update. Please check your internet connection.");
}
})
}
$("#show-stats").on("click",function(){
$("#show-stats").hide();
$("#aircast-preview").hide();
$("#aircast-preview-first").show();
$("#aircast-preview").html("");
});
var $rows = $('#rpi-table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
var $rows2 = $('#table-contacts tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows2.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
$("#toggle-campaign").on("click",function(){
if (varToggleCampaign) {
$("#toggle-campaign").html('Show all campaigns');
$("#show-stats").css("right","210px");
$("td[data-hasData='false']").parent('tr').hide();
varToggleCampaign = false;
}else {
$("td[data-hasData='false']").parent('tr').show();
varToggleCampaign = true;
$("#toggle-campaign").html('Show only active campaigns');
$("#show-stats").css("right","260px");
}
})
function checkboxAddToNUmberList(item) {
if ( $('.site-to-send-message li:contains("'+$(item).attr('data-name')+'")').length ) {
$('.site-to-send-message li:contains("'+$(item).attr('data-name')+'")').remove();
}else {
$('.site-to-send-message').append('<li data-num='+$(item).attr('data-number')+'>'+$(item).attr('data-name')+'</li>');
}
}
function sendMessage() {
var messg = $("#text-message").val();
var listItems = $(".site-to-send-message li");
var numList = [];
if (messg == '') {
swal(
'Oops...',
'Don\'t forget to add your message',
'info'
)
}
else if (listItems.length == 0) {
swal(
'Oops...',
'You forgot to add the list of numbers to send the message',
'info'
)
}else {
listItems.each(function(idx, li) {
var numbers_of_sites_to_send = $(li).attr('data-num');
numList.push('63'+numbers_of_sites_to_send);
});
sendMes(numList,messg);
}
function sendMes(num_list,mess) {
$.ajax({
type: "POST",
url: "http://ec2-54-169-234-246.ap-southeast-1.compute.amazonaws.com/api/v0/message-per-site.php",
data: {numbers:num_list,message:mess},
dataType: 'json',
success: function(item){
console.log(item);
console.log('done');
},
error: function(err) {
console.log(err);
}
});
swal({
title: 'Sending Your Messages',
text: 'this will only take a few seconds',
timer: 5000,
onOpen: () => {
swal.showLoading()
}
}).then((result) => {
if (result.dismiss === 'timer') {
$("#text-message").val('');
swal(
'Message Sent!',
'',
'success'
)
}
})
}
}
function updateParameter(campaign_id) {
var new_param = $("#param-"+campaign_id).val();
$.ajax({
type: 'POST', // http method
url: '/update-campaign/'+campaign_id+'/'+new_param,
success: function (data) {
console.log(data);
if (data.success) {
toastr.success("Updated");
}else {
toastr.warning("Failed to update. Please try again.");
}
},
error: function (data) {
toastr.warning("Failed to update. Please check your internet connection.");
}
})
}
function confirmCampaignDelete(data){
var campaign_id_to_delete = $(data).attr('id').split("-");
var status = $("#campaign-"+campaign_id_to_delete[1]).parent().attr('data-hasData');
if (status == 'true') {
toastr.warning('Campaign is currently active. Disable it first to delete the campaign.');
}else {
$(data).html('<img src="/img/trash-confirm.png" class="trash-image" onclick="deleteItem('+campaign_id_to_delete[1]+')">');
$(data).parent().parent().css('background-color','#dfdfdf');
}
}
function deleteItem(campaign_id) {
var rpid = $("#tv_id").text();
$.ajax({
type: 'POST', // http method
url: '/delete-campaign/'+rpid+'/'+campaign_id,
success: function (data) {
console.log(data);
if (data.success) {
toastr.success('Campaign id: ' + campaign_id+ ' successfully deleted.');
$("#deleteCampaign-"+campaign_id).parent().parent().remove();
}else {
toastr.warning("Failed to delete. Please try again.");
}
},
error: function (data) {
toastr.warning("Failed to delete. Please check your internet connection.");
}
})
$("#deleteCampaign-"+campaign_id).parent().parent().remove();
}
function previewCampaign(data) {
$("#aircast-preview").show();
$("#show-stats").show();
$("#aircast-preview-first").hide();
var link = $(data).attr("data-link");
var type = $(data).attr("data-type");
console.log(link + type);
var orientation = $("#orientation-type").text();
if (orientation == 'landscape') {
$("#aircast-preview").css("width","410px");
if (type == 'Image') {
$("#aircast-preview").html("<img src="+link+" style='width: 400px;' />");
}else {
$("#aircast-preview").html("<video src="+link+" style='width: 400px;' autoplay loop controls />")
}
}else {
if (type == 'Image') {
$("#aircast-preview").css("width","260px");
$("#aircast-preview").html("<img src="+link+" style='width: 250px;' />");
}else {
$("#aircast-preview").css("width","410px");
$("#aircast-preview").html("<video src="+link+" style='width: 400px;' autoplay loop controls />")
}
}
} |
import * as React from "react";
function ButtonItem({ children }) {
return (
<>
<li className="h-full w-full">
{children}
</li>
</>
);
}
export default ButtonItem;
|
/**
*
*/
window.onload = function(){
document.getElementById("signout")
.addEventListener("click", signout);
}
function signout(){
//document.getElementById('signout').onclick=function(){
//session.invalidate();
response.sendRedirect("../../Login.html");
// };
console.log(5 + 6);
}
window.onload=init; |
/* global angular */
/* global window */
angular.module('mean.system')
.factory('dashboard',
['$http', ($http) => {
const getGameLog = () => new Promise((resolve, reject) => {
$http.get('/api/games/history',
{ headers: { token: window.localStorage.token } })
.success((response) => {
resolve(response);
})
.error((error) => {
reject(error);
});
});
const leaderGameLog = () => new Promise((resolve, reject) => {
$http.get('/api/leaderboard',
{ headers: { token: window.localStorage.token } })
.success((response) => {
resolve(response);
})
.error((error) => {
reject(error);
});
});
const userDonations = () => new Promise((resolve, reject) => {
$http.get('/api/donations',
{ headers: { token: window.localStorage.token } })
.success((response) => {
resolve(response);
})
.error((error) => {
reject(error);
});
});
return {
getGameLog,
leaderGameLog,
userDonations
};
}]);
|
var React = require('react'),
AvailableTaskIndexItem = require('./available_task_index_item'),
TaskerStore = require('../../stores/tasker');
module.exports = React.createClass({
getInitialState: function() {
return {
tasker: this._getTaskerFromStore()
};
},
componentDidMount: function() {
this.taskerListener = TaskerStore.addListener(this._onTaskerChange);
},
componentWillUnmount: function() {
this.taskerListener.remove();
},
_onTaskerChange: function () {
this.setState({
tasker: this._getTaskerFromStore()
});
},
_getTaskerFromStore: function () {
return TaskerStore.find(this.props.params.tasker_id);
},
render: function () {
if (this.state.tasker && this.state.tasker.available_tasks) {
var items = this.state.tasker.available_tasks.map(function (task, index) {
return <AvailableTaskIndexItem task={task} key={index}/>;
});
return (
<div className="available-task-container">
<ul className="tasker-task-list">
{items}
</ul>
</div>
);
} else {
return <div className="loader">Loading...</div>;
}
}
});
|
/**
* @param {number[]} A
* @return {number}
*/
var repeatedNTimes = function(A) {
var map = {};
for (var i = 0; i< A.length; i++) {
var value = A[i];
if(!map[value]) {
map[value] = true;
} else {
return value;
}
}
};
console.log(repeatedNTimes([1,2,3,3]));
console.log(repeatedNTimes([2,1,2,5,3,2]));
console.log(repeatedNTimes([5,1,5,2,5,3,5,4])); |
const koalaBio = "The koala or, inaccurately, koala bear is an arboreal herbivorous marsupial native to Australia. It is the only extant representative of the family Phascolarctidae and its closest living relatives are the wombats, which are members of the family Vombatidae.";
const dingoBio = "The dingo is a dog that is found in Australia. Its taxonomic classification is debated. It is a medium-sized canine that possesses a lean, hardy body adapted for speed, agility, and stamina. The dingo's three main coat colours are: light ginger or tan, black and tan, or creamy white.";
const platypusBio = "The platypus, sometimes referred to as the duck-billed platypus, is a semiaquatic egg-laying mammal endemic to eastern Australia, including Tasmania. The platypus is the sole living representative of its family and genus, though a number of related species appear in the fossil record.";
const tasmanianDevilBio = "The Tasmanian devil is a carnivorous marsupial of the family Dasyuridae. It was once native to mainland Australia and is now found in the wild only on the island state of Tasmania, including tiny east-coast Maria Island where there is a conservation project with disease-free animals.";
const wombatBio = "Wombats are short-legged, muscular quadrupedal marsupials that are native to Australia. They are about 1 m in length with small, stubby tails and weigh between 20 and 35 kg. There are three extant species and they are all members of the family Vombatidae.";
let animals = [
{ name: "Koala", img: "./images/koala.jpg", bio: koalaBio },
{ name: "Dingo", img: "./images/dingo.jpg", bio: dingoBio },
{ name: "Platypus", img: "./images/platypus.jpg", bio: platypusBio },
{ name: "Tasmanian Devil", img: "./images/tasmanian_devil.jpg", bio: tasmanianDevilBio },
{ name: "Wombat", img: "./images/wombat.jpg", bio: wombatBio }
]
document.addEventListener("DOMContentLoaded", function() {
const container = document.getElementById("container");
let animalList = Handlebars.compile(document.getElementById("animal-list").innerHTML);
let animalTemplate = Handlebars.compile(document.getElementById("animal-template").innerHTML);
Handlebars.registerPartial("animalTemplate", animalTemplate);
let htmlString = animalList({ animals });
container.innerHTML = htmlString;
let images = document.querySelectorAll("img");
let timeoutId;
images.forEach(img => img.addEventListener("mouseenter", displayBio));
images.forEach(img => img.addEventListener("mouseleave", hideBio));
function displayBio(e) {
timeoutId = setTimeout(function() {
e.target.parentNode.querySelector("figcaption").style.display = "inline";
}, 2000);
};
function hideBio(e) {
clearTimeout(timeoutId);
e.target.nextElementSibling.style.display = "none";
};
});
|
import request from '@/utils/request'
export function login(data1,data2) {
return request({
url: `/zhjg/login/${data1}?userPass=${data2}`,
method: 'get',
})
}
export function getInfo(token) {
return request({
url: '/user/info',
method: 'get',
params: { token }
})
}
export function getUserInfo(data) {
return request({
url: '/sys/user/list',
method: 'get',
params:data
})
}
export function logout() {
return request({
url: '/user/logout',
method: 'post'
})
}
export function getPermission(token) {
return request({
url: `/zhjg/login/?id_token=${token}`,
method: 'get'
})
}
export function goPublic(url) {
return request({
url: `/zhjg/goToService/?urlParm=${url}`,
method: 'get'
})
}
export function updateUserInfo(userId) {
return request({
url: `/sys/user/userInfo/${userId}`,
method: 'get',
})
}
export function updateUser(data) {
return request({
url: `/sys/user/update`,
method: 'post',
data
})
}
export function deleteUser(data) {
return request({
url: `/sys/user/delete`,
method: 'post',
data
})
}
|
export default function(accepts = [], props = {}) {
return function(widget) {
function getData(e) {
return JSON.parse(e.dataTransfer.getData("text"));
}
function handleDragEnter(e) {
e.stopPropagation();
e.preventDefault();
props.onDragEnter && props.onDragEnter(e);
}
function handleDragLeave(e) {
e.stopPropagation();
e.preventDefault();
props.onDragLeave && props.onDragLeave(e);
}
function handleDragOver(e) {
e.preventDefault();
props.onDragOver && props.onDragOver(e);
}
function handleDrop(e) {
e.stopPropagation();
e.preventDefault();
const data = getData(e);
if (accepts.indexOf(data.type) === -1) {
return;
}
props.onDrop && props.onDrop(data, e);
}
return {
...widget,
props: {
...widget.props,
onDragEnter: handleDragEnter,
onDragLeave: handleDragLeave,
onDragOver: handleDragOver,
onDrop: handleDrop
}
};
}
} |
//Create main class
function Bank () {
this.customers = {};
}
// Create a new customer, we need to pass the name of the curstomer
Bank.prototype.addCustomer = function(customerName) {
var customersLenght = Object.keys(this.customers).length;;
var key = customersLenght + 1;
this.customers[key] = {};
this.customers[key]["account"] = key;
this.customers[key]["name"] = customerName;
this.customers[key]["deposit"] = 0;
}
// Print the account for the customer with the name...
Bank.prototype.printAccount = function(customerName) {
for ( key in this.customers) {
if (this.customers[key].name == customerName){
console.log(this.customers[key].name + " account is " + this.customers[key].deposit );
}
}
}
//Function to allow deposit some money in the account
Bank.prototype.deposit = function(customerName, amount) {
for ( key in this.customers) {
if (this.customers[key].name == customerName){
this.customers[key].deposit = this.customers[key].deposit + amount;
}
}
}
//FUnction to withdraw money from all accounts. It controls there won't be negative numbers
Bank.prototype.withdraw = function(customerName, amount) {
for ( key in this.customers) {
if (this.customers[key].name == customerName){
estimatedTotal = this.customers[key].deposit - amount;
if (estimatedTotal >= 0) {
this.customers[key].deposit = this.customers[key].deposit - amount;
}else{
console.log("Action could not be commited. Not enough money in the account.")
}
}
}
}
//Print all accounts
Bank.prototype.printAll = function(customerName, amount) {
for ( key in this.customers) {
console.log(this.customers[key].name + " account is " + this.customers[key].account + " and the saldo is " + this.customers[key].deposit );
}
}
//Running commands
var bank = new Bank();
bank.addCustomer('Sheldor');
bank.printAccount('Sheldor');
bank.deposit('Sheldor', 10);
bank.printAccount('Sheldor');
bank.addCustomer('Raj');
bank.printAccount('Raj');
bank.deposit('Raj', 10000);
bank.printAccount('Raj');
bank.withdraw('Raj', 100000);
bank.withdraw('Raj', 100);
bank.printAccount('Sheldor');
bank.printAccount('Raj');
bank.printAll('Raj');
|
import magic from '@kuba/magic'
export default magic.validator_outlet
|
export const
indicatorColor = 'secondary',
textColor = 'secondary'
|
import React, { useState, useEffect } from 'react';
import { Link } from "react-router-dom";
import './css/Login.css';
import { useDispatch, useSelector } from 'react-redux';
import { loginUser } from './../../actions/authActions';
import AOS from 'aos';
import 'aos/dist/aos.css'
import Nav from "../Nav/Nav"
const StudentLogin = (props) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [errors, setErrors] = useState({});
const dispatch = useDispatch();
const formErrors = useSelector(state => state.errors);
const isAuthenticated = useSelector(state => state.auth.isAuthenticated);
if (isAuthenticated) {
props.history.push('/dashboard');
}
useEffect(() => {
setErrors(formErrors)
}, [formErrors]);
const onChangeEmail = e => {
setEmail(e.target.value);
}
const onChangePassword = e => {
setPassword(e.target.value);
}
const onClick = e => {
e.preventDefault();
let student = {
email: email,
password: password
};
dispatch(loginUser(student))
}
AOS.init({
duration: 3000,
mirror: true,
})
return (
<div className="loginWrapper">
<div>
<div id="loginNav">
<Nav />
</div>
<div id="pageImage">
<h1 data-aos="fade-up">"Your <m>limitation</m> - it's only your <m>imagination</m>."</h1>
</div>
<div id="LoginForm" data-aos="fade-up">
<h1 id="loginText">Student <m>Sign In</m></h1>
<span className="red-text">
{errors.email}
{errors.emailNotFound}
</span>
<span className="red-text">
{errors.password}
{errors.passwordIncorrect}
</span>
<form id="loginEmail">
<h5>E-MAIL</h5>
<input type="text" onChange={onChangeEmail} value={email} error={errors.email} />
</form>
<form id="loginPass">
<h5>PASSWORD</h5>
<input type="password" onChange={onChangePassword} value={password} error={errors.password} />
</form>
<form id="loginButton" >
<button type="submit" data-aos="fade-up" onClick={onClick}>Sign In</button>
</form>
<p className="log-have-an-acc">
Don't have an account? <Link id="link" to="/student/register"> <m>Register</m></Link>
</p>
</div>
</div>
</div>
)
}
export default StudentLogin; |
const assert = require('chai').assert
const expect = require('chai').expect
const {foo, obj1, arr, add, arr2, doMath } = require('../app')
describe('index file', function() {
describe('foo', function(){
it('should return type of string', function(){
assert.typeOf(foo, 'string', 'foo is a string')
})
it('should have value of "bar"', function(){
assert.equal(foo, 'bar', 'the value of foo is "bar"')
})
})
describe('arr variable', function(){
it('should contain 4 values', function(){
assert.lengthOf(arr, 4, 'arr has 4 values')
})
it('should have an object at index 3', function(){
assert.typeOf(arr[3], 'object', 'value is an object')
})
it('should have a number at index 0', function(){
assert.typeOf(arr[0], 'number', 'value is a number')
})
})
describe('obj1 variable', function(){
it('should have at least 1 value', function(){
assert.isAbove(Object.keys(obj1).length, 1, 'obj1 has at least 1 key')
})
it('should have 2 keys', function(){
assert.lengthOf(Object.keys(obj1), 2, 'obj1 has 2 keys')
})
})
describe('add function', function(){
it('should be a function', function(){
expect(add).to.be.a('function')
})
it('should return a number', function(){
expect(add(1,1)).to.be.a('number')
})
it('should return a number greater than either given number', function(){
let num1 = 5
let num2 = 7
expect(add(num1,num2)).to.be.above(num1)
expect(add(num1,num2)).to.be.above(num2)
})
it('should return a correct sum of the two numbers', function(){
expect(add(2,2)).to.equal(4)
expect(add(9999,9999)).to.equal(19998)
})
})
describe('arr2', function(){
it('should have no elements below 3', function(){
for (let value of arr2){
expect(value).to.be.above(3)
}
})
})
describe('doMath function', function(){
it('should return a single value squared', function(){
expect(doMath(9)).to.equal(81)
})
it('should return false with unexpected input in the first position', function(){
expect(doMath(9, 9)).to.equal(false)
})
describe('doMath(add)', function(){
it('should accurately return the sum of the 2 given numbers', function(){
expect(doMath('add', 2, 2)).to.equal(4)
})
})
describe('doMath(mult)', function(){
it('should accurately return the product of the 2 given numbers', function(){
expect(doMath('mult', 2, 2)).to.equal(4)
})
})
describe('doMath(div)', function(){
it('should accurately return the quotient of the 2 given numbers', function(){
expect(doMath('div', 2, 2)).to.equal(1)
})
})
describe('doMath(mod)', function(){
it('should accurately return the modulus of the 2 given numbers', function(){
expect(doMath('mod', 3, 2)).to.equal(1)
})
})
describe('doMath(sub)', function(){
it('should accurately return the difference of the 2 given numbers', function(){
expect(doMath('sub', 3, 2)).to.equal(1)
})
})
describe('doMath(exp)', function(){
it('should accurately return num1 to the power of num2', function(){
expect(doMath('exp', 3, 3)).to.equal(27)
})
})
})
}
)
|
import Link from "next/link";
import NavStyles from "./styles/NavStyles";
const Nav = () => (
<NavStyles data-test="nav">
<Link href="/tech">
<a>Tech</a>
</Link>
<Link href="/health">
<a>Health</a>
</Link>
<Link href="mailto:alaindwight@gmail.com">
<a>Contact</a>
</Link>
</NavStyles>
);
export default Nav;
|
import clientEvents from '../../../constants/clientEvents';
const sConnect = (user) => {
return {
type: clientEvents.CONNECT,
user: user
}
}
const sAuth = (user) => {
return {
type: clientEvents.AUTH,
user: user
}
}
const sLeaveRoom = () => {
return {
type: clientEvents.LEAVE_ROOM
}
}
const sJoinQueue = (payload) => {
return {
type: clientEvents.JOIN_QUEUE,
payload
}
}
const sStartGame = () => {
return {
type: clientEvents.START_GAME,
}
}
const sEndTurn = () => {
return {
type: clientEvents.END_TURN
}
}
const sUpdateGameState = (payload) => {
return {
type: clientEvents.UPDATE_GAME_STATE,
payload
}
}
const sEndGame = (payload) => {
return {
type: clientEvents.END_GAME,
payload
}
}
const sRequestReset = () => {
return {
type: clientEvents.REQUEST_RESET
}
}
const sDeclineReset = () => {
return {
type: clientEvents.DECLINE_RESET
}
}
const sAcceptReset = () => {
return {
type: clientEvents.ACCEPT_RESET
}
}
export default {
sConnect,
sAuth,
sLeaveRoom,
sJoinQueue,
sStartGame,
sEndTurn,
sUpdateGameState,
sEndGame,
sRequestReset,
sDeclineReset,
sAcceptReset
} |
var interface_i_notify =
[
[ "ListenFor", "interface_i_notify.html#a60a6e16d55d60a9c9ee3940fbeb01135", null ],
[ "PostNotification", "interface_i_notify.html#a0a8970c686057a0d1f9ee0b3773c8b69", null ],
[ "PostSimpleNotification", "interface_i_notify.html#ac4543617ce432d84b202503515a087b6", null ],
[ "StopListeningFor", "interface_i_notify.html#a13cf2c4d37b9a6c000f6f51c0f84a901", null ]
]; |
/**
* Copyright (c) Benjamin Ansbach - all rights reserved.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const BC = require('./../BC');
const AbstractType = require('./AbstractType');
const P_SIZE_ENCODED = Symbol('size_encoded');
const P_REPEAT_LIMIT = Symbol('repeat_limit');
const P_REPEAT_MARKER = Symbol('repeat_marker');
const P_TYPE = Symbol('type');
/**
* A Type that itself is made up of multiple other types.
*/
class Repeating extends AbstractType {
/**
* Constructor
*/
constructor(id, type, repeatLimit = -1, repeatMarker = null) {
super(id || 'repeating');
super.description('A type that itself has one repeating type that will ' +
'be written / read until the limit is reached or data is empty.');
this[P_TYPE] = type;
this[P_REPEAT_LIMIT] = repeatLimit;
this[P_REPEAT_MARKER] = repeatMarker;
}
/**
* @inheritDoc AbstractType#encodedSize
*/
get encodedSize() {
return this[P_SIZE_ENCODED];
}
/**
* Decodes the given bytes into an object.
*
* @param {BC|Buffer|Uint8Array|String} bc
* @return {Object}
*/
decodeFromBytes(bc, options = {}, all = null) {
let result = [];
let offset = 0;
bc = BC.from(bc);
let limit = this[P_REPEAT_MARKER] !== null ? all[this[P_REPEAT_MARKER]] : this[P_REPEAT_LIMIT];
let counter = limit;
while ((limit > -1 && counter > 0) || (limit === -1 && bc.length > offset)) {
const decoded = this[P_TYPE].decodeFromBytes(bc.slice(offset));
result.push(decoded);
offset += this[P_TYPE].encodedSize;
counter--;
}
this[P_SIZE_ENCODED] = offset;
return result;
}
/**
* Encodes the given object to a list of bytes.
*
* @param {Object|Array} objOrArray
* @returns {BC}
*/
encodeToBytes(arr) {
let bc = BC.empty();
arr.forEach((item, idx) => {
if (idx >= this[P_REPEAT_LIMIT] && this[P_REPEAT_LIMIT] > -1) {
return;
}
bc = bc.append(this[P_TYPE].encodeToBytes(item));
});
this[P_SIZE_ENCODED] = bc.length;
return bc;
}
get repeatingType() {
return this[P_TYPE];
}
}
module.exports = Repeating;
|
const gulp = require('gulp')
const browserSync = require('browser-sync').create()
const inject = require('gulp-inject')
const htmlmin = require('gulp-htmlmin')
const uglify = require('gulp-uglify')
const zip = require('gulp-zip')
const checkFilesize = require('gulp-check-filesize')
const concat = require('gulp-concat')
const del = require('del')
gulp.task('html', function () {
return gulp.src('src/*.html')
.pipe(inject(
gulp.src('src/**/*.js', {read: false}),
{relative: true}
))
.pipe(gulp.dest('src'))
})
gulp.task('html:dist', function () {
return gulp.src('src/*.html')
.pipe(gulp.dest('build'))
.pipe(inject(
gulp.src('build/**/*.js', {read: false}),
{relative: true}
))
.pipe(htmlmin({
collapseWhitespace: true,
collapseBooleanAttributes: true,
// removeAttributeQuotes: true,
minifyCSS: true,
removeComments: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
useShortDoctype: true
}))
.pipe(gulp.dest('build'))
})
gulp.task('scripts:dist', function () {
return gulp.src(['src/**/*.js', '!src/**/debug.js'])
.pipe(concat('game.js'))
.pipe(uglify())
.pipe(gulp.dest('build'))
})
gulp.task('zip', function () {
return gulp.src('build/**/*')
.pipe(zip('game.zip'))
.pipe(checkFilesize({
fileSizeLimit: 13312 // 13Kb
}))
.pipe(gulp.dest('dist'))
})
gulp.task('browsersync', function () {
browserSync.init({
server: 'src',
files: 'src'
})
})
gulp.task('browsersync:dist', function () {
browserSync.init({
server: 'build',
files: 'build'
})
})
gulp.task('watch', watch)
gulp.task('clean', clean)
gulp.task('build', gulp.series('html'))
gulp.task('build:dist', gulp.series('clean', 'scripts:dist', 'html:dist', 'zip'))
gulp.task('serve', gulp.series('build', 'watch', 'browsersync'))
gulp.task('serve:dist', gulp.series('build:dist', 'browsersync:dist'))
gulp.task('default', gulp.series('build:dist', 'serve'))
function watch (done) {
gulp.watch('src/**/*', gulp.series('build:dist'))
gulp.watch('src/**/*.js', gulp.series('html'))
done()
}
function clean () {
return del(['build', 'dist'])
}
|
(function() {
function toggleClass(element, className) {
var currentClasses = element.className;
if (currentClasses.indexOf(className) >= 0) {
element.className = currentClasses.replace(className, '').trim();
}
else {
element.className += ' ' + className;
}
}
var modalTrigger = document.querySelector('.modal--btn');
var modal = document.querySelector('.modal');
var modalBox = document.querySelector('.modal__box');
var modalSubmit = document.querySelector('.modal__submit');
var modalExit = document.querySelector('.modal__exit');
var modalOpen = document.querySelector('.modal--open');
modalTrigger.addEventListener('click', function(e) {
e.stopPropagation();
toggleClass(modal.parentNode, 'modal--open');
});
function modalClose(element) {
element.addEventListener('click', function(e) {
e.stopPropagation();
var modalOpen = document.querySelector('.modal--open');
if (modalOpen) {
toggleClass(modal.parentNode, 'modal--open');
}
});
}
modalClose(modal);
modalClose(modalExit);
modalClose(modalSubmit);
//Using this to prevent propogation of on click for body when clicking on modal box due to body event listener
modalBox.addEventListener('click', function(e) {
e.stopPropagation();
});
})();
|
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
export { default as Carousel1 } from './components/Carousel1';
export { default as Carousel2 } from './components/Carousel2';
|
'use strict';
import Study from './study.model';
import config from '../../config/environment';
import jwt from 'jsonwebtoken';
function validationError( res, statusCode ) {
statusCode = statusCode || 422;
return function ( err ) {
res.status( statusCode ).json( err );
}
}
function handleError( res, statusCode ) {
statusCode = statusCode || 500;
return function ( err ) {
res.status( statusCode ).send( err );
};
}
/**
* Get list of studys
* restriction: 'admin'
*/
export function index( req, res ) {
return Study.find( {} ).exec()
.then( studys => {
return res.status( 200 ).json( studys );
} )
.catch( handleError( res ) );
}
/**
* Creates a new study
*/
export function create( req, res, next ) {
var newDoc = new Study( req.body );
newDoc.save()
.then( function ( study ) {
return res.json( study );
} )
.catch( validationError( res ) );
}
/**
* Updates a new study
*/
export function update( req, res, next ) {
let studyId = req.params.id;
Study.findOneAndUpdate({_id:req.params.id}, req.body, {new: true, runValidators: true}, function (err, study) {
if (err) {
console.log(err);
return res.status(422).send(err);
}
return res.json( study );
});
}
/**
* Get a single study
*/
export function show( req, res, next ) {
var studyId = req.params.id;
return Study.findById( studyId ).exec()
.then( study => {
if ( !study ) {
return res.status( 404 ).end();
}
res.json( study.profile );
} )
.catch( err => next( err ) );
}
/**
* Deletes a study
* restriction: 'admin'
*/
export function destroy( req, res ) {
return Study.findByIdAndRemove( req.params.id ).exec()
.then( function () {
return res.status( 204 ).end();
} )
.catch( handleError( res ) );
}
|
/* Given a linked list, determine if it has a cycle in it.
Definition for singly-linked list.
function ListNode(val) {
this.val = val;
this.next = null;
To represent a cycle in the given linked list, we use an integer
pos which represents the position (0-indexed) in the linked list where tail
connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.*/
function ListNode(val) {
this.val = val;
this.next = null;
}
// var hasCycle = function(head) {
// if (!head || !head.next) {
// // no list
// // or just the head (can't have a cycle right?!)
// return false;
// }
// //slow pointer moves one node at a time
// //fast pointer moves two nodes at a time
// let slow = head;
// let fast = head.next;
// while (fast && fast.next) {
// //when two nodes are the same, it is a cycle
// if (fast === slow) return true;
// slow = slow.next;
// fast = fast.next.next;
// }
// return false;
// };
function hasCycle(head){
let current = head;
while(current){
if(current.val === 'seen'){
return true;
}
current.val = 'seen';
current = current.next;
}
return false;
}
//create LL
let node1 = new ListNode(1);
let node2 = new ListNode(2);
let node3 = new ListNode(3);
let node4 = new ListNode(4);
let node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node2;
console.log(hasCycle(node1)); //True |
export {default as TimeSliderTitle } from "./TimeSliderTitle";
|
import React, { Component } from 'react';
import './styles.css'
class SelectorIndex extends Component {
render() {
return (
<div className='selectorIndexCont'>
<h3>Cuéntanos, <span>¿qué eres?</span></h3>
<div className='selectionCont'>
<div>
<a className={`studentCont`} href='#/loginEstudiante'>E</a>
<p className='student'>Estudiante</p>
</div>
<div>
<a className='masterCont' href='#/loginTutor'>T</a>
<p className='tutor'>Tutor</p>
</div>
</div>
</div>
);
}
}
export default SelectorIndex; |
export const CHANGE_FORM_FIELD = 'CHANGE_FORM_FIELD';
export const CHANGE_FORM_FIELD_IN_ARRAY = 'CHANGE_FORM_FIELD_IN_ARRAY';
export const ADD_FIELD_TO_ARRAY = 'ADD_FIELD_TO_ARRAY';
export const DELETE_FIELD_FROM_ARRAY = 'DELETE_FIELD_FROM_ARRAY';
export const SET_ERROR = 'SET_ERROR';
export const SET_RESPONSE_ERROR = 'SET_RESPONSE_ERROR';
export const RESET_RESPONSE = 'RESET_RESPONSE';
export const RESET_ERRORS = 'RESET_ERRORS';
export const SET_REQUEST_LIST = 'SET_REQUEST_LIST';
export const ADD_TO_LIST = 'ADD_TO_LIST';
export const SET_REQUEST_TO_FORM = 'SET_REQUEST_TO_FORM';
export const SET_RESPONSE = 'SET_RESPONSE';
export const RESET_REQUEST = 'RESET_REQUEST';
export const METHOD = 'method';
export const URL = 'url';
export const PARAMS = 'params';
export const HEADERS = 'headers';
export const BODY = 'body';
export const ACCEPT = 'accept';
export const CACHE_CONTROL = 'cacheControl';
export const CONTENT_TYPE = 'contentType';
export const REQUEST_PAYLOAD = 'requestPayload';
export const RAW_BODY = 'rawBody';
export const COMMON = 'common';
|
export function getScroll() {
var x, y;
if(window.pageYOffset) { // all except IE
y = window.pageYOffset;
x = window.pageXOffset;
} else if(document.documentElement && document.documentElement.scrollTop) { // IE 6 Strict
y = document.documentElement.scrollTop;
x = document.documentElement.scrollLeft;
} else if(document.body) { // all other IE
y = document.body.scrollTop;
x = document.body.scrollLeft;
}
return {
X: x,
Y: y
};
}
export function getScrollTop() {
var y;
if(window.pageYOffset) { // all except IE
y = window.pageYOffset;
} else if(document.documentElement && document.documentElement.scrollTop) { // IE 6 Strict
y = document.documentElement.scrollTop;
} else if(document.body) { // all other IE
y = document.body.scrollTop;
}
return y;
}
export function getScrollLeft() {
var x;
if(window.pageYOffset) { // all except IE
x = window.pageXOffset;
} else if(document.documentElement && document.documentElement.scrollTop) { // IE 6 Strict
x = document.documentElement.scrollLeft;
} else if(document.body) { // all other IE
x = document.body.scrollLeft;
}
return x;
}
export default {
getScroll: getScroll,
getScrollTop: getScrollTop,
getScrollLeft: getScrollLeft,
}; |
/**
* first part : level 1, 3 exercices
* @returns
*/
/**
* exercise 1 : make a function to say hello
*
* @returns
*/
function hello() { // creation of the main function to display hello
return alert("Hello World !");
}
const plevel1 = document.querySelector("p.level1"); // selection of paragraph in
// the body where we want to
// localise the function hello
// call
const newElement1 = document.createElement("a"); // creation of one link to
// call the function hello
newElement1.href = "#";
newElement1.id = "helloLink"; // creation of an id to select it
newElement1.textContent = "1 - Hello world by alert"; // creation of text of
// link
plevel1.appendChild(document.createElement("br")); // insertion of a line break
plevel1.appendChild(newElement1); // add the link in the paragraph
const link1 = document.getElementById("helloLink"); // localise the link to add
// an event
link1.addEventListener("click", hello); // add call function when click
/**
* exercise 2 : make a function to add two numbers and display the result in the
* html page
*
* @returns
*/
function addTwoNb() { // creation of the main function to add two numbers
const nb1 = parseInt(prompt("Please, what is your first number ?")); // window
// to
// ask
// the
// number
const nb2 = parseInt(prompt("What is your second number ?"));
return nb1 + nb2;
}
const newElement2 = document.createElement("a"); // creation of one link to
// call the function add
newElement2.href = "#";
newElement2.id = "addLink"; // creation of an id to select it
newElement2.textContent = "2 - Add two numbers => "; // creation of text of
// link
plevel1.appendChild(document.createElement("br")); // insertion of a line break
plevel1.appendChild(newElement2); // add the link in the paragraph
const result = document.createElement("span"); // creation of a span tag to
// insert the result
result.id = "result"; // creation of an id to select it
plevel1.appendChild(result); // add the tag in the paragraph
const link2 = document.getElementById("addLink"); // localise the link to add
// an event
link2.addEventListener("click", function() { // add call function when click
const res = addTwoNb(); // the function call the add function
result.textContent = "le résultat est " + res; // insert the result in the
// tag span
});
/**
* exercise 3 : sort a table with 5 numbers and display it in the html page
*
* @returns
*/
function sortNb() { // function to sort the table
const array = [ // creation of table that contains 5 numbers
nb1 = parseInt(prompt("Please, what is your first number ?")), // window to
// ask the
// number
nb2 = parseInt(prompt("What is your second number ?")),
nb3 = parseInt(prompt("What is your third number ?")),
nb4 = parseInt(prompt("What is your fourth number ?")),
nb5 = parseInt(prompt("What is your fifth number ?")) ]
array.sort(function compare(a, b) { // function to sort the table with a
// comparator
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
if (a = b) {
return 0;
}
});
return array;
}
const newElement3 = document.createElement("a"); // creation of one link to
// call the function sort
newElement3.href = "#";
newElement3.id = "arrayLink"; // creation of an id to select it
newElement3.textContent = "3 - Sort a table of 5 numbers"; // creation of text
// of
// link
plevel1.appendChild(document.createElement("br")); // insertion of a line break
plevel1.appendChild(newElement3); // add the link in the paragraph
const insert = document.createElement("div"); // creation of a div tag to
// insert the result
insert.id = "resultarray"; // creation of an id to select it
plevel1.appendChild(insert); // add the tag in paragraph
const response = document.querySelector("#resultarray"); // select the div
// tag to insert the
// result of sort
const link3 = document.getElementById("arrayLink"); // localise the link to add
// an event
link3.addEventListener("click", function() { // add call function when click
const result = sortNb(); // the function call the add function
const answer = document.createElement("table"); // creation of table tag
answer.style.border = "solid blue 3px"; // draw the table border
answer.textContent = result; // insert the result in the table tag
response.appendChild(answer); // insert the table in the div tag
});
/**
* Second part : level 2, 1 exercise => manage a form and its insertions in a
* table
*
* @returns
*/
function validForm() // function to take a food since a form and insert it in
// object and after in a row of table
{
var parameters = location.search.substring(1).split("&"); // catch the
// elements
// whose send by
// GET
for (x in parameters) // loop for catch the value only
{
var temp = parameters[x].split("=");
thevalue = unescape(temp[1]);
thevalue = thevalue.replace("+", " ");
parameters[x] = thevalue;
}
var food = { // insert the values in an object
name : parameters[0],
category : parameters[1],
energy : parameters[2]
}
var table = document.getElementById("foodBody"); // select the table
var line = table.insertRow(-1); // insert a line in the table
for(var i in food){
line.insertCell().innerHTML = food[i];
}
/*
var col1 = line.insertCell(0); // insert a box in first column
col1.innerHTML = food.name; // insert the value of name object
var col2 = line.insertCell(1); // insert a box in second column
col2.innerHTML = food.category; // insert the value of category food
var col3 = line.insertCell(2); // insert a box in third column
col3.innerHTML = food.energy; // insert the value of energy food
*/
}
const form = document.getElementById("form"); // localise the form to add
// an event
form.addEventListener("click", validForm()); // call the function after to
// have click on submit button
// TODO CHECK THE FORM BEFORE SEND IT
function highlight(item, error) // function to underline a box whose empty
{
if (error)
item.style.backgroundColor = "#fba";
else
item.style.backgroundColor = "";
}
function test() { // function to check the form => TODO finish it
const tags = document.getElementsByTagName("input");
const lengthTags = tags.length;
console.log(tags);
console.log(lengthTags);
console.log("=>" + tags.name.value);
for (var i = 0; i != lengthTags; i++) {
if (tags[i] === "") {
highlight(tags[i], true);
} else {
highlight(tags[i], false);
}
}
}
/**
* third part : level 3, 1 exercise => make some links to display the body of
* another page in the main page
*
* @returns
*/
const replyPage = document.getElementById("displayPage");
function display(text){
replyPage.innerHTML = "<object type='text/htmlFileContent' data='"+text+"' style='width:100%'/>";
//document.getElementById("displayPage").innerHTML= "<object type='text/htmlFileContent' data='"+text+"' style='width:100%'/>";
}
|
/// <reference path="../../../../Scripts/jquery-1.7.2.min.js" />
(function ($) {
HiddenDropbox = function (_options) {
//start init
this.settings = _options;
this.ensureDefault = function (settingName, defaultValue) {
this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
};
this.ensureDefault('data', []);
this.ensureDefault('optionClass', '');
this.ensureDefault('change', function () { });
var $$this = this;
var $this = $(this);
this.enable = true;
$this.addClass('hidden-dropbox');
var id = $this.attr('id');
if ($this.children('label').length == 0) {
$this.append('<label class="hidden-dropbox-text"></label>');
}else {
$this.children('label').addClass("hidden-dropbox-text");
}
if ($this.children('input[type=hidden]').length == 0)
$this.append('<input type="hidden" id="hddValue_' + id + '" />');
if ($this.children('.hidden-dropbox-options').length == 0)
$this.append('<div class="hidden-dropbox-options ' + this.settings.optionClass + '"></div>');
this.value = $this.children('input[type=hidden]');
this.text = $this.children('label');
this.options = $this.children('.hidden-dropbox-options');
this.defaultText = $this.attr('placeholder');
if (this.defaultText == undefined)
this.defaultText = 'Chọn';
this.data = this.settings.data;
this.text.unbind('click');
this.text.bind('click', this, function (evt) {
if (evt.data.enable == false) {
alert('Bạn hãy xóa vùng khoanh trên bản đồ');
return;
}
if (evt.data.options.hasClass('hidden-dropbox-options-hover') == false) {
$('.hidden-dropbox-options').removeClass("hidden-dropbox-options-hover");
$('.hidden-dropbox').removeClass('hidden-dropbox-current');
var width = evt.data.options.width();
//var currentLeft = $this.position().left;
var currentLeft = evt.pageX;
if (currentLeft + width > $('body').width()) {
var left = -1 * (currentLeft + width + 20 - $('body').width());
evt.data.options.css('left', left + 'px');
} else {
evt.data.options.css('left', '0px');
}
evt.data.options.addClass('hidden-dropbox-options-hover');
evt.data.addClass('hidden-dropbox-current');
} else {
$('.hidden-dropbox-options').removeClass("hidden-dropbox-options-hover");
}
});
this.options.unbind('hover');
this.options.hover(function () {
$(this).addClass('hidden-dropbox-options-hover');
}, function () {
$(this).removeClass("hidden-dropbox-options-hover");
});
//end init
this.getText = function () {
return this.text.text();
}
this.getHtmlOptions = function () {
var html = '';
html = '<table border="0"><tr>';
if (this.data.length > 0 && this.data[0].length > 0) {
for (var i = 0; i < this.data.length; i++) {
html += '<td>';
for (var j = 0; j < this.data[i].length; j++) {
if (i == 0 && j == 0)
html += '<span val="" class="hidden-dropbox-options-defaultvalue">'+ this.defaultText +'</span>';
if (this.data[i][j][0] + '' == this.value.val()) {
html += '<span class="current" val="' + this.data[i][j][0] + '">' + this.data[i][j][1] + '</span>';
}
else {
html += '<span val="' + this.data[i][j][0] + '">' + this.data[i][j][1] + '</span>';
}
}
html += '</td>';
}
} else {
html += '<td><span val="" class="hidden-dropbox-options-defaultvalue"> Chọn </span></td>';
}
html += '</tr></table>';
return html;
}
this.clearValue = function () {
this.value.val('');
this.text.text(this.defaultText);
}
this.setEnable = function () {
this.enable = true;
}
this.setDisable = function () {
this.enable = false;
}
this.getValue = function () {
return this.value.val();
}
this.getValueData = function () {
var val = this.getValue();
for (var i = 0; i < this.data.length; i++) {
for (var j = 0; j < this.data[i].length; j++) {
if (this.data[i][j][0] + '' == val) {
return this.data[i][j];
}
}
}
}
this.setValue = function (val, callback) {
for (var i = 0; i < this.data.length; i++) {
for (var j = 0; j < this.data[i].length; j++) {
if (this.data[i][j][0] + '' == val) {
if (this.value.val() != val) {
this.value.val(val);
this.settings.change(this, this.settings.scope, callback);
}
this.value.val(val);
this.text.text(this.data[i][j][1]);
this.text.attr('title', this.data[i][j][1]);
this.options.find('span').removeClass('current');
this.options.find('span[val='+ val +']').addClass('current');
return;
}
}
}
this.clearValue();
}
this.ReLoadData = function (_data) {
if (_data != undefined) {
this.data = _data;
}
this.options.html(this.getHtmlOptions());
this.options.find('span').bind('click', this, function (evt) {
evt.data.text.text($(this).text());
evt.data.text.attr('title', $(this).text());
evt.data.value.val($(this).attr('val'));
evt.data.options.removeClass("hidden-dropbox-options-hover");
evt.data.options.find('span').removeClass('current');
$(this).addClass('current');
evt.data.settings.change(evt.data, evt.data.settings.scope, true);
});
///reset text value;
for (var i = 0; i < this.data.length; i++) {
for (var j = 0; j < this.data[i].length; j++) {
if (this.data[i][j][0] + '' == this.value.val()) {
this.text.text(this.data[i][j][1]);
return;
}
}
}
this.clearValue();
}
if (this.settings.value != undefined && this.settings.value != null) {
this.value.val(this.settings.value);
} else {
this.value.val('');
}
this.ReLoadData();
//start load default value
if (this.settings.value != undefined && this.settings.value != null) {
var _break = false;
for (var i = 0; i < this.data.length; i++) {
for (var j = 0; j < this.data[i].length; j++) {
if (this.data[i][j][0] + '' == this.settings.value) {
this.text.text(this.data[i][j][1]);
this.text.attr('title', this.data[i][j][1]);
this.settings.change(this, this.settings.scope);
_break = true;
break;
}
}
if (_break)
break;
}
}
//endstart load default value
return this;
}
HiddenDropbox.getValueById = function () {
var id = $(this).attr('id');
return $('#hddValue_' + id).val();
}
$.fn.HiddenDropbox = HiddenDropbox;
$.fn.HiddenDropboxValue = HiddenDropbox.getValueById;
}(jQuery)); |
import TestDraggableList from "./TestDraggableList";
export default {
title: 'component/TestDraggableList',
component: TestDraggableList
}
export const normal = () => <TestDraggableList/>; |
var Hapi = require('hapi');
var jwt = require('jsonwebtoken');
var hapiAuthJWT = require('hapi-auth-jwt2');
var couchbase = require('couchbase');
var Boom = require('boom');
var bcrypt = require('bcrypt-nodejs');
var smtpKey = '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';
var sendgrid = require('sendgrid')(smtpKey);
var Joi = require('joi');
var cluster = new couchbase.Cluster('couchbase://127.0.0.1');
var apiUsers = cluster.openBucket('apiUsers', 'apiPass');
var ViewQuery = couchbase.ViewQuery;
var secretKey = 'po3xzUXF7pZVLBkkvzec4B99HjMpqxroK9pGWiokO9Ilu2GsMPNpDrKnjtGVWyL';
function randomInt (low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
var openRoutes = require('./openRoutes');
var authRoutes = require('./authRoutes')(apiUsers, Boom, bcrypt, jwt, secretKey, sendgrid, randomInt);
var restrictedRoutes = require('./restrictedRoutes')(apiUsers, Boom, bcrypt, jwt, sendgrid);
var validate = function (decoded, request, callback) {
//console.log(decoded.email);
// Try to retrieve user account record from db based on email field in auth token
var authQuery = ViewQuery.from('user_accounts', 'list_users').key(decoded.email);
apiUsers.query(authQuery, function (err, results) {
if (err) {
// DB error
console.log(err);
return callback(null, false);
}
else {
if (results == null) {
// No results from db
return callback(null, false);
}
else if (results[0] != null && decoded.email != results[0].key) {
// Results retrieved but no email match
return callback(null, false);
}
else {
// Email account found in database. Success
return callback(null, true);
}
}
});
};
// Create a server with a host and port
var server = new Hapi.Server();
server.connection({
host: '0.0.0.0',
port: 8000,
routes: {cors: true}
});
// Register plugins
server.register(hapiAuthJWT, function (err) {
if (err){
console.log(err);
}
server.auth.strategy('jwt', 'jwt', true, {
key: secretKey,
validateFunc: validate
});
});
// Add the routes
server.route({
method: 'POST',
path: '/authenticate',
config: {
auth: false,
validate: {
payload: {
email: Joi.string().email(),
password: Joi.string().min(2)
}
}
},
handler: authRoutes.authenticate
});
server.route({
method: 'POST',
path: '/authenticate/forgot',
config: {
auth: false,
validate: {
payload: {
email: Joi.string().email()
}
}
},
handler: authRoutes.forgotPassword
});
server.route({
method: 'GET',
path: '/authenticate/forgot/{resetToken}',
config: {
auth: false,
validate: {
params: {
resetToken: Joi.string()
}
}
},
handler: authRoutes.forgotPasswordVerify
});
server.route({
method: 'POST',
path: '/register',
config: {
auth: false,
validate: {
payload: {
email: Joi.string().email().required(),
password: Joi.string().min(2).required(),
passwordConfirm: Joi.string().min(2),
firstName: Joi.string().required(),
lastName: Joi.string().required()
}
}
},
handler: authRoutes.register
});
server.route({
method: 'GET',
path: '/register/{regToken}',
config: { auth: false },
handler: authRoutes.registerToken
});
server.route({
method: 'POST',
path:'/user/password',
config: {
auth: 'jwt',
validate: {
payload: {
email: Joi.string().email().required(),
oldPassword: Joi.required(),
password: Joi.string().min(2).required(),
passwordConfirm: Joi.string().min(2).required()
}
}
},
handler: restrictedRoutes.changePassword
});
server.route({
method: 'GET',
path:'/hello',
config: {auth: false},
handler: openRoutes.hello
});
// Start the server
server.start();
|
import React from 'react'
import {connect} from 'react-redux'
import Product from './Product'
import {CardDeck} from 'react-bootstrap'
class AllProducts extends React.Component {
render() {
const {products} = this.props
if (!products) {
return <h1>Loading!</h1>
} else {
return (
<div>
<h4 className="page-head">ALL-PRODUCTS</h4>
<CardDeck className="allProducts">
{products.map(currentProduct => {
return <Product key={currentProduct.id} {...currentProduct} />
})}
</CardDeck>
</div>
)
}
}
}
const mapStateToProps = state => ({
products: state.allProducts
})
const Products = connect(mapStateToProps, null)(AllProducts)
export default Products
|
const router = require('express').Router();
const TeacherController = require('../Controllers/TeacherController');
const ResponseError = require('../../Enterprise_business_rules/Manage_error/ResponseError');
const { TYPES_ERROR } = require('../../Enterprise_business_rules/Manage_error/codeError');
const errorToStatus = require('../../Frameworks_drivers/errorToStatus');
/* List Teachers */
router.get('/', async (req, res, next) => {
try {
// Comprobamos que se reciben el idAdmin y el idUser
if (!req.body.id) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El ID es necesario para listar los usuarios', 'incomplete_data');
}
// Comprobamos que los ids recibidos son números
if (Number.isNaN(Number(req.body.id))) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El ID debe ser un número', 'id_format_error');
}
const teachers = await TeacherController.listTeachers(req.body.id);
res.json(teachers);
} catch (err) {
next(err);
}
});
/* Get Teacher */
router.get('/:id', async (req, res, next) => {
try {
// Comprobamos que se reciben el idAdmin y el idUser
if (!req.params.id || !req.body.id) {
throw new ResponseError(TYPES_ERROR.FATAL, 'Los ids deben ser números', 'incomplete_data');
}
// Comprobamos que los ids recibidos son números
if (Number.isNaN(Number(req.params.id)) || Number.isNaN(Number(req.body.id))) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El ID debe ser un número', 'id_format_error');
}
const teacher = await TeacherController.getTeacher({ usersData: { idAdmin: req.params.id, idUser: req.body.id } });
res.json(teacher);
} catch (err) {
next(err);
}
});
/* Create Teacher */
router.post('/:id', async (req, res, next) => {
try {
const { name, fSurname, sSurname, email } = req.body;
// Se comprueba si algún dato requerido no ha sido introducido
if (!name || !fSurname || !sSurname || !email || !req.params.id) {
throw new ResponseError(TYPES_ERROR.ERROR, 'Los parámetros introducidos no son incorrectos o están incompletos', 'incomplete_data');
}
const teacher = await TeacherController.createTeacher({ teacherData: { idAdmin: req.params.id, name, fSurname, sSurname, email } });
res.json(teacher);
} catch (err) {
next(err);
}
});
/* Modify Teacher */
router.put('/:id', async (req, res, next) => {
try {
// Se comprueba que se ha recibido el idAdmin y el del usuario
if (!req.params.id || !req.body.id) {
throw new ResponseError(TYPES_ERROR.FATAL, 'Los IDs son necesarios para actualizar el profesor', 'id_empty');
}
// Se comrprueba que los IDs sean números
if (Number.isNaN(Number(req.params.id)) || Number.isNaN(Number(req.body.id))) {
throw new ResponseError(TYPES_ERROR.FATAL, 'Los IDs deben ser números', 'id_format_error');
}
// Se comprueba que al menos exista un dato para ser actualizado
const { name, fSurname, sSurname, email } = req.body;
if (!name && !fSurname && !sSurname && !email) {
throw new ResponseError(TYPES_ERROR.ERROR, 'Es necesario al menos un parámetro para actualizar', 'incomplete_data');
}
const usersData = {
idAdmin: req.params.id,
...req.body,
};
await TeacherController.updateTeacher({ usersData });
res.json({ state: 'OK' });
} catch (err) {
next(err);
}
});
/* Delete Teacher */
router.delete('/:id', async (req, res, next) => {
try {
// Comprobamos que se reciben el idAdmin y el idUser
if (!req.params.id || !req.body.id) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El ID debe ser un número', 'incomplete_data');
}
// Comprobamos que los ids recibidos son números
if (Number.isNaN(Number(req.params.id)) || Number.isNaN(Number(req.body.id))) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El ID debe ser un número', 'id_format_error');
}
await TeacherController.deleteTeacher({ usersData: { idAdmin: req.params.id, idUser: req.body.id } });
res.json({ state: 'OK' });
} catch (err) {
next(err);
}
});
// eslint-disable-next-line no-unused-vars
router.use((err, req, res, next) => {
const status = errorToStatus(err);
res.status(status).json(err.toJSON());
});
module.exports = router;
|
import ReactDOMComponent from 'react/lib/ReactDOMComponent';
var assign = require('Object.assign');
var warning = require('fbjs/lib/warning');
var voidElementTags = assign({
'menuitem': true
}, omittedCloseTags);
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
};
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (process.env.NODE_ENV !== 'production') {
if (voidElementTags[component._tag]) {
process.env.NODE_ENV !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined;
}
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined;
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined;
}
!(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined;
}
class ReactFastUpdateDOMComponent extends ReactDOMComponent {
updateComponent(transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'button':
lastProps = ReactDOMButton.getNativeProps(this, lastProps);
nextProps = ReactDOMButton.getNativeProps(this, nextProps);
break;
case 'input':
ReactDOMInput.updateWrapper(this);
lastProps = ReactDOMInput.getNativeProps(this, lastProps);
nextProps = ReactDOMInput.getNativeProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getNativeProps(this, lastProps);
nextProps = ReactDOMOption.getNativeProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getNativeProps(this, lastProps);
nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
lastProps = ReactDOMTextarea.getNativeProps(this, lastProps);
nextProps = ReactDOMTextarea.getNativeProps(this, nextProps);
break;
}
assertValidProps(this, nextProps);
if (!nextProps.__lazy) {
this._updateDOMProperties(lastProps, nextProps, transaction);
}
this._updateDOMChildren(lastProps, nextProps, transaction, context);
if (this._tag === 'select') {
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
}
}
}
module.exports = ReactFastUpdateDOMComponent;
|
import React, { Component } from 'react';
import 'whatwg-fetch';
import { throttle } from '../utils';
import KanbanBoard from './KanbanBoard';
const API_URL = 'http://kanbanapi.pro-react.com';
const API_HEADERS = {
'Content-Type': 'application/json',
Authorization: 'meowmeowbeanz'
};
class App extends Component {
constructor(props) {
super(props);
this.state = {
cards: []
};
this.addCard = this.addCard.bind(this);
this.addTask = this.addTask.bind(this);
this.deleteTask = this.deleteTask.bind(this);
this.toggleTask = this.toggleTask.bind(this);
this.updateCard = this.updateCard.bind(this);
this.updateCardStatus = throttle(this.updateCardStatus.bind(this));
this.updateCardPosition = throttle(this.updateCardPosition.bind(this), 500);
this.persistCardDrag = this.persistCardDrag.bind(this);
}
componentDidMount() {
fetch(`${API_URL}/cards`, { headers: API_HEADERS })
.then(response => response.json())
.then(responseData => {
this.setState({ cards: responseData })
})
.catch(error => {
console.error('Error fetching and parsing data', error);
});
}
addCard(card) {
const previousState = this.state,
{ cards } = this.state;
let nextState,
nextCards;
if (card.id === null) {
card = Object.assign({}, card, { id: Date.now() });
}
nextCards = [
...cards,
card
];
this.setState({ cards: nextCards });
fetch(`${API_URL}/cards`, {
method: 'post',
headers: API_HEADERS,
body: JSON.stringify(card)
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Server response wasn't OK");
}
})
.then(responseData => {
card.id = responseData.id;
this.setState({ cards: nextCards });
})
.catch(error => {
this.setState(previousState);
});
}
updateCard(updatedCard) {
const previousState = this.state,
{ cards } = this.state;
let cardIndex,
nextCards;
cardIndex = cards.findIndex(card => card.id === updatedCard.id);
nextCards = [
...cards.slice(0, cardIndex),
updatedCard,
...cards.slice(cardIndex + 1)
];
this.setState({ cards: nextCards });
fetch(`${API_URL}/cards/${updatedCard.id}`, {
method: 'PUT',
headers: API_HEADERS,
body: JSON.stringify(updatedCard)
})
.then(response => {
if (!response.ok) {
throw new Error("Server response wasn't OK");
}
})
.catch(error => {
console.error("Fetch error:", error);
this.setState(previousState);
});
}
addTask(cardId, taskName) {
let previousState = this.state,
{ cards } = this.state,
cardIndex,
card,
tasks,
nextTask,
nextTasks,
nextCard,
nextCards;
cardIndex = cards.findIndex(card => card.id === cardId);
card = cards[cardIndex];
tasks = card.tasks;
nextTask = { id: Date.now(), name: taskName, done: false };
nextTasks = [
...tasks,
nextTask
];
nextCard = Object.assign({}, card, {
tasks: nextTasks
});
nextCards = [
...cards.slice(0, cardIndex),
nextCard,
...cards.slice(cardIndex + 1)
];
this.setState({ cards: nextCards })
fetch(`${API_URL}/cards/${cardId}/tasks`, {
headers: API_HEADERS,
method: 'post',
body: JSON.stringify(nextTask)
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Server response wasn't OK");
}
})
.then(responseData => {
nextTask.id = responseData.id;
this.setState({ cards: nextCards })
})
.catch(error => {
this.setState(previousState);
});
}
deleteTask(cardId, taskId, taskIndex) {
let previousState = this.state,
{ cards } = this.state,
cardIndex,
card,
tasks,
nextTasks,
nextCard,
nextCards;
cardIndex = cards.findIndex(card => card.id === cardId);
card = cards[cardIndex];
tasks = card.tasks;
nextTasks = [
...tasks.slice(0, taskIndex),
...tasks.slice(taskIndex + 1),
];
nextCard = Object.assign({}, card, {
tasks: nextTasks
});
nextCards = [
...cards.slice(0, cardIndex),
nextCard,
...cards.slice(cardIndex + 1)
];
this.setState({ cards: nextCards })
fetch(`${API_URL}/cards/${cardId}/tasks/${taskId}`, {
headers: API_HEADERS,
method: 'delete'
})
.then(response => {
if (!response.ok) {
throw new Error("Server response wasn't OK");
}
})
.catch(error => {
console.error('Fetch error:', error);
this.setState(previousState);
});
}
toggleTask(cardId, taskId, taskIndex) {
let previousState = this.state,
{ cards } = this.state,
cardIndex,
card,
tasks,
task,
nextDone,
nextTask,
nextTasks,
nextCard,
nextCards;
cardIndex = cards.findIndex(card => card.id === cardId);
card = cards[cardIndex];
tasks = card.tasks;
task = tasks.find(task => task.id === taskId);
nextDone = !task.done;
nextTask = Object.assign({}, task, {
done: nextDone
});
nextTasks = [
...tasks.slice(0, taskIndex),
nextTask,
...tasks.slice(taskIndex + 1),
];
nextCard = Object.assign({}, card, {
tasks: nextTasks
});
nextCards = [
...cards.slice(0, cardIndex),
nextCard,
...cards.slice(cardIndex + 1)
];
this.setState({ cards: nextCards })
fetch(`${API_URL}/cards/${cardId}/tasks/${taskId}`, {
headers: API_HEADERS,
method: 'put',
body: JSON.stringify({ done: nextDone })
})
.then(response => {
if (!response.ok) {
throw new Error("Server response wasn't OK");
}
})
.catch(error => {
console.error('Fetch error:', error);
this.setState(previousState);
});
}
updateCardStatus(cardId, listId) {
let previousState = this.state,
{ cards } = this.state,
cardIndex,
card,
nextCard,
nextCards;
cardIndex = cards.findIndex(card => card.id === cardId);
card = cards[cardIndex];
if (card.status !== listId) {
nextCard = Object.assign({}, card, {
status: listId
});
nextCards = [
...cards.slice(0, cardIndex),
nextCard,
...cards.slice(cardIndex + 1)
];
this.setState({
cards: nextCards
});
}
}
updateCardPosition(cardId, afterId) {
let previousState = this.state,
{ cards } = this.state,
cardIndex,
card,
afterIndex,
nextCard,
nextCards;
if (cardId !== afterId) {
cardIndex = cards.findIndex(card => card.id === cardId);
card = cards[cardIndex];
nextCards = [
...cards.slice(0, cardIndex),
...cards.slice(cardIndex + 1)
];
afterIndex = cards.findIndex(card => card.id === afterId);
nextCards.splice(afterIndex, 0, card);
this.setState({
cards: nextCards
});
}
}
persistCardDrag(cardId, status) {
const { cards } = this.state;
let cardIndex,
previousCards,
previousCard;
cardIndex = cards.findIndex(card => card.id === cardId);
const card = cards[cardIndex];
fetch(`${API_URL}/cards/${cardId}`, {
method: 'put',
headers: API_HEADERS,
body: JSON.stringify({ status: card.status, row_order_position: cardIndex })
})
.then(response => {
if (!response.ok) {
throw new Error("Server response wasn't OK");
}
})
.catch(error => {
console.error('Fetch error:', error);
previousCard = Object.assign({}, card, { status });
previousCards = [
...cards.slice(0, cardIndex),
previousCard,
...cards.slice(cardIndex + 1),
];
this.setState({ cards: previousCards });
})
}
render() {
const { children } = this.props,
{ cards } = this.state;
let kanbanBoard = children && React.cloneElement(children, {
cards,
taskCallbacks: {
toggle: this.toggleTask,
remove: this.deleteTask,
add: this.addTask
},
cardCallbacks: {
addCard: this.addCard,
updateCard: this.updateCard,
updateStatus: this.updateCardStatus,
updatePosition: this.updateCardPosition,
persistCardDrag: this.persistCardDrag
}
});
return kanbanBoard;
}
}
export default App;
|
'use strict';
const scriptInfo = {
name: 'idle',
desc: 'Provide random gibberish should the primary channel be inactive for to long',
createdBy: 'IronY'
};
const _ = require('lodash');
const fml = require('../generators/_fmlLine');
const bofh = require('../generators/_bofhExcuse');
const shower = require('../generators/_showerThoughts');
const moment = require('moment');
const logger = require('../../lib/logger');
const Models = require('bookshelf-model-loader');
const scheduler = require('../../lib/scheduler');
// New and Improved
module.exports = app => {
// Gate
if (!Models.Logging ||
_.isUndefined(app.Config.features.idleChat) ||
app.Config.features.idleChat.enabled !== true ||
!_.isSafeInteger(app.Config.features.idleChat.timeOutInMins) ||
!_.isArray(app.Config.features.idleChat.channels) ||
_.isEmpty(app.Config.features.idleChat.channels)
) return scriptInfo;
// Clear cache every four hours on the 30 min mark
scheduler.schedule('checkIdleChat', {
minute: 0 // First min of every hour
}, () => {
isActive();
});
const isActive = () => {
let promises = [];
let timeoutInMins = app.Config.features.idleChat.timeOutInMins;
let channels = app.Config.features.idleChat.channels;
// Log Chance
logger.info('Checking for idleChat timeout');
// Iterate over channels
_.forEach(channels, channel => {
// Bot must be a Op or Voice in the channel
if (!app._ircClient.isOpOrVoiceInChannel(channel)) return;
// Push on to promises chain
promises.push(
Models.Logging.query(qb => qb
.select(['timestamp'])
.where('to', 'like', channel)
.orderBy('timestamp', 'desc')
.limit(1)
)
.fetch()
.then(result => {
// Parse timestamp into Moment.js
let lastTime = moment(result.get('timestamp'));
// Get time diff between now and previous timestamp
let timeDiffInMins = moment().diff(lastTime, 'minutes');
// Verify the channel has been active
if (timeDiffInMins < timeoutInMins) return;
// Send to the message
_.sample([fml, bofh, shower])(1)
.then(message => app.notice(channel, _.first(message)));
})
);
});
// Resolve the results
Promise
.all(promises)
.catch(err => logger.error('Error in idleChat Promise chain', {
err
}));
};
return scriptInfo;
};
|
import React, {useState, useEffect} from 'react';
import {Alert, StyleSheet, Text, TouchableOpacity, View, Modal, TouchableHighlight} from 'react-native';
import {colors} from '../../utils/colors';
import Icon from 'react-native-vector-icons/FontAwesome';
import {ScrollView, TextInput} from 'react-native-gesture-handler';
import DropDownPicker from 'react-native-dropdown-picker';
import Axios from 'axios';
import {useSelector, useDispatch} from 'react-redux';
import {Rupiah} from '../../helper/Rupiah';
import {ButtonCustom, Header2, Releoder} from '../../component';
import {useIsFocused} from '@react-navigation/native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Config from 'react-native-config';
const Transfer = ({navigation, route}) => {
const data1 = [
{
label: '---',
value: '---',
icon: () => <Icon name="user" size={18} color="#900" />,
},
];
const [isLoading, setIsLoading] = useState(true);
const [point, setPoint] = useState(0);
const [member, setMember] = useState([]);
const userReducer = useSelector((state) => state.UserReducer);
const TOKEN = useSelector((state) => state.TokenApi);
const [userTujuan, setUserTujuan] = useState(null);
const [nominalTransfer, setNominalTransfer] = useState(0);
const [phone, setPhone] = useState(null)
const [userSelect, setUserSelect] = useState(null)
const isFocused = useIsFocused();
const [code, setCode] = useState('');
let isMounted = true
const [modalVisible, setModalVisible] = useState(false);
const [codeOTP, setCodeOTP] = useState('');
useEffect(() => {
// selectScanMember()
// setUserSelect(null)
isMounted = true
setPhone(null)
getPoint();
getMember();
if(route.params){
setPhone(route.params.dataScan)
}
}, [])
const dateRegister = () => {
var todayTime = new Date();
var month = todayTime.getMonth() + 1;
var day = todayTime.getDate();
var year = todayTime.getFullYear();
return year + "-" + month + "-" + day;
}
const selectScanMember = () => {
// setIsLoading(true)
if(route.params){
if(route.params.dataScan){
Axios.post(Config.API_MEMBER_SHOW, {phone : route.params.dataScan},
{
headers: {
Authorization: `Bearer ${TOKEN}`,
'Accept' : 'application/json' ,
'content-type': 'application/json'
}
}
).then((result) => {
setUserSelect(result.data.data.id)
setUserTujuan(result.data.data.id)
setIsLoading(false)
console.log('id',result.data.data.id)
}).catch((e) => {
console.log(e)
navigation.navigate('MenuScan');
})
}
}else{
setIsLoading(false)
}
return () => { isMounted = false };
};
const getPoint = () => {
Axios.get(Config.API_POINT +`${userReducer.id}`, {
headers : {
Authorization: `Bearer ${TOKEN}`,
'Accept' : 'application/json'
}
})
.then((result) => {
// console.log('data point api', result.data)
setPoint(parseInt(result.data.data[0].balance_points))
// if(phone ===null){
// // console.log('jalan')
// setIsLoading(false)
// }
});
}
const getMember = () => {
// setUserSelect(null)
// setIsLoading(true)
Axios.get(Config.API_MEMBER , {
headers : {
Authorization: `Bearer ${TOKEN}`,
'Accept' : 'application/json'
}
})
.then((result) => {
// console.log('data point api', result.data)
result.data.data.map((data, index) => {
data1[index] = {
label: data.name + ' - ' + data.code,
value: data.id,
icon: () => <Icon name="user" size={18} color="#900" />,
};
});
setMember(data1);
selectScanMember()
});
}
const Transfer = () => {
setIsLoading(true)
if(nominalTransfer > 0 && userTujuan !== null){
var data = {
register : dateRegister(),
amount : nominalTransfer,
from : userReducer.id,
to : userTujuan
}
Axios.post(Config.API_TRANSFER, data,
{
headers: {
Authorization: `Bearer ${TOKEN}`,
'Accept' : 'application/json' ,
'content-type': 'application/json'
}
}
).then((result) => {
console.log('transefer',result.data)
// alert('tansfer sukses')
navigation.navigate('NotifAlert', {notif: 'Transaksi Sukses'})
setNominalTransfer(0)
setModalVisible(false)
setIsLoading(false)
}).catch((e) => {
alert('tansfer gagal, jika tetap hubungi admin')
console.log(e)
setIsLoading(false)
})
console.log(data)
setIsLoading(false)
}
}
const generateCodeOTP = () => {
setModalVisible(true)
var digits = '0123456789';
let OTP = '';
for (let i = 0; i < 5; i++ ) {
OTP += digits[Math.floor(Math.random() * 10)];
}
setCodeOTP(OTP)
}
useEffect(() => {
// send otp
if(codeOTP !== ''){
Axios.post(Config.API_NUSA_SMS + `&SMSText=${codeOTP}&GSM=${userReducer.phone.replace(0, "62")}&otp=Y&output=json`)
.then((res) => {
alert('Otp Send via SMS')
console.log(res)
}).catch((err)=>{
console.log('gagal')
})
}
}, [codeOTP])
const verifyOtp = () => {
// console.log(route.params.phone)
// console.log(code)
console.log(codeOTP)
if(code === codeOTP){
Transfer()
}else{
alert('OTP SALAH')
}
}
if (isLoading) {
return (
<Releoder/>
)
}
return (
<SafeAreaView style={styles.container}>
{/* modal */}
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<TouchableOpacity onPress={() => {setModalVisible(!modalVisible)}}>
<Icon name='times' size={20}/>
</TouchableOpacity>
<View style={{alignItems : 'center'}}>
<Text style={{fontSize : 20, fontWeight : 'bold'}}>Code OTP</Text>
<TextInput
placeholder= '****'
keyboardType='number-pad'
secureTextEntry={true}
maxLength ={5}
style={{borderWidth : 1, width : '100%', marginTop : 30, borderRadius : 10, borderColor : colors.disable, textAlign : 'center', fontSize : 30}}
onChangeText ={(value) => setCode(value)}
/>
<TouchableHighlight
style={{ marginTop : 50, borderWidth : 1, padding : 10, width : '100%', alignItems:'center', justifyContent : 'center', borderRadius : 10, borderColor : colors.btn, backgroundColor : colors.btn}}
onPress={() => {
verifyOtp()
}}
>
<Text style={{color : '#ffffff', fontWeight : 'bold'}}>Submit</Text>
</TouchableHighlight>
</View>
</View>
</View>
</Modal>
{/* modal */}
<View style={{alignItems:'center', justifyContent : 'center'}}>
</View>
<View style={{flex: 1}}>
<Header2 title ='Transfer' btn={() => navigation.goBack()}/>
<View style={{padding: 20}}>
{/* {console.log('data yang di render', item1)} */}
<DropDownPicker
placeholder = 'Select Member'
searchable={true}
searchablePlaceholder="Search users"
searchablePlaceholderTextColor="gray"
seachableStyle={{}}
dropDownMaxHeight = '85%'
searchableError={() => <Text>Not Found</Text>}
items={
member
}
defaultValue ={userSelect != null ? userSelect : ''}
containerStyle={{height: 60}}
style={{
borderBottomWidth: 1,
borderBottomColor: colors.disable,
fontSize: 15,
}}
itemStyle={{
justifyContent: 'flex-start',
}}
dropDownStyle={{backgroundColor: '#fafafa'}}
onChangeItem={(item) => setUserTujuan(item.value)}
/>
<Text style={{marginTop: 40, color: '#bbbbbb'}}>Sumber dana</Text>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
borderWidth: 1,
marginTop: 10,
borderColor: colors.disable,
padding: 15,
borderRadius: 10,
}}>
<Icon
name="credit-card"
size={30}
color={colors.default}
style={{marginRight: 20}}
/>
<View>
<Text style={{fontWeight: 'bold'}}>Minyak Belog Cash</Text>
<Text style={{color: colors.dark}}>
Saldo {Rupiah(point)}
</Text>
</View>
</View>
<View
style={{backgroundColor: '#fbf6f0', marginTop: 20, padding: 15}}>
<Text style={{color: colors.dark}}>Nominal Transfer</Text>
<TextInput
placeholder="Rp."
style={{fontSize: 30}}
keyboardType="number-pad"
value={isNaN(nominalTransfer.toString()) ? '0' : nominalTransfer.toString()}
onChangeText={(value) => setNominalTransfer(parseInt(value))}
/>
</View>
<Text style={{color: colors.dark, marginTop: 40}}>
Pesan (opsional)
</Text>
</View>
</View>
<View
// style={{display: display}}
style={{
backgroundColor: '#ffffff',
height: 55,
// borderWidth: 1,
// borderColor: colors.disable,
alignItems: 'center',
justifyContent: 'center',
// color : nominalTransfer
}}>
{isNaN(nominalTransfer.toString()) ? setNominalTransfer(0) : (nominalTransfer != 0 && userTujuan !==null ? (
nominalTransfer <= point ? (
<ButtonCustom
name='Transfer'
width= '85%'
color= {colors.btn}
// func = {() => {generateCodeOTP(); setModalVisible(true)}}
func = {() => Alert.alert(
'Peringatan',
`Anda akan melakukan Transfer ? `,
[
{
text : 'Tidak',
onPress : () => console.log('tidak')
},
{
text : 'Ya',
onPress : () => {Config.OTP ==1 ? generateCodeOTP() : Transfer() }
}
]
)}
/>
):(
<ButtonCustom
name='Trasnfer'
width= '85%'
color= {colors.disable}
func = {() => alert('Poin Anda Kurang ')}
/>
)
) : (
<ButtonCustom
name='Trasnfer'
width= '85%'
color= {colors.disable}
func = {() => alert('Data belum Lengkap')}
/>
))}
</View>
</SafeAreaView>
);
};
export default Transfer;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ffffff',
},
header: {
paddingHorizontal: 20,
paddingVertical: 10,
flexDirection: 'row',
backgroundColor: colors.default,
alignItems: 'center',
},
btnBack: {
marginRight: 10,
},
textTopUp: {
color: '#ffffff',
fontSize: 20,
fontWeight: 'bold',
},
textTambahKartu: {
marginTop: 10,
color: colors.dark,
},
modalView: {
marginHorizontal: 20,
backgroundColor: "white",
height : 300,
marginTop : '60%',
borderRadius: 20,
padding: 35,
// alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
btnTransfer :{
borderWidth: 1,
borderRadius: 10,
height : 45,
alignItems : 'center',
justifyContent : 'center',
backgroundColor: colors.default,
borderColor: colors.default,
paddingHorizontal: 100,
paddingVertical: 5,
width : 350
},
btnTransfer1:{
borderWidth: 1,
borderRadius: 10,
height : 45,
alignItems : 'center',
justifyContent : 'center',
backgroundColor: colors.disable,
borderColor: colors.disable,
paddingHorizontal: 100,
paddingVertical: 5,
width : 350
}
});
|
"use strict";
$(document).ready(function() {
// Process about button: Pop up a message with an Alert
function about() {
alert(ODSA.AV.aboutstring(interpret(".avTitle"), interpret("av_Authors")));
}
$('#about').click(about);
// Processes the reset button
function initialize() {
// if (JSAV_EXERCISE_OPTIONS.code)
// av.clear();
// JSAV_EXERCISE_OPTIONS.code = "delete";
//config = ODSA.UTILS.loadConfig();
// code = config.code; // get the code object
// pseudo = av.code(code[0]);
clearInterval(intv);
if (stack)
stack.clear(); // Clear the numbers in the stack.
if (userArr)
userArr.clear(); // Clear the array.
//if (pseudo)
// pseudo.clear();
//pseudo = av.code({url: "delete_code.txt", lineNumbers: false})
initialArray = genArrNoRepeat(89, arraySize) // Generate the array values.
stack = createStackLayout(av);
stackArray = [];
for (var i = 0; i < stackSize; i++) {
var value = initialArray[Math.floor(Math.random() * initialArray.length)]
while (stackArray.includes(value))
value = initialArray[Math.floor(Math.random() * initialArray.length)]
stackArray[i] = value
stack.addLast(value);
}
// Highlight the top number of the stack.
stack.first().highlight();
stack.layout();
// Create the array the user will intereact with and highlight the first value
userArr = createArrayLayout(av, initialArray, true, arrayLayout.val())
addArrayClick()
return userArr;
}
// Add a click event to userArr
function addArrayClick() {
userArr.click(function(index) {
userArr.unhighlight(getHighlight(userArr))
userArr.highlight(index)
av.gradeableStep()
});
}
// Create the model solution used for grading the exercise
function modelSolution(modelav) {
// create stack and populate with values from stackArray
modelStack = createStackLayout(modelav)
modelStack = buildStackFromArr(stackArray, stackSize, modelStack)
modelStack.layout();
modelStack.first().highlight();
var modelArr = createArrayLayout(modelav, initialArray, true, arrayLayout.val())
modelav.displayInit();
while (modelStack.size() > 0) {
var ind = 1
modelArr.highlight(0)
modelav.gradeableStep()
while (modelArr.value(ind) <= modelStack.first().value() && modelArr.value(ind) != "") {
moveHighlight(ind - 1, ind, modelArr)
modelav.gradeableStep();
ind++;
}
ind--;
modelArr.unhighlight(ind);
modelArr.addClass(ind, "correctIndex");
modelav.gradeableStep();
modelStack.removeFirst()
modelArr.removeClass(getFirstIndWithClass(modelArr, "correctIndex"), "correctIndex")
modelArr.value(ind, "");
while (ind < arraySize - 1) {
modelArr.value(ind, modelArr.value(ind + 1));
modelArr.value(ind + 1, "");
ind++;
}
modelav.step();
}
return modelArr;
}
// Fixstate function called if continuous feedback/fix mode is used
function fixState(modelState) {
var modelArray = modelState[0];
// Get the raw array elements so we can access their list of class names
var modArrElems = JSAV.utils._helpers.getIndices($(modelArray.element).find("li"));
var userArrElems = JSAV.utils._helpers.getIndices($(userArr.element).find("li"));
for (var i = 0; i < modelArray.size(); i++) {
// Fix any incorrect values
userArr.value(i, modelArray.value(i))
// Ensure the classes of each element in the user array match those in the model solution
userArrElems[i].className = modArrElems[i].className;
}
}
function deleteButton() {
if (arrHasHighlight(userArr)) {
var hlPos = getHighlight(userArr);
var array_value = userArr.value(hlPos);
if (array_value == stack.first().value()) {
userArr.addClass(hlPos, "correctIndex")
userArr.unhighlight(hlPos)
exercise.gradeableStep()
stack.removeFirst()
if (stack.size() > 0) // If the stack is not empty
stack.first().highlight() // highlight the top value.
}
else {
userArr.addClass(hlPos, "wrongIndex")
userArr.unhighlight(hlPos)
exercise.gradeableStep()
}
var ind = hlPos;
userArr.value(hlPos, "");
intv = setInterval(function animateStep() {
while (ind < arraySize - 1) {
userArr.value(ind, userArr.value(ind + 1))
userArr.value(ind + 1, "")
ind++;
}
stopAnimation()
}, 1400)
userArr.removeClass(getFirstIndWithClass(userArr, "correctIndex"), "correctIndex");
userArr.removeClass(getFirstIndWithClass(userArr, "wrongIndex"), "wrongIndex");
}
}
$('#Delete').click(deleteButton)
//////////////////////////////////////////////////////////////////
// Start processing here
//////////////////////////////////////////////////////////////////
var arraySize = 13,
stackSize = 5,
initialArray = [],
stack,
intv,
modelStack,
stackArray,
pseudo,
code,
// Load the config object with interpreter created by odsaUtils.js
config = ODSA.UTILS.loadConfig(),
interpret = config.interpreter, // get the interpreter
code = config.code,
codeOptions = {
after: {element: $(".instructions")},
visible: true
},
settings = config.getSettings(), // Settings for the AV
av = new JSAV($('.avcontainer'), {
settings: settings
});
av.recorded(); // we are not recording an AV with an algorithm
// show a JSAV code instance only if the code is defined in the parameter
// and the parameter value is not "none"
//if (code)
// pseudo = av.code($.extend(codeOptions, code));
var exercise = av.exercise(modelSolution, initialize, {
compare: {css: "backgroundColor"},//feedback: "continuous",
controls: $(".jsavexercisecontrols")
});
// add the layout setting prelow, high, valference
var arrayLayout = settings.add("layout", {
"type": "select",
"options": {
"bar": "Bar",
"array": "Array"
},
"label": "Array layout: ",
"value": "array"
});
exercise.reset();
// Initialize userArr
var userArr; // JSAV array
});
|
import styled from "styled-components";
export const Wrapper = styled.div`
position: relative;
transform: translateY(-30px);
`;
|
import React from 'react'
const TableHeader = () =>{
return(
<thead>
<tr>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
)
}
// class TableHeader extends Component {
// render() {
// return (
// <thead>
// </thead>
// )
// }
// }
export default TableHeader; |
// JavaScript Document
function pidChange(){
var pid = document.getElementById("prodid").value;
if(pid.length!=0){
getprice("id",pid);
}
else
document.getElementById("prodname").disabled=false;
document.getElementById("prodname").value="";
document.getElementById("quantity").setAttribute("placeholder","");
}
function pnameChange(){
var pname = document.getElementById("prodname").value;
if(pname.length!=0){
getprice("name",pname);
}
else
document.getElementById("prodid").disabled=false;
document.getElementById("prodid").value="";
document.getElementById("quantity").setAttribute("placeholder","");
}
/*function phsnChange(){
var phsn = document.getElementById("prodhsn").value;
if(phsn.length!=0){
getprice("hsn",phsn);
}
else
document.getElementById("prodid").disabled=false;
document.getElementById("prodid").value="";
document.getElementById("quantity").setAttribute("placeholder","");
}*/
//transaction 1st half validate
function transadd(){
var id = document.getElementById("prodid").value;
var name = document.getElementById("prodname").value;
//var hsn = document.getElementById("prodhsn").value;
var q = document.getElementById("quantity").value;
var d = document.getElementById("discount").value;
//if(id!=0 & id.length & name.length & q.length & q!=0) {
addData();
//document.getElementById("prodid").value = document.getElementById("prodname").value = document.getElementById("quantity").value = "";
//document.getElementById("quantity").setAttribute("placeholder","");
//document.getElementById("itemPrice").innerHTML="";
//}
//else {
//alert("Errors in input. Please fix them");
//return false;
//}
}
function validate(){
if(document.getElementById("discount").value==""){
document.getElementById("discount").value=0;
}
if(document.getElementById("cid").value==""){
document.getElementById("cid").value=0;
}
return true;
}
|
import { default as Edge } from './edge.js';
import { default as EdgeSemantics } from './index.semantical.js';
import { default as EdgePresentation } from './index.presentational.js';
export { Edge, EdgeSemantics, EdgePresentation };
|
const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
return sequelize.define('CatalogProductEntityMediaGalleryValueVideo', {
value_id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
comment: "Media Entity ID",
references: {
model: 'catalog_product_entity_media_gallery',
key: 'value_id'
}
},
store_id: {
type: DataTypes.SMALLINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: "Store ID",
references: {
model: 'store',
key: 'store_id'
}
},
provider: {
type: DataTypes.STRING(32),
allowNull: true,
comment: "Video provider ID"
},
url: {
type: DataTypes.TEXT,
allowNull: true,
comment: "Video URL"
},
title: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Title"
},
description: {
type: DataTypes.TEXT,
allowNull: true,
comment: "Page Meta Description"
},
metadata: {
type: DataTypes.TEXT,
allowNull: true,
comment: "Video meta data"
}
}, {
sequelize,
tableName: 'catalog_product_entity_media_gallery_value_video',
timestamps: false,
indexes: [
{
name: "CAT_PRD_ENTT_MDA_GLR_VAL_VIDEO_VAL_ID_STORE_ID",
unique: true,
using: "BTREE",
fields: [
{ name: "value_id" },
{ name: "store_id" },
]
},
{
name: "CAT_PRD_ENTT_MDA_GLR_VAL_VIDEO_STORE_ID_STORE_STORE_ID",
using: "BTREE",
fields: [
{ name: "store_id" },
]
},
]
});
};
|
import React from "react";
import "./ProjectWindow.css";
import Draggable from "react-draggable";
const ProjectWindow = (props) => {
const renderProjectWindow = () => {
if (props.projectDisplay === true) {
return (
<>
<Draggable handle="#handle" onMouseDown={(e) => props.onStart(e)}>
<div className="project-window-container">
<div className="project-header" id="handle">
<p>Project 1</p>
<p
className="close-project"
onClick={() =>
props.setProjectDisplay(false)
}
>
X
</p>
</div>
</div>
</Draggable>
</>
);
}
};
return <>{renderProjectWindow()}</>;
};
export default ProjectWindow;
|
const dbquery = require('./dbquery');
const client = require('./redisClient');
exports.GetAllStops = (req, res) => {
let routeid = req.body.route_id;
client.lrange(routeid, 0, -1, function (error, result) {
if (error) console.error();
if (result && result.length) {
console.log("from redis");
res.send(result);
}
else{
console.log("nothing found in redis, going to DB");
dbquery.getStopsFromDB(req, res);
}
});
}
exports.GetCurrentTrail = (req,res)=>{
let roomid = req.body.room_id;
client.lrange(roomid, 0, -1, function (error, result) {
if (error) throw error;
if (result && result.length) {
console.log("from redis");
res.send(result);
}
else {
console.log("nothing in redis... so oops!");
res.sendStatus(404);
}
});
}
|
/*
In-Field Label jQuery Plugin
http://fuelyourcoding.com/scripts/infield.html
Copyright (c) 2009 Doug Neiner
Dual licensed under the MIT and GPL licenses.
Uses the same license as jQuery, see:
http://docs.jquery.com/License
*/
(function(d){d.InFieldLabels=function(e,b,f){var a=this;a.$label=d(e);a.label=e;a.$field=d(b);a.field=b;a.$label.data("InFieldLabels",a);a.showing=true;a.init=function(){a.options=d.extend({},d.InFieldLabels.defaultOptions,f);if(a.$field.val()!==""){a.$label.hide();a.showing=false}a.$field.focus(function(){a.fadeOnFocus()}).blur(function(){a.checkForEmpty(true)}).bind("keydown.infieldlabel",function(c){a.hideOnChange(c)}).bind("paste",function(){a.setOpacity(0)}).change(function(){a.checkForEmpty()}).bind("onPropertyChange",
function(){a.checkForEmpty()})};a.fadeOnFocus=function(){a.showing&&a.setOpacity(a.options.fadeOpacity)};a.setOpacity=function(c){a.$label.stop().animate({opacity:c},a.options.fadeDuration);a.showing=c>0};a.checkForEmpty=function(c){if(a.$field.val()===""){a.prepForShow();a.setOpacity(c?1:a.options.fadeOpacity)}else a.setOpacity(0)};a.prepForShow=function(){if(!a.showing){a.$label.css({opacity:0}).show();a.$field.bind("keydown.infieldlabel",function(c){a.hideOnChange(c)})}};a.hideOnChange=function(c){if(!(c.keyCode===
16||c.keyCode===9)){if(a.showing){a.$label.hide();a.showing=false}a.$field.unbind("keydown.infieldlabel")}};a.init()};d.InFieldLabels.defaultOptions={fadeOpacity:0.5,fadeDuration:300};d.fn.inFieldLabels=function(e){return this.each(function(){var b=d(this).attr("for");if(b){b=d("input#"+b+"[type='text'],input#"+b+"[type='search'],input#"+b+"[type='tel'],input#"+b+"[type='url'],input#"+b+"[type='email'],input#"+b+"[type='password'],textarea#"+b);b.length!==0&&new d.InFieldLabels(this,b[0],e)}})}})(jQuery);
var $view = $(window);
var navSensor = function() {
var processOffset = $('#process').offset().top;
var portfolioOffset = $('#portfolio').offset().top;
var aboutOffset = $('#team').offset().top;
var contactOffset = $('#contact').offset().top;
var viewScrollTop = $view.scrollTop();
if (viewScrollTop > $('#section-nav').offset().top ) {
$('#section-nav').addClass('fixed');
}
else if (viewScrollTop < $('#process').offset().top ) {
$('#section-nav').removeClass('fixed');
}
if (viewScrollTop < processOffset) {
$('#section-nav a').removeClass('active');
$('#link-start').addClass('active');
}
else if (viewScrollTop < portfolioOffset) {
$('#section-nav a').removeClass('active');
$('#link-process').addClass('active');
}
else if (viewScrollTop < aboutOffset) {
$('#section-nav a').removeClass('active');
$('#link-portfolio').addClass('active');
}
else if (viewScrollTop < contactOffset) {
$('#section-nav a').removeClass('active');
$('#link-company').addClass('active');
}
else {
$('#section-nav a').removeClass('active');
$('#link-contact').addClass('active');
}
}
$(function() {
$view.bind('scroll resize', function() {
navSensor();
});
}); |
const eventBus = require('./event-bus')
class AnalyticsManager {
actions = []
constructor() {
eventBus.on((event) => this.track(event))
}
track(action) {
this.actions.push({
action,
time: new Date(),
})
}
printActions() {
console.log(this.actions)
}
}
module.exports = new AnalyticsManager()
|
// To run this script use this command
// node bs.js yourBSGuest yourBSKey
var webdriver = require('selenium-webdriver')
var test = require('./bs_test.js')
// Input capabilities
var iPhone = {
browserName: 'iPhone',
device: 'iPhone 7',
realMobile: 'true',
os_version: '10.3',
'browserstack.user': process.argv[2],
'browserstack.key': process.argv[3]
}
// var android = {
// browserName: 'android',
// device: 'Samsung Galaxy S8',
// realMobile: 'true',
// os_version: '7.0',
// 'browserstack.user': process.argv[2],
// 'browserstack.key': process.argv[3]
// }
var desktopFF = {
browserName: 'Firefox',
browser_version: '59.0',
os: 'Windows',
os_version: '10',
resolution: '1024x768',
'browserstack.user': process.argv[2],
'browserstack.key': process.argv[3]
}
var desktopEdge = {
browserName: 'Edge',
browser_version: '16.0',
os: 'Windows',
os_version: '10',
resolution: '1024x768',
'browserstack.user': process.argv[2],
'browserstack.key': process.argv[3]
}
var desktopIE = {
browserName: 'Chrome',
browser_version: '69.0',
os: 'Windows',
os_version: '10',
resolution: '1024x768',
'browserstack.user': process.argv[2],
'browserstack.key': process.argv[3]
}
var iPhoneDriver = new webdriver.Builder()
.usingServer('http://hub-cloud.browserstack.com/wd/hub')
.withCapabilities(iPhone)
.build()
// var androidDriver = new webdriver.Builder()
// .usingServer('http://hub-cloud.browserstack.com/wd/hub')
// .withCapabilities(android)
// .build()
var desktopFFDriver = new webdriver.Builder()
.usingServer('http://hub-cloud.browserstack.com/wd/hub')
.withCapabilities(desktopFF)
.build()
var desktopEdgeDriver = new webdriver.Builder()
.usingServer('http://hub-cloud.browserstack.com/wd/hub')
.withCapabilities(desktopEdge)
.build()
var desktopIEDriver = new webdriver.Builder()
.usingServer('http://hub-cloud.browserstack.com/wd/hub')
.withCapabilities(desktopIE)
.build()
test.runTest(iPhoneDriver)
//test.runTest(androidDriver)
test.runTest(desktopFFDriver)
test.runTest(desktopEdgeDriver)
test.runTest(desktopIEDriver)
|
import DataType from 'sequelize';
import to from 'await-to-js';
import Model from '../../sequelize';
const UserAuthStatus = Model.define('UserAuthStatus', {
id: {
type: DataType.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
twoFactorAuthEnabled: {
type: DataType.BOOLEAN,
defaultValue: false,
},
twoFactorAuthSecret: {
type: DataType.STRING(4000),
allowNull: true,
},
smsVerificationToken: {
type: DataType.STRING,
},
smsEnabled: {
type: DataType.BOOLEAN,
defaultValue: false,
},
phoneNumber: {
type: DataType.STRING(50),
},
});
export const initialize = async () => {
const data = [];
const initialUsersId = [1, 2, 3, 501, 502];
for (let i = 0; i < initialUsersId.length; i += 1) {
data.push({
id: i + 1,
twoFactorAuthEnabled: false,
smsEnabled: false,
userId: initialUsersId[i],
});
}
const [err] = await to(
UserAuthStatus.bulkCreate(data, {
// fields: Object.keys(data[0]),
updateOnDuplicate: 'id',
}),
);
if (err) {
console.warn(
`problem with adding initial data to UserAuthStatus table: `,
err,
);
} else {
console.warn(`initial rows added to UserAuthStatus table successfully.`);
}
};
export default UserAuthStatus;
|
import { createSelector } from 'reselect';
/**
* Direct selector to the botHeaderContainer state domain
*/
const selectBotHeaderContainerDomain = () => (state) => state.get('botHeaderContainer');
/**
* Other specific selectors
*/
/**
* Default selector used by BotHeaderContainer
*/
const makeSelectBotHeaderContainer = () => createSelector(
selectBotHeaderContainerDomain(),
(substate) => substate.toJS()
);
export default makeSelectBotHeaderContainer;
export {
selectBotHeaderContainerDomain,
};
|
'use strict';
const { expect } = require('chai');
const { createStubInstance } = require('sinon');
const {
CollectionReference,
DocumentReference,
Firestore,
WriteBatch
} = require('@google-cloud/firestore');
const ServiceOfferingRepository = require('../../../src/lib/repository/service-offering-repository');
describe('service-offering-repository unit tests', () => {
let repo, firestore;
let collectionReference, documentReference, writeBatchReference;
before(() => {
firestore = createStubInstance(Firestore);
collectionReference = createStubInstance(CollectionReference);
documentReference = createStubInstance(DocumentReference);
writeBatchReference = createStubInstance(WriteBatch);
collectionReference.doc.returns(documentReference);
documentReference.collection.returns(collectionReference);
firestore.collection.returns(collectionReference);
firestore.batch.returns(writeBatchReference);
repo = new ServiceOfferingRepository(firestore);
});
afterEach(() => {
documentReference.get.resetHistory();
documentReference.set.resetHistory();
documentReference.delete.resetHistory();
documentReference.create.resetHistory();
collectionReference.doc.resetHistory();
collectionReference.where.resetHistory();
documentReference.collection.resetHistory();
documentReference.create.resetHistory();
collectionReference.add.resetHistory();
writeBatchReference.delete.resetHistory();
writeBatchReference.commit.resetHistory();
firestore.batch.resetHistory();
});
context('create', () => {
it('should save the document', () => {
collectionReference.add.resolves({ id: 'TEST' });
const service = {
styleId: 'FADE',
description: 'We give the best fade with super highly trained staff.',
price: 15.0,
currency: 'USD'
};
expect(repo.create('TEST-PROVIDER', service)).to.be.fulfilled.then(
documentId => {
expect(
collectionReference.add.calledWith({
styleId: 'FADE',
description:
'We give the best fade with super highly trained staff.',
price: 15.0,
currency: 'USD'
})
).to.be.true;
expect(documentId).to.equal('TEST');
}
);
});
it('should return the collection name', () => {
expect(repo.collection).to.equal('services');
});
it('should save the document with defaults', () => {
collectionReference.add.resolves({ id: 'TEST' });
const service = {
description: 'We give the best fade with super highly trained staff.',
price: 15.0
};
expect(repo.create('TEST-PROVIDER', service)).to.be.fulfilled.then(
documentId => {
expect(
collectionReference.add.calledWith({
styleId: 'CUSTOM',
description:
'We give the best fade with super highly trained staff.',
price: 15.0,
currency: 'USD'
})
).to.be.true;
expect(documentId).to.equal('TEST');
}
);
});
it('should save the document with defaults and force styleId = CUSTOM', () => {
collectionReference.add.resolves({ id: 'TEST' });
const service = {
description: 'We give the best fade with super highly trained staff.',
price: 15.0
};
expect(repo.create('TEST-PROVIDER', service)).to.be.fulfilled.then(
documentId => {
expect(
collectionReference.add.calledWith({
styleId: 'CUSTOM',
description:
'We give the best fade with super highly trained staff.',
price: 15.0,
currency: 'USD'
})
).to.be.true;
expect(documentId).to.equal('TEST');
}
);
});
});
context('findAllServiceOfferings', () => {
const services = [
{
currency: 'USD',
price: 40.58,
styleId: 'FADE',
description: 'Beard Trim',
serviceId: 'SERVICE1'
},
{
styleId: 'CUSTOM',
description: 'Beard Trim',
currency: 'USD',
price: 40.58,
serviceId: 'SERVICE2'
}
];
it('should return an array of offerings', () => {
const querySnapshotSub = {
docs: [
{
data: () => services[0]
},
{
data: () => services[1]
}
]
};
collectionReference.get.resolves(querySnapshotSub);
expect(
repo.findAllServiceOfferings('TEST-PROVIDER')
).to.be.fulfilled.then(results => {
expect(results).to.deep.equal(services);
});
});
it('should return an empty array when none exist', () => {
const querySnapshotSub = {
docs: []
};
collectionReference.get.resolves(querySnapshotSub);
expect(
repo.findAllServiceOfferings('TEST-PROVIDER')
).to.be.fulfilled.then(results => {
expect(results).to.deep.equal([]);
});
});
});
context('deleteAllForProvider', () => {
const services = [
{
ref: {}
},
{
ref: {}
}
];
it('should trigger the delete in batch', () => {
const querySnapshotSub = {
forEach: func => services.forEach(func),
size: 2
};
collectionReference.get.resolves(querySnapshotSub);
writeBatchReference.delete.returns();
writeBatchReference.commit.resolves();
expect(repo.deleteAllForProvider('TEST-PROVIDER')).to.be.fulfilled.then(
() => {
expect(firestore.batch.called).to.be.true;
expect(writeBatchReference.delete.callCount).to.equal(2);
expect(writeBatchReference.commit.called).to.be.true;
}
);
});
it('should do nothing if no services exist', () => {
const querySnapshotSub = {
docs: [],
size: 0
};
collectionReference.get.resolves(querySnapshotSub);
expect(repo.deleteAllForProvider('TEST-PROVIDER')).to.be.fulfilled.then(
() => {
expect(firestore.batch.called).to.be.false;
}
);
});
});
context('update', () => {
it('should resolve', () => {
const service = {
styleId: 'FADE',
description: 'We give the best fade with super highly trained staff.',
price: 15.0,
currency: 'USD',
serviceId: 'SERVICE1'
};
documentReference.set.resolves();
expect(
repo.update('TEST', 'TEST-OFFERING', service)
).to.be.fulfilled.then(() => {
expect(collectionReference.doc.calledWith('TEST')).to.be.true;
expect(collectionReference.doc.calledWith('TEST-OFFERING')).to.be.true;
expect(documentReference.set.called).to.be.true;
});
});
});
});
|
var mongoose = require('mongoose');
var wasteSchema = new mongoose.Schema({
title: String,
body: String,
keywords: String,
favorite: {
type: Boolean,
default: false
}
});
var Waste = mongoose.model('Waste', wasteSchema);
module.exports = Waste; |
/**
* @author: yunfour
* @email: yunfour@163.com
* @version: 0.0.1
*/
define(function (require, exports, module) {
/**
* @param {Object} targetObj 对象、数组类型;必填;如果只有这一个参数,则返回值为该对象的克隆版本的对象
* @param {Object} obj 对象;选填;如果设置了该参数,则会将该对象的属性复制到目标对象targetObj上,然后返回targetObj
* @description 克隆对象,可以将obj的属性复制到目标对象targetObj,也可以也可以单独克隆一个对象
*/
function cloneObj(targetObj, obj) {
var result;
if(typeof obj === 'object') {
for(var k in obj) {
// 在 iPhone 1 代等设备的 Safari 中,prototype 也会被枚举出来,需排除
if(k !== 'prototype') {
targetObj[k] = obj[k];
}
}
result = targetObj;
} else {
if(typeof targetObj === 'object') {
if(targetObj.constructor === Array) {
result = targetObj.slice();
} else {
result = {};
for(var kk in targetObj) {
// 在 iPhone 1 代等设备的 Safari 中,prototype 也会被枚举出来,需排除
if(kk !== 'prototype') {
result[kk] = targetObj[kk];
}
}
}
} else {
result = targetObj;
}
}
return result;
}
/**
* @param {Object} conf 对创建的构造函数进行配置;可选;参数 conf 支持的属性如下:
* attrs: {Object} 初始私有属性;可选
* superClass: {Function/Array} 设置父类,可以是一个构造函数,也可以是多个构造函数组成的数组(继承多个类)
* init: {Function} 实例化对象是对实例初始化函数
* methods: {Object} 该类拥有的方法,即:设置类原型链上的方法
*
* @description 通过该函数可以创建一个类/构造函数,该函数实现了类的(多)继承、私有变量的管理。通过该函数创建的类的实例,都会拥有三个共同的方法:setAttr()、setAttr()、instanceOf(),前两个方法是对实例的私有属性的管理,instanceOf()方法是判断继承关系
*
*/
function createClass(conf) {
conf = conf || {};
// 所有的方法
var methods = conf.methods,
superClasses = conf.superClass;
// 定义构造函数
function Constructor() {
var that = this;
/**
* 私有属性对象(集合),将私有属性集合放在构造函数中的闭包环境中,通过
* setAttr()、getAttr() 两个方法对attrs存取操作,这样可以保护私有变
* 量,达到封装的目的
*/
var attrs = {};
var __superClasses = [];
// 判断是否设置了父类
if(superClasses && superClasses.constructor === Array) {
for(var i = 0, l = superClasses.length, superClass; i < l; i ++) {
superClass = superClasses[i];
if(typeof superClass === 'function') {
// 执行父类的构造函数中的内容
superClass.apply(that, arguments);
__superClasses.push(superClass);
}
}
}
if(typeof that.getAttr === 'function') {
// 获取父类的私有属性集合
attrs = cloneObj(attrs, that.getAttr() || {});
}
attrs = cloneObj(attrs, conf.attrs || {});
// 方法:添加属性
function setAttr(attrName, attrVal) {
var that = this,
attrObj = {};
if(!attrs || typeof attrs !== 'object') {
attrs = {};
}
if(typeof attrName === 'object') {
attrObj = attrName;
} else if(typeof attrName === 'string') {
attrObj[attrName] = attrVal;
}
if(attrObj) {
for(var k in attrObj) {
if(attrObj.hasOwnProperty(k)) {
// 触发事件:setAttrBefore(设置attr之前触发)
if(typeof that.trigger === 'function') {
that.trigger('setAttrBefore', k, attrObj[k]);
}
attrs[k] = attrObj[k];
// 触发事件:setAttr(设置attr之后触发)
if(typeof that.trigger === 'function') {
that.trigger('setAttr', k, attrObj[k]);
}
}
}
}
return that;
};
// 方法:获取属性值
function getAttr(attrName) {
var that = this,
attrVal;
if(arguments.length === 0) {
// 如果没有设置任何参数,则将attrs对象(所有属性集合)返回
attrVal = cloneObj(attrs);
} else {
if(typeof attrName !== 'string') {
throw new Error('方法 getAttr() 的参数 attrName 必须为字符串类型');
}
if(typeof attrs === 'object') {
attrVal = attrs[attrName];
}
}
return attrVal;
};
that.setAttr = setAttr;
that.getAttr = getAttr;
// 缓存超类列表
that.setAttr('__superClasses', __superClasses);
// 调用初始化方法
if(typeof conf.init === 'function') {
conf.init.apply(that, arguments);
}
};
if(typeof superClasses === 'function') {
superClasses = [superClasses];
}
if(superClasses && superClasses.constructor === Array) {
// 遍历父类列表,实现多继承
for(var i = 0, l = superClasses.length, superClass, subClass, subObj; i < l; i ++) {
superClass = superClasses[i];
if(typeof superClass !== 'function') {
continue;
}
subClass = function() {};
subClass.prototype = superClass.prototype;
subObj = new subClass();
/*
* 将列表中第一个父类设置成直接父类(通过instanceOf运算符可以判
* 断出继承关系),而当前类之使用(继承)出第一个之外的其他类的属
* 性(属性和方法),因此使用instanceOf运算符判断当前类的实例和
* 第一个类的关系式会得到true的结果,而与其他类运算的结果则问false
* 如:obj为当前对象的实例,
* 则:
* obj instanceof superClasses[0] 的结果为true
* obj instanceof superClasses[1+] 的结果为false
* 不过可以使用该对象的instanceOf(superClass)方法来判断继承关系
* 如果参数superClass在superClasses存在,则该结果返回为true
*/
if(i === 0) {
Constructor.prototype = subObj;
} else {
for(var k in subObj) {
Constructor.prototype[k] = subObj[k];
}
}
}
if(typeof superClasses[0] === 'function') {
Constructor.prototype._superClass = superClasses[0];
}
} else {
Constructor.prototype._superClass = Object;
}
if(typeof Constructor.prototype.instanceOf === 'undefined') {
Constructor.prototype.instanceOf = function(superClass) {
var that = this,
result = that instanceof superClass;
var superClasses = this.getAttr('__superClasses');
if(!result && superClasses) {
for(var i = 0, l = superClasses.length; i < l; i++) {
if(superClass === superClasses[i]) {
return true;
}
}
}
return result;
};
}
if(methods && typeof methods === 'object') {
// 遍历:methods,将遍历得到的函数,追加至构造函数的原型对象中
for(var key in methods) {
if(typeof methods[key] === 'function' && methods.hasOwnProperty(key)) {
Constructor.prototype[key] = methods[key];
}
}
}
// 返回构造函数
return Constructor;
}
return createClass;
}); |
var searchData=
[
['hmat',['hmat',['../classhmat.html',1,'hmat'],['../classhmat.html#aab11e1638abca5cfcfa1c8912f172318',1,'hmat::hmat()']]],
['hierarchical_20matrix_20construction_20library',['Hierarchical Matrix construction library',['../index.html',1,'']]]
];
|
function removeTile() {
$('.grid-stack-item').remove();
}
function addNew() {
var serialization = [
{x: 0, y: 0, width: 9, height: 7, id:'video'},
{x: 9, y: 0, width: 3, height: 6, id:'image-carousel'},
{x: 0, y: 7, width: 9, height: 3, id:'text-carousel'},
{x: 9, y: 6, width: 3, height: 4, id:'social-carousel'}
];
serialization = GridStackUI.Utils.sort(serialization);
var grid = $('.grid-stack').data('gridstack');
grid.remove_all();
_.each(serialization, function (node) {
var test = document.createElement('div');
test.id = node.id;
var cont = document.createElement('div');
cont.className = "grid-stack-item-content";
var player = document.createElement('div');
player.id = 'player';
cont.appendChild(player);
test.appendChild(cont);
grid.add_widget(test,
node.x, node.y, node.width, node.height
);
});
}
function test1() {
$('#text-carousel').slick({
autoplay:true
});
$('#image-carousel').slick({
autoplay:true
});
$('#social-carousel').slick({
autoplay:true
});
}
$(function () {
var options = {
};
$('.grid-stack').gridstack(options);
});
|
var searchData=
[
['weak_5fattribute_876',['WEAK_ATTRIBUTE',['../weakmacros_8h.html#a7b4e8308dcb91579fb0a11c039b8b70d',1,'weakmacros.h']]]
];
|
import React, { useCallback, useEffect, useRef } from "react";
import UserIcon from "../../assets/svgJs/UserIcon";
import { makeStyles, Typography } from "@material-ui/core";
import VideoTrack from "../VideoTrack";
import useVideoContext from "../Hooks/useVideoContext";
import useLocalVideoToggle from "../Hooks/useLocalVideoToggle";
import useLocalAudioToggle from "../Hooks/useLocalAudioToggle";
import Footer from "./footer";
import { useSelector } from "react-redux";
const useStyles = makeStyles((theme) => ({
container: {
position: "relative",
height: "100%",
overflow: "hidden",
background: "black",
},
innerContainer: {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
},
identityContainer: {
position: "absolute",
bottom: 0,
zIndex: 1,
},
identity: {
background: "rgba(0, 0, 0, 0.5)",
color: "white",
padding: "0.18em 0.3em",
margin: 0,
display: "flex",
alignItems: "center",
},
avatarContainer: {
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "black",
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
[theme.breakpoints.down("sm")]: {
"& svg": {
transform: "scale(0.7)",
},
},
},
}));
export default function VideoPreview({ onStartCall }) {
const classes = useStyles();
const { token } = useSelector((state) => state.meetingReducer);
const {
connect,
localTracks,
getAudioAndVideoTracks,
isAcquiringLocalTracks,
isConnecting,
} = useVideoContext();
const [isVideoEnabled, toggleVideoEnabled] = useLocalVideoToggle();
const [isAudioEnabled, toggleAudioEnabled] = useLocalAudioToggle();
const lastClickTimeRef = useRef(0);
const toggleVideo = useCallback(() => {
if (Date.now() - lastClickTimeRef.current > 500) {
lastClickTimeRef.current = Date.now();
toggleVideoEnabled();
}
}, [toggleVideoEnabled]);
const onCall = () => {
if (!isAcquiringLocalTracks && !isConnecting) {
connect(token);
onStartCall();
}
};
useEffect(() => {
getAudioAndVideoTracks().then(() => {
toggleVideo();
toggleAudioEnabled();
});
}, []);
const videoTrack = localTracks.find((track) => track.name.includes("camera"));
return (
<div className={classes.container}>
<div className={classes.innerContainer}>
{videoTrack ? (
<VideoTrack track={videoTrack} isLocal />
) : (
<div className={classes.avatarContainer}>
<UserIcon width={30} height={30} fill="#fff" />
</div>
)}
<Footer
isStartedVideo={isVideoEnabled}
isStartedAudio={isAudioEnabled}
isMuted={false}
onMicrophoneClick={toggleAudioEnabled}
onCameraClick={toggleVideo}
onStartCall={onCall}
/>
</div>
</div>
);
}
|
/**
* @author v.lugovsky
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.app.specialmenu.specialmenupage')
.controller('SpecialMenuPageCtrl', SpecialMenuPageCtrl)
.controller('SpecialMenuAddModalCtrl', SpecialMenuAddModalCtrl)
.controller('SpecialMenuEditModalCtrl', SpecialMenuEditModalCtrl)
.controller('SpecialMenuDeleteModalCtrl', SpecialMenuDeleteModalCtrl);
/** @ngInject */
function SpecialMenuPageCtrl($scope, iAPI, iXLSX, $timeout, $filter, toastr,$uibModal,$log) {
console.log('SpecialMenuPageCtrl');
$scope.specialitem_list;
$scope.specialmenu_list;
$scope.mes;
$scope.cc={
'spmenu_id':''
};
$scope.langsl={
'lng_num_used':'',
'one':'',
'two':'',
'three':''
};
$scope.lng=localStorage.langnumber;
iAPI.get('item.iView_specialItem',{}).success(function(res){
$scope.specialitem_list=res;
// console.log("yyy",$scope.specialitem_list);
});
iAPI.get('item.iView_specialMenu',{}).success(function(res){
$scope.specialmenu_list=res;
// console.log("qqq",$scope.specialmenu_list);
});
$scope.FR=angular.fromJson(sessionStorage.FR_WEB_APP);
iAPI.post('company.iGet_company/?token='+iAPI.tokenStr,{'id':$scope.FR.location_id}).success(function(res) {
$scope.cp_id=res.company_id;
if(res.c_setting==""){
$scope.langsl={
'lng_num_used':'2',
'one':'assets/img/flags/th.png',
'two':'assets/img/flags/en.png',
'three':''
};
}
else if(res.c_setting!=""){
// $scope.set = angular.fromJson(res.c_setting);
// res.c_setting=$scope.set;
$scope.langsl.lng_num_used=res.lng_num_used;
$scope.langsl.one=res.lng1_text;
$scope.langsl.two=res.lng2_text;
$scope.langsl.three=res.lng3_text;
}
});
$scope.filter2 = function(field1, field2) {
if(field2 === "" || field2 === null) return true;
return field1 === field2;
};
$scope.Add = function(group_sp,spmenu_id,sp,langsl,cp_id) {
$scope.modalInstance = $uibModal.open({
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'FREnSPMModalContent.html',
controller: 'SpecialMenuAddModalCtrl',
size: 'lg',
resolve: {
group_sp: function(){
return $scope.specialmenu_list;
},
spmenu_id: function(){
return $scope.cc.spmenu_id;
},
sp:function(){
return $scope.specialitem_list;
},
langsl:function(){
return $scope.langsl;
},
cp_id:function(){
return $scope.cp_id;
}
}
});
$scope.modalInstance.result.then(function() {
console.log('Success');
iAPI.get('item.iView_specialItem',{}).success(function(res){
$scope.specialitem_list=res;
});
});
};
$scope.Edit = function(item,group_sp,sp,langsl,cp_id){
$scope.modalInstance = $uibModal.open({
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'FREnSPMModalContent.html',
controller:'SpecialMenuEditModalCtrl',
size: 'lg',
resolve: {
item : function(){
return item;
},
group_sp: function(){
return $scope.specialmenu_list;
},
sp:function(){
return $scope.specialitem_list;
},
langsl:function(){
return $scope.langsl;
},
cp_id:function(){
return $scope.cp_id;
}
}
});
$scope.modalInstance.result.then(function() {
console.log('Success');
iAPI.get('item.iView_specialItem',{}).success(function(res){
$scope.specialitem_list=res;
});
});
};
$scope.Delete = function(item){
$scope.modalInstance = $uibModal.open({
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'FREnSPMDelModalContent.html',
controller:'SpecialMenuDeleteModalCtrl',
resolve: {
item: function(){
return item;
}
}
});
$scope.modalInstance.result.then(function() {
console.log('Success');
iAPI.get('item.iView_specialItem',{}).success(function(res){
$scope.specialitem_list=res;
});
});
};
}
function SpecialMenuAddModalCtrl($scope, iAPI, $timeout, toastr, $filter, $uibModalInstance,group_sp,spmenu_id,sp,langsl,Upload,cp_id) {
console.log('SpecialMenuAddModalCtrl');
$scope.rawmaterial_group_list;
$scope.rawmaterial_subgroup_list;
$scope.rawmaterial_list;
$scope.subgroup_special_list;
$scope.rawmat = [];
$scope.rawlist={};
$scope.Inventory='0';
// $scope.company_group_list;
// $scope.food_bevarage={'type':"food"};
$scope.cc={
'specialGroup_id':''
};
$scope.lng=localStorage.langnumber;
$scope.new_loc = {
'lng1_c_name': '',
'lng2_c_name': '',
'lng3_c_name':'',
'img_name':'',
'setspecial_id':'0',
'price_special':'0',
'specialGroup_id':'',
'RawMatList':[]
};
$scope.group_sps={};
$scope.group_sps=group_sp;
$scope.langsl=langsl;
if(spmenu_id!=''||spmenu_id!=null){
$scope.popup=spmenu_id;
}
if(spmenu_id==''||spmenu_id==null){
$scope.popup=$scope.group_sps[0].setspecial_id;
}
iAPI.get('item.iView_specialGroup',{}).success(function(res) {
$scope.subgroup_special_list=res;
});
iAPI.get('stock.iView_productGroup',{}).success(function(res3) {
$scope.rawmaterial_group_list=res3;
});
iAPI.get('stock.iView_productGroup2',{}).success(function(res4) {
$scope.rawmaterial_subgroup_list=res4;
});
iAPI.get('stock.iView_product',{}).success(function(res5) {
$scope.rawmaterial_list=res5;
});
$scope.filter2 = function(field1, field2) {
if(field2 === "" || field2 === null) return true;
return field1 === field2;
};
$scope.uploadPic = function(file) {
if(file!=undefined ||file!=''){
file.upload = Upload.upload({
url: BASE_URL+"item.iUpload_specialItem",
data:{file: file},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}else if (file==''){
}else{
toastr.error("size should be less than 100kB");
return false;
}
}
// $scope.removePicture = function () {
// $scope.picture = $filter('appImage')('theme/no-photo.png');
// $scope.noPicture = true;
// };
// $scope.uploadPicture = function () {
// var fileInput = document.getElementById('uploadFile');
// fileInput.click();
// };
// $scope.getFile = function () {
// fileReader.readAsDataUrl($scope.file, $scope)
// .then(function (result) {
// $scope.picture = result;
// // console.log("pic",$scope.picture);
// });
// };
$scope.getProductDetails = function(row) {
console.log(row);
angular.forEach($scope.rawmaterial_list, function(p) {
if (p.ProdNum == row.mat) {
row.unit1 = p.lng1_c_unit;
row.unit2 = p.lng2_c_unit;
row.unit3 = p.lng3_c_unit;
}
})
}
// remove user
$scope.removeUser = function(index) {
$scope.rawmat.splice(index, 1);
};
// add user
$scope.addUser = function() {
console.log("yy",$scope.rawmat);
$scope.inserted = {
// id: $scope.users.length+1,
amount: null,
mat_group: '',
sub_mat: '',
mat: '',
unit1:'',
unit2:'',
unit3:''
};
$scope.rawmat.push($scope.inserted);
};
// iAPI.get('Company.iView_company_group',{}).success(function(res) {
// $scope.company_group_list=res;
// });
$scope.Action = function(){
var check_code=0;
if($scope.popup == '') {
toastr.error("Please fill in all required fields");
return false;
}
if($scope.new_loc.lng1_c_name == '') {
toastr.error("Please fill in all required fields");
return false;
}
if($scope.picFile!=undefined){
var image = 'user-data/'+cp_id+'/images/specialitems/0-'+$scope.picFile.name;
$scope.new_loc.img_name = image;
}else if($scope.picFile==''){
toastr.error("size should be less than 100kB");
return false;
}
if($scope.Inventory == '1') {
// console.log("qqqqqq",$scope.rawmat);
var len= 0;
if($scope.rawmat.length==0||$scope.rawmat.length==null){
toastr.error("Please insert Raw material (s)");
return false;
}else{
if(len<=$scope.rawmat.length){
if($scope.rawmat[len].mat=='0'){
toastr.error("Please select Raw material in field number "+ len);
return false;
len++
}else{
if($scope.rawmat[len].amount==''){
toastr.error("Please insert Raw material amount in field number "+ len);
return false;
len++
}
}
}
}
}
// if($scope.new_loc.lng2_c_name == '') {
// toastr.error("Please fill in all required fields");
// return false;
// }
// if($scope.new_loc.lng3_c_name == '') {
// toastr.error("Please fill in all required fields");
// return false;
// }
if($scope.new_loc.price_special == '') {
toastr.error("Please fill in all required fields");
return false;
}
if($scope.new_loc.lng1_c_name != ''&& $scope.new_loc.price_special != '' && $scope.popup != ''){
if($scope.cc.specialGroup_id ==null || $scope.cc.specialGroup_id==''){
$scope.new_loc.specialGroup_id='0';
}else{
$scope.new_loc.specialGroup_id=$scope.cc.specialGroup_id;
}
$scope.new_loc.setspecial_id=$scope.popup;
if($scope.Inventory=='1'){
angular.forEach($scope.rawmat,function(r){
$scope.rawlist={
ProdNum:r.mat,
Amount:r.amount,
lng1_c_unit:r.unit1,
lng2_c_unit:r.unit2,
lng3_c_unit:r.unit3
};
$scope.new_loc.RawMatList.push($scope.rawlist);
});
}else{
$scope.new_loc.RawMatList=[];
}
angular.forEach(sp,function(v){
if($scope.new_loc.lng1_c_name == v.lng1_c_name){
check_code++;
toastr.error("special name is already exists");
return false;
}
});
if(check_code==0){
$scope.new_loc.img_name = image;
iAPI.post('item.iInsert_specialItem',$scope.new_loc).success(function(res) {
$uibModalInstance.close();
});
}
}
}
$scope.close = function() {
$uibModalInstance.dismiss('cancel');
}
}
function SpecialMenuEditModalCtrl($scope, iAPI, $timeout, toastr, $filter, $uibModalInstance,item,group_sp,sp,langsl,Upload,cp_id) {
console.log('SpecialMenuEditModalCtrl');
$scope.subgroup_special_list;
$scope.get_check_name;
$scope.rawmaterial_group_list;
$scope.rawmaterial_subgroup_list;
$scope.rawmaterial_list;
$scope.Inventory='0';
$scope.rawmat = [];
// $scope.company_group_list;
// $scope.location_list;
// $scope.food_bevarage={'type':"food"};
$scope.lng=localStorage.langnumber;
$scope.new_loc = {
'special_id':item.special_id,
'lng1_c_name': '',
'lng2_c_name': '',
'lng3_c_name':'',
'img_name':'',
'setspecial_id':'0',
'price_special':'0',
'specialGroup_id':'',
'RawMatList':[]
};
$scope.cc={
'specialGroup_id':''
};
$scope.group_sps={};
$scope.check_image;
$scope.group_sps=group_sp;
$scope.langsl=langsl;
iAPI.get('item.iView_specialGroup',{}).success(function(res) {
$scope.subgroup_special_list=res;
});
iAPI.get('stock.iView_productGroup',{}).success(function(res4) {
$scope.rawmaterial_group_list=res4;
});
iAPI.get('stock.iView_productGroup2',{}).success(function(res5) {
$scope.rawmaterial_subgroup_list=res5;
});
iAPI.get('stock.iView_product',{}).success(function(res6) {
$scope.rawmaterial_list=res6;
});
iAPI.post('item.iGet_specialItem',{'special_id':item.special_id}).success(function(res) {
$scope.picFile=res.img_name;
$scope.new_loc.lng1_c_name = res.lng1_c_name;
$scope.new_loc.lng2_c_name = res.lng2_c_name;
$scope.new_loc.lng3_c_name = res.lng3_c_name;
$scope.popup = res.setspecial_id;
$scope.new_loc.img_name = res.img_name;
$scope.new_loc.price_special=res.price_special;
$scope.cc.specialGroup_id=res.specialGroup_id;
$scope.get_check_name=res.lng1_c_name;
$scope.new_loc.img_name=res.img_name;
$scope.check_image=res.img_name;
});
iAPI.post('item.iView_Rawmat',{'special_id':item.special_id}).success(function(ans) {
console.log("ans",ans);
if(ans!=''){
$scope.Inventory='1';
angular.forEach(ans,function(e){
// console.log('v',$scope.rawmaterial_list);
angular.forEach($scope.rawmaterial_list,function(rwg){
// console.log('rwg',rwg);
if(rwg.ProdNum==e.ProdNum){
var inte=parseInt(e.Amount);
console.log(inte);
$scope.insert = {
// id: $scope.users.length+1,
amount:inte,
mat_group: rwg.ProdGroup_id,
sub_mat: rwg.ProdGroup2_id,
mat: e.ProdNum,
unit1:e.lng1_c_unit,
unit2:e.lng2_c_unit,
unit3:e.lng3_c_unit
};
$scope.rawmat.push($scope.insert);
}
});
})
console.log("check",$scope.rawmat);
}
});
$scope.uploadPic = function(file) {
if(file!=undefined ||file!=''){
file.upload = Upload.upload({
url: BASE_URL+"item.iUpload_specialItem",
data:{special_id:item.special_id,file: file},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}else if (file==''){
}else{
toastr.error("size should be less than 100kB");
return false;
}
}
$scope.getProductDetails = function(row) {
console.log(row);
angular.forEach($scope.rawmaterial_list, function(p) {
if (p.ProdNum == row.mat) {
row.unit1 = p.lng1_c_unit;
row.unit2 = p.lng2_c_unit;
row.unit3 = p.lng3_c_unit;
}
})
}
// remove user
$scope.removeUser = function(index) {
$scope.rawmat.splice(index, 1);
};
// add user
$scope.addUser = function() {
console.log("yy",$scope.rawmat);
$scope.inserted = {
// id: $scope.users.length+1,
amount: null,
mat_group: '',
sub_mat: '',
mat: '',
unit1:'',
unit2:'',
unit3:''
};
$scope.rawmat.push($scope.inserted);
};
// $scope.removePicture = function () {
// $scope.picture = $filter('appImage')('theme/no-photo.png');
// $scope.noPicture = true;
// };
// $scope.uploadPicture = function () {
// var fileInput = document.getElementById('uploadFile');
// fileInput.click();
// };
// $scope.getFile = function () {
// fileReader.readAsDataUrl($scope.file, $scope)
// .then(function (result) {
// $scope.picture = result;
// // console.log("pic",$scope.picture);
// });
// };
$scope.Action = function(){
var check_code=0;
if($scope.popup == '') {
toastr.error("Please fill in all required fields");
return false;
}
if($scope.new_loc.lng1_c_name == '') {
toastr.error("Please fill in all required fields");
return false;
}
if($scope.Inventory == '1') {
var len= 0;
if($scope.rawmat.length==0||$scope.rawmat==null){
toastr.error("Please insert Raw material (s)");
return false;
}else{
if(len<=$scope.rawmat.length){
if($scope.rawmat[len].mat==0){
toastr.error("Please select Raw material in field number "+ len);
return false;
len++
}else{
if($scope.rawmat[len].amount==''){
toastr.error("Please insert Raw material amount in field number "+ len);
return false;
len++
}
}
}
}
}
if($scope.picFile!=''){
if($scope.picFile!=$scope.check_image){
var image = 'user-data/'+cp_id+'/images/specialitems/'+item.special_id+'-'+$scope.picFile.name;
$scope.new_loc.img_name=image;
}
}else if($scope.picFile==undefined){
toastr.error("size should be less than 100kB");
return false;
}else{
$scope.new_loc.img_name='';
}
// if($scope.new_loc.lng2_c_name == '') {
// toastr.error("Please fill in all required fields");
// return false;
// }
// if($scope.new_loc.lng3_c_name == '') {
// toastr.error("Please fill in all required fields");
// return false;
// }
if($scope.new_loc.price_special == '') {
toastr.error("Please fill in all required fields");
return false;
}
// if($scope.new_loc.lng1_c_name != ''&&$scope.new_loc.lng2_c_name != ''&&$scope.new_loc.lng3_c_name != ''&& $scope.new_loc.price_special != ''&& $scope.popup != ''){
if($scope.new_loc.lng1_c_name != ''&& $scope.new_loc.price_special != '' && $scope.popup != ''){
// $scope.array.lng1_c_name=$scope.new_loc.lng1_c_name;
// angular.forEach($scope.popup, function(v,k){
// loc['location_id'] = v;
// $scope.array.location_list.push(loc);
// });
if($scope.cc.specialGroup_id ==null || $scope.cc.specialGroup_id==''){
$scope.new_loc.specialGroup_id='0';
}else{
$scope.new_loc.specialGroup_id=$scope.cc.specialGroup_id;
}
$scope.new_loc.setspecial_id=$scope.popup;
if($scope.Inventory=='1'){
angular.forEach($scope.rawmat,function(r){
$scope.rawlist={
ProdNum:r.mat,
Amount:r.amount,
lng1_c_unit:r.unit1,
lng2_c_unit:r.unit2,
lng3_c_unit:r.unit3
};
$scope.new_loc.RawMatList.push($scope.rawlist);
});
}else{
$scope.new_loc.RawMatList=[];
}
angular.forEach(sp,function(v){
if($scope.get_check_name!=$scope.new_loc.lng1_c_name){
if($scope.new_loc.lng1_c_name== v.lng1_c_name){
check_code++;
toastr.error("special name is already exists");
return false;
}
}
});
if(check_code==0){
iAPI.post('item.iInsert_specialItem',$scope.new_loc).success(function(res) {
// console.log("dddddddeee",res);
$uibModalInstance.close();
});
}
}
}
$scope.close = function() {
$uibModalInstance.dismiss('cancel');
}
}
function SpecialMenuDeleteModalCtrl($scope, iAPI, $timeout, toastr, $filter, $uibModalInstance,item) {
console.log('SpecialMenuDeleteModalCtrl');
$scope.array={
"special_id":item.special_id,
"e_status":"cancel"
};
$scope.spmenu = {
'lng1_c_name':item.lng1_c_name,
'lng2_c_name':item.lng2_c_name,
'lng3_c_name':item.lng3_c_name
};
$scope.Action = function(){
console.log("Edit ");
iAPI.post('item.iInsert_specialItem',{"e_status":'cancel',"special_id":item.special_id}).success(function(res) {
$uibModalInstance.close();
});
}
$scope.close = function() {
$uibModalInstance.dismiss('cancel');
}
}
})();
|
import React from 'react';
const HomePage = () => {
return(
<div style={{marginLeft:'11vw'}}><p>Hello There, In our Company we have decided to give each employee a CAR 🥳 🎊.</p>
<p>So each one of you will inter the website with his UserName and PassWord.</p>
<p>If your Salary is more then 30K so you can get an isGold car</p>
<p>when someone picks a car his rentDetails will has for his name and the status of the car if she is available or not will change for false</p>
</div>
)
}
export default HomePage; |
import React from "react";
import Column from "./column";
import Career from "./career";
import Study from "./study";
import Main_in from "./Main_in";
import Search from "./search";
import Uploadimage from './Uploadimage';
const Column_page = () =>{
return <Column />
}
const Career_page = () =>{
return <Career />
}
const Study_page = () =>{
return <Study />
}
const Search_page = () =>{
return <Search />
};
const Main_in_page = () =>{
return <Main_in/>
}
const Upload_image_page = () =>{
return <Uploadimage/>
}
export { Column_page,Career_page, Study_page, Search_page, Main_in_page, Upload_image_page}; |
import React from 'react'
import ppp1 from './UP主.png'
import ppp2 from './时间.png'
import ppp3 from './播放量.png'
import ppp4 from './弹幕的副本.png'
import ppp5 from './arrowbottom.png'
import side_1 from './cover-m1.png'
import side_2 from './cover-m2.png'
import side_3 from './cover-m3.png'
import side_4 from './cover-m4.png'
import side_5 from './cover-m6.png'
import side_6 from './换一换.png'
import side_7 from './arrowblue.png'
const side_list=[
{
title:'《第一视频标题》',
image:side_1,
},
{
title:'《第二视频标题》',
image:side_2,
},
{
title:'《第三视频标题》',
image:side_3,
},
{
title:'《第四视频标题》',
image:side_4,
},
{
title:'《第五视频标题》',
image:side_5,
},
]
class Video_content_side extends React.Component{
render(){
return(
<div id={'V_side'}>
<div id={'side_top'}>
<div id={'side_unfold'}>
<p>弹幕列表</p>
<div>
<span>展开
<img src={ppp5}></img></span>
</div>
</div>
<div id={'side_white'}>相关视频</div>
</div>
<div id={'V_sidelist'}>
{side_list.map(
(item)=>(
<div className={'square'}>
<p>{item.title}</p>
<div className={'things'}>
<div className={'thing'} className={'clear'}>
<span><img className={'sight'} src={ppp1} ></img></span>
<span>用户名</span>
</div>
<div className={'thing'} className={'clear'}>
<img className={'sight'} src={ppp2} ></img>
<span>11-27</span>
</div>
<div className={'thing'}>
<img className={'sight'} src={ppp3}></img>
<span>486W</span>
</div>
<div className={'thing'}>
<img className={'sight'} src={ppp4}></img>
<span>2W</span>
</div>
</div>
<div className={'thing_pic'}>
<img src={item.image}>
</img>
</div>
</div>
)
)}
</div>
<div id={'more'}>
<div className="litlrr">
<span>换一换</span>
<img src={side_6} id={'change'}></img>
</div>
<div className="litlr">
<span>更多</span>
<img src={side_7} if={'lot'}></img>
</div>
</div>
</div>
)
}
}
export default Video_content_side |
import React from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
FlatList,
Alert,
Modal,
} from 'react-native';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import * as Progress from 'react-native-progress';
// import { CheckBox } from 'react-native-elements';
import CheckBox from 'react-native-check-box';
export default class SignUpScreen extends React.Component {
static navigationOptions = {
title: 'Home',
headerStyle: {
backgroundColor: 'rgb(244,226,212)',
},
}
state = {
agreement: false,
personalInfo: false,
personalInfoOptional: false,
delegatePersonalInfo: false,
thirdPartyPersonalInfo: false,
isCheckedAll: false,
}
onPressNextButton = () => {
const { agreement, personalInfo } = this.state;
const { navigation } = this.props;
if (agreement && personalInfo) {
navigation.navigate('SignUpTwo');
} else {
Alert.alert('약관에 동의해주세요');
}
}
render() {
const { navigation } = this.props;
const { agreement, personalInfo, personalInfoOptional, delegatePersonalInfo, thirdPartyPersonalInfo, isCheckedAll } = this.state;
return (
<View style={styles.container}>
<View style={{ flex: 1, marginTop: 20, marginBottom: hp('3%') }}>
<View style={{ alignItems: 'center', marginBottom: hp('5%') }}>
<Progress.Bar progress={0} width={wp('80%')} height={hp('2%')} />
</View>
<View style={{ marginLeft: wp('2%') }}>
<CheckBox
onClick={() => {
if (isCheckedAll) {
this.setState({
agreement: agreement ? false : agreement,
personalInfo: personalInfo ? false : personalInfo,
personalInfoOptional: personalInfoOptional ? false : personalInfoOptional,
delegatePersonalInfo: delegatePersonalInfo ? false : delegatePersonalInfo,
thirdPartyPersonalInfo: thirdPartyPersonalInfo ? false : thirdPartyPersonalInfo,
isCheckedAll: false,
});
} else {
this.setState({
agreement: agreement ? true : !agreement,
personalInfo: personalInfo ? true : !personalInfo,
personalInfoOptional: personalInfoOptional ? true : !personalInfoOptional,
delegatePersonalInfo: delegatePersonalInfo ? true : !delegatePersonalInfo,
thirdPartyPersonalInfo: thirdPartyPersonalInfo ? true : !thirdPartyPersonalInfo,
isCheckedAll: true,
});
}
}
}
isChecked={isCheckedAll}
rightText="크런치 프라이스의 모든 약관을 확인하고 전체 동의합니다."
/>
</View>
<View style={{ borderWidth: 1, borderColor: 'black', margin: 10, marginTop: hp('2%') }} />
</View>
<View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 0.4, borderBottomColor: 'grey', width: wp('90%'), height: hp('20%'), alignSelf: 'center', alignItems: 'center' }}>
<CheckBox
onClick={() => {
this.setState({
agreement: !agreement,
});
}
}
isChecked={agreement}
/>
<Text style={{ fontSize: 15 }}> (필수) 이용약관</Text>
<Text onPress={() => { navigation.navigate('content1'); }} style={styles.contentText}>내용보기</Text>
</View>
<View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 0.4, borderBottomColor: 'grey', width: wp('90%'), height: hp('20%'), alignSelf: 'center', alignItems: 'center' }}>
<CheckBox
onClick={() => {
this.setState({
personalInfo: !personalInfo,
});
}
}
isChecked={personalInfo}
/>
<Text style={{ fontSize: 15 }}> (필수) 개인정보 수집 및 이용</Text>
<Text onPress={() => { navigation.navigate('content1'); }} style={styles.contentText}>내용보기</Text>
</View>
<View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 0.4, borderBottomColor: 'grey', width: wp('90%'), height: hp('20%'), alignSelf: 'center', alignItems: 'center' }}>
<CheckBox
onClick={() => {
this.setState({
personalInfoOptional: !personalInfoOptional,
});
}
}
isChecked={personalInfoOptional}
/>
<Text style={{ fontSize: 15 }}> (선택) 개인정보 수집 및 이용</Text>
<Text onPress={() => { navigation.navigate('content1'); }} style={styles.contentText}>내용보기</Text>
</View>
<View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 0.4, borderBottomColor: 'grey', width: wp('90%'), height: hp('20%'), alignSelf: 'center', alignItems: 'center' }}>
<CheckBox
onClick={() => {
this.setState({
delegatePersonalInfo: !delegatePersonalInfo,
});
}
}
isChecked={delegatePersonalInfo}
/>
<Text style={{ fontSize: 15 }}> (선택) 개인정보 수집위탁</Text>
<Text onPress={() => { navigation.navigate('content1'); }} style={styles.contentText}>내용보기</Text>
</View>
<View style={{ flex: 1, flexDirection: 'row', borderBottomWidth: 0.4, borderBottomColor: 'grey', width: wp('90%'), height: hp('20%'), alignSelf: 'center', alignItems: 'center' }}>
<CheckBox
onClick={() => {
this.setState({
thirdPartyPersonalInfo: !thirdPartyPersonalInfo,
});
}
}
isChecked={thirdPartyPersonalInfo}
/>
<Text style={{ fontSize: 15 }}> (선택) 개인정보 제 3 자 제공</Text>
<Text onPress={() => { navigation.navigate('content1'); }} style={styles.contentText}>내용보기</Text>
</View>
<View style={{ flex: 1, flexDirection: 'row', width: wp('90%'), alignSelf: 'center' }}>
<View style={{ marginTop: hp('2%') }}>
<TouchableOpacity onPress={() => { navigation.replace('StartScreen'); }} style={styles.prevNextButton}>
<Text style={{ alignSelf: 'center', justifyContent: 'center' }}>이전</Text>
</TouchableOpacity>
</View>
<View style={{ marginTop: hp('2%'), marginLeft: 'auto' }}>
<TouchableOpacity onPress={this.onPressNextButton} style={styles.prevNextButton}>
<Text style={{ alignSelf: 'center', justifyContent: 'center', color: 'white' }}>다음</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'rgb(244,226,212)',
},
prevNextButton: {
width: wp('44%'),
height: hp('8%'),
backgroundColor: 'rgb(162,222,161)',
justifyContent: 'center',
alignItems: 'center',
},
prevButton: {
width: wp('44%'),
height: hp('8%'),
backgroundColor: 'rgb(162,222,161)',
justifyContent: 'center',
alignItems: 'center',
},
contentText: {
fontSize: 15,
color: 'blue',
fontWeight: 'bold',
marginLeft: 'auto',
},
});
// 차일드 엘리먼트 세로 중앙으로 맞추는 법: flexDirection이 column이면 justiContent: 'center', row라면 alignItems: 'center'
// marginRight: 'auto'는 부모 뷰 맨 오른쪽으로 엘리먼트를 보낸다
|
function encode(str){
let strArray = str.split("");
let newStr = '';
let newObj=strArray.reduce((acc, curr)=>({
...acc,
[curr]: acc[curr] ? acc[curr]+1 : 1
}),{});
for(let i in newObj){
newStr += (newObj[i]===1)?`${i}` : `${newObj[i]}[${i}]`;
}
return newStr;
}
console.log(encode("abbcccdd"));
|
import React, { Component } from "react";
import "./Landing.css";
import { Link } from "react-router-dom";
import { withFirebase } from "../Firebase";
// import * as ROUTES from "../../constants/routes";
import styled from "styled-components";
import HomeImage from "../../resources/images/home_farmland.png";
import renderIf from "render-if";
const MainDiv = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
const TopDiv = styled.div`
height: 60vh;
width: 100%;
background-color: black;
display: flex;
align-items: center;
justify-content: center;
background-image: url(${HomeImage});
background-size: cover;
background-repeat: no-repeat;
`;
const SearchDiv = styled.div`
position: absolute;
width: 60vw;
height: auto;
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
`;
const SearchTitle = styled.h3`
font-family: Helvetica;
font-weight: 700;
font-style: normal;
font-size: 2.3em;
line-height: 41.4px;
color: white;
`;
const SearchInputs = styled.div`
display: flex;
flex-flow: wrap;
align-items: center;
justify-content: space-evenly;
width: 80%;
`;
const Input = styled.input`
height: 2.5em;
width: 11em;
border-radius: 8px;
border: none;
padding-left: 1em;
margin: 0.4em;
:focus {
border: none;
}
`;
const SearchButton = styled.button`
height: 2.5em;
width: 40%;
background-color: #3d9a04;
color: white;
border-radius: 8px;
margin-top: 1.5em;
border: none;
cursor: pointer;
`;
const ItemsContainer = styled.div`
margin-top: 1.3em;
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
`;
const ItemsName = styled.h3`
font-family: Helvetica;
font-style: normal;
font-weight: 700;
font-size: 1.2em;
color: #3d9a04;
`;
const ItemsDiv = styled.div`
width: 100%;
padding: 1em;
display: flex;
flex-flow: wrap;
align-items: flex-start;
justify-content: space-evenly;
`;
const Item = styled.div`
width: 326px;
height: 341px;
background: #ffffff;
border: 1px solid #e5e5e5;
box-sizing: border-box;
border-radius: 8px;
margin: 1em;
`;
const ItemImageDiv = styled.div`
height: 200px;
width: 100%;
`;
const Image = styled.img`
height: 100%;
width: 100%;
object-fit: cover;
`;
const ItemDetailsDiv = styled.div`
height: 140px;
width: 100%;
padding-left: 1em;
padding-top: 0.5em;
`;
const ItemName = styled.h3`
font-family: Helvetica;
font-style: normal;
font-weight: bold;
font-size: 1.2em;
`;
const Crops = styled.h3`
font-family: Helvetica;
font-style: normal;
font-weight: 400;
font-size: 1em;
`;
const Price = styled.h3`
font-family: Helvetica;
font-style: normal;
font-weight: bold;
font-size: 1.3em;
color: #3d9a04;
`;
class Landing extends Component {
constructor(props) {
super(props);
this.state = {
landLoading: false,
allLand: [],
productsLoading: false,
allProducts: [],
crop: "",
location: "",
price: "",
error: "",
};
}
componentDidMount() {
this.setState({ landLoading: true });
// fetching all the lands available in the database
this.props.firebase.land().on("value", (snapshot) => {
const landObject = snapshot.val();
const landList = Object.keys(landObject).map((key) => ({
...landObject[key],
id: key,
}));
this.setState({
allLand: landList,
landLoading: false,
});
});
this.setState({ productsLoading: true });
// fetching all available products
this.props.firebase.products().on("value", (snapshot) => {
const productsObject = snapshot.val();
const productsList = Object.keys(productsObject).map((key) => ({
...productsObject[key],
id: key,
}));
this.setState({
allProducts: productsList,
productsLoading: false,
});
this.setState({
productsLoading: false,
});
});
}
componentWillUnmount() {
this.props.firebase.land().off();
this.props.firebase.products().off();
}
handleChange = (event) => {
let name = event.target.name;
this.setState({ [name]: event.target.value });
};
handleSearch = async (e) => {
e.preventDefault();
const landLocation = this.state.location;
this.setState({ landLoading: true, allLand: [] });
this.props.firebase
.land()
.orderByChild("location")
.equalTo(landLocation)
.on("value", (snapshot) => {
const searchLandObject = snapshot.val();
if (searchLandObject) {
const searchLandList = Object.keys(searchLandObject).map((key) => ({
...searchLandObject[key],
id: key,
}));
this.setState({
allLand: searchLandList,
landLoading: false,
});
} else {
this.setState({ error: "Empty", landLoading: false });
}
});
};
render() {
return (
<MainDiv>
<TopDiv>
<SearchDiv>
<SearchTitle>Search for Land</SearchTitle>
<SearchInputs>
<Input
type="text"
placeholder="crop"
value={this.state.crop}
name="crop"
onChange={this.handleChange}
></Input>
<Input
type="text"
placeholder="location"
value={this.state.location}
name="location"
onChange={this.handleChange}
></Input>
<Input
type="text"
placeholder="price"
value={this.state.price}
name="price"
onChange={this.handleChange}
></Input>
</SearchInputs>
<SearchButton onClick={this.handleSearch}>Find Land</SearchButton>
</SearchDiv>
</TopDiv>
<ItemsContainer>
<ItemsName>Land Available</ItemsName>
{renderIf(this.state.landLoading === true)(<div>Loading...</div>)}
{renderIf(this.state.error === "Empty")(
<div>No land available in {this.state.location}</div>
)}
{renderIf(this.state.landLoading === false)(
<ItemsDiv>
{this.state.allLand.map((land) => (
<Link
to={`land-details/${land.id}`}
style={{ textDecoration: "none", color: "black" }}
key={land.id}
>
<Item>
<ItemImageDiv>
<Image src={land.image} alt={land.name}></Image>
</ItemImageDiv>
<ItemDetailsDiv>
<ItemName>{land.name}</ItemName>
<Crops>{land.suitableCrop}</Crops>
<Price>Ksh. {land.price}</Price>
</ItemDetailsDiv>
</Item>
</Link>
))}
</ItemsDiv>
)}
</ItemsContainer>
<ItemsContainer>
<ItemsName>Products Available</ItemsName>
{renderIf(this.state.productsLoading === true)(<div>Loading...</div>)}
{renderIf(this.state.productsLoading === false)(
<ItemsDiv>
{this.state.allProducts.map((product) => (
<Item key={product.id}>
<ItemImageDiv>
<Image src={product.image} alt={product.name}></Image>
</ItemImageDiv>
<ItemDetailsDiv>
<ItemName>{product.name}</ItemName>
<Crops>{product.merchantName}</Crops>
<Price>Ksh. {product.price}</Price>
</ItemDetailsDiv>
</Item>
))}
</ItemsDiv>
)}
</ItemsContainer>
</MainDiv>
);
}
}
export default withFirebase(Landing);
|
import { regexConst } from '../utils/regexConst.js';
// check the form content
function checkFormInputs(formContent) {
/* firstName, lastName, email, and birthdate are checked against a Regex
formerContest amount must be a number
a city must be selected
conditionsAgreement must be checked by the user: no default check to comply with GDPR */
const isFormValid = {
firstName: regexConst.nameRegex.test(formContent.firstName),
lastName: regexConst.nameRegex.test(formContent.lastName),
email: regexConst.emailRegex.test(formContent.email),
birthdate: regexConst.birthdateRegex.test(formContent.birthdate),
formerContestAmount: !Number.isNaN(Number.parseInt(formContent.formerContestAmount, 10)),
city: formContent.city.length > 0,
conditionsAgreement: formContent.conditionsAgreement,
};
// checksum evaluates to true only if all form inputs are valid
isFormValid.checksum = Object.values(isFormValid).reduce((a, b) => a && b);
return isFormValid;
}
export default checkFormInputs;
|
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
export default class MyDocument extends Document {
render() {
return (
<html lang="pt-BR">
<Head>
<title>Dominando Promises</title>
<link rel="stylesheet" href="/_next/static/style.css" />
<meta name="author" content="Quero Educação" />
<meta name="description" content="Veja com exemplos tudo o que você precisa saber de Promises." />
<meta name="keywords" content="Promise,JavaScript" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="static/questions.js" />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
|
define(['jquery'], function($) {
return {
scrollIntoView: function(element, duration) {
if (duration === undefined) {
duration = 500;
}
var offset = $(element).offset().top;
$('html, body').animate({ scrollTop: offset }, duration);
}
};
}); |
$(document).ready(function () {
var search = {}
search["bookTitle"] = "";
search["pageNumber"] = 1;
ajaxGetBooks(search);
$('#search').click(function() {
search["bookTitle"] = $("#search-data").val();
search["pageNumber"] = 1;
ajaxGetBooks(search);
});
});
function ajaxGetBooks(search) {
$.ajax({
type: "POST",
contentType: "application/json",
url: "/api/book/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
var html = "";
$.each( data.content, function( key, val ) {
html += "<tr>"
html +='<td><a href="/bookDetail?bookId=' + val.bookId + '">' + val.title + '</a></td>';
html +="<td>" + val.author + "</td>";
html += '<td><a href="/updateBook?bookId=' + val.bookId + '">Edit </a>';
html += '<a href="/deleteBook?bookId='+ val.bookId +'"> Delete</a></td>';
html += "</tr>"
});
$('#bookContent').html(html);
var pagingButton = '<button >Total Pages: ' + data.totalPages + '</button>';
pagingButton += '<button class="paging-button" data-page="1">First</button>';
if (data.first) {
pagingButton += '<button class="paging-button" disabled data-page="' + (data.number) + '">Previous</button>';
} else {
pagingButton += '<button class="paging-button" data-page="' + (data.number) + '">Previous</button>';
}
pagingButton += '<button class="paging-button" data-page="' + (data.number + 1) + '">Current page ' + (data.number + 1) + '</button>';
if (data.last) {
pagingButton += '<button class="paging-button" disabled data-page="' + (data.number + 2) + '">next</button>';
} else {
pagingButton += '<button class="paging-button" data-page="' + (data.number + 2) + '">Next</button>';
}
if (data.totalPages == 0) {
pagingButton += '<button class="paging-button" data-page="1">Last</button>';
} else {
pagingButton += '<button class="paging-button" data-page="' + (data.totalPages) + '">Last</button>';
}
$("#pagingButton").html(pagingButton);
$('.paging-button').click(function() {
search["bookTitle"] = $("#search-data").val();
search["pageNumber"] = $(this).attr("data-page");
ajaxGetBooks(search);
});
},
error: function (e) {
console.log("ERROR : ", e);
}
});
} |
//main package used for sending mails
import nodemailer from 'nodemailer';
//templating engine for sending mail and create beautiful templates
import hbs from 'nodemailer-express-handlebars'
//inbuilt module for resolving the path of the template files to look for sending emails
import path from 'path'
//package for reading the environment variables
import dotenv from 'dotenv'
//calling the config method to read the variables saved in the '.env file'
dotenv.config()
//main sending function
const sendMail = (req,res) => {
//initializing __dirname since it is deprecate din ES6 so we need to do path.resolve()
const __dirname = path.resolve()
//creating the transporter object which is the main instance to send emails
//passing two parameters in createTransport -->
//service provider ( gmail in this case ) can be anything read here --> https://www.nodemailer.com/usage
//auth object taking in two keys user --> the user email who is sendng the email
//------------------------------ pass --> the password of email provided
const transporter = nodemailer.createTransport({service: 'gmail',auth:{user:process.env.USER, pass:process.env.PASSWORD}})
//setting the template engine for the email template using the path module
transporter.use('compile',hbs({viewEngine:'nodemailer-express-handlebars', viewPath:path.join(__dirname,'/controller/views/')}))
//initializing some variables to provide a dynamic email
let name, emails;
//if request contains name query string then assign it to the name variable
if (req.query.name){
name = req.query.name
}
else{
name = 'Beginner'
}
//if request contains emails query string then assign it to the emails variable ( can be more than one comma separated values )
if(req.query.emails){
emails = req.query.emails.split(',').toString()
}
else{
emails = process.env.USER
}
//the key part of the//setting the mailing options
//NOTE --> from and auth.user ( in createTransport ) should be same if using Gmail else it will give error
const mailOptions = {
//who is sending emails
from : process.env.USER,
//to whom is sending emails
to: emails,
//subject of the email
subject : 'Test boilerplate for sending emails',
//use the handlebars file with name 'sample'
template : 'sample',
//pass in the variable in the handlebars file
context : {
name:name
}
}
//calling the sendMail method on the transporter object created
//take sin two parameters mailOptions and a callback function
//the callback function takes two parameters ( error, info )
//see console logging each to know more
transporter.sendMail(mailOptions,(err, info) => {
if(err){
console.log(err.message)
res.status(500)
res.send(err.message)
}
else{
res.status(200)
res.send(`Email sent`)
}
})
}
//exporting the function sendMail
export { sendMail } |
import React, {useEffect, useState} from 'react';
import { Modal, Table, Badge, Image} from 'react-bootstrap';
import { getPokemonSpecies, getPokemonDetails, getGender, getEvolutionChain } from '../../utils/HTTPRequests';
import './ModalPokemon.scss'
const ModalPokemon = ({ show, onHide, image, pokemonDetails, pokemonSpecies, numberId}) => {
let [isMale, setIsMale] = useState(false)
let [isFemale, setIsFemale] = useState(false)
let [isGenderless, setIsGenderless] = useState(false)
let [evolutionChain, setEvolutionChain] = useState([])
useEffect(() => {
const fetchPokemonGender = async() => {
for (let i = 1; i <= 3; i++){
let response = await getGender(i)
let filter = response.pokemon_species_details && response.pokemon_species_details.some(elem => elem.pokemon_species.name === pokemonDetails.name )
switch(i){
case 1:
setIsFemale(filter)
break;
case 2:
setIsMale(filter)
break;
case 3:
setIsGenderless(filter)
break;
default:
break;
}
}
}
if (show) fetchPokemonGender()
},[show])
useEffect(() => {
const fetchEvolutions = async () => {
let chain = [];
let url = pokemonSpecies.evolution_chain ? pokemonSpecies.evolution_chain.url : ''
console.log(url)
const response = await getEvolutionChain(url)
console.log(response)
for (let key in response.chain){
if(key == 'species'){
const pokemonNumber = response.chain.species.url.split("/")[6].toString().padStart(3,"000")
chain.push({name: response.chain.species.name, image: `https://assets.pokemon.com/assets/cms2/img/pokedex/detail/${pokemonNumber}.png`})
}
if (key == "evolves_to" && response.chain.evolves_to.length > 0){
response.chain.evolves_to.map((element, index) => {
for ( let secondKey in response.chain.evolves_to[index]){
if(secondKey == 'species'){
const pokemonNumber = response.chain.evolves_to[index].species.url.split("/")[6].toString().padStart(3,"000")
chain.push({name: response.chain.evolves_to[index].species.name, image: `https://assets.pokemon.com/assets/cms2/img/pokedex/detail/${pokemonNumber}.png`})
}
if (secondKey == "evolves_to" && response.chain.evolves_to[index].evolves_to.length >= 0) {
response.chain.evolves_to[index].evolves_to.map((secondElem, secondIndex) => {
for ( let thirdKey in response.chain.evolves_to[index].evolves_to[secondIndex]) {
if (thirdKey == "species"){
const pokemonNumber = response.chain.evolves_to[index].evolves_to[secondIndex].species.url.split("/")[6].toString().padStart(3,"000")
chain.push({name: response.chain.evolves_to[index].evolves_to[secondIndex].species.name, image: `https://assets.pokemon.com/assets/cms2/img/pokedex/detail/${pokemonNumber}.png` })
}
}
})
}
}
})
}
}
console.log(evolutionChain)
setEvolutionChain(chain)
}
if (show) fetchEvolutions()
},[show])
const { name, flavor_text_entries, height, weight, types} = pokemonDetails || {};
const { color, habitat } = pokemonSpecies || {};
const pokemonTypes = types && types.map(elem => <Badge pill variant="info"><h4>{elem.type.name.charAt(0).toUpperCase() + elem.type.name.slice(1)}</h4></Badge>)
let gender = ''
gender = isFemale ? gender += 'Female ' : gender += ''
gender = isMale ? gender += 'Male ' : gender += ' '
gender = isGenderless ? gender += 'Genderless ' : gender += ' '
let showEvolutionChain = evolutionChain && evolutionChain.length > 1 ? evolutionChain.map(element => <div><div className="pokemonImage"><Image src={element.image}></Image></div><div className="pokemonName">{element.name}</div></div>).reverse() : "This pokemon does not evolve"
return (
<Modal show={show} onHide={onHide} size={'lg'}>
<div className="pokemon-details">
<div className="image">
<Image src={image}></Image>
</div>
<div className="name">
{name ? <h3>{name.charAt(0).toUpperCase() + name.slice(1)}</h3> : null}
</div>
<div className="number">
<Badge pill variant="dark"><h4>{numberId}</h4></Badge>
</div>
<div className="data">
<Table striped bordered hover variant="dark">
<tbody>
<tr>
<th>Height</th>
<th>{height}</th>
</tr>
<tr>
<th>Weight</th>
<th>{weight}</th>
</tr>
<tr>
<th>Category</th>
<th>{weight}</th>
</tr>
<tr>
<th>Gender</th>
<th>{gender}</th>
</tr>
<tr>
<th>Habitat</th>
<th>{habitat && habitat.name}</th>
</tr>
<tr>
<th>Color</th>
<th>{color && color.name}</th>
</tr>
</tbody>
</Table>
</div>
<div className="types">
<h5>Types:</h5>
{pokemonTypes}
</div>
<div className="evolution">
<h6>Evolution Chain</h6>
<div className="info">
{showEvolutionChain}
</div>
</div>
</div>
</Modal>
)
}
export default ModalPokemon |
var status_string;
var status_url;
var didFinishValidating = true;
var intval;
function buildError(data, classname){
var error = $("<div />").addClass(classname);
var line = $("<p />").addClass("line-no");
line.append("Line " + data.num + ": ");
line.append($("<code />").append(data.line))
var msg = $("<p />").append(data.string);
error.append(line);
error.append(msg);
return error;
}
function appendResult(result){
if(result.warnings.length > 0 || result.errors.length > 0){
$('#result').append($("<p />").text(result.namespace));
}
var canonical_errors = [];
$.each(result.errors, function(key, value){
console.log(value);
if(canonical_errors.indexOf(value.string) == -1){
canonical_errors.push(value.string);
var error = buildError(value, "error");
$("#result").append(error);
}
});
var canonical_warnings = [];
$.each(result.warnings, function(key, value){
if(canonical_warnings.indexOf(value.string) == -1){
canonical_warnings.push(value.string);
var warn = buildError(value, "warning");
$("#result").append(warn);
}
});
}
function storeResults(data){
url = ontology = errors = ont_name = msg = undefined;
didFinishValidating = true;
$("#working").empty();
$.each(data, function(key, value){
appendResult(value);
});
if($("#result").is(":empty")){
$("#result").append("No errors found!");
}
}
function getStatus(){
$.getJSON(status_url, function(response){
if(response.status == 'WORKING'){
$("#working").html("<p style='text-align: center;'>Validating...<br /><img src='static/img/loading.gif' /></p>");
} else {
clearInterval(intval);
storeResults(response.data);
}
});
}
function postData(){
$("#linkform").submit(function(e){
e.preventDefault();
$("#result").empty();
if(didFinishValidating){
$.post("/validate", $("#linkform").serialize(),
function(data){
status_url = data.url;
}, "json");
didFinishValidating = false;
}
});
intval = setInterval('getStatus()', 500);
}
|
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser')
var helpers = require('./helpers.js')
var Message = require('./messages/messageModel')
var app = express();
app.use(bodyParser.json());
app.use(express.static(__dirname + '/../client'));
mongoose.connect('mongodb://localhost/codeChat');
Message.remove({}, function(err) {});
app.post('/message' , function(req, res) {
Message.create({message: helpers.codify(req.body.message), createdAt: Date.now(), text: req.body.message}, function() {
res.end();
});
});
app.get('/message', function(req, res) {
Message.find()
.exec(function(err, message) {
if (err) {console.error(err);}
res.send(message);
});
});
app.listen(8000);
// add sockets
// add ngrok
// add user accounts, sign in, multiple conversations, another view
|
alert("Pronto para iniciar o jogo? Clique em ok.")
var userChoice = prompt("Voce escolhe pedra, papel ou tesoura?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "pedra";
} else if (computerChoice <= 0.67) {
computerChoice = "papel";
} else {
computerChoice = "tesoura";
}
alert("Computer: " + computerChoice);
var compare = function (choice1, choice2) {
if (choice1 === choice2)
alert ("O resultado é um empate!");
else if (choice1 === "pedra") {
if (choice2 === "tesoura")
alert ("pedra vence");
else {
alert ("papel vence");
}
}
else if (choice1 === "papel") {
if (choice2 === "pedra")
alert ("papel vence");
else {
alert ("tesoura vence");
}
}
else if (choice1 === "tesoura") {
if (choice2 === "pedra")
alert ("pedra vence");
else {
alert( "tesoura vence");
}
} else if (choice1 === "Pedra") {
if (choice2 === "tesoura")
alert ("pedra vence");
if (choice2 === "pedra")
alert ("O resultado é um empate!");
else {
alert ("papel vence");
}
}
else if (choice1 === "Papel") {
if (choice2 === "pedra")
alert ("papel vence");
if (choice2 === "papel")
alert ("O resultado é um empate!");
else {
alert ("tesoura vence");
}
}
else if (choice1 === "Tesoura") {
if (choice2 === "pedra")
alert ("pedra vence");
if (choice2 === "tesoura")
alert ("O resultado é um empate!");
else {
alert( "tesoura vence");
}
}
};
compare(userChoice, computerChoice)
|
import React from 'react';
import {View, StyleSheet, Image} from 'react-native';
import {Text} from 'react-native-paper';
const ForecastData = ({day, img, temp}) => {
return (
<View style={styles.container}>
<View style={styles.left}>
<Text style={styles.text}>{day}</Text>
</View>
<Image source={img} style={styles.image} />
<View style={styles.right}>
<Text style={styles.text}>{temp}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
height: 60,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
left: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
marginLeft: 12,
},
image: {
width: 26,
height: 26,
},
right: {
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-end',
marginRight: 12,
},
text: {
fontWeight: 'bold',
color: '#FFFFFF',
},
});
export default ForecastData;
|
function iter(a,b,x,y,ba,mi) {
var n = 0;
var x2 = x*x;
var y2 = y*y;
do {
y = 2*x*y + b;
x = x2 - y2 + a;
x2 = x*x;
y2 = y*y;
n++;
}
while (x2+y2 < ba && n < mi);
return n;
}
self.onmessage = function (event) {
var data = event.data;
var a = data.a;
var b = data.b;
var re = data.re;
var im = data.im;
var lp1 = data.lp1;
var maxiter = data.maxiter;
var escapevalue = data.escapevalue;
var surfacewidth = data.surfacewidth;
var julia = data.julia;
data.values = [];
for (var j = 0; j < surfacewidth; j++) {
a = a+lp1;
if (!julia)
n = iter(a,b,re,im,escapevalue,maxiter);
else
n = iter(re,im,a,b,escapevalue,maxiter);
data.values.push(n);
}
self.postMessage(data);
}
|
/**
* RoomController
*
* @module :: Controller
* @description :: Contains logic for handling requests.
*/
module.exports = {
'list': function(req,res,next){
res.view();
},
'index': function(req,res){
Room.find(function foundRoom(err,rooms){
if(err) return console.log(err);
else {
// console.log('---------------')
// console.log(rooms);
var roomsOnlyIDName = [];
// console.log('---------------')
for( var i = 0; i< rooms.length; i++){
if (rooms[i].msgs != undefined) {
delete rooms[i].msgs;
roomsOnlyIDName.push(rooms[i]);
}
}
rooms = roomsOnlyIDName;
res.json({
success: true,
message: rooms
});
Room.subscribe(req.socket);
};
});
},
'new': function(req,res){
res.view()
},
'update': function(req,res,next){
// var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
// var regEx = /<\w>|<\/\w>/g
var paramsAll = req.params.all();
var msgData = {
msg: paramsAll.msg.replace(/(<([^>]+)>)/ig,"<code>"),
tick: paramsAll.tick,
roomid: req.param('id'),
usr: req.session.User
};
// var msgData = { msg: paramsAll.msg.replace(regEx,"scr_ipt"), roomid: req.param('id'), usr: req.session.User };
Room.findOne(req.param('id')).done(function(err,r){
if(err) return console.log(err);
// console.log(r);
r.msgs.push(msgData);
// console.log(r.msgs);
Room.update(req.param('id'),{ msgs: r.msgs },function updateRoom(err){
if (err) return console.log(err);
if (!err){
Room.publishUpdate(r.id,{msgs: r.msgs});
}
});
res.send(r);
});
},
'create': function(req,res,next){
// debugger;
Room.create(req.params.all(), function roomCreated(err,room){
if(err){
console.log(err);
return res.redirect('/')
}
Room.publishCreate({
id:room.id,
name: room.name
});
});
},
'show': function(req,res){
// Room.subscribe(req.socket, req.param('id'));
var clients = Room.subscribers(req.param('id'));
// Room.publish(req.socket, req.param('id'),{clients: clients});
Room.findOne(req.param('id'), function foundRoom(err,room){
if(err) return console.log(err);
if(!room) return res.redirect('/');
if(!err){
var clients = Room.subscribers(req.param('id'));
// console.log(clients);
// Room.publishUpdate(req.param('id'),{clients: clients});
res.view({
success: true,
room: room,
clients: clients
});
}
});
},
// 'clients': function(req,res){
// var clients = Room.subscribers(req.param('id'));
// res.json({
// success:true,
// message: clients
// });
// }
};
|
'use strict';
let Hapi = require('hapi');
let Util = require('util');
let Config = require('../config');
let server = new Hapi.Server({
connections: {
routes: {
cors: {
origin: Config.CORS,
credentials: true
},
json: {
space: 4
},
payload: {
maxBytes: 1073741824
}
}
}
});
server.connection({
host: '0.0.0.0',
port: Config.PORT
});
server.register([
require('./plugins/routes')
], function (err) {
if (err) {
throw err;
}
});
server.start(function (err) {
if (err) {
return Util.log('Error:', err.message);
}
Util.log('Server started on port ' + Config.PORT);
});
module.exports = server;
|
const findKthPositive = (arr, k) => {
let s=0;
let e=arr.length -1;
while(s < e){
let m = s + Math.floor((e-s)/2);
if(arr[m] - m -1 < k)
s = m +1;
else
e = m-1;
}
return s + k;
}
console.log(findKthPositive([2,3,4,7,11],5));
console.log(findKthPositive([1,10,21,22,25],12)); |
/**
* Load all employees from the database
* The result is saved to res.locals.employees
*/
const requireOption = require('../requireOption');
const getAge = require('age-by-birthdate');
module.exports = function (objectrepository) {
const EmployeeModel = requireOption(objectrepository, 'EmployeeModel');
return function (req, res, next) {
EmployeeModel.find({})
.populate('_employer').exec((err,employees) => {
if(err) {
return next(err);
}
res.locals.employees = employees;
res.locals.employees.forEach(element => {
element.age = getAge(element.dateOfBirth);
});
return next();
})
};
}; |
var gulp = require('gulp');
var karma = require('gulp-karma');
var nodemon = require('gulp-nodemon');
var sass = require('gulp-sass');
var minify = require('gulp-minify');
var browserify = require('browserify');
var es6ify = require('es6ify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify-css');
var rev = require('gulp-rev');
var clean = require('gulp-clean');
var mold = require('mold-source-map');
var shell = require('gulp-shell');
var jsdoc = require('gulp-jsdoc');
var Dgeni = require('dgeni');
gulp.task('build:clean', function () {
return gulp.src('dist', {read: false})
.pipe(clean({force: true}));
});
gulp.task('sass:compile', function() {
return gulp.src('./public/app.scss')
.pipe(sass())
.pipe(gulp.dest('./public/compiled'));
});
gulp.task('js:compile', function() {
return browserify('./public/app.js', {transform: es6ify, debug:true }) // debug is true for sourcemaps
.transform(es6ify)
.bundle()
.pipe(mold.transformSourcesRelativeTo('./public/compiled')) // convert absolute paths to relative ones
.pipe(source('app.js'))
.pipe(gulp.dest('./public/compiled'));
});
gulp.task('app:dist', function() {
gulp.src('./public/index.html')
.pipe(usemin({
css: [minify(), rev()],
js: [uglify(), rev()]
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('app:copy-views', function() {
return gulp.src('./public/modules/**/*.html')
.pipe(gulp.dest('dist/modules/'));
});
gulp.task('sass:watch', function() {
gulp.watch('./public/app.scss', ['sass:compile']);
gulp.watch('./public/modules/**/*.scss', ['sass:compile']);
gulp.watch('./public/css/*.scss', ['sass:compile']);
});
gulp.task('js:watch', function() {
gulp.watch('./public/app.js', ['js:compile']);
gulp.watch('./public/js/*.js', ['js:compile']);
gulp.watch('./public/script/*.js', ['js:compile']);
gulp.watch('./public/modules/**/*.js', ['js:compile']);
});
gulp.task('jsdoc:generate', function(){
gulp.src(["../README.md", "./public/app.js", "./public/modules/**/*.js"])
.pipe(jsdoc('./doc'))
});
gulp.task('doc:generate', shell.task([
'./node_modules/jsdoc/jsdoc.js '+
'-c ./docs-template/conf.json '+ // config file
'-t ./docs-template/template '+ // template file
'-d ./docs '+ // output directory
'../README.md ' + // to include README.md as index contents
'-r ./public/app.js ' + // source code app.js
'-r ./public/modules/**/*.js' // source code directory
]));
function useKarma(autotest) {
return function() {
return gulp.src([
'./public/bower_components/jquery/dist/jquery.js',
'./public/bower_components/bootstrap/dist/js/bootstrap.min.js',
'./public/bower_components/angular/angular.js',
'./public/bower_components/angular-animate/angular-animate.js',
'./public/bower_components/angular-route/angular-route.js',
'./public/bower_components/angular-messages/angular-messages.js',
'./public/bower_components/angular-mocks/angular-mocks.js',
'./public/bower_components/angular-cookies/angular-cookies.js',
'./public/bower_components/angular-sanitize/angular-sanitize.js',
'./public/bower_components/angular-resource/angular-resource.js',
'./public/bower_components/angular-resource/angular-resource.js',
'./public/bower_components/underscore/underscore.js',
'./public/bower_components/moment/moment.js',
'./public/bower_components/angular-moment/angular-moment.js',
'./public/app.js',
'./test/spec/**/*.js'
])
.pipe(karma({
configFile: 'karma.conf.js',
action: autotest ? 'watch' : 'run'
}));
};
}
gulp.task('dgeni', function() {
try {
// copying image files
gulp.src('./fit-docs-package/templates/images/*.*')
.pipe(gulp.dest('./public/dgeni-docs/images'));
// copying css files
gulp.src('./fit-docs-package/templates/css/*.css')
.pipe(gulp.dest('./public/dgeni-docs/css'));
// compiling dgeni
var dgeni = new Dgeni([require('./fit-docs-package')]);
return dgeni.generate();
} catch(x) {
console.log(x);
console.log(x.stack);
throw x;
}
});
gulp.task('test', useKarma(false));
gulp.task('autotest', useKarma(true));
gulp.task('build', ['build:clean', 'sass:compile', 'js:compile', 'app:dist', 'doc:generate', 'app:copy-views']);
gulp.task('dev', ['sass:compile', 'js:compile', 'sass:watch', 'js:watch']);
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import PersonIcon from '@material-ui/icons/Person';
import { styles } from './Styles/Header'
class UserMenu extends Component {
state = {
anchorEl: null,
};
componentWillMount() {
this.setState({imageError: false});
}
handleClick = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = (event) => {
this.setState({ anchorEl: null });
};
render() {
const { classes } = this.props;
const { anchorEl } = this.state;
return (
<div>
<Button
aria-owns={anchorEl ? 'simple-menu' : null}
aria-haspopup="true"
onClick={this.handleClick}
>
<Avatar alt="User" className={classNames(classes.avatar, classes.bigAvatar)}>
<PersonIcon />
</Avatar>
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
>
<MenuItem onClick={this.handleClose}>Logout</MenuItem>
</Menu>
</div>
);
}
}
UserMenu.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
export default withStyles(styles, { withTheme: true })(UserMenu);
|
/**
* wx
*/
var FDDrillingMgr = function (viewer) {
var version = "0.0.1";
var dsc = "用于钻井柱管理";
var scene = viewer.scene;
var drillingData = [];
var playModel = null ;
var pickedModels = [];
var clickedColor = new FreeDo.Color(1,3,1,1);
var unClickedColor =new FreeDo.Color(1,1,1,1);
function cameraSetView(nowLocation) {
scene.camera.setView( {
position : FreeDo.Cartesian3.fromDegrees( nowLocation.lon, nowLocation.lat, nowLocation.alt ),//北京100000公里上空
heading : FreeDo.Math.toRadians( nowLocation.heading ),
pitch : FreeDo.Math.toRadians( nowLocation.pitch ),
} );
}
//添加钻井柱
function addDrilling(id, url, lon, lat, height, course, alpha, roll, scaleX, scaleY, scaleZ) {
this.id = id;
this.url = url;
this.lon = lon;
this.lat = lat;
this.height = height;
this.course = course;
this.alpha = alpha;
this.roll = roll;
this.scaleX = scaleX;
this.scaleY = scaleY;
this.scaleZ = scaleZ;
var modelMatrix = getModelMatrix(lon, lat, height, course, alpha, roll, scaleX, scaleY, scaleZ);
var primitive = viewer.scene.primitives.add(FreeDo.Model.fromGltf(
{
id: id,
url: url,
show: true, // default
modelMatrix: modelMatrix,
allowPicking: true, // not pickable
debugShowBoundingVolume: false, // default
debugWireframe: false
}));
/* flyToModelByModel(lon,lat);*/
return primitive;
}
//定位到模型
function flyToModelByModel(lon,lat) {
var camera = viewer.camera;
camera.flyTo({
destination : FreeDo.Cartesian3.fromDegrees( lon, lat-0.0014,70 ),
orientation : {
heading : FreeDo.Math.toRadians( 0 ),
pitch : FreeDo.Math.toRadians( -15 ),
roll : FreeDo.Math.toRadians( 0 )
},
duration : 3,//动画持续时间
});
}
//添加钻井柱描述信息
function addDsc(id,lon,lat) {
var citizensBankPark = viewer.entities.add( {
id : id,
name : id,
position : FreeDo.Cartesian3.fromDegrees( lon, lat ),
label : { //文字标签
text : id,
font : '14pt monospace',
style : FreeDo.LabelStyle.FILL_AND_OUTLINE,
outlineWidth : 2,
verticalOrigin : FreeDo.VerticalOrigin.BOTTOM, //垂直方向以底部来计算标签的位置
pixelOffset : new FreeDo.Cartesian2( 0, -19 ) //偏移量
} ,
billboard : {
image : "static/webgl/drillingColumn/images/1.png",
width : 30,
height : 30
},
} );
}
var sceneCameraAnimationRenderFunction = function (e,t) {
if(playModel){
for(var i =0;i<playModel.model.length;i++){
if(playModel.model[i].ready){
// Center in WGS84 coordinates
var center1 = FreeDo.Matrix4.multiplyByPoint(playModel.model[i].modelMatrix, playModel.model[i].boundingSphere.center, new FreeDo.Cartesian3());
var cartographic = scene.globe.ellipsoid.cartesianToCartographic(center1);
if(i==0&&playModel.cacheNowHeight[i]>5){
scene.preRender.removeEventListener(sceneCameraAnimationRenderFunction);
}
var lon = cartographic.longitude / Math.PI * 180;
var lat = cartographic.latitude / Math.PI * 180;
var nowScaleZ = playModel.drilling[i].height/10;
playModel.cacheNowHeight[i] += 2;
var modelMatrix = getModelMatrix(lon, lat, playModel.cacheNowHeight[i], playModel.position.heading, playModel.position.pitch, playModel.position.roll, playModel.position.scaleR, playModel.position.scaleR, nowScaleZ);
playModel.model[i].modelMatrix = modelMatrix;
}
}
}
}
//左键双击事件
function leftDoubleClickEvent(callback) {
var ent= viewer.selectedEntity ;
var selectComponentEventType = FreeDo.ScreenSpaceEventType.LEFT_DOUBLE_CLICK;
viewer.screenSpaceEventHandler = new FreeDo.ScreenSpaceEventHandler(viewer.canvas);
viewer.screenSpaceEventHandler.setInputAction(function (movement) {
var po = movement.position;
var pick= new FreeDo.Cartesian2(po.x,po.y);
var cartesian = viewer.scene.globe.pick(viewer.camera.getPickRay(pick), viewer.scene);
var cartographic = FreeDo.Cartographic.fromCartesian(cartesian);
var point=[ cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180];
var picked = viewer.scene.pick(movement.position);
//console.log(picked);
if(FreeDo.defined(picked)&&isString(picked.id)){
var arr = picked.id.split("_");
callback(arr[0],arr[1]);
return;
}
if(FreeDo.defined(picked)){
for(var i =0;i<drillingData.length;i++){
if(picked.id.name==drillingData[i].id){
playModel=drillingData[i];
if(playModel.cacheNowHeight.length>0&&playModel.cacheNowHeight[0]>4) return;
scene.preRender.addEventListener(sceneCameraAnimationRenderFunction);
if(typeof callback == "function"){
callback(drillingData[i].id,null);
}
}
}
}
}, selectComponentEventType);
}
//左键点击事件
function leftClickEvent(callback){
var selectComponentEventType = FreeDo.ScreenSpaceEventType.LEFT_CLICK;
viewer.screenSpaceEventHandler = new FreeDo.ScreenSpaceEventHandler(viewer.canvas);
viewer.screenSpaceEventHandler.setInputAction(function (movement){
/*var picked = viewer.scene.pick(movement.position);
if(picked==undefined){
for(var i=0;i<pickedModels.length;i++)
pickedModels[i].primitive.color=unClickedColor;
pickedModels=[];
return ;
}
if(pickedModels.length!=0){ //使之前点变色的模型重置颜色并清空所选模型容器
for(var i=0;i<pickedModels.length;i++)
pickedModels[i].primitive.color=unClickedColor;
pickedModels=[];
}
pickedModels.push(picked); //缓存点选模型
pickedModels[0].primitive.color=clickedColor */
},selectComponentEventType)
}
function isString(obj){ //判断对象是否是字符串
return Object.prototype.toString.call(obj) === "[object String]";
}
function getModelMatrix(lon,lat,height,heading,pitch,roll,scaleX,scaleY,scaleZ)
{
var scaleCartesian3=new FreeDo.Cartesian3(scaleX,scaleY,scaleZ); //获得三元素,直接通过数字获得
var scaleMatrix=FreeDo.Matrix4.fromScale(scaleCartesian3);//获得缩放矩阵
var position = FreeDo.Cartesian3.fromDegrees(lon,lat,height);//根据经纬高获得位置三元素
var heading=FreeDo.Math.toRadians(heading);
var pitch=FreeDo.Math.toRadians(pitch);
var roll=FreeDo.Math.toRadians(roll);
var hpr=new FreeDo.HeadingPitchRoll(heading,pitch,roll);
var transform=FreeDo.Transforms.headingPitchRollToFixedFrame(position,hpr);//获得姿态矩阵
var matrix4=new FreeDo.Matrix4();
FreeDo.Matrix4.multiply(transform,scaleMatrix,matrix4);
return matrix4;
}
return {
//开始监听
startlistening : function(callback) {
leftClickEvent(callback);
leftDoubleClickEvent(callback);
},
//添加钻井柱数据
add : function(parameter){
for(var i =0;i<drillingData.length;i++){
if(drillingData[i].id==parameter.id) return false;
}
parameter.model=[];
parameter.cacheNowHeight=[];
addDsc(parameter.id,parameter.position.lon, parameter.position.lat);
var nowHeight = parameter.position.height;
for(var i=0;i<parameter.drilling.length;i++){
var nowScaleZ = parameter.drilling[i].height/10;
if(i==0){
//nowHeight = nowHeight + parameter.drilling[i].height/2;
nowHeight = nowHeight ; //建模如果以模型中心点为基准则采用上一句
var model = addDrilling(parameter.id+"_"+i,parameter.drilling[i].filePath, parameter.position.lon, parameter.position.lat, nowHeight, parameter.position.heading, parameter.position.pitch, parameter.position.roll, parameter.position.scaleR, parameter.position.scaleR, nowScaleZ);
parameter.model.push(model);
parameter.cacheNowHeight.push(nowHeight);
}else{
//nowHeight = nowHeight + parameter.drilling[i].height/2 + parameter.drilling[i-1].height/2;
nowHeight = nowHeight + parameter.drilling[i-1].height; //建模如果以模型中心点为基准则采用上一句
var model = addDrilling(parameter.id+"_"+i,parameter.drilling[i].filePath, parameter.position.lon, parameter.position.lat, nowHeight, parameter.position.heading, parameter.position.pitch, parameter.position.roll, parameter.position.scaleR, parameter.position.scaleR, nowScaleZ);
parameter.model.push(model);
parameter.cacheNowHeight.push(nowHeight);
}
}
drillingData.push(parameter);
},
//移除钻井柱数据
removeByID : function(id) {
for(var i=0;i<drillingData.length;i++){
if(id==drillingData[i].id){
var entity = viewer.entities.getById(id);
if(entity){
viewer.entities.remove(entity);
}
for(var j=0;j<drillingData[i].model.length;j++){
scene.primitives.remove(drillingData[i].model[j]);
}
drillingData.splice(i,1);
if(playModel.id==id){
playModel=null;
}
}
}
},
//清空
clean : function() {
for(var i=0;i<drillingData.length;i++){
var entity = viewer.entities.getById(drillingData[i].id);
if(entity){
viewer.entities.remove(entity);
}
for(var j=0;j<drillingData[i].model.length;j++){
scene.primitives.remove(drillingData[i].model[j]);
}
}
drillingData=[];
playModel=null;
}
};
} |
import React, { useState, useEffect } from "react";
// Styled Component
import styled from "styled-components";
// Bootstrap
import Form from "react-bootstrap/Form";
// Draggablevertice Component
import { DraggableVertice } from "..";
const Playground = styled.div`
width: 100%;
`;
const Box = styled.div`
width: ${props => props.width || '100px'};
height: ${props => props.height || '100px'};
margin: 0 auto;
position: relative;
`;
const Shadow = styled.div`
background-color: ${props => props.backgroundColor || '#00c4ff'};
opacity: 0.25;
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
`;
const Component = styled.div`
clip-path: ${props => props.formula};
background-color: ${props => props.backgroundColor || '#00c4ff'};
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
`;
const ShapePreview = (props) => {
// Holds an array of DraggableVertices
const [vertices, setVertices] = useState([]);
// Set to a number that determines which DraggableVertice has its tooltip showing
// This way, only one vertice can show its close button at a time
const [focusNumber, setFocusNumber] = useState(-1);
// Creation of DraggableVertices depending on shapeInformation values
useEffect(() => {
const array = [];
for (let i = 0; i < props.shapeInformation.vertices; i++) {
if (props.shapeInformation.verticeCoordinates[i] === undefined) {
return;
}
array.push(
<DraggableVertice
key={1000 + i}
number = {i}
x={props.shapeInformation.verticeCoordinates[i].x}
y={props.shapeInformation.verticeCoordinates[i].y}
handleChange={props.handleChange}
focusNumber={focusNumber}
setFocusNumber={setFocusNumber}
/>
);
}
setVertices(array);
}, [props.shapeInformation, focusNumber]);
return(
<>
<Playground>
<Box height="300px" width="300px" onClick={(e) => props.handleChange(e)}>
{ props.shapeInformation.showShadow && <Shadow backgroundColor={props.shapeInformation.backgroundColor} id="shapeShadow" /> }
<Component formula={props.shapeInformation.formula} backgroundColor={props.shapeInformation.backgroundColor} id="clippedShape" />
{vertices}
</Box>
<Form style={{padding: '7px', textAlign: 'center'}}>
<Form.Check
type="switch"
name="showShadow"
id="modal-custom-switch"
label="Show Outside of the Clipped Area"
checked={props.shapeInformation.showShadow}
onChange={(e) => props.handleChange(e)}
/>
</Form>
</Playground>
</>
);
}
export default ShapePreview; |
angular.module('ngApp.pastShipment').controller('ShipmentDocumentDownloadController', function ($scope, $state, $translate, $location, $stateParams, $filter, CustomerService, SessionService, $uibModal, uiGridConstants, toaster, ShipmentService, shipmentId) {
//Set Multilingual for Modal Popup
var setModalOptions = function () {
$translate(['FrayteError', 'ErrorGetting', 'past', 'shipments']).then(function (translations) {
$scope.TitleFrayteError = translations.FrayteError;
$scope.TextErrorGettingShipmentRecord = translations.ErrorGetting + " " + translations.shipment + " " + translations.document + " " + translations.records;
});
};
$scope.gridOptions = {
showFooter: true,
enableSorting: true,
multiSelect: false,
enableFiltering: true,
enableRowSelection: true,
enableSelectAll: false,
enableRowHeaderSelection: false,
selectionRowHeaderWidth: 35,
noUnselect: true,
enableGridMenu: true,
enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
enableVerticalScrollbar: uiGridConstants.scrollbars.NEVER,
columnDefs: [
{ name: 'SN', displayName: 'SN', headerCellFilter: 'translate', enableFiltering: false, width: 50 },
{ name: 'DocumentType', displayName: 'DocumentType', headerCellFilter: 'translate' },
{ name: 'DocumentTitle', displayName: 'Document', headerCellFilter: 'translate' },
{ name: 'Edit', displayName: "", enableFiltering: false, enableSorting: false, enableGridMenuenableRowSelection: false, noUnselect: false, cellTemplate: "shipment/shipmentDocumentDownload/shipmentDocumentDownloadLink.tpl.html", width: 100 }
]
};
$scope.RearrangeSerialNumbers = function (collectionObject) {
if (collectionObject.length > 0) {
for (var i = 0; i < collectionObject.length; i++) {
collectionObject[i].SN = i + 1;
}
}
return collectionObject;
};
$scope.LoadPastShipmentDownloads = function (shipmentId) {
ShipmentService.GetShipmentDocuments(shipmentId).then(function (response) {
//Need to crete SN
var snData = $scope.RearrangeSerialNumbers(response.data);
$scope.gridOptions.data = snData;
}, function () {
toaster.pop({
type: 'error',
title: $scope.TitleFrayteError,
body: $scope.TextErrorGettingShipmentRecord,
showCloseButton: true
});
});
};
function init() {
// set Multilingual Modal Popup Options
setModalOptions();
$scope.ShipmentId = shipmentId;
$scope.LoadPastShipmentDownloads($scope.ShipmentId);
}
init();
});
|
/*const produto = {};
produto.nome = 'celular';
produto.preco = 10000;
produto.cor = 'azul';
console.log(produto.nome, produto.preco);*/
function imprimir_soma(n1, n2){
console.log(n1+n2)
}
imprimir_soma(2,5);
//operador ternário:
const resultado = nota => nota>=7? 'Aprovado' : 'Reprovado';
console.log(resultado(6));
|
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
const Electronics = ({products}) => {
return (
<div>
<div className="min-h-[80vh] flex flex-col space-y-5">
<div>
<div>
<h2 className="text-3xl my-3 font-semibold">Mens's Clothing</h2>
</div>
<div className="grid grid-cols-1 gap-5 md:grid-cols-2 lg:grid-cols-4 ">
{products
.filter((item) => item.category === "electronics")
// .filter((p, i) => i < 5)
.map((prod) => (
<ProductItem key={prod.title} product={prod} />
))}
</div>
</div>
</div>
</div>
);
};
const mapDispatchToProps = (dispatch) => ({
// googleSignInStart: () => dispatch(googleSignInStart()),
});
const mapStateToProps = createStructuredSelector({
products: selectProducts,
});
export default connect(mapStateToProps, mapDispatchToProps)(Electronics);
|
const express = require('express');
const router = express.Router();
const mainController = require('./controllers');
// GET
router.get('/api/v1/allTables', mainController.allTablesSelect);
router.get('/api/v1/tables', mainController.tablesSelect);
// POST
router.post('/api/v1/tables', mainController.tablesInsert);
// PATCH
router.patch('/api/v1/tables', mainController.tablesUpdate);
// DELETE
router.delete('/api/v1/tables', mainController.tablesDelete);
module.exports = router;
|
angular.module('influences')
.service('genreService', function($http, $state) {
this.getMainGenres = function() {
return $http({
method: 'GET',
url: '/api/main/genres'
})
.then(function(res) {
return res.data;
})
}
this.getRandomGenre = function() {
return $http({
method: 'GET',
url: '/api/genre/random'
})
.success(function(res) {
$state.go('genre', {id: res.id});
})
},
this.createGenre = function(genre) {
return $http({
method: 'POST',
url: '/api/genre',
data: genre
})
.then(function (response) {
return response.data;
})
}
this.getAllGenres = function() {
return $http({
method: 'GET',
url: '/api/genre/'
})
.then(function(res) {
return res.data;
})
},
this.getGenre = function(id) {
return $http({
method: 'GET',
url: '/api/genre/' + id
})
.then(function(res) {
return res.data;
})
},
this.updateGenre = function(genre) {
genre = {
name: genre.name,
type: genre.type,
founders: genre.founders,
artists: genre.artists,
id: genre.id,
description: genre.description
}
return $http({
method: 'PUT',
url: '/api/genre/' + genre.id,
data: genre
})
.then(function(data) {
return data.data;
})
}
});
|
const storeItemKey = 'state';
/**
* Try to load state from localStorage
* Do nothing if user disabled localStorage
* @returns {*}
*/
export const loadState = () => {
try {
const serializedState = localStorage.getItem(storeItemKey);
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (e) {
return undefined;
}
};
/**
* Try to save Redux store into localStorage.
* This function doesn't cover case when user disabled localStorage
* @param state - object
*/
export const saveState = state => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem(storeItemKey, serializedState);
} catch (e) {
// do something
}
};
|
var namespacejava_1_1lang =
[
[ "Object", "classjava_1_1lang_1_1_object.html", "classjava_1_1lang_1_1_object" ]
]; |
class comunicacaoEletronicaC{
constructor(id, meioComunicacao, telefone, preferencia, utilizacao){
this.id = id;
this.meioComunicacao = meioComunicacao;
this.telefone = telefone;
this.preferencia = preferencia;
this.utilizacao = utilizacao;
}
} |
function datos_Docentes_ValidacionDatos_Cargar(pCicloEstimulo) {
/* var Docentes_ValidacionDatosSource =
{
datatype: "json",
datafields: [
{name: 'accion', type: 'string'},
{name: 'idEstimulo', type: 'bigint'},
{name: 'idEstadoRevisado', type: 'bigint'},
{name: 'numeroEmpleado', type: 'bigint'},
{name: 'nombreCompleto', type: 'varchar'},
{name: 'tipo', type: 'varchar'},
{name: 'envioSolicitud', type: 'varchar'},
{name: 'numeroHojas', type: 'int'}
],
url: "/modelo/modListadocentesAprobadosConsultar.php",
type: 'POST',
data: {'pCicloEstimulo': pCicloEstimulo},
async: false
};
var dataAdapter = new $.jqx.dataAdapter(Docentes_ValidacionDatosSource);
return dataAdapter; */
//////////////////////
var data = new Array();
var accion =
[
"<button class='btnInfoEmpleado' id='btngVerInfo' title='Ver información del empleado' onclick='verInformacionEmpleado()'; >Ver información del empleado</button>"
];
var nombreCompleto =
[
"Flores Lopez Teodoro", "Trejo Rivas Alejandra", "Morales Islas Teresa", "Sanchez Espinosa Xochitl",
"Espinosa Osorio Carlos", "Saavedra Cervantes Mario", "Oropeza Lopez Pedro", "Dominguez Saavedra Marisol",
"Perez Diaz Karla", "Prado Zapata Liliana", "Cervantes Soria Olga", "Barron Quintero Luciana", "Perez Diaz Luis",
"Rosas Villa Lorena", "Valle Ortiz Elena", "Zapata Flores Eduardo", "Nuno Islas Sandra", "Narez Rios Esperanza"
];
var tipos =
[
"PTC", "PMT", "PH"
];
var envioSolicitud =
[
"20/01/2016", "15/01/2016", "16/01/2015", "17/01/2016", "18/01/2016", "19/01/2016", "21/01/2016"
];
var estados =
[
"Si", "No"
];
for (var i = 0; i < 200; i++) {
var row = {};
var idEstimulo = 1 + Math.round(Math.random() * 10);
var numeroEmpleado = 2000 + Math.round(Math.random() * 100);
var numeroHojas = 1 + Math.round(Math.random() * 10);
row["accion"] = accion[Math.floor(Math.random() * accion.length)];
row["nombreCompleto"] = nombreCompleto[Math.floor(Math.random() * nombreCompleto.length)];
row["tipo"] = tipos[Math.floor(Math.random() * tipos.length)];
row["envioSolicitud"] = envioSolicitud[Math.floor(Math.random() * envioSolicitud.length)];
row["idEstadoRevisado"] = estados[Math.floor(Math.random() * estados.length)];
row["numeroHojas"] = numeroHojas;
row["idEstimulo"] = idEstimulo;
row["numeroEmpleado"] = numeroEmpleado;
data[i] = row;
}
var source =
{
localdata: data,
datatype: "array",
datafields: [
{name: 'accion', type: 'string'},
{name: 'idEstimulo', type: 'bigint'},
{name: 'idEstadoRevisado', type: 'bigint'},
{name: 'numeroEmpleado', type: 'bigint'},
{name: 'nombreCompleto', type: 'varchar'},
{name: 'tipo', type: 'varchar'},
{name: 'envioSolicitud', type: 'varchar'},
{name: 'numeroHojas', type: 'int'}
]
};
var dataAdapter = new $.jqx.dataAdapter(source);
return dataAdapter;
}
function Docentes_ValidacionDatos_TablaCargar(sControl, piCicloEstimuloID) {
var dataAdapter = datos_Docentes_ValidacionDatos_Cargar(piCicloEstimuloID);
dataAdapter.dataBind();
var registros = dataAdapter.records;
Docentes_ValidacionDatos_FormularioEnvioCargar(registros);
var cellsrenderer = function (row, column, value, defaultHtml) {
var hdnEstado = "#hdnEstado_" + registros[row].idEstimulo;
var sEstado = $(hdnEstado).val();
var element = $(defaultHtml);
return element[0].outerHTML;
};
console.info("Cambio para evitar que se muestre el filtro sobre la columna de acciones");
console.info("Cambio para hacer que el boton de informacion de empleado abarque toda su celda");
$(sControl).jqxGrid({
width: '99.5%',
height: '100%',
source: dataAdapter,
theme: 'energyblue',
rowsheight: 40,
localization: getLocalization('es'),
autoshowfiltericon: true,
filterable: true,
sortable: true,
pageable: true,
editable: false,
columns: [
{text: '', datafield: 'accion', width: '40px', cellsalign: 'center', pinned: true, sortable: false, filterable: false, menu: false},
{text: 'No. empleado', datafield: 'numeroEmpleado', cellsalign: 'center', width: '120px', cellsrenderer: cellsrenderer},
{text: 'Nombre completo', datafield: 'nombreCompleto', cellsrenderer: cellsrenderer},
{text: 'ID', datafield: 'idEstimulo', hidden: true}
]
});
// Configurar clics en rows
$(sControl).bind('rowselect', function (event) {
var row = event.args.rowindex,
datafield = event.args.datafield,
datarow = $(sControl).jqxGrid('getrowdata', row);
var mensajeCargando = '<div class="txtCentrado"><h2 style="width: 500px; padding-top: 90px; margin: 0 auto; color: #ABABAB;">Cargando...</h2></div>';
$("#detalleDatosPatentes").html(mensajeCargando);
window.setTimeout(function(){ //Simular carga de datos
Docentes_DetallePatentes_CargarVista(datarow.idEstimulo, datarow);
}, 1800);
});
}
function Docentes_ValidacionDatos_FormularioEnvioCargar(arrDocentes) {
$("#frmValidacionDatos").html('');
for (var i = 0; i < arrDocentes.length; i++) {
var idEstimulo = arrDocentes[i].idEstimulo;
// Input estado
var mapInputEstado = document.createElement("input");
mapInputEstado.type = "hidden";
mapInputEstado.id = "hdnEstado_" + idEstimulo;
mapInputEstado.name = "hdnEstado_" + idEstimulo;
mapInputEstado.value = arrDocentes[i].idEstadoRevisado;
// Input hojas expediente
var mapInputNoHojas = document.createElement("input");
mapInputNoHojas.type = "hidden";
mapInputNoHojas.id = "hdnNoHojas_" + idEstimulo;
mapInputNoHojas.name = "hdnNoHojas_" + idEstimulo;
mapInputNoHojas.value = arrDocentes[i].numeroHojas;
// Agrega el input al form
$("#frmValidacionDatos").append(mapInputEstado);
$("#frmValidacionDatos").append(mapInputNoHojas);
}
} |
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { List, ListItem, ListItemText, Checkbox } from '@material-ui/core/';
import { fetchMessagesByCategory } from '../../../actions/messages';
import Toolbar from '../Toolbar/Toolbar';
import Loader from '../../UI/Loader/Loader';
import { errorToaster } from '../../UI/Toaster/Toaster';
import './List.css';
const MessageList = ({ category, fetchMessagesByCategory, messagesList, isLoading, appErrors }) => {
const [checkedMessages, setCheckedMessages] = useState([]);
const [isChecked, setIsChecked] = useState(false);
const filterCheckedMessages = () => {
const filteredMessages = messagesList.filter(message => !checkedMessages.includes(message.id));
fetchMessagesByCategory(filteredMessages);
setIsChecked(false);
setCheckedMessages('');
};
const handleSelectAllCheckbox = evt => {
const checked = evt.currentTarget.checked ? true : false;
if (messagesList.length > 0) {
setIsChecked(checked);
}
if (checked) {
messagesList.map(message => setCheckedMessages(prevState => [...prevState, message.id]));
} else {
setCheckedMessages('');
}
};
const handleCheckboxClick = id => {
const currentIndex = checkedMessages.indexOf(id);
let newChecked = [...checkedMessages];
if (currentIndex === -1) {
newChecked = [...newChecked, id];
} else {
newChecked.splice(currentIndex, 1);
}
const isAllChecked = newChecked.length === messagesList.length;
setIsChecked(isAllChecked);
setCheckedMessages(newChecked);
};
useEffect(() => {
const fetchMessages = (category = 'inbox') => {
fetchMessagesByCategory(category);
};
setIsChecked(false);
setCheckedMessages('');
fetchMessages(category);
if (appErrors.type === 'server') {
errorToaster(appErrors.message);
}
}, [appErrors.message, appErrors.type, category, fetchMessagesByCategory]);
return (
<div className="messages-container">
<Toolbar
filterCheckedMessages={filterCheckedMessages}
handleSelectAllCheckbox={handleSelectAllCheckbox}
checkedMessages={checkedMessages}
isChecked={isChecked}
category={category}
/>
<List className="message-list">
{isLoading ? (
<Loader />
) : messagesList.length > 0 ? (
messagesList.map(message => (
<ListItem key={message.id} className="message-item">
<Checkbox
className="message-checkbox"
color="primary"
checked={checkedMessages.indexOf(message.id) !== -1}
onClick={() => handleCheckboxClick(message.id)}
/>
<Link to={`/${message.id}`} className="message-link">
<ListItemText primary={message.subject} className="message-text" />
</Link>
</ListItem>
))
) : (
<div>
<h4 className="no-messages">No messages in this category</h4>
</div>
)}
</List>
</div>
);
};
const mapStateToProps = ({ loader, messages, appErrors }) => ({
isLoading: loader.isLoading,
messagesList: messages.messagesList,
appErrors
});
const mapDispatchToProps = dispatch => ({
fetchMessagesByCategory: data => {
dispatch(fetchMessagesByCategory(data));
}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(MessageList);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.