text
stringlengths
7
3.69M
function initialize_phone() { touchable = 0, i = 0, $(".flip-card-inner").css("transform", "rotateY(0deg)"), $("#earringsL").css("opacity", "0"), $("#earringsR").css("opacity", "0"), $(".flip-card").css("z-index", "1"), $(".flip-card").eq(1).css("z-index", "2"), $("#cover").css("z-index", "5"), $("#cup").css("display", "block"), $("#ink").css("display", "block"), $("#resources").css("display", "none"), $("#credits").css("display", "none"), $("#book-bg").remove(), $("#quilldren").unbind("click"), $("#earringsL").unbind("click"), $("#earringsR").unbind("click"), $("#cup").css("opacity", "1"), $("#ink").css("opacity", "1"), $("#toast").css("opacity", "0"), $("#book").css("transform", "translate(calc(0 * var(--unit)),calc(35 * var(--unit)))"), $("#book").css("z-index", "5"), $("#book2").css("transform", "rotate(-4.81deg)"), $("#book2").css("width", "calc(95.5 * var(--unit))"), $("#book2").css("height", "calc(117.25 * var(--unit))"), $("#book2").css("background-image", "url('img/book.webp')"), $("#book").unbind("click"), $(".flip-card").css("padding-top", "calc(3.4 * var(--unit))"), $(".flip-card").css("padding-left", "calc(12.7 * var(--unit))"), $(".flip-card").css("width", "calc(83 * var(--unit))"), $(".flip-card").css("height", "calc(112.5 * var(--unit))"), $("#quilldren").css("background-image", "url('img/Quildren-2.gif')"), $("#quilldren").css("width", "calc(65 * var(--unit))"), $("#quilldren").css("height", "calc(65 * var(--unit))"), $("#quilldren").css("transform", "translate(calc(55 * var(--unit)),calc(100 * var(--unit)))"), $("#pad").css("transform", "translate(calc(29 * var(--unit)),calc(-1 * var(--unit)))"), $("#pad2").css("background-image", "url('img/Pad.webp')"), $("#pad2").css("transform", "rotate(11deg)"), $("#pad2").css("width", "calc(72 * var(--unit))"), $("#pad2").css("height", "calc(57.08 * var(--unit))"), $("#twitter").css("transform", "translate(calc(-12 * var(--unit)),calc(155 * var(--unit)))"), $("#twitter2").css("background-image", "url('img/Twitter.webp')"), $("#twitter2").css("transform", "rotate(-13deg)"), $("#twitter2").css("width", "calc(52 * var(--unit))"), $("#twitter2").css("height", "calc(44.3 * var(--unit))"), $("#pen").css("transform", "translate(calc(29 * var(--unit)),calc(155 * var(--unit)))"), $("#pen2").css("background-image", "url('img/Pen.webp')"), $("#pen2").css("transform", "rotate(26deg)"), $("#pen2").css("width", "calc(23 * var(--unit))"), $("#pen2").css("height", "calc(82.2 * var(--unit))"), $("#page_cover").css("background-image", "url('img/page-cover.webp')"), setTimeout(function() { $("#book").click(change_scene_phone); }, 500); } function change_scene_phone() { touchable = 1, $("#cup").css("opacity", "0"), $("#ink").css("opacity", "0"), $("#toast").css("opacity", "1"), $("#book").css("transform", "translate(calc(-6 * var(--unit)),calc(35 * var(--unit)))"), $("#book").css("z-index", "7"), $("#book2").css("transform", "rotate(0)"), $("#book2").css("width", "calc(109 * var(--unit))"), $("#book2").css("height", "calc(133.83 * var(--unit))"), $("#book").append('<div id="book-bg"></div>'), $(".flip-card").css("padding-top", "calc(4 * var(--unit))"), $(".flip-card").css("padding-left", "calc(14 * var(--unit))"), $(".flip-card").css("width", "calc(95 * var(--unit))"), $(".flip-card").css("height", "calc(128 * var(--unit))"), $("#quilldren").css("background-image", "url('img/Quildren-phone.webp')"), $("#quilldren").css("width", "calc(24 * var(--unit))"), $("#quilldren").css("height", "calc(32.88 * var(--unit))"), $("#quilldren").css("transform", "translate(calc(5 * var(--unit)),calc(5 * var(--unit)))"), $("#pad").css("transform", "translate(calc(30 * var(--unit)),calc(5 * var(--unit)))"), $("#pad2").css("background-image", "url('img/Pad-phone.webp')"), $("#pad2").css("transform", "rotate(0deg)"), $("#pad2").css("width", "calc(24 * var(--unit))"), $("#pad2").css("height", "calc(32.88 * var(--unit))"), $("#twitter").css("transform", "translate(calc(55 * var(--unit)),calc(5 * var(--unit)))"), $("#twitter2").css("background-image", "url('img/Twitter-phone.webp')"), $("#twitter2").css("transform", "rotate(0deg)"), $("#twitter2").css("width", "calc(24 * var(--unit))"), $("#twitter2").css("height", "calc(32.88 * var(--unit))"), $("#pen").css("transform", "translate(calc(77 * var(--unit)),calc(5 * var(--unit)))"), $("#pen2").css("background-image", "url('img/Pen-phone.webp')"), $("#pen2").css("transform", "rotate(0deg)"), $("#pen2").css("width", "calc(24 * var(--unit))"), $("#pen2").css("height", "calc(32.88 * var(--unit))"), $("#book").unbind("click"), $("#page_cover").css("background-image", "url('img/Cover.webp')"), setTimeout(function() { $("#quilldren").click(initialize_phone), $("#book-bg").css("opacity", "1"), $("#cup").css("display", "none"), $("#resources").css("display", "block"), $("#credits").css("display", "block"), $("#ink").css("display", "none"), $("#book").click(first_page_phone); }, 500); } function first_page_phone() { /* 跳到第一頁,取消隱藏第二頁 */ $(".flip-card").eq(2).css("display", "block"); i = 1, $("#earringsL").css("opacity", "1"), $("#earringsR").css("opacity", "1"), $("#earringsL").click(previous_phone), $("#earringsR").click(next_phone), $(".flip-card-inner").eq(0).css("transform", "rotateY(-180deg)"), $(".flip-card").eq(1).css("z-index", "4"), $("#book").unbind("click"), setTimeout(function() { $(".flip-card-back").eq(0).css("z-index", "3"); }, 250); } function next_phone() { if(i == 0){ /* 跳到第一頁,取消隱藏第二頁 */ $(".flip-card").eq(2).css("display", "block"); }else if(i < $(".flip-card-inner").length -1){ /* 跳到第i+1頁,取消隱藏第i+2頁,隱藏第i-1頁 (不隱藏0,1) */ if (i < $(".flip-card-inner").length - 2) { $(".flip-card").eq(i+2).css("display", "block"); } if (i-1 > 1) { $(".flip-card").eq(i-1).css("display", "none"); } }else if(i == $(".flip-card-inner").length -1){ if (i-1 > 1) { $(".flip-card").eq(i-1).css("display", "none"); } } $("#earringsR").unbind("click"), 0 == i ? ($(".flip-card-inner").eq(0).css("transform", "rotateY(-180deg)"), $(".flip-card").eq(1).css("z-index", "3"), $("#earringsL").css("opacity", "1"), $("#earringsR").css("opacity", "1"), setTimeout(function() { i += 1, $("#earringsR").click(next_phone); }, 250)) : i < $(".flip-card-inner").length - 1 ? ($(".flip-card-inner").eq(i).css("transform", "rotateY(-180deg)"), $(".flip-card").eq(i).css("z-index", "4"), $(".flip-card").eq(i + 1).css("z-index", "3"), setTimeout(function() { $(".flip-card").eq(i - 1).css("z-index", "2"), $(".flip-card").eq(i).css("z-index", "3"), i += 1, $("#earringsR").click(next_phone); }, 250)) : i == $(".flip-card-inner").length - 1 ? ($(".flip-card-inner").eq(i).css("transform", "rotateY(-180deg)"), $(".flip-card").eq(i).css("z-index", "4"), $(".flip-card").eq(i + 1).css("z-index", "3"), $("#earringsR").css("opacity", "0"), $("#book2").css("transform", "translateX(calc(87 * var(--unit)))"), $("#book2").css("background-image", "none"), $("#book-bg").css("transition", "transform 0.5,left 0.5s"), $("#book-bg").css("left", "calc(6.5 * var(--unit))"), $("#earringsR").css("opacity", "0"), setTimeout(function() { $(".flip-card").eq(i - 1).css("z-index", "2"), $(".flip-card").eq(i).css("z-index", "3"), i += 1, $("#earringsR").click(next_phone); }, 500)) : setTimeout(function() { $("#earringsR").click(next_phone); }, 250); } function previous_phone() { if(i == $(".flip-card-inner").length){ if (i-2 > 1) { $(".flip-card").eq(i-2).css("display", "block"); } } if(i > 1){ $(".flip-card").eq(i+1).css("display", "none"); if (i-2 > 1) { $(".flip-card").eq(i-2).css("display", "block"); } }else if(i == 1){ $(".flip-card").eq(2).css("display", "none"); } $("#earringsL").unbind("click"), i == $(".flip-card-inner").length && ($("#earringsL").css("opacity", "1"), $("#earringsR").css("opacity", "1"), $("#book2").css("transform", "translateX(calc(0 * var(--unit)))"), $("#book-bg").css("transition", "transform 0.5,left 0.3s"), $("#book-bg").css("left", "calc(-82 * var(--unit))"), setTimeout(function() { $("#book2").css("background-image", "url('img/book.webp')"); }, 300)), i > 1 ? ($(".flip-card-inner").eq(i - 1).css("transform", "rotateY(0deg)"), $(".flip-card").eq(i - 2).css("z-index", "3"), $(".flip-card").eq(i - 1).css("z-index", "4"), setTimeout(function() { $(".flip-card").eq(i).css("z-index", "2"), $(".flip-card").eq(i - 1).css("z-index", "3"), i -= 1, $("#earringsL").click(previous_phone); }, 250)) : 1 == i ? ($(".flip-card-inner").eq(0).css("transform", "rotateY(0deg)"), $(".flip-card").eq(0).css("z-index", "4"), $("#earringsL").css("opacity", "0"), setTimeout(function() { $(".flip-card").eq(i).css("z-index", "3"), $(".flip-card").eq(i + 1).css("z-index", "2"), i -= 1, $("#earringsL").click(previous_phone); }, 250)) : setTimeout(function() { $("#earringsL").click(previous_phone); }, 250); }
define(['./module'], function(app){ 'use strict'; app.controller('GeneratorController', [ '$scope','$interval','$rootScope','$http', 'config.paths','config.generator','config.http','config.messages','service.profileHistory','profiles', function($scope, $interval, $rootScope, $http, paths, config, http, messages, history, $profiles){ $scope.loading = false; $scope.defaultImage = paths.image + "default.jpg"; // batman $scope.$history = history; // expose the history service on the $scope $scope.generator = function(){ var httpCallCounter = 0; $scope.loading = true; $scope.searchError = false; (function search(){ var FBRandomId = Math.floor(Math.random() * (config.FBMaxUser - config.FBMinUser + 1)) + config.FBMinUser; $http.get(paths.openGraph + FBRandomId + "?callback", http.httpCallTimeout) .success(function(profile){ // if gender not match the gender filter, search again! if (!profile.error) { var gender = $scope.gender; if (gender != null && profile.gender !== gender) { search(); return false; }; // check if the profile have an image checkProfileImage(profile); return false; }; // profile ID not exist. Try again! search(); }) .error(function(){ $scope.searchError = true; }); function checkProfileImage(profile){ var size = config.FBProfilePicSize; $http.get(paths.openGraph + profile.id + "/picture?callback&width=" + size + "&height=" + size, http.httpCallTimeout) .success(function(picture){ if (!picture.data.is_silhouette && !(picture.data.width < size)) { profile.image = picture.data.url; $scope.$user = profile; history.addItem(profile); return false; }; // the profile have only the silhouette search(); }) .error(function(){ console.log("errore"); $scope.searchError = true; }); } httpCallCounter++; })(); } $scope.resetGenderFilter = function(){ $scope.gender = null; } $scope.add = function(){ for (var i = 0; i < $rootScope.profiles.length; i++) { if($scope.$user.id === $rootScope.profiles[i].profile.id){ return false; // if facebookID exists don't add to the database } }; $profiles.add({ 'profile_facebook_id' : $scope.$user.id, 'profile_facebook_callback' : JSON.stringify($scope.$user) }).success(function(result){ // send result via $broadcast at /controllers/mosaic.js $rootScope.$broadcast('profileSaved', result.profile); }); } $scope.isLocked = function(){ return $scope.loading || !$scope.connection; } }]); });
const Order = require("./assignment1Order"); const OrderState = Object.freeze({ WELCOMING: Symbol("welcoming"), OPTION: Symbol("option"), SIZE: Symbol("size"), TOPPINGS: Symbol("toppings"), DRINKS: Symbol("drinks"), PAYMENT: Symbol("payment") }); module.exports = class ShwarmaOrder extends Order{ constructor(){ super(); this.stateCur = OrderState.WELCOMING; this.sOption = ""; this.sSize = ""; this.sToppings = ""; this.sDrinks = ""; this.sItem = ""; this.sPayment = ""; } handleInput(sInput){ let aReturn = []; if(sInput === "ORDER") { aReturn.push(`Your orders is: Size: ${this.sSize}, Item: ${this.sOption}, Toppings: ${this.sToppings}, Drinks: ${this.sDrinks}`) return aReturn; } switch(this.stateCur) { case OrderState.WELCOMING: this.stateCur = OrderState.OPTION; aReturn.push("Welcome to Gopi's Maxican cafe."); aReturn.push("What kind of dish do you like to eat?"); aReturn.push(" Burritobowl , Wrap "); break; case OrderState.OPTION: this.stateCur = OrderState.SIZE; this.sOption = sInput; aReturn.push('What size do you want?') aReturn.push(" Large , Medium , Small "); break; case OrderState.SIZE: this.stateCur = OrderState.TOPPINGS; this.sSize = sInput; aReturn.push("What toppings would you like?"); aReturn.push(" Falafal , Chicken , Tofu , Vegies "); break; case OrderState.TOPPINGS: this.stateCur = OrderState.DRINKS; this.sToppings = sInput; aReturn.push("Your order would be ready in next 3 minutes. "); aReturn.push("Do you need any drink?"); aReturn.push(" CanadaDry , Crush , Sprite , DietCoke "); break; case OrderState.DRINKS: this.stateCur = OrderState.PAYMENT; if(sInput.toLowerCase() != "no") { this.sDrinks = sInput; } aReturn.push("How would you like to pay?"); aReturn.push(" Visa , DebitCard , Cash "); break; case OrderState.PAYMENT: this.isDone(true); aReturn.push("Thank you for your order"); aReturn.push(`${this.sSize} ${this.sOption} with ${this.sToppings}`); if(this.sDrinks){ aReturn.push(this.sDrinks); } let d = new Date(); d.setMinutes(d.getMinutes() + 20); aReturn.push(`Please pick it up at ${d.toTimeString()}`); break; } return aReturn; } }
var unirest = require('unirest'); exports.run = function(client, message, args) { unirest.get("http://api.icndb.com/jokes/random?firstName=Chuck&amp;lastName=Norris") .header("Accept", "application/json") .end(function(result) { // For Debug Only //console.log(result.status, result.headers, result.body); console.log("Running Command for Chuck Norris"); message.channel.send(result.body.value["joke"]); }); }
var map; var boxpolys; var directions; var routeBoxer; var distance; //km var service; var gmarkers = []; var boxes; var infowindow = new google.maps.InfoWindow(); var places; var countryRestrict = { 'country': 'it' }; var countries = { 'fr': { center: { lat: 46.2, lng: 2.2 }, zoom: 6 }, 'it': { center: { lat: 41.9, lng: 12.6 }, zoom: 6 }, 'es': { center: { lat: 40.5, lng: -3.7 }, zoom: 6 }, 'pt': { center: { lat: 39.4, lng: -8.2 }, zoom: 6 }, }; function initialize() { // Default view Italy. var mapOptions = { center: new google.maps.LatLng(43.4230, 10.2412), mapTypeId: google.maps.MapTypeId.ROADMAP, zoom: countries['it'].zoom, center: countries['it'].center, zoomControl: true, streetViewControl: false, styles: [{ "featureType": "administrative", "elementType": "all", "stylers": [{ "visibility": "on" }, { "saturation": -100 }, { "lightness": 20 }] }, { "featureType": "road", "elementType": "all", "stylers": [{ "visibility": "on" }, { "saturation": -100 }, { "lightness": 40 }] }, { "featureType": "water", "elementType": "all", "stylers": [{ "visibility": "on" }, { "saturation": -10 }, { "lightness": 30 }] }, { "featureType": "landscape.man_made", "elementType": "all", "stylers": [{ "visibility": "simplified" }, { "saturation": -60 }, { "lightness": 10 }] }, { "featureType": "landscape.natural", "elementType": "all", "stylers": [{ "visibility": "simplified" }, { "saturation": 10 }, { "lightness": 20 }] }, { "featureType": "poi", "elementType": "all", "stylers": [{ "visibility": "off" }, { "saturation": -100 }, { "lightness": 60 }] }, { "featureType": "transit", "elementType": "all", "stylers": [{ "visibility": "off" }, { "saturation": -100 }, { "lightness": 60 }] }] }; map = new google.maps.Map(document.getElementById("map"), mapOptions); service = new google.maps.places.PlacesService(map); map.controls[google.maps.Animation.BOUNCE].push(card); console.log(google.maps.Animation.BOUNCE); var card = document.getElementById('pac-card'); var from = document.getElementById('from'); var to = document.getElementById('to'); //var autocomplete = new google.maps.places.Autocomplete(from); //var autocomplete = new google.maps.places.Autocomplete(to); // Create the autocomplete object and associate it with the UI input control. // Restrict the search to the default country, and to place type "cities". autoFrom = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */ (from), { types: ['(cities)'], componentRestrictions: countryRestrict }); console.log(autoFrom) autoTo = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */ (to), { types: ['(cities)'], componentRestrictions: countryRestrict }); places = new google.maps.places.PlacesService(map); autoFrom.addListener('place_changed', onPlaceChanged); autoTo.addListener('place_changed', onPlaceChanged); // Add a DOM event listener to react when the user selects a country. document.getElementById('country').addEventListener( 'change', setAutocompleteCountry); // When the user selects a city, get the place details for the city and // zoom the map in on the city. function onPlaceChanged() { var place = autoFrom.getPlace(); if (place.geometry) { map.panTo(place.geometry.location); map.setZoom(15); search(); } else { document.getElementById('from').placeholder = 'From'; document.getElementById('to').placeholder = 'to'; } } function setAutocompleteCountry() { var country = document.getElementById('country').value; if (country == 'all') { autoFrom.setComponentRestrictions({ 'country': [] }); autoTo.setComponentRestrictions({ 'country': [] }); map.setCenter({ lat: 15, lng: 0 }); map.setZoom(2); } else { autoFrom.setComponentRestrictions({ 'country': country }); autoTo.setComponentRestrictions({ 'country': country }); map.setCenter(countries[country].center); map.setZoom(countries[country].zoom); } clearMarkers(); } //lib router box routeBoxer = new RouteBoxer(); directionService = new google.maps.DirectionsService(); directionsRenderer = new google.maps.DirectionsRenderer({ map: map }); // skip the first character, we are not interested in the "?" var query = location.search.substring(1); // split the rest at each "&" character to give a list of "argname=value" pairs var pairs = query.split("&"); for (var i = 0; i < pairs.length; i++) { // break each pair at the first "=" to obtain the argname and value var pos = pairs[i].indexOf("="); var argname = pairs[i].substring(0, pos).toLowerCase(); var value = pairs[i].substring(pos + 1).toLowerCase(); // process each possible argname - use unescape() if theres any chance of spaces if (argname == "to") { document.getElementById('to').value = unescape(value); } if (argname == "from") { document.getElementById('from').value = unescape(value); } if (argname == "dist") { document.getElementById('distance').value = parseFloat(value); } if (argname == "type") { document.getElementById('type').value = unescape(value); } if (argname == "keyword") { document.getElementById('keyword').value = unescape(value); } if (argname == "name") { document.getElementById('name').value = unescape(value); } if (argname == "submit") { route(); } } } //bind get var myRoute = document.getElementById('route'); myRoute.onclick = function() { route(); } function route() { // Clear any previous route boxes from the map clearBoxes(); deleteMarkers(); console.log('markers', gmarkers) // Convert the distance to box around the route from miles to km distance = parseFloat(document.getElementById("distance").value) * 1, 63871; var request = { origin: document.getElementById("from").value, destination: document.getElementById("to").value, travelMode: google.maps.DirectionsTravelMode.DRIVING } // Make the directions request directionService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsRenderer.setDirections(result); // Box around the overview path of the first route var path = result.routes[0].overview_path; boxes = routeBoxer.box(path, distance); // alert(boxes.length); drawBoxes(); findPlaces(0); } else { alert("Directions query failed: " + status); } }); } // Draw the array of boxes as polylines on the map function drawBoxes() { boxpolys = new Array(boxes.length); for (var i = 0; i < boxes.length; i++) { boxpolys[i] = new google.maps.Rectangle({ bounds: boxes[i], fillOpacity: 0, strokeOpacity: 1.0, strokeColor: '#000000', strokeWeight: 1, map: map }); } } function findPlaces(searchIndex) { var type = document.getElementById('type').value; var keyword = document.getElementById('keyword').value; var name = document.getElementById('name').value; var request = { bounds: boxes[searchIndex], }; if (!!type && (type != "")) { if (type.indexOf(',') > 0) request.types = type.split(','); else request.types = [type]; } if (!!keyword && (keyword != "")) request.keyword = keyword; if (!!name && (name != "")) request.name = name; service.radarSearch(request, function(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0, result; result = results[i]; i++) { var marker = createMarker(result); } } else { console.log('check-bounds', boxes[searchIndex]); } if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) { searchIndex++; if (searchIndex < boxes.length) findPlaces(searchIndex); } else { // delay 1 second and try again setTimeout("findPlaces(" + searchIndex + ")", 2000); } }); } // Sets the map on all markers in the array. function setMapOnAll(map) { for (var i = 0; i < gmarkers.length; i++) { gmarkers[i].setMap(map); } } // Removes the markers from the map, but keeps them in the array. function clearMarkers() { setMapOnAll(null); } // Deletes all markers in the array by removing references to them. function deleteMarkers() { clearMarkers(); gmarkers = []; } // Clear boxes currently on the map function clearBoxes() { if (boxpolys != null) { console.log(boxpolys) for (var i = 0; i < boxpolys.length; i++) { boxpolys[i].setMap(null); } } boxpolys = null; } function createMarker(place) { var placeLoc = place.geometry.location; if (place.icon) { var image = new google.maps.MarkerImage( place.icon, new google.maps.Size(71, 71), new google.maps.Point(0, 0), new google.maps.Point(17, 34), new google.maps.Size(25, 25)); } else var image = { url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png", size: new google.maps.Size(7, 7), anchor: new google.maps.Point(3.5, 3.5) }; var marker = new google.maps.Marker({ map: map, icon: image, position: place.geometry.location }); var request = { reference: place.reference }; //print stuff google.maps.event.addListener(marker, 'click', function() { service.getDetails(request, function(place, status) { console.log('place', place) if (status == google.maps.places.PlacesServiceStatus.OK) { var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address; if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number; if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>'; contentStr += '<br>' + place.types + '</p>'; contentStr += '<br>' + '<p>' + 'Lat: </p>' + marker.position.lat(); contentStr += '<br>' + '<p>' + 'Lng: </p>' + marker.position.lng(); infowindow.setContent(contentStr); infowindow.open(map, marker); } else { var contentStr = "<h5>No Result, status=" + status + "</h5>"; infowindow.setContent(contentStr); infowindow.open(map, marker); } }); }); console.log('marker', marker) service.getDetails(request, function(place, status) { gmarkers.push(marker); if (status == google.maps.places.PlacesServiceStatus.OK) { var lat = marker.position.lat(); var lng = marker.position.lng(); //if (place.name === undefined) place.name = "result " + gmarkers.length; var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>"; side_bar_html += ` <form action="/" method="post"> <label>Lat</label> <input type="text" id="latitude" name="latitude" value="${lat}"> <label>Lng</label> <input type="text" id="longitude" name="longitude" value="${lng}"> <label>Place Name</label> <input type="text" id="placeName" name="placeName" value="${place.name}"/> <label>Save</label> <input type="submit" name="save" value="saveRoute"> </form><br><br>` document.getElementById('side_bar').innerHTML += side_bar_html; // document.getElementById('latitude').value = marker.position.lat(); // document.getElementById('longitude').value = marker.position.lng(); // //we have to find the name and other info in place.name or marker.position. // document.getElementById('placeName').value = place.name; } }); } google.maps.event.addDomListener(window, 'load', initialize);
import React, { useEffect, useState } from 'react' import Tabela from "../../components/tabela" import { GetPosts } from '../../common/Service'; const Posts = () => { const [posts , setPosts] = useState(null); // componentDidMount useEffect(() => { getPosts(); }, []); const getPosts = async () => { const postsResponse = await GetPosts(); const postsNormalized = { titulos: [ 'UserID', 'ID', 'Title', 'Body' ], linhas: postsResponse.map((item) => { return [item.userId, item.id, item.title, item.body]; }), }; setPosts(postsNormalized); } return ( <> {posts === null ? 'Estamos carregando os dados' : <Tabela titulo={'Postagens'} objeto={posts} />} </> ) } export default Posts;
import React, { Component } from 'react'; import { View, Text, TouchableOpacity, StyleSheet, Modal, TouchableHighlight, } from 'react-native'; import { StackActions, NavigationActions } from 'react-navigation'; import firebase from 'react-native-firebase'; import DatePicker from 'react-native-datepicker'; export default class AppointmentDetail extends Component { state = { patientuid: '', patientName: '', appointmentDate: '', appointmentStatus: '', confModel: false, pospmod: false, cancelmod: false, date: '2019-10-22' } componentDidMount() { let date = new Date(); let year = date.getFullYear().toString(); let month = date.getMonth() + 1; let month1 = month.toString(); let day = date.getDate().toString(); var patientuid = this.props.navigation.getParam('patientuid', ''); var patientName = this.props.navigation.getParam('patientName', ''); var appointmentStatus = this.props.navigation.getParam('AppointmentStatus', ''); var appointmentDate = this.props.navigation.getParam('AppointmentDate', ''); this.setState({ patientuid: patientuid, patientName: patientName, appointmentDate: appointmentDate, appointmentStatus: appointmentStatus, }) } render() { return ( <View style={{ justifyContent: 'center', alignContent: 'center' }}> <Text style={{ justifyContent: 'center', alignSelf: 'center', fontSize: 20, paddingTop: 10, }}> Appointment Detail </Text> <View style={styles.content}> <Text style={styles.texthead}>Patient Name</Text> <Text style={styles.textdata}>{this.state.patientName != '' ? this.state.patientName : ''}</Text> </View> <View style={styles.content}> <Text style={styles.texthead}>Appointment Date</Text> <Text style={styles.textdata}>{this.state.appointmentDate != '' ? this.state.appointmentDate : ''}</Text> </View> <View style={styles.content}> <Text style={styles.texthead}>Appointment Status</Text> <Text style={styles.textdata}>{this.state.appointmentStatus != '' ? this.state.appointmentStatus : ''}</Text> </View> <View style={{ flexDirection: 'row', marginTop: 20 }}> <TouchableOpacity style={{ marginStart: 20, backgroundColor: 'lightgreen', width: 80, height: 30, justifyContent: 'center', borderRadius: 3 }} onPress={() => { this.setState({ confModel: true, }) }}> <Text style={{ color: 'white', fontWeight: 'bold', justifyContent: 'center', alignSelf: 'center', }}>Confirm</Text> </TouchableOpacity> <TouchableOpacity style={{ marginStart: 20, backgroundColor: '#c91010', justifyContent: 'center', height: 30, width: 80, borderRadius: 3, }} onPress={() => { var patientuid = this.state.patientuid; var ref = firebase.database().ref(); var user = firebase.auth().currentUser; var uid; if (user != null) { uid = user.uid; } ref.child('users').child('Appointments').child(uid).child(patientuid).update({ 'status': 'canceled' }) .then(() => { const resetAction = StackActions.reset({ index: 0, actions: [ // NavigationActions.navigate({ routeName: 'QRCodeScanner' }), NavigationActions.navigate({ routeName: 'DoctorHome' }), ], }); this.props.navigation.dispatch(resetAction); // this.props.navigation.navigate('DoctorHome'); }) }}> <Text style={{ color: 'white', fontWeight: 'bold', alignSelf: 'center' }}>Cancel</Text> </TouchableOpacity> <TouchableOpacity style={{ marginStart: 20, backgroundColor: 'lightblue', justifyContent: 'center', height: 30, width: 80, borderRadius: 3, }} onPress={() => { this.setState({ pospmod: true }) }}> <Text style={{ color: 'white', fontWeight: 'bold', alignSelf: 'center' }}>Pospond</Text> </TouchableOpacity> </View> <Modal style={{ justifyContent: 'center', backgroundColor: 'red' }} animationType="fade" transparent={true} visible={this.state.confModel} onRequestClose={() => { // Alert.alert('Modal has been closed.'); this.setModalVisible(!this.state.confModel); }}> <View style={{ backgroundColor: 'rgba(203, 192, 192, 0.8)', flex: 1, justifyContent: 'center' }}> <View style={{ marginTop: '20%', justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', height: 270, width: 300, alignSelf: 'center', borderRadius: 10, justifyContent: 'center' }}> <View style={{ justifyContent: 'center', alignItems: 'center', paddingRight: 20, paddingLeft: 20 }}> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>Confirmation</Text> <View style={{ borderColor: 'black', borderWidth: 1, width: 120, marginBottom: 10 }} /> <Text>Are you Sure , The appointment will be confirmed After pressing Confirm</Text> </View> <View> <TouchableHighlight style={{ backgroundColor: 'green', height: 35, width: 200, justifyContent: 'center', borderRadius: 4, marginTop: 20 }} onPress={() => { var patientuid = this.state.patientuid; var ref = firebase.database().ref(); var user = firebase.auth().currentUser; var uid; if (user != null) { uid = user.uid; } ref.child('users').child('Appointments').child(uid).child(patientuid).update({ 'status': 'confirmed' }) .then(() => { const resetAction = StackActions.reset({ index: 0, actions: [ // NavigationActions.navigate({ routeName: 'QRCodeScanner' }), NavigationActions.navigate({ routeName: 'DoctorHome' }), ], }); this.props.navigation.dispatch(resetAction); // this.props.navigation.navigate('DoctorHome'); }) this.setModalVisible(!this.state.confModel); }}> <Text style={{ alignSelf: 'center', fontWeight: 'bold', color: 'white' }}>Confirm</Text> </TouchableHighlight> <TouchableHighlight style={{ backgroundColor: 'red', height: 35, width: 200, justifyContent: 'center', borderRadius: 4, marginTop: 10 }} onPress={() => { this.setModalVisible(!this.state.confModel); }}> <Text style={{ alignSelf: 'center', fontWeight: 'bold', color: 'white', }}>Close</Text> </TouchableHighlight> </View> </View> </View> </Modal> {/* Pospond modal */} <Modal style={{ justifyContent: 'center', backgroundColor: 'red' }} animationType="fade" transparent={true} visible={this.state.pospmod} onRequestClose={() => { // Alert.alert('Modal has been closed.'); this.setpospModalVisible(!this.state.pospmod); }}> <View style={{ backgroundColor: 'rgba(203, 192, 192, 0.8)', flex: 1, justifyContent: 'center' }}> <View style={{ marginTop: '20%', justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', height: 330, width: 300, alignSelf: 'center', borderRadius: 10, justifyContent: 'center' }}> <View style={{ justifyContent: 'center', alignItems: 'center', paddingRight: 20, paddingLeft: 20 }}> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>Confirmation</Text> <View style={{ borderColor: 'black', borderWidth: 1, width: 120, marginBottom: 10 }} /> <Text>Are you Sure , The appointment will be posponded to the given date</Text> </View> <View> <View style={{ margin: 10, alignSelf: 'center', marginTop: 30, }}> <DatePicker style={{ width: 275 }} mode="date" date={this.state.date} placeholder="select date" format="YYYY-MM-DD" minDate="1980-01-01" maxDate="2025-01-01" showIcon={false} customStyles={{ dateIcon: { position: 'relative', left: 0, top: 4, marginLeft: 0 }, dateInput: { marginLeft: 10 } }} onDateChange={(newDate) => { this.setState({ date: newDate, }) }} /> </View> </View> <View> <TouchableHighlight style={{ backgroundColor: 'green', height: 35, width: 200, justifyContent: 'center', borderRadius: 4, marginTop: 20 }} onPress={() => { this.setpospModalVisible(!this.state.pospmod); }}> <Text style={{ alignSelf: 'center', fontWeight: 'bold', color: 'white' }}>Confirm</Text> </TouchableHighlight> <TouchableHighlight style={{ backgroundColor: 'red', height: 35, width: 200, justifyContent: 'center', borderRadius: 4, marginTop: 10 }} onPress={() => { this.setpospModalVisible(!this.state.pospmod); }}> <Text style={{ alignSelf: 'center', fontWeight: 'bold', color: 'white', }}>Close</Text> </TouchableHighlight> </View> </View> </View> </Modal> </View> ); } setModalVisible(visible) { this.setState({ confModel: visible }); } setpospModalVisible(visible) { this.setState({ pospmod: visible }); } } const styles = StyleSheet.create({ content: { flexDirection: 'row', marginTop: 20, alignSelf: 'center' }, texthead: { fontWeight: 'bold', color: 'gray' }, textdata: { marginLeft: 40 } })
/*******************************************************************************************************/ /** *************************************** 房源平台--房源跟进记录 *****************************************/ /*******************************************************************************************************/ import {onGet, onPost} from '../main' // 查询房源跟进记录主页数据 export const queryHouseFollowRecordPageList = params => { return onPost('house/HsFollowRecord/queryHsFollowRecordData', params) } // 查询房源跟进记录详细 export const queryHouseFollowRecordDetailPageList = params => { return onPost('house/HsFollowRecord/queryAllHsFollowRecordByHouseId', params) } // 查询房源跟进房源交易类型 export const houseTransactionType = params => { return onPost('house/HsFollowRecord/houseTransactionType', params) } // 查询房源跟进状态 export const queryHouseStatus = params => { return onPost('house/HsFollowRecord/houseStatus', params) }
import "../Header/header.css" import Freshnesecom from "../Icons/freshnesecom" import Person from "../Icons/person" import Basket from "../Icons/basket" import Four from "../Icons/four" import GreenDown from "../Icons/greenDown" import Search from "../Icons/search" import { Link } from "react-router-dom" function Header(){ return( <header className="Header"> <div className="HeaderDiv1"> <div className="chatWithUs"> <p className="chatWithUsp1">Chat with us</p> <p className="chatWithUsp2">+420 336 775 664</p> <p>info@freshnesecom.com</p> </div> <div className="aboutUs"> <p>Blog</p> <p>About Us</p> <p>Careers</p> </div> </div> <div className="line"></div> <div className="HeaderDiv2"> <Link to="/"><Freshnesecom/></Link> <div className="HeaderSearch"> <strong>All categories</strong> <GreenDown/> <div className="lineHeight"></div> <input className="HeaderInput" type="search" placeholder="Search Products, categories ..."/> <Search/> </div> <div className="HeaderIcons"> <Person/> <Basket/> <Four/> </div> </div> </header> ) } export default Header
var mysql = require('mysql'); module.exports = { /** * データベース接続の初期化 * @return {Connection} MySQL DB connection */ db: function () { var connection = mysql.createConnection({ host : 'chloringoame17.dip.jp', user : 'oden', password : 'Oden-1218', port : 993, database : 'robocup' }); return connection; } };
const continueButton = document.getElementById('overlayContinue'); const overlay = document.getElementById('overlay'); continueButton.addEventListener('click', (e)=>{ console.log(overlay); overlay.style.opacity = 0; setTimeout(()=>{ overlay.style.display = 'none'; }, 500); }); // let svg = d3.select("svg"), // angles = d3.range(0, 2* Math.PI, Math.PI / 400); // // svg.attr('width', width).attr('height', height); // // let path = svg.append("g") // .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")") // .attr("fill", "none") // .attr("stroke-width", 10) // .attr("stroke-linejoin", "round") // .selectAll("path") // .data(["#EA0000", "#00F000", "#0000EC"]) // .enter().append("path") // .attr("stroke", function(d) { return d; }) // .style("mix-blend-mode", "lighten") // .datum(function(d, i) { // return d3.radialLine() // .curve(d3.curveLinearClosed) // .angle(function(a) { return a; }) // .radius(function(a) { // var t = d3.now() / 1000; // a += Math.PI/3 // return 100 + Math.cos(a * 2 - i * Math.PI/9 + t) * Math.pow((1 + Math.cos(a - t)) / 2, 3) * 120; // }); // }); // // d3.timer(function() { // path.attr("d", function(d) { // return d(angles); // }); // });
/** * DomoGeeek v0.1 * https://github.com/ltoinel/domogeeek * * Copyright 2014 DomoGeeek * Released under the Apache License 2.0 (Apache-2.0) * * @desc: Energy module for the Aenon Lab HEM2. * @author: ltoinel@free.fr */ // Local require var bus = require( '../bus' ); var config = require('../config'); var openkarotz = require('../../../libs/openkarotz'); //Model var Event = require('../models/event'); // The command to listen const COMMAND_CLASS_METER = 50; // RGB to Hex function rgbToHex(r, g, b) { return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); } /** * We listen for a COMMAND_CLASS_METER event. * This event is sent by the Aeon HEM2 power energy meter. */ bus.on(COMMAND_CLASS_METER, function(nodeid, value){ // Global Energy if (nodeid == 7 && value['label'] == "Energy"){ var energy = value['value']; global.data['energy'] = energy; } // Current power consumed else if (nodeid == 7 && value['label'] == "Power"){ var power = value['value']; global.data['power'] = power; // Max possible consume is 12000 Wh var n = power / config.power.max * 100; var red = (255 * n) / 100; var green = (255 * (100 - n)) / 100; var blue = 0; var color = rgbToHex(red,green,blue); console.log("Color : " + color); // Change the OpenKarotz led openkarotz.led(config.openkarotz, color); // Make the OpenKarotz talking if (power > config.power.voice){ openkarotz.talk(config.openkarotz, "La maison consomme "+ power + " Watt"); } // Saving the event new Event({ nodeid: nodeid, comclass: comclass, type: value['type'], label: value['label'], value: value['value']}).save(); } });
import "../../Styles/HomePageStyle/ExclusiveBrands.css" import React from 'react'; const ExclusiveBrands = () => { return ( <div className="ExclusiveBrands"> <h5>ExclusiveBrands</h5> <div className="ExclusiveBrandsImg"> <div className="ExclusiveBrandsImg1"> </div> <div className="ExclusiveBrandsImg2"> </div> <div className="ExclusiveBrandsImg3"> </div> <div className="ExclusiveBrandsImg4"> </div> </div> </div> ); }; export default ExclusiveBrands;
for(var i = 0; i < 24; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); } $axure.eventManager.pageLoad( function (e) { }); gv_vAlignTable['u3'] = 'center';gv_vAlignTable['u21'] = 'center';u12.tabIndex = 0; u12.style.cursor = 'pointer'; $axure.eventManager.click('u12', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u8'] = 'center';gv_vAlignTable['u19'] = 'top';gv_vAlignTable['u17'] = 'top';gv_vAlignTable['u5'] = 'center';gv_vAlignTable['u1'] = 'center';u9.tabIndex = 0; u9.style.cursor = 'pointer'; $axure.eventManager.click('u9', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u9'] = 'top';gv_vAlignTable['u14'] = 'center';document.getElementById('u20_img').tabIndex = 0; u20.style.cursor = 'pointer'; $axure.eventManager.click('u20', u20Click); InsertAfterBegin(document.body, "<div class='intcases' id='u20LinksClick'></div>") var u20LinksClick = document.getElementById('u20LinksClick'); function u20Click(e) { windowEvent = e; ToggleLinks(e, 'u20LinksClick'); } InsertBeforeEnd(u20LinksClick, "<div class='intcaselink' onmouseout='SuppressBubble(event)' onclick='u20Clickub481a93fb35e4beb88c2728501ece7ec(event)'>用例 1</div>"); function u20Clickub481a93fb35e4beb88c2728501ece7ec(e) { self.location.href=$axure.globalVariableProvider.getLinkUrl('创作.html'); ToggleLinks(e, 'u20LinksClick'); } InsertBeforeEnd(u20LinksClick, "<div class='intcaselink' onmouseout='SuppressBubble(event)' onclick='u20Clicku72302353c16f489c9046376d66f2bb30(event)'>用例 2</div>"); function u20Clicku72302353c16f489c9046376d66f2bb30(e) { self.location.href=$axure.globalVariableProvider.getLinkUrl('新建文章.html'); ToggleLinks(e, 'u20LinksClick'); } u15.tabIndex = 0; u15.style.cursor = 'pointer'; $axure.eventManager.click('u15', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u15'] = 'top';gv_vAlignTable['u16'] = 'top';u6.tabIndex = 0; u6.style.cursor = 'pointer'; $axure.eventManager.click('u6', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u6'] = 'top';gv_vAlignTable['u11'] = 'center';gv_vAlignTable['u23'] = 'center';gv_vAlignTable['u18'] = 'top';
function TactileController(){ this.texture = GET().texture || "corn"; this.engine = GET().engine || "shade"; this.current_model; this.loaded = {}; this.env = new WebEnv($("#ThreeJS")); this.preview; this.magnitude = parseFloat(GET().m) || 5; this.base_height = parseFloat(GET().bh) || 10; this.width = parseFloat(GET().w) || 70; this.height = parseFloat(GET().h) || 70; this.resolution = parseFloat(GET().r) || 350; console.log("BH", this.base_height); } TactileController.prototype = { init: function(){ var self = this; this.load(); this.preview = new ImagePreview(this.env.container, textureMap[this.texture]); this.dim = new DimensionsPreview(this.env.container); }, load:function(){ console.log("Loading", this.texture, "on", this.engine); var self = this; var model = this.loaded[this.texture]; if(typeof model === "undefined") model = new TactileModel(textureMap[this.texture], this.width, this.height, this.base_height, this.resolution, self.magnitude); model.load(this.engine, this.add, self); }, bh_adj: function(){ var self = this; var model = new TactileModel(textureMap[this.texture], this.width, this.height, this.base_height, this.resolution, self.magnitude); model.load(this.engine, this.add, self); }, add: function(tc, model){ console.log("Added " + model.name); tc.clear(); tc.current_model = model; tc.env.scene.add(tc.current_model[tc.engine].obj.mesh); tc.preview.swap(textureMap[tc.texture]); tc.mag(); if(tc.engine == "bump"){ alert.hide(); tc.update_dim(); } hist = generateURL(); history.pushState({}, hist.title, hist.href); }, switch: function(){ console.log("Switching to", textureMap[this.texture]); var self = this; UIAlert.sync(function(){ if(self.engine == "shade") alert.flash("Switching to: " + textureMap[self.texture], 1500); if(this.engine == "bump") alert.notice("Calculating " + self.texture + " model ..."); }, function(){ self.load(); }); }, mag: function(){ this.current_model.mag(this.engine, this.magnitude); this.update_dim(); }, update_dim: function(){ if(this.engine == "bump"){ var dimensions = this.current_model.bump.dimensions(); this.dim.set(dimensions.x, dimensions.y, dimensions.z); } else this.dim.set(0, 0, 0); }, clear: function(){ console.log("Clearing the stage."); if(typeof this.current_model === "undefined") return; if(typeof this.current_model.bump.obj !== "undefined") this.env.scene.remove(this.current_model.bump.obj.mesh); if(typeof this.current_model.shade.obj !== "undefined") this.env.scene.remove(this.current_model.shade.obj.mesh); console.log("Cleared the stage."); }, save: function(){ // TODO: trigger change with controller // this.engine = "bump"; // tc.switch(); var self = this; this.current_model.save(this.texture); alert.flash("Model saved!", 1000); }, clear_cache: function(){ storage.clear(); alert.flash("Cleared cache", 1000); }, clear_self: function(){ storage.remove(this.current_model.name); alert.flash("Cleared self from cache", 1000); } }
function material(id, unitmass){ return {id: id, unitmass: unitmass}; } const materials = { oil: material('oil', 0.97), saltwater: material('salt water', 1.04), freshwater: material('fresh water', 1.0), honey: material('honey', 1.42), quartz: material('quartz', 2.37), shale: material('shale', 2.74), gravel: material('gravel', 1.38), mud: material('mud', 1.95), clay: material('clay', 1.74), treasure: material('treasure', 4.42 ), fish: material('fish', 3.84), shrimp: material('shrimp', 1.68), algae: material('algae', 0.48 ), oysters: material('oysters', 1.27 ), clams: material('clams', 1.47 ), shells: material('shells', 1.07 ), crabs: material('crabs', 1.39 ), deadwood: material('deadwood', 0.78 ), plums: material('plums', 0.97 ), reeds: material('reeds', 0.41 ), skunkweed: material('skunkweed', 1.06 ), flowers: material('flowers', 0.29 ), berries: material('berries', 0.78 ), apples: material('apples', 0.82 ), wood: material('wood', 0.93 ), loam: material('loam', 1.36 ), saplings: material('saplings', 0.22 ), mushrooms: material('mushrooms', 0.18 ), moss: material('moss', 0.36 ), vines: material('vines', 0.59 ), ore: material('ore', 5.27 ), gems: material('gems', 2.31 ), snow: material('snow', 0.56 ) }
import React from 'react'; import './BodyComponents.css'; function BodyComponent(props) { return ( <div className='bodyComponents'> <img src={props.image} alt='reference'/> <h1>{props.title}</h1> <p>{props.text}</p> </div> ) } export default BodyComponent
var controller = require('../index').getController(); /** * Lits all of the OOO events a user has set * @param {Object} bot * @param {Object} message */ module.exports = function list(bot, message) { bot.startPrivateConversation(message, function(err, convo) { if (err) { return console.trace(err); } controller.storage.users.get(message.user, function(err, user) { if (err) { console.trace(err); } if (!user) { convo.transitionTo('setup', 'I don\'t know you, let me introduce myself.'); return; } var url = process.env.NODE_ENV === 'production' ? 'https://' + process.env.HOST : 'http://' + process.env.HOST + ':' + process.env.PORT; url += '/' + user.id + '/events'; convo.addMessage('Direct your gaze towards ' + url, 'default'); }); }); };
export const validationConstants = { VALIDATION_REQUEST: "VALIDATION_REQUEST" }
$(document).ready(function () { initSeaechCriteriaSkill(); }); function initSeaechCriteriaSkill() { viewModel.jobSeekerList = ko.observableArray(); viewModel.listJobSeeker = ko.observable('0'); viewModel.dataCompetency = ko.observable(createListCompetency()); viewModel.dataSkill = ko.observable(); viewModel.dataProficiency = ko.observable(createListProficiency()); viewModel.selectedCompetemcy = ko.observable(0); viewModel.selectedSkill = ko.observable(0); viewModel.selectedProficiency = ko.observable(0); viewModel.selectedCompetemcy.subscribe(function (newValue) { var competencyId = viewModel.dataCompetency()[viewModel.selectedCompetemcy()].value; if (competencyId != "") { var apiUrlSkill = GetWebAPIURL() + '/api/SkillMap/?specialityId=' + competencyId; //To get State for lookup $.ajax({ url: apiUrlSkill, type: 'GET', async: false, success: function (data) { viewModel.dataSkill(createListSkill(data)); }, error: function (xhr, status, error) { alert('Error :' + status); } }); } }); } viewModel.searchBySkills = function () { var dataJobSeekerWithSkill; var apiUrlJobSeekerWithSkill = GetWebAPIURL() + '/api/GetJobSeekerSkillsWithSkillId?id=' + viewModel.dataSkill()[viewModel.selectedSkill()].value; //To get JobSeekerSkillList $.ajax({ url: apiUrlJobSeekerWithSkill, type: 'GET', async: false, contentType: "application/json; charset=utf-8", success: function (data) { dataJobSeekerWithSkill = data; getUniqueJobSeekerId(data); }, error: function (xhr, status, error) { alert('ErrorList :' + status); } }); } viewModel.expandJobSeekerList = function (objExpand) { if (objExpand.btnExpandJobSeekerList() == '+') { objExpand.btnExpandJobSeekerList('-'); } else { objExpand.btnExpandJobSeekerList('+'); } } viewModel.jobSeekerMarkFavourite = function () { } viewModel.jobSeekerWatch = function () { } viewModel.jobSeekerViewFullProfile = function () { } viewModel.jobSeekerMessages = function () { } viewModel.JobSeekerSendMessage = function () { } viewModel.JobSeekerInviteToApply = function () { } var jobSeekerIdArray = []; function getUniqueJobSeekerId(dataJobSeekerWithSkill) { for (da in dataJobSeekerWithSkill) { if (jobSeekerIdArray.indexOf(dataJobSeekerWithSkill[da].JobSeekerId) == -1) jobSeekerIdArray.push(dataJobSeekerWithSkill[da].JobSeekerId); } if (jobSeekerIdArray.length > 0) createJobSeekerList(dataJobSeekerWithSkill); } function createJobSeekerList(dataJobSeekerWithSkill) { viewModel.jobSeekerList.removeAll(); viewModel.jobSeekerDetails.removeAll(); var dataObjJobSeekersWorkExpList = getJobSeekersWorkHistoryDetails(); var dataObjJobSeekersOverviewList = getJobSeekersOverviewDetails(); var dataObjEducationList = getJobSeekersEducationDetails(); var dataObjTrainingList = getJobSeekersTrainingCourseDetails(); var dataObjCertificationList = getJobSeekersCertificationDetails(); for (var i = 0; i < jobSeekerIdArray.length; i++) { var overview; for (da in dataObjJobSeekersOverviewList) { if (dataObjJobSeekersOverviewList[da].JobSeekerId == jobSeekerIdArray[i]) { overview = dataObjJobSeekersOverviewList[da]; break; } } var listJobSeeker = new fillJobSeekerDetails(overview, dataJobSeekerWithSkill, dataObjJobSeekersWorkExpList, dataObjEducationList, dataObjTrainingList, dataObjCertificationList); viewModel.jobSeekerList.push(listJobSeeker); } } function fillJobSeekerDetails(overview, dataJobSeekerSkillListObj, dataObjJobSeekersWorkExpList, dataObjEducationList, dataObjTrainingList, dataObjCertificationList) { var self = this; self.btnExpandJobSeekerList = ko.observable('+'); self.IndustryName = ko.observableArray(); self.jobSeekerName = "Job Seeker"; for (da in dataObjJobSeekersWorkExpList) { if (overview.JobSeekerId == dataObjJobSeekersWorkExpList[da].JobSeekerId) { self.companyNames = dataObjJobSeekersWorkExpList[da].CompanyName; self.currentPositions = dataObjJobSeekersWorkExpList[da].EndingPosition; self.startDates = dataObjJobSeekersWorkExpList[da].StartDate; self.endDates = dataObjJobSeekersWorkExpList[da].EndDate; self.companyLocations = dataObjJobSeekersWorkExpList[da].CompanyLocation; break; } } self.summary = overview.Summary; self.specialityName = overview.Speciality; for (var j = 0; j < dataObjSecurityLookUp.length; j++) { if (dataObjSecurityLookUp[j].Id == overview.SecurityClearanceId) { self.securityCleareance = dataObjSecurityLookUp[j].Name; break; } } for (var j = 0; j < dataObjRelocateLookUp.length; j++) { if (dataObjRelocateLookUp[j].Id == overview.WillingToRelocateId) { self.relocate = dataObjRelocateLookUp[j].Name; break; } } var getIndustryId = overview.Industry.split(','); for (var j = 0; j < dataObjIndustryLookUp.length; j++) { for (var index = 0; index < getIndustryId.length; index++) { if (dataObjIndustryLookUp[j].Id == getIndustryId[index]) { self.IndustryName.push(dataObjIndustryLookUp[j].Name); } } } self.categoryArray = ko.observableArray(); var categoryId; var specialityId; var currentCategoryObj; var currentSpecialityObj; for (da in dataJobSeekerSkillListObj) { if (overview.JobSeekerId == dataJobSeekerSkillListObj[da].JobSeekerId) { if (dataJobSeekerSkillListObj[da].CategoryId != categoryId) { specialityId = 0; var categoryObj = new createCategory(dataJobSeekerSkillListObj[da]); categoryId = dataJobSeekerSkillListObj[da].CategoryId; specialityId = dataJobSeekerSkillListObj[da].SpecialityId; self.categoryArray.push(categoryObj); currentCategoryObj = categoryObj; } else { if (dataJobSeekerSkillListObj[da].SpecialityId != specialityId) { var skillObj = new createSpeciality(dataJobSeekerSkillListObj[da]); specialityId = dataJobSeekerSkillListObj[da].SpecialityId; currentSpecialityObj = skillObj; currentCategoryObj.specialityArray.push(skillObj); } else { var skillObj = new createSkil(dataJobSeekerSkillListObj[da]); currentSpecialityObj.skillArray.push(skillObj); categoryId = dataJobSeekerSkillListObj[da].CategoryId; } } } } function createCategory(skillCollection) { var self = this; self.categoryName = ko.observable(); self.btnCategoryList = ko.observable('+'); self.specialityArray = ko.observableArray(); if (skillCollection) { var specialityObj = new createSpeciality(skillCollection); currentSpecialityObj = specialityObj; self.categoryName(skillCollection.CategoryName); self.specialityArray.push(specialityObj); } } function createSpeciality(skillCollection) { var self = this; self.specialityName = ko.observable(''); self.btnSpecialityList = ko.observable('+'); self.skillArray = ko.observableArray(); var skillObj = new createSkil(skillCollection); if (skillCollection) { self.specialityName(skillCollection.SpecialityName); self.skillArray.push(skillObj); } } function createSkil(skillCollection) { var self = this; var score; self.skillName = ko.observable(''); self.SkillId = ko.observable(''); if (skillCollection.SkillScore == null) { score = 1; } else { score = skillCollection.SkillScore; } self.val = ko.observable(score); self.btnSkillList = ko.observable('+'); self.validationFactor = ko.observable(); if (skillCollection) { self.skillName(skillCollection.SkillName); self.SkillId(skillCollection.Id); } } self.workExperienceDetails = ko.observableArray(); for (da in dataObjJobSeekersWorkExpList) { if (dataObjJobSeekersWorkExpList[da].JobSeekerId == overview.JobSeekerId) { var workExp = new createWorkExp(dataObjJobSeekersWorkExpList[da]); self.workExperienceDetails.push(workExp); } } self.educationDetails = ko.observableArray(); for (da in dataObjEducationList) { if (dataObjEducationList[da].JobSeekerId == overview.JobSeekerId) { var education = new createEducation(dataObjEducationList[da]); self.educationDetails.push(education); } } self.trainingCourse = ko.observableArray(); for (da in dataObjTrainingList) { if (dataObjTrainingList[da].JobSeekerId == overview.JobSeekerId) { var trainingCourse = new createtTrainingCourse(dataObjTrainingList[da]); self.trainingCourse.push(trainingCourse); } } self.certification = ko.observableArray(); for (da in dataObjCertificationList) { if (dataObjCertificationList[da].JobSeekerId == overview.JobSeekerId) { var certification = new createCertification(dataObjCertificationList[da]); self.certification.push(certification); } } } viewModel.expandSpecialityDetails = function (objExpand) { if (objExpand.btnSpecialityList() == '+') { objExpand.btnSpecialityList('-'); } else { objExpand.btnSpecialityList('+'); } } function getJobSeekersOverviewDetails() { var dataobjOverview; var apiUrlOverview = GetWebAPIURL() + '/api/GetJobSeekersOverview?JobSeekerId=' + jobSeekerIdArray.toString(); //To get workhistory details from workhistory table $.ajax({ url: apiUrlOverview, type: 'GET', async: false, contentType: "application/json; charset=utf-8", success: function (data) { dataobjOverview = data; }, error: function (xhr, status, error) { alert('Erooororlang :' + status); } }); return dataobjOverview; } function getJobSeekersWorkHistoryDetails() { var dataobjWorkExpereince; var apiUrlWorkExperience = GetWebAPIURL() + '/api/GetJobSeekerWorkHistory?JobSeekerId=' + jobSeekerIdArray.toString(); //To get workhistory details from workhistory table $.ajax({ url: apiUrlWorkExperience, type: 'GET', async: false, contentType: "application/json; charset=utf-8", success: function (data) { dataobjWorkExpereince = data; }, error: function (xhr, status, error) { alert('Erooororlang :' + status); } }); return dataobjWorkExpereince; } var parentid = "31ce822c-cebb-433e-91cd-16834ec4d8c4"; function getCompetencyList() { var apiUrlCategory = GetWebAPIURL() + '/api/Category?parentId=' + parentid; var dataCategoryObj; //To get Category name from Category table $.ajax({ url: apiUrlCategory, type: 'GET', async: false, //headers: app.securityHeaders(), contentType: "application/json; charset=utf-8", success: function (data) { dataCategoryObj = data; }, error: function (xhr, status, error) { alert('Error :' + status); } }); return dataCategoryObj; } function createListCompetency() { var dataCompetencyObj = getCompetencyList(); var list = []; list.push({ label: "Select", value: "" }); for (da in dataCompetencyObj) { list.push({ label: dataCompetencyObj[da].CategoryName, value: dataCompetencyObj[da].Id }); } return list; } function createListSkill(dataObjSkill) { var list = []; list.push({ label: "Select", value: "" }); for (da in dataObjSkill) { list.push({ label: dataObjSkill[da].SkillName, value: dataObjSkill[da].SkillMapId }); } return list; } function createListSkill(dataObjSkill) { var list = []; list.push({ label: "Select", value: "" }); for (da in dataObjSkill) { list.push({ label: dataObjSkill[da].SkillName, value: dataObjSkill[da].SkillMapId }); } return list; } function createListProficiency(dataObjSkill) { var list = []; list.push({ label: "Select", value: "" }); for (i = 1; i <= 10; i++) { list.push({ label: i, value: i }); } return list; } function getSecurityClearanceLookup() { var apiUrlSecurityCleareance = GetWebAPIURL() + '/api/Lookup/?name=SecurityClearance'; var dataSecurityCleareanceObj; //To get details of security cleareance lookup $.ajax({ url: apiUrlSecurityCleareance, type: 'GET', async: false, contentType: "application/json; charset=utf-8", success: function (data) { dataSecurityCleareanceObj = data; }, error: function (xhr, status, error) { alert('Error :' + status); } }); return dataSecurityCleareanceObj; } function getWillingToRelocateLookup() { var apiUrlWillingToRelocate = GetWebAPIURL() + '/api/Lookup/?name=WillingToRelocate'; var dataWillingToRelocate; //TO get details of willing to relocate lookup details $.ajax({ url: apiUrlWillingToRelocate, type: 'GET', async: false, contentType: "application/json; charset=utf-8", success: function (data) { dataWillingToRelocate = data; }, error: function (xhr, status, error) { alert('Error :' + status); } }); return dataWillingToRelocate; } function getIndustryTypeLookup() { var apiUrlIndustryType = GetWebAPIURL() + '/api/Lookup/?name=IndustryType'; var dataIndustryTypeObj; //To get details of Industry lookup $.ajax({ url: apiUrlIndustryType, type: 'GET', async: false, success: function (data) { dataIndustryTypeObj = data; }, error: function (xhr, status, error) { alert('Error :' + status); } }); return dataIndustryTypeObj; }
import { Swal } from '../../utils' describe('getIcons()', () => { it('getIcons()', () => { Swal.fire({ icon: 'success' }) const icons = Swal.getIcons() expect(icons.length).to.equal(5) expect(icons.filter(icon => icon.className.match('success'))[0].style.display).to.equal('flex') expect(icons.filter(icon => icon.className.match('error'))[0].style.display).to.equal('none') expect(icons.filter(icon => icon.className.match('question'))[0].style.display).to.equal('none') expect(icons.filter(icon => icon.className.match('warning'))[0].style.display).to.equal('none') expect(icons.filter(icon => icon.className.match('info'))[0].style.display).to.equal('none') }) })
#!/usr/bin/env node var CLI = require('./cli'); module.exports = new CLI(); module.exports.start();
import React from 'react'; const CallToAction = () => ( <section> <div class="front-splatter"></div> <div class="call2action"> <span class="action-text">Paint Your Rage</span> <span class="today-text">Today</span> <a href="/pricing" class="res-button">Make A Reservation</a> </div> </section> ); export default CallToAction;
var validator = require('yode-validator'); Ext.define('Gvsu.modules.orgs.model.OrgsPubl', { extend: "Gvsu.modules.orgs.model.OrgsModel" ,regPatterns: { name: ['name', false] ,fullname: ['name', false] ,headers: ['string', false] ,founders: ['string', false] ,inn: ['number', false] ,kpp: ['number', false] ,ogrn: ['number', false] ,legal_address: ['string', false] ,fact_address: ['string', false] ,www: ['string', false] ,contact_person: ['string', false] ,headers_phones: ['string', false] ,phone: ['string', false] ,email: ['email', false] ,sro: ['number', false] ,info: ['string', false] } ,getInfo: function(params, cb) { var me = this; [ function(next) { if(!params.auth) cb(null, {code: 401}) else next() } ,function(next) { me.src.db.collection('gvsu_users').findOne({_id: params.auth}, {org: 1}, function(e,d) { if(d && d.org) next(d.org) else cb({}) }) } ,function(org_id) { me.src.db.collection('gvsu_orgs').findOne({_id: org_id}, {}, function(e,d) { cb(d) }) } ].runEach() } ,saveInfo: function(params, cb) { var me = this ,res = validator.validateAll(this.regPatterns, params) res.success = false; [ function(next) { if(!params.auth) { cb({success: false}) } else next() } ,function(next) { if(!res.errors) { next() } else { cb(res) } } // Looking for user's organisation ,function(next) { me.src.db.collection('gvsu_users').findOne({_id: params.auth}, {org: 1}, function(e,d) { if(d) next(d.org) else { cb({success: false}) } }) } ,function(org, next) { var find = {$or: []}; if(res.values.name) find.$or.push({name: res.values.name}) if(res.values.fullname) find.$or.push({name: res.values.fullname}) if(res.values.inn) find.$or.push({name: res.values.inn}) if(!find.$or.length) { next(org) return; } if(org) find._id = {$ne: org} me.src.db.collection('gvsu_orgs').findOne(find, {_id: 1}, function(e,d) { if(d && d._id) { res.errors = {name:'dbl'} cb(res) } else { next(org) } }) } ,function(org, next) { res.values.active = false if(org) { me.src.db.collection('gvsu_orgs').update({_id: org}, {$set:res.values}, function(e,d) { next(org, false) }) } else { me.src.db.collection('gvsu_orgs').insert(res.values, function(e,d) { if(d && d[0] && d[0]._id) { next(d[0]._id, true) } }) } } ,function(org, log, next) { var vals = {status: false} if( log ) vals.org = org me.src.db.collection('gvsu_users').update({_id: params.auth}, {$set: vals}, function(e,d) { next(org) }) } ,function(org) { me.markAsModerate({org: org}, null, 0) cb(res) } ].runEach() } ,markAsModerate: function(params, cb, active) { var me = this; [ function(next) { if(params && params.org) { me.src.db.collection('gvsu_orgs').findOne({_id: params.org}, {}, function(e,org) { if(active === null) active = org.active; next(org) }) } else if(!!cb) cb() } // проверим, все ли документы в наличии и не устарели ,function(org, next) { me.callModel('Gvsu.modules.docs.model.Docs.checkOrgDocs', {org: org._id}, function(log) { org.docsComplite = log next(org) }) } // проверим выбрано ли хотя бы одно направление ,function(org, next) { me.callModel('Gvsu.modules.distinations.model.DistinationsPubl.checkOrgDist', {org: org._id}, function(log) { org.distComplite = log next(org) }) } ,function(org, next) { var set = {active: active}; if(!active) set.date_reg = Ext.Date.format(new Date(), 'c'); me.src.db.collection('gvsu_orgs').update({_id: org._id}, {$set:set}, function(e,d) { org.active = active me.changeModelData('Gvsu.modules.orgs.model.OrgsModel', 'ins', org) if(!!cb) cb() next(org) }) } ,function(org) { if(org.docsComplite && org.distComplite) { me.sendMessageToModerator(org) } } ].runEach() } ,sendMessageToModerator: function(org) { var me = this; org.url = 'http://' + me.config.hostName + '/admin/#' + encodeURIComponent(JSON.stringify({ controller: 'Gvsu.modules.orgs.controller.Orgs', data: { _id: org._id, name: org.name } })) me.callModel('Gvsu.modules.mail.controller.Mailer.orgActivateRequest', org, function() { }) } // Проверка статусов организаций ,checkOranisationsStatus: function() { var me = this; [ function(next) { me.checkOranisationsStatusDay(3, 2, next) } ,function(next) { me.checkOranisationsStatusDay(15, 1, next) } ,function(next) { me.checkOranisationsStatusDay(30, 0, function() { }) } ].runEach() } ,checkOranisationsStatusDay: function(days, warn, cb) { var me = this; [ // ищем доки за 30 дней до конца function(next) { var dt = new Date((new Date()).getTime() + days*24*3600000) me.src.db.collection('gvsu_userdocs').find({date_fin: {$lte: Ext.Date.format(dt, 'Y-m-d')}}, {}, function(e,d) { if(d && d.length) { var out = [], delta = 24*3600000; d.each(function(r) { if((r.date_fin.getTime() - r.date_add.getTime())>delta) out.push(r) }) next(out) } else cb() }) } ,function(docs, next) { var ids = [] docs.each(function(r) {if(ids.indexOf(r.org) == -1) ids.push(r.org)}) me.src.db.collection('gvsu_orgs').find({_id: {$in: ids}}, {_id: 1, email: 1}, function(e,d) { if(d && d.length) { next(docs, d) } else cb() }) } // Удалим документы с истекшим сроком годности ,function(docs, orgs, next) { me.checkDeprecatedDocs(docs, orgs, next) } ,function(docs, orgs, next) { var out = [] orgs.each(function(o) { o.docs = [] for(var i=0;i<docs.length;i++) { if(docs[i].warn<warn && docs[i].org == o._id) { o.docs.push(docs[i].doc_name) } } if(o.docs.length) out.push(o) }) next(out, docs) } ,function(orgs, docs, next) { me.callModel('Gvsu.modules.mail.controller.Mailer.orgStatusDay', { orgs: orgs, warn: warn }, function() { next(docs) }) } ,function(docs) { var ids = [] docs.each(function(r) {ids.push(r._id)}) me.src.db.collection('gvsu_userdocs').update({_id: {$in: ids}}, {$set: {warn: (warn+1)}}, function(e,d) { cb() }) } ].runEach() } ,checkDeprecatedDocs: function(docs, orgs, cb) { var me = this ,delIds = [] ,normDocs = [] ,now = new Date(); [ function(next) { docs.each(function(d) { if(d.date_fin<now) { delIds.push(d) } else { normDocs.push(d) } }) next() } ,function(next) { if(delIds.length) next() else cb(docs, orgs) } // Удалим документ ,function(next) { var f = function(i) { if(i>=delIds.length) { cb(normDocs, orgs) return; } me.callModel('Gvsu.modules.docs.model.Docs.delDoc', {del: delIds[i]._id, auth: delIds[i].uid, org: delIds[i].org}, function() { f(i+1) }) } f(0) } ].runEach() } })
import Lote from '@/models/ModeloLote'; export default { namespaced: true, state: { lote: new Lote('', '', '', '', '', ''), // Modelo lote formLoteValido: false, // Indica si el formulario de lote es valido }, actions: { }, mutations: { // Coloca un nuevo lot setLot(state, nuevoLote) { state.lote = nuevoLote }, // Vacia el modelo lote vaciarLote(state) { state.lote = new Lote('', '', '', '', '', '') }, cambiarEstadoFormLoteValido(state, nuevoEstado) { state.formLoteValido = nuevoEstado }, }, getters: { formLoteValido: (state) => state.formLoteValido, // Devuelve la variable formLoteValido }, }
import React from 'react' import { shallow } from 'enzyme' import toJson from 'enzyme-to-json' jest.mock('fm-components', () => ({ SearchBar: 'SearchBarMocked', LayoutGrid: 'LayoutGridMocked' })) import SearchView from './SearchView' describe('<SearchView />', () => { describe('@renders', () => { it('in default state', () => { const wrapper = shallow(<SearchView.WrappedComponent />) expect(toJson(wrapper)) .toMatchSnapshot() }) it('in with movies state', () => { const props = { movies: { 1: {}, 2: {} } } const wrapper = shallow(<SearchView.WrappedComponent {...props}/>) expect(toJson(wrapper)) .toMatchSnapshot() }) }) })
import React, { useEffect, useState } from 'react'; import { Table } from 'react-bootstrap'; import ListDetails from './ListDetails'; const List = () => { const [listInfo, setListInfo] = useState([]); useEffect(() =>{ fetch('https://powerful-fjord-39182.herokuapp.com/allUsersBooking') .then(res => res.json()) .then(data => { setListInfo(data); }) }, []) return ( <div> <div className="servicelist-table"> <Table borderless> <thead> <tr> <th>Name</th> <th>Email ID</th> <th>Service</th> <th>Product Details</th> <th className="text-center">status</th> </tr> </thead> { listInfo.map(data => <ListDetails data={data} id={data._id}/>) } </Table> </div> </div> ); }; export default List;
import {combineReducers} from "redux"; import query from "./query"; import ui from "./ui"; const rootReducer = combineReducers({query, ui}); export default rootReducer;
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // ================================================================================ function MneIframeEditorUndo(editor, param) { editor.undoit = new Array(); editor.undonum = -1; editor.undo_add = function(sel) { var u = new Object; var s; var obj, objnum; var html; var i; try { this.undo_need = false; if ( typeof sel == 'undefined' ) s = this.getSelection(); else s = sel; this.clearNode(s); html = this.editarea.innerHTML.replace(/> </g, ">&nbsp;<"); u.html = html; if ( this.undonum >= 0 && this.undoit[this.undonum].html == html ) return false; if ( this.undonum >= 0 ) this.buttons.setModify(true); if ( this.undonum != this.undoit.length-1 ) for ( i=this.undoit.length-2; i >= this.undonum; i-- ) this.undoit[this.undoit.length] = this.undoit[i]; this.undonum = this.undoit.length - 1; if ( s != null ) { try { obj = s.startContainer; objnum = new Array(); while ( obj != this.editarea ) { var i; for ( i=0; i<obj.parentNode.childNodes.length; i++ ) if ( obj == obj.parentNode.childNodes[i] ) break; objnum[objnum.length] = i; obj = obj.parentNode; } u.start = objnum; u.startOffset = s.startOffset; obj = s.endContainer; objnum = new Array(); while ( obj != this.editarea ) { var i; for ( i=0; i<obj.parentNode.childNodes.length; i++ ) if ( obj == obj.parentNode.childNodes[i] ) break; objnum[objnum.length] = i; obj = obj.parentNode; } u.end = objnum; u.endOffset = s.endOffset; } catch(e) { u.start = u.end = null; } } else { u.start = u.end = null; } this.undonum++; this.undoit[this.undonum] = u; return true; } catch(e) { this.error(e.message + "\n" + e.stack); } }; editor.undo_setCursor = function(ele) { var i; var obj; var sel = new Object; if ( ele.start == null ) return; try { obj = this.editarea; for ( i=ele.start.length -1; i>=0; i-- ) { obj = obj.childNodes[ele.start[i]];} sel.startContainer = obj; sel.startOffset = ele.startOffset; obj = this.editarea; for ( i=ele.end.length -1; i>=0; i-- ) { obj = obj.childNodes[ele.end[i]]; } sel.endContainer = obj; sel.endOffset = ele.endOffset; this.moveCursorSelect(sel); } catch(e) { this.error("#mne_lang#kann Cursor nach undo nicht setzen" + "\n" + e.message + " " + e.stack); } }; editor.undo_undo = function() { if ( this.undoit.length == 0 ) return; this.win.focus(); this.undo_add(); if ( this.undonum > 0 ) { this.undonum--; this.editarea.innerHTML = this.undoit[this.undonum].html; if ( this.undoit[this.undonum].start != null ) this.undo_setCursor(this.undoit[this.undonum]); } if ( this.undonum == 0 ) this.buttons.setModify(false); }; editor.undo_redo = function() { this.win.focus(); if ( this.undonum + 1 < this.undoit.length ) { this.undonum++; this.editarea.innerHTML = this.undoit[this.undonum].html; this.undo_setCursor(this.undoit[this.undonum]); this.buttons.setModify(true); } }; editor.buttons.newSeperator(param.line); editor.buttons.newButton(param.line, "undo.gif", function() { this.buttons.mne_editor.undo_undo(); }, "#mne_lang#Änderung rückgängig machen"); editor.buttons.newButton(param.line, "redo.gif", function() { this.buttons.mne_editor.undo_redo(); }, "#mne_lang#Änderung wieder herstellen"); }
import { Cart } from '../../model/cart' const cart = new Cart() Page({ /** * 页面的初始数据 */ data: { cartItems: [], allChecked: null, isEmpty: false, totalPrice: 0, totalCount: 0, }, /** * 生命周期函数--监听页面加载 */ onLoad: async function (options) { if (cart.isEmpty()) { this.isEmpty() return } await cart.getServerCartData() }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () {}, /** * 生命周期函数--监听页面显示 */ onShow: function () { const cartItems = cart.getLocalCartData().items if (cart.isEmpty()) { this.isEmpty() return } this.setData({ cartItems, }) this.isnotEmpty() this.isAllChecked() cart._calCheckedPrice() this.refreshData() }, //重新计算 refreshData() { this.setData({ totalPrice: cart.checkedPrice, totalCount: cart.checkedCount, }) }, // 空操作 isEmpty() { this.setData({ isEmpty: true, }) wx.hideTabBarRedDot({ index: 2, }) }, // 非空操作 isnotEmpty() { this.setData({ isEmpty: false, }) wx.showTabBarRedDot({ index: 2, }) }, // 删除购物车的回调 deleteCartItem() { if (cart.isEmpty()) { this.isEmpty() } this.isAllChecked() this.refreshData() }, // 选中购物车商品的回调 checkCartItem() { this.isAllChecked() this.refreshData() }, // 改变购物车商品数量的回调 changeCartItemCount() { this.refreshData() }, // 判断是否全选 isAllChecked() { if (cart.isAllChecked()) { this.setData({ allChecked: true, }) } else { this.setData({ allChecked: false, }) } }, checkAll(event) { const checked = event.detail.checked this.setData({ allChecked: checked, }) cart.checkALl(checked) this.setData({ cartItems: this.data.cartItems, totalPrice: cart.checkedPrice, totalCount: cart.checkedCount, }) }, onSettle() { const checkednums = cart.getCheckedItems() if (!checkednums.length) { wx.lin.showToast({ title: '至少选择一件商品', icon: 'error', }) return } else { wx.navigateTo({ url: '/pages/order/index', }) } }, })
import React, { useContext, useState } from 'react'; import { PostContext } from './App'; import { Button, Modal } from 'react-bootstrap'; const RenderList = (props) => { const [modalOpen, setModalOpen] = useState(false) const { handleDelete, updateValues, setUpdateValues, handleUpdate } = useContext(PostContext); const { posts } = props; function reversePostsArr({ posts }) { let reverseArr = []; for (let i = posts.length - 1; i >= 0; i--) { let index = posts[i] reverseArr.push(index) } return reverseArr }; const handleUpdateChange = (e) => { const { name, value } = e.target setUpdateValues({ ...updateValues, [name]: value }) } const handleSaveChanges = (id) => { handleUpdate(id) setModalOpen(!modalOpen) } const handleModalOpen = (id) => { setUpdateValues(posts.filter(post => { return post.id === id })[0] ); setModalOpen(!modalOpen) } const postsArr = reversePostsArr({ posts }); return ( <div className="render-list display-wrap"> {postsArr.map((post) => ( <div key={post.id} className="render-container display-justify-center"> <div className="render-card display-space-between flex-direction"> <div className="render-actions display-space-between"> <span className="timestamp"> {post.createdAt} </span> <div className="btn-flex display-column"> <button className="edit-btn" onClick={() => handleModalOpen(post.id)}> EDIT </button> <button className="delete-btn" onClick={() => handleDelete(post.id)}> DELETE </button> </div> </div> <div> <h3 className="render-dropdown">{post.dropdown}</h3> </div> <div className="renderlist"> <div className="render-message"> <strong>ENTRY:</strong> <p>{post.message}</p> </div> <div className="render-headwinds"> <strong>HEADWINDS:</strong> <p>{post.headwinds}</p> </div> <div className="render-tailwinds"> <strong>TAILWINDS:</strong> <p>{post.tailwinds}</p> </div> </div> </div> </div> ))} <> <Modal show={modalOpen} onHide={() => setModalOpen(!modalOpen)}> <Modal.Header closeButton> <Modal.Title className="modal-header">Edit Entry</Modal.Title> </Modal.Header> <Modal.Body> <label htmlFor="dropdown" className="modal-dropdown display-column">Entry Title:</label> <input className="modal-dropdown" type="text" name="dropdown" value={updateValues.dropdown} onChange={handleUpdateChange} /> <label htmlFor="message">Message:</label> <input className="modal-message" type="text" name="message" value={updateValues.message} onChange={handleUpdateChange} /> <label htmlFor="headwinds">Headwinds:</label> <input className="modal-headwinds" type="text" name="headwinds" value={updateValues.headwinds} onChange={handleUpdateChange} /> <label htmlFor="dropdown">Tailwinds:</label> <input className="modal-tailwinds" type="text" name="tailwinds" value={updateValues.tailwinds} onChange={handleUpdateChange} /> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={() => setModalOpen(!modalOpen)}> Close </Button> <Button variant="primary" onClick={() => handleSaveChanges(updateValues.id)}> Save Changes </Button> </Modal.Footer> </Modal> </> </div> ); }; export default RenderList;
import addUserData from './addUserData'; import hasLoggedIn from './hasLoggedIn'; import userCity from './userCity'; import addCenters from './addCenters'; import {combineReducers} from 'redux'; const allReducers = combineReducers({ addUserData, hasLoggedIn, userCity, addCenters }) export default allReducers;
/** * Http 请求 */ var HttpClient = (function () { function HttpClient() { this.callbackList = new HashMap(); } var d = __define,c=HttpClient;p=c.prototype; p.send = function (url, data, callback) { var loader = new egret.URLLoader(); this.callbackList.set(loader.hashCode, callback); loader.dataFormat = egret.URLLoaderDataFormat.TEXT; loader.addEventListener(egret.Event.COMPLETE, this.onPostComplete, this); var request = new egret.URLRequest(url); request.method = egret.URLRequestMethod.POST; var argsArr = []; for (var key in data) { argsArr.push(key + "=" + data[key]); } request.data = new egret.URLVariables(argsArr.join("&")); loader.load(request); }; p.test = function () { var req = new egret.HttpRequest(); req.responseType = egret.HttpResponseType.TEXT; req.open("http://www.bmob.cn/app/runcloud/65830/_e/test/method/post", egret.HttpMethod.POST); //var buff:egret.ByteArray = new egret.ByteArray(); //buff.writeUTF("a=123"); //buff.position = 0; //req.send(buff); req.send("a=1"); }; p.test2 = function () { var Bmob = window["Bmob"]; var key = "uyaer"; var timestamp = Math.floor(Date.now() / 1000) + ""; var data = "{a:123,b:321}"; var vertify = new md5().hex_md5(key + timestamp + data); var sendData = { "vertify": vertify, "data": data, "timestamp": timestamp }; Bmob.Cloud.run('test', { "data": JSON.stringify(sendData) }, { success: function (result) { alert(result); }, error: function (error) { } }); }; p.onPostComplete = function (event) { var loader = event.currentTarget; loader.removeEventListener(egret.Event.COMPLETE, this.onPostComplete, this); loader.removeEventListener(egret.IOErrorEvent.IO_ERROR, this.onPostIOError, this); var data = JSON.parse(loader.data); if (loader._request.url.indexOf("xj_update_res.tr") == -1) { console.log("post data : ", data); } //TODO 错误码判断 var callback = this.callbackList.get(loader.hashCode); if (callback) { callback(data); this.callbackList.remove(loader.hashCode); } }; p.onPostIOError = function (event) { egret.error("post error : " + event); }; return HttpClient; })(); egret.registerClass(HttpClient,"HttpClient",["IClient"]);
import { NEW_CARD, DELETE_CARD, NEW_CATEGORY } from './types.js'; export const deleteCard = (categories, categoryIndex, cardIndex) => dispatch => { let updatedCards = {name: categories[categoryIndex].name, cards:categories[categoryIndex].cards.slice(0, cardIndex).concat(categories[categoryIndex].cards.slice(cardIndex + 1))}; let copy = categories.slice(); copy[categoryIndex] = updatedCards dispatch({ type: DELETE_CARD, payload: copy }); }
import React, { Fragment, useEffect, useState } from 'react'; import { Container, Row, Col, Image } from 'react-bootstrap'; import BootstrapTable from 'react-bootstrap-table-next'; import { connect } from 'react-redux'; import noImage from '../../images/image-not-found.png'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faTrash, faEdit } from '@fortawesome/free-solid-svg-icons'; import Rating from '../Utility/Rating'; import { removeRating, updateRating } from '../../actions/profile'; import { Link } from 'react-router-dom'; const Ratings = ({ ratings, stats, updateRating, removeRating }) => { const [data, updateData] = useState([]); const [selectedCategory, updateCategory] = useState('movie'); useEffect(() => { let content = []; console.log(ratings); const modified_rating = ratings[selectedCategory].map((item) => { return { id: item.id, title: item.title, tmdb_rating: stats[selectedCategory].filter( (content) => item.id === content.contentId )[0].tmdb_rating, my_rating: item.rating, backdrop: item.backdrop, }; }); Array.prototype.push.apply(content, modified_rating); console.log(content); updateData(content); }, [ratings, selectedCategory]); const imageFormatter = (row, cell) => { console.log(cell); return ( <Link to={`/${selectedCategory}/${cell.id}`} style={{ textDecoration: 'none' }} > <Image src={ cell === null ? noImage : `https://image.tmdb.org/t/p/w780${cell.backdrop}` } style={{ width: '100%', height: 'auto', maxHeight: 'inherit' }} /> </Link> ); }; const editRatingFormatter = (row, cell) => { console.log('edit', row); console.log(cell); return ( <span style={{ cursor: 'pointer' }}> <Rating item={cell} itemType={selectedCategory} handleRating={updateContentRating} type="edit" /> </span> ); }; const deleteRatingFormatter = (row, cell) => { console.log('edit', row); console.log('edit', cell); return ( <span style={{ cursor: 'pointer' }}> <FontAwesomeIcon icon={faTrash} color="red" onClick={() => deleteContentRating(cell)} /> </span> ); }; const columns = [ { dataField: 'id', hidden: true, }, { dataField: 'backdrop', formatter: imageFormatter, style: { padding: '2px 0px' }, headerStyle: (col, colIndex) => { return { width: '10%', textAlign: 'center' }; }, // style: (col, colIndex) => { // return { // marginTop: 'auto', // marginBottom: 'auto', // padding: '0 0', // display: 'flex', // alignItem: 'center', // }; // }, }, { dataField: 'title', text: 'Title', headerStyle: (col, colIndex) => { return { width: '65%', color: '#c3d1d9', paddingLeft: '2%' }; }, formatter: (row, cell) => { return ( <Link to={`/${selectedCategory}/${cell.id}`} style={{ textDecoration: 'none', color: '#c3d1d9' }} > {cell.title} </Link> ); }, }, { dataField: 'tmdb_rating', text: 'TMDB Rating', headerStyle: (col, colIndex) => { return { width: '15%', color: '#c3d1d9', textAlign: 'center' }; }, align: 'center', }, { dataField: 'my_rating', text: 'My Rating', headerStyle: (col, colIndex) => { return { width: '15%', color: '#c3d1d9', textAlign: 'center' }; }, align: 'center', }, { dataField: 'edit_rating', headerStyle: (col, colIndex) => { return { width: '5%' }; }, formatter: editRatingFormatter, }, { dataField: 'delete_rating', headerStyle: (col, colIndex) => { return { width: '5%' }; }, formatter: deleteRatingFormatter, }, ]; const updateContentRating = (item, action, rating = 0) => { updateRating(item.id, selectedCategory, rating); }; const deleteContentRating = (item) => { removeRating(item.id, selectedCategory); }; return ( <Fragment> <Container className="px-0" fluid> <div className="d-flex flex-row flex-wrap align-items-center pt-3 pb-2 px-0" style={{ position: 'sticky', top: '7vh', zIndex: '50', borderBottom: '2px solid #30363d', background: 'black', }} > <h3 className="px-2 pb-1" style={{ color: '#c3d1d9' }}> Ratings </h3> <div className="pl-4 d-flex flex-row"> {['movie', 'tv'].map((item, index) => { return ( <h5 className="px-2 pb-1" style={{ width: 'auto', borderBottom: item === selectedCategory && '3px solid green', }} key={`watched_${item}`} > <span className="px-1" style={{ cursor: 'pointer', color: '#c3d1d9' }} onClick={() => updateCategory(item)} > {item === 'movie' ? 'Movies' : 'TV Shows'} </span> </h5> ); })} </div> </div> <div style={{ zIndex: '-20' }} className="d-md-flex flex-md-row flex-md-wrap px-2" > {data.length !== 0 && ( <BootstrapTable keyField="title" columns={columns} data={data} bootstrap4 striped rowStyle={{ color: '#c3d1d9' }} bordered={false} /> )} {data.length === 0 && ( <Container> <Row> <Col style={{ color: '#c3d1d9' }}> No {selectedCategory === 'movie' ? 'Movies' : 'TV Shows'}{' '} rated yet </Col> </Row> </Container> )} </div> </Container> </Fragment> ); }; const mapStateToProps = (state) => ({ ratings: state.profile.ratings, stats: state.dashboard.stats, }); export default connect(mapStateToProps, { updateRating, removeRating })( Ratings );
'use strict'; $(document).ready(function(){ $('#open_nav, #close_nav').on('click', function(){ $('#nav').toggleClass('show'); }); });
import React from 'react'; import axios from 'axios'; import { Button, Container, Typography, TextField } from '@material-ui/core'; import { useForm } from 'react-hook-form'; import { useStyles } from './styles'; import { useHistory } from 'react-router-dom'; import { useDispatch } from 'react-redux'; import { saveAuthUserAction } from '../../redux/actions/authUserActions'; export const Login = () => { const classes = useStyles(); const history = useHistory(); const dispatch = useDispatch(); const { register, handleSubmit, errors } = useForm(); const signin = (data) => { axios({ url: `${process.env.REACT_APP_BACKEND_URL}/users/signin`, method: 'POST', data: { ...data }, }) .then(({ data }) => { dispatch(saveAuthUserAction({ ...data, isAuth: true })); history.push('/match'); }) .catch((res) => alert(res.response.data.message)); }; return ( <Container maxWidth="sm"> <form className={classes.root} noValidate autoComplete="off" onSubmit={handleSubmit(signin)}> <Typography variant="h5" className={classes.title}> Login </Typography> <TextField id="email" name="email" label="Email" fullWidth={true} size="small" variant="outlined" inputRef={register({ required: true })} error={errors.email ? true : false} helperText={errors.email && 'Name is required'} /> <TextField id="password" name="password" label="Password" type="password" fullWidth={true} size="small" variant="outlined" inputRef={register({ required: true })} error={errors.password ? true : false} helperText={errors.password && 'Password is required'} /> <Button color="primary" variant="contained" fullWidth={true} type="submit"> Login </Button> </form> </Container> ); };
import React from 'react'; import { TouchableOpacity, ImageBackground, View, Text, StyleSheet, } from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; const FoodCard = ({item, setModalVisible, setSelectedFood}) => { return ( <TouchableOpacity onPress={() => { setSelectedFood(item); setModalVisible(true); }}> <View key={item.id} style={styles.item}> <ImageBackground source={item.img} style={styles.image}> <Text style={styles.text}>{item.title}</Text> </ImageBackground> <View style={styles.descriptions}> <Text numberOfLines={2} ellipsizeMode="tail"> {item.description} </Text> </View> <View style={styles.priceAndTime}> <Text style={{fontWeight: 'bold'}}>KD-{item.kd}</Text> <Ionicons style={{backgroundColor: '#e2e1e1', padding: 6, marginBottom: 10}} size={15} name="time-outline"> {` ${item.time} min`} </Ionicons> </View> </View> </TouchableOpacity> ); }; const styles = StyleSheet.create({ item: { height: 300, justifyContent: 'center', marginVertical: 8, marginHorizontal: 5, shadowColor: '#dcd8d8', borderRadius: 2, shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.8, shadowRadius: 1.41, elevation: 2, // padding: 20, }, image: { flex: 4, resizeMode: 'cover', justifyContent: 'flex-end', }, descriptions: { flex: 2, padding: 10, }, priceAndTime: { flex: 1, flexDirection: 'row', justifyContent: 'space-between', marginHorizontal: 10, }, text: { color: 'white', fontSize: 32, margin: 10, }, }); export default FoodCard;
function create_card(id, header, responsible_name, responsible_surname, deadline, priority_name, description, status_name) { let title_color = "text-muted"; if(status_name === "Выполнена") { title_color = "text-success"; } else if(Date.now() > Date.parse(deadline)) { title_color = "text-danger"; } return ` <div class="card m-2 col-md-3 hand" id="${id}" onclick="update_modal(this)"> <div class="card-body"> <h5 class="card-title ${title_color}">${header} <span class="card-text float-end text-muted font-16 mt-1">${status_name}</span></h5> <h6 class="card-subtitle text-muted">для ${responsible_name} ${responsible_surname}</h6> <h6 class="card-subtitle text-muted">до ${deadline}</h6> <h6 class="card-subtitle text-muted">${priority_name} приоритет</h6> <p class="card-text mt-2">${description}</p> </div> </div>`; } function create_modal() { $('#create-modal').modal('show'); } function update_modal(element) { tasks.forEach((task)=> { if(task['id'] == element.id) { let deadline = task['deadline'].replace(' ', 'T').substr(0, 16); let title = $('#update-title'); let desc = $('#update-description'); let date = $('#update-deadline'); let priority = $('#update-priority'); let resp = $('#update-responsible'); $('#update-id').val(task['id']); title.val(task['header']); desc.val(task['description']); date.val(deadline); priority.val(task['priority']['id']); resp.val(task['responsible']['id']); if($('#user-id').val() == task['responsible']['id']) { title.attr('disabled', true); desc.attr('disabled', true); date.attr('disabled', true); priority.attr('disabled', true); resp.attr('disabled', true); } else { title.attr('disabled', false); desc.attr('disabled', false); date.attr('disabled', false); priority.attr('disabled', false); resp.attr('disabled', false); } $('#update-status').val(task['status']['id']); } }) $('#update-modal').modal('show'); } let tasks; function get_tasks(groupBy) { $.get( "/tasks/get") .done(function( data ) { tasks = data; let list = document.getElementById('tasks_list'); list.innerHTML = group(groupBy); }); } function groupNone() { let html = ""; tasks.forEach((task)=> { html += create_card(task['id'], task['header'], task['responsible']['name'], task['responsible']['surname'], task['deadline'], task['priority']['name'], task['description'], task['status']['name']); }); return html; } function groupByDate() { let html = ""; let now = new Date(); let day_end = new Date(Date.parse(now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate()) + 86400000); let week_end = new Date(day_end.getTime() + 86400000 * 6); let group = [ ['Задачи на сегодня', ''], ['Задачи на неделю', ''], ['Задачи позже', ''], ['Истекшие', ''] ]; tasks.forEach((task)=> { let card = create_card(task['id'], task['header'], task['responsible']['name'], task['responsible']['surname'], task['deadline'], task['priority']['name'], task['description'], task['status']['name']); let deadline = Date.parse(task['deadline']); if(deadline < now) { group[3][1] += card; } else if(deadline < day_end) { group[0][1] += card; } else if(deadline < week_end) { group[1][1] += card; } else { group[2][1] += card; } }); group.forEach((category) => { if(category[1] !== '') html += "<div class='col-9 text-center'><h5>" + category[0] + "</h5></div>" + category[1]; }) return html; } function groupByResponsible() { let html = ""; let tasksByUser = {}; tasks.forEach((task)=> { let user_id = task['responsible']['id']; let user_name = task['responsible']['name'] let user_surname = task['responsible']['surname']; let card = create_card(task['id'], task['header'], task['responsible']['name'], task['responsible']['surname'], task['deadline'], task['priority']['name'], task['description'], task['status']['name']); if(tasksByUser[user_id] === undefined) { tasksByUser[user_id] = `<div class='col-9 text-center'><h5>${user_name} ${user_surname}</h5></div>` + card; } else { tasksByUser[user_id] += card; } }); for (const [key, value] of Object.entries(tasksByUser)) { html += value; } return html; } function group(groupBy) { switch (groupBy) { case "group-none": return groupNone(); case "group-date": return groupByDate(); case "group-responsible": return groupByResponsible(); } } $(function () { get_tasks("group-none"); });
/* ====== Primitive Type ====== 1. Number 2. String 3. Boolean 4. undefined 5. null 6. Symbol */ // Number let num = '10.66'; // String let name = 'Saidur Rahman'; // Boolean let isAged = true; // undefined let variable; // Initial // null let myVar; console.log(typeof myVar);
 $(document).ready(function () { $("#main-menu-min").click(); var notification = $("#notification").kendoNotification({ position: { pinned: true, top: 50, right: 450 }, autoHideAfter: 2000, stacking: "down", templates: [ { type: "error", template: $("#errorTemplate").html() }, { type: "upload-success", template: $("#successTemplate").html() } ], show: function (e) { e.element.parent().css('z-index', 22222); } }).data("kendoNotification"); //#region Grid Hợp đồng $("#grid_hd").kendoGrid({ dataSource: { transport: { read: function (options) { $.ajax({ type: "POST", url: "assets/ajax/Ajax_ThongKe_TienTrinh.aspx", data: { cmd: 'ThongKe_TienTrinh_HopDong' }, dataType: 'json', success: function (result) { if (result == "err401") { alert("Phiên đã hết hạn!Vui lòng đăng nhập lại."); window.location.href = "DangNhap.aspx?p=ThanhToan_HopDong.aspx"; } else { options.success(result); } } }); } } }, pageable: true, pageable: { messages: { display: "Tổng số {2} dòng", empty: "Không có dữ liệu", page: "Trang", of: "of {0}", itemsPerPage: "Số mục trong một trang" } }, filterable: { extra: false, operators: { string: { contains: "Chứa", eq: "Bằng", neq: "Khác" } }, messages: { info: "Chọn kiểu lọc: ", filter: "Lọc", clear: "Hủy lọc" } }, groupable: { messages: { empty: "<b style='color:#fabb3d;'>Kéo một tiêu đề cột và thả nó vào đây để nhóm theo cột đó</b>" } }, //toolbar: kendo.template($("#Templ_NguoiDung").html()), columns: [ { title: "Số hợp đồng", headerAttributes: { class: "header_css" }, field: "MaHD", filterable: { ui: function (element) { element.kendoComboBox({ dataTextField: "MaHD", dataValueField: "MaHD", dataSource: $("#grid_hd").data("kendoGrid").dataSource.data(), filter: "startswith", dataBound: function (e) { var $dropDown = $(e.sender.element), dataWidth = $dropDown.data("kendoComboBox").list.width(), listWidth = dataWidth + 300, containerWidth = listWidth + 6; // Set widths to the new values $dropDown.data("kendoComboBox").list.width(listWidth); $dropDown.closest(".k-widget").width(containerWidth); } }); } }, attributes: { class: "row_css", style: "font-weight:bold;" }, width: 140 }, { title: "Số PO", headerAttributes: { class: "header_css" }, field: "SoPO", attributes: { class: "row_css", style: "font-weight:bold;" }, filterable: { ui: function (element) { element.kendoComboBox({ dataTextField: "SoPO", dataValueField: "SoPO", dataSource: $("#grid_hd").data("kendoGrid").dataSource.data(), filter: "startswith", dataBound: function (e) { var $dropDown = $(e.sender.element), dataWidth = $dropDown.data("kendoComboBox").list.width(), listWidth = dataWidth + 300, containerWidth = listWidth + 6; // Set widths to the new values $dropDown.data("kendoComboBox").list.width(listWidth); $dropDown.closest(".k-widget").width(containerWidth); } }); } }, width: 100 }, //{ // title: "Tới bước", // headerAttributes: { // class: "header_css" // }, // field: "Buoc_TienTrinh_TT", // template: function (data) { // if (data.Buoc_TienTrinh_TT == 1) { // return '<a>Bước 1 :</a><br>CHUYỂN HỒ SƠ THỤ LÝ'; // } // else if (data.Buoc_TienTrinh_TT == 2) { // return '<a>Bước 2 :</a><br>TIẾP NHẬN HỒ SƠ'; // } // else if (data.Buoc_TienTrinh_TT == 3) { // return '<a>Bước 3 :</a><br>KIỂM TRA TÍNH HỢP LÝ CỦA CHỨNG TỪ'; // } // else { // return '<a>Bước 0 :</a><br>CHƯA CHUYỂN HỒ SƠ THỤ LÝ'; // } // }, // attributes: { // class: "row_css", // style: "font-weight:bold;color:red;" // }, // width: 140 //}, { title: "Tiến trình", headerAttributes: { class: "header_css" }, field: "Buoc_TienTrinh_TT", filterable: false, groupHeaderTemplate:function (data) { if (data.value == 1) { return 'Bước 1 : CHUYỂN HỒ SƠ THỤ LÝ'; } else if (data.value == 2) { return 'Bước 2 : TIẾP NHẬN HỒ SƠ'; } else if (data.value == 3) { return 'Bước 3 : KIỂM TRA TÍNH HỢP LÝ CỦA CHỨNG TỪ'; } else { return 'Bước 0 : CHƯA CHUYỂN HỒ SƠ THỤ LÝ'; } }, template: function (data) { if (data.Buoc_TienTrinh_TT == 1) { if (data.TT_TienTrinh_TT == 1) { return '<a>Bước 1 </a><br><a style="font-weight:bold;color:red;">CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>ĐÃ CHUYỂN - CHỜ TIẾP NHẬN'; } else if (data.TT_TienTrinh_TT == 2) { return '<a>Bước 1 </a><br><a style="font-weight:bold;color:red;">CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>HOÀN TRẢ HỒ SƠ'; } else if (data.TT_TienTrinh_TT == 3) { return '<a>Bước 1 </a><br><a style="font-weight:bold;color:red;">CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>ĐÃ TIẾP NHẬN HỒ SƠ'; } else { return '<a>Bước 1 </a><br><a style="font-weight:bold;color:red;">CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>CHỜ NHÀ THẦU CHUYỂN HỒ SƠ'; } } else if (data.Buoc_TienTrinh_TT == 2) { if (data.TT_TienTrinh_TT == 1) { return '<a>Bước 2 </a><br><a style="font-weight:bold;color:red;">TIẾP NHẬN HỒ SƠ</a><br><a>Tình trạng</a><br>ĐÃ CHUYỂN HỒ SƠ CHO NHÂN VIÊN THỤ LÝ'; } else { return '<a>Bước 2 </a><br><a style="font-weight:bold;color:red;">TIẾP NHẬN HỒ SƠ</a><br><a>Tình trạng</a><br>ĐANG TIẾP NHẬN HỒ SƠ'; } } else if (data.Buoc_TienTrinh_TT == 3) { if (data.TT_TienTrinh_TT == 1) { return '<a>Bước 3 </a><br><a style="font-weight:bold;color:red;">KIỂM TRA TÍNH HỢP LÝ CỦA CHỨNG TỪ</a><br><a>Tình trạng</a><br>HỒ SƠ CHƯA HỢP LÝ - HOÀN TRẢ NHÀ THẦU'; } else if (data.TT_TienTrinh_TT == 2) { return '<a>Bước 3 </a><br><a style="font-weight:bold;color:red;">KIỂM TRA TÍNH HỢP LÝ CỦA CHỨNG TỪ</a><br><a>Tình trạng</a><br>HOÀN TẤT HỒ SƠ THANH TOÁN'; } else { return '<a>Bước 3 </a><br><a style="font-weight:bold;color:red;">KIỂM TRA TÍNH HỢP LÝ CỦA CHỨNG TỪ</a><br><a>Tình trạng</a><br>ĐANG KIỂM TRA TÍNH HỢP LÝ CỦA CHỨNG TỪ'; } } else { if (data.TT_TienTrinh_TT == 1) { return '<a>Bước 0 </a><br><a style="font-weight:bold;color:red;">CHƯA CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>ĐÃ CHUYỂN - CHỜ TIẾP NHẬN'; } else if (data.TT_TienTrinh_TT == 2) { return '<a>Bước 0 </a><br><a style="font-weight:bold;color:red;">CHƯA CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>HOÀN TRẢ HỒ SƠ'; } else if (data.TT_TienTrinh_TT == 3) { return '<a>Bước 0 </a><br><a style="font-weight:bold;color:red;">CHƯA CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>ĐÃ TIẾP NHẬN HỒ SƠ'; } else { return '<a>Bước 0 </a><br><a style="font-weight:bold;color:red;">CHƯA CHUYỂN HỒ SƠ THỤ LÝ</a><br><a>Tình trạng</a><br>CHỜ NHÀ THẦU CHUYỂN HỒ SƠ'; } } }, attributes: { class: "row_css", style: "font-weight:bold;color:green;background-color:lightyellow;" }, width: 170 }, { title: "Người phân công", headerAttributes: { class: "header_css" }, field: "Nguoi_PhanCong", attributes: { class: "row_css" }, filterable: { ui: function (element) { element.kendoComboBox({ dataTextField: "Nguoi_PhanCong", dataValueField: "Nguoi_PhanCong", dataSource: $("#grid_hd").data("kendoGrid").dataSource.data(), filter: "startswith", dataBound: function (e) { var $dropDown = $(e.sender.element), dataWidth = $dropDown.data("kendoComboBox").list.width(), listWidth = dataWidth + 300, containerWidth = listWidth + 6; // Set widths to the new values $dropDown.data("kendoComboBox").list.width(listWidth); $dropDown.closest(".k-widget").width(containerWidth); } }); } }, groupHeaderTemplate: function (data) { if (data.value == null) { return 'Chưa phân công'; } else { return data.value; } }, template: $("#photo-template").html(), width: 150 }, { title: "Mã hồ sơ thanh toán", headerAttributes: { class: "header_css" }, field: "Ma_HS_TT", attributes: { class: "row_css" }, template: function (data) { if (data.Ma_HS_TT == null) { return 'Chưa tiếp nhận' } else { return data.Ma_HS_TT } }, filterable: { ui: function (element) { element.kendoComboBox({ dataTextField: "Ma_HS_TT", dataValueField: "Ma_HS_TT", dataSource: $("#grid_hd").data("kendoGrid").dataSource.data(), filter: "startswith", dataBound: function (e) { var $dropDown = $(e.sender.element), dataWidth = $dropDown.data("kendoComboBox").list.width(), listWidth = dataWidth + 300, containerWidth = listWidth + 6; // Set widths to the new values $dropDown.data("kendoComboBox").list.width(listWidth); $dropDown.closest(".k-widget").width(containerWidth); } }); } }, width: 150 }, { title: "Ngày thanh toán", headerAttributes: { class: "header_css" }, field: "NgayDK_ThanhToan", attributes: { class: "row_css" }, groupHeaderTemplate: function (data) { if (data.value == null) { return 'Chưa phân công'; } else { return data.value; } }, template: function (data) { if (data.NgayDK_ThanhToan == null) { return 'Chưa tiếp nhận' } else { return data.NgayDK_ThanhToan } }, width: 100 } ] }); //#endregion });
import React from 'react'; import { Link } from 'react-router-dom'; const NoAuthor = () => { return ( <div> <h4 className="text-danger mt-5 mb-5">We're sorry, but we could not find the author you are looking for. Would you like to add this author to our database?</h4> <Link to="/add_author">Add author</Link> </div> ); }; export default NoAuthor;
var Light = artifacts.require("./Light.sol"); module.exports = function(deployer) { deployer.deploy(Light); };
import React from "react"; import { View, Text, TextInput, TouchableHighlight, StyleSheet, Alert } from "react-native"; const styles = StyleSheet.create({ bar: { backgroundColor: "#333", flexDirection: "row", paddingHorizontal: 5, paddingVertical: 5 }, btn: { backgroundColor: "#1976D2", paddingVertical: 10, paddingHorizontal: 15 }, search: { flexGrow: 1 }, input: { paddingHorizontal: 10, color: "#333", backgroundColor: "#fff", height: 43 } }); const SearchBar = ({ search, handleText, value }) => ( <View style={styles.bar}> <View style={styles.search}> <TextInput style={styles.input} underlineColorAndroid="transparent" placeholder="search github" onChange={handleText} value={value} /> </View> <View> <TouchableHighlight onPress={search}> <View style={styles.btn}> <Text>Search</Text> </View> </TouchableHighlight> </View> </View> ); export default SearchBar;
'use strict'; var app = angular.module('confusionApp', []); app.controller('menuController', ['$scope', function ($scope) { var dishes=[ { name:'Uthapizza', image: 'img/uthapizza.png', category: 'mains', label:'Hot', price:'4.99', description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.', comment: '' }, { name:'Zucchipakoda', image: 'img/zucchipakoda.png', category: 'appetizer', label:'', price:'1.99', description:'Deep fried Zucchini coated with mildly spiced Chickpea flour batter accompanied with a sweet-tangy tamarind sauce', comment: '' }, { name:'Vadonut', image: 'img/vadonut.png', category: 'appetizer', label:'New', price:'1.99', description:'A quintessential ConFusion experience, is it a vada or is it a donut?', comment: '' }, { name:'ElaiCheese Cake', image: 'img/elaicheesecake.png', category: 'dessert', label:'', price:'2.99', description:'A delectable, semi-sweet New York Style Cheese Cake, with Graham cracker crust and spiced with Indian cardamoms', comment: '' } ]; $scope.dishes = dishes; $scope.tab = 1; $scope.filtText = ""; $scope.select = function(setTab) { $scope.tab = setTab; switch(setTab) { case 2: $scope.filtText = "appetizer"; break; case 3: $scope.filtText = "mains"; break; case 4: $scope.filtText = "dessert"; break; default: $scope.filtText = ""; } }; $scope.isSelected = function (checkTab) { return ($scope.tab === checkTab); }; $scope.showDetails = false; $scope.toggleDetails = function() { $scope.showDetails = !$scope.showDetails; }; }]);
const AsUrl = 'https://c5.gluu.org'; const clientID = '@!82F6.00B8.C20E.272F!0001!DC79.0594!0008!1E13.CB20.2F74.F9BE'; // const responseType = 'id_token token code' const scopes = 'openid profile email' // Utilities // function randomString() { // Create unique identifiers for state and nonce. const validChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let array = new Uint8Array(40); window.crypto.getRandomValues(array); array = array.map(x => validChars.charCodeAt(x % validChars.length)); const randomState = String.fromCharCode.apply(null, array); return randomState; } function parseJwt (token) { // Parse the Base 64 encoded ID Token from the authorization response. var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); decoded = atob(base64); parsed = JSON.parse(decoded); return parsed; } function parseUrl () { // Gather current URL var url = window.location.href; url = url.substring(1); var params = {}, responses, temp, i, l; // Split into key/value pairs if (url.includes("#")) { url = url.split('#').pop(); } else { url = url.split('?').pop(); } responses = url.split("&"); // Convert the array of strings into an object for ( i = 0, l = responses.length; i < l; i++ ) { temp = responses[i].split('='); params[temp[0]] = temp[1]; } // Store certain params, like ID Token, scope, etc in a "database" and store session_state in a cookie. window.localStorage.setItem("authResp", JSON.stringify(params)); setCookie("session_state",params.session_state,1); } function setCookie(cname,cvalue,exdays) { // Create cookie to store session state from authorization response. var d = new Date(); //Create a date object d.setTime(d.getTime() + (exdays*1000*60*60*24)); //Set the time to exdays from the current date in milliseconds. 1000 milliseonds = 1 second var expires = "expires=" + d.toGMTString(); //Compose the expiration date window.document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/"; //Set the cookie with value and the expiration date } function getCookieValue(cookieName) { var name = cookieName + "="; var cookies = document.cookie.split(';'); if (!cookies) { return null; } for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.indexOf(name) == 0) { return cookie.substring(name.length, cookie.length); } } return null; } function parseJsonResponseForHtml (jsonobject) { var output = ''; var obj = jsonobject; for (var key in obj) { if (obj.hasOwnProperty(key)) { output = output + key + ' : ' + obj[key] + '<br />'; } } return output; } // Session Management // function logout () { // End current local application session. if (JSON.parse(window.localStorage.getItem("authResp"))){ var response = JSON.parse(window.localStorage.getItem("authResp")) idToken64 = response.id_token; } const postLogoutUri = 'http://localhost:8080/finish_logout' const getUrl = AsUrl + '/oxauth/restv1/end_session' + '?post_logout_redirect_uri=' + postLogoutUri; document.cookie = "session_state=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; window.location.replace(getUrl); window.localStorage.removeItem("authResp"); } // Implicit Flow Authentication // function authRequest(type){ if ( type == 'implicit'){ responseType = 'id_token token'; } else if ( type == 'code'){ responseType = 'code'; } else if ( type == 'hybrid'){ responseType = 'id_token token code'; } const AsAuthUrl=AsUrl + '/oxauth/restv1/authorize'; const redirectUri='http://localhost:8080/success/'; let state = randomString(); let nonce = randomString(); // Auth requested formatted as such according to https://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthRequest const getUrl = AsAuthUrl + '?response_type=' + responseType + '&client_id=' + clientID + '&redirect_uri=' + redirectUri + '&scope=' + scopes + '&state=' + state + '&nonce=' + nonce; // Store nonce and state setCookie("nonce", nonce, 1); setCookie("state", state, 1); // Redirect for Implicit Flow window.location.replace(getUrl); } function validate (issuer, nonce, audience) { // Should fully validate based off of OpenID Connect Core 3.2.2.8. Authentication Response Validation // 3.2.2.9. Access Token Validation and 3.2.2.11. ID Token Validation var appNonce = getCookieValue('nonce'); if (issuer != AsUrl) { alert("Issuer does not match."); // Redirect to attempt to login agai. return; } if (nonce != appNonce) { alert("Nonce does not match."); // Redirect to attempt to login again. return; } if (audience != clientID) { alert("Client ID does not match."); // Redirect to attempt to login again. return; } return true; } function gatherToken (code) { url = AsUrl + '/oxauth/restv1/token'; redirectUri = 'http://localhost:8080/' var http = new XMLHttpRequest(); data = 'grant_type=authorization_code&code=' + code + '&client_id=' + clientID + '&client_secret=secret' + "&redirect_uri=" + redirectUri; http.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Store access token and redirect to demo page. } }; http.open("POST", url); http.send(data); } function postAuthRedirect () { // Gather our authentication response to verify var response = JSON.parse(window.localStorage.getItem("authResp")); url = document.location.href; if (url.includes('access_token')){ if (url.includes('code')) { alert('Hybrid Flow'); responseType = 'hybrid'; } alert('Implicit Flow'); responseType = 'implicit'; } else if (url.includes('code')) { alert('Authorization Code Flow'); responseType = 'code'; } if (responseType == 'implicit') { // Base64 Decode the id_token from the authentication response idToken64 = response.id_token; idToken = parseJwt(idToken64); // Verify nonce, audience, response type and issuer then forward the user to a pseudo passed authentication page. if (validate(idToken['iss'], idToken['nonce'], idToken['aud'])) { window.location.replace("http://localhost:8080/"); } else { document.getElementById("passFail").innerHTML = "Failed to validate response!"; } } else if (responseType = 'code') { var response = JSON.parse(window.localStorage.getItem("authResp")); authCode = response.code; gatherToken(authCode); } } function gatherUserClaims () { if (authData = JSON.parse(window.localStorage.getItem('authResp'))) { accessToken = authData.access_token; } else { // Fake access token for testing accessToken = 'c769d7ff-c476-42ab-b531-fe2f60b2f5cc'; } url = AsUrl + '/oxauth/restv1/userinfo'; var http = new XMLHttpRequest(); http.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("user_claims").innerHTML = parseJsonResponseForHtml(JSON.parse(this.responseText)); } else { document.getElementById("user_claims").innerHTML = parseJsonResponseForHtml(JSON.parse(this.responseText)); } }; http.open("GET", url); http.setRequestHeader('Authorization','Bearer ' + accessToken); http.send(); }
// 预约功能 const koa = require( 'koa') const bodyParser= require('koa-bodyparser') // 实例化 const app = new koa() const router = require('koa-router')() const DB = require('../../db') app.use(bodyParser()); // 将模块作为koa的中间件引入 // 查询全部信息 router.get("/appointment", async (ctx) => { const data = await DB.find('appointment', {}) ctx.body = JSON.stringify(data); // 响应请求,发送处理后的信息给客户端 }) // id查询 router.get("/appointment/:id", async (ctx) => { let ids = ctx.params let id = parseInt(ids.id) await DB.find('appointment', {id: id}).then((data) => { ctx.body = JSON.stringify(data); // 响应请求,发送处理后的信息给客户端 }) }) // 个人预约 router.post("/appointment/establish", async (ctx) => { let body = ctx.request.body console.log(body) const dataId = await DB.find('appointment', {}) const lastId = dataId[dataId.length - 1] const ids = lastId.id + 1 // 随机数 var Num = ('000000' + Math.floor(Math.random() * 999999)).slice(-6); const params = { username:body.name, mobile:body.mobile, curriculum:body.region, fraction: 0, // 预约号 number:Number(Num), // // 对应账号id // userId: body.id, type:1, id:ids } const data = await DB.insert('appointment', params) // 将个人预约添加到fraction 做小程序登录用 const datas = await DB.insert('fraction', params) ctx.body = JSON.stringify(data, datas); // 响应请求,发送处理后的信息给客户端 }) // 修改个人预约预留信息 router.post("/appointment/modify/:id", async (ctx) => { // 查询id let ids = ctx.params let id = parseInt(ids.id) var ChangedData = [] await DB.find('appointment', {id: id}).then((data) => { ChangedData = data }) let username = '' let mobile = '' let curriculum = '' for (const key in ChangedData) { username = ChangedData[key].username mobile = ChangedData[key].mobile curriculum = ChangedData[key].curriculum } const original = { username: username, mobile: mobile, curriculum: curriculum } // 修改内容 let body = ctx.request.body const datas = await DB.update('appointment', original, body) console.log(datas.result); ctx.body = JSON.stringify(datas); // 响应请求,发送处理后的信息给客户端 }) // 删除个人预约 router.delete("/appointment/remove/:id", async (ctx) => { let ids = ctx.params let id = parseInt(ids.id) const data = await DB.remove('appointment', {id: id}) ctx.body = JSON.stringify(data); // 响应请求,发送处理后的信息给客户端 }) module.exports = router
import React, {Component} from 'react'; import ColorBox from './ColorBox'; class App extends Component { constructor(){ super(); this.boxes = [ { title: "Animal", subtitle: 'strange', information: "It's a very rare sort", backgroundColor: "beige" }, { title: "Cat", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "lobster" }, { title: "Dog", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "green" }, { title: "Mewtwo", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "red" }, { title: "Poo", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "purple" }, { title: "Penguin", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "orange" }, { title: "Giraffe", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "yellow" }, { title: "Butterfly", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "white" }, { title: "Housefly", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "blue" }, { title: "Grasshopper", subtitle: 'A New Kind', information: "It's a very rare sort", backgroundColor: "brown" } ] } render(){ const boxesJSX = this.boxes.map(box => { return <ColorBox title={box.title} subtitle={box.subtitle} information={box.information} backgroundColor={box.backgroundColor} /> }) return( <div> {boxesJSX} </div> ); } } export default App;
//https://www.hackerrank.com/challenges/insertionsort2 //sorting strings doesn't work so well... next time remember to .map(Number) function processData(input) { 'use strict'; const size = input.split('\n'); const arr = size.pop().split(' ').map(Number); let e = 0; let prev = 0; for(let i = 1; i<size; i++){ e = arr[i]; prev = arr[i-1]; if(e<prev){ arr.splice(i,1,prev); //copies previous into current position. arr.splice(i-1,1); //deletes old location. let ib = i; while(ib--){ if(arr[ib]<e){ arr.splice(ib+1,0,e); //slices e into previous position console.log(arr.join(' ')); break; //have to break the loop in case there are duplicates. }else if(ib == 0){ arr.splice(ib,0,e); //slices e into current pos if at index 0. console.log(arr.join(' ')); break; } } }else{ console.log(arr.join(' ')); } } }
const ObjectId = require("mongodb").ObjectID; const sendMail = require("./../helper/mail"); const scheduleJob = require("./../helper/scheduler"); const { createLogger, format, transports } = require("winston"); const { combine, prettyPrint, timestamp } = format; const logger = createLogger({ format: combine(timestamp(), prettyPrint()), transports: [new transports.Console()], }); // Get All Customers Data const getTableData = (req, res, db) => { db.collection("table") .find() .toArray() .then((data) => { if (data.length > 0) { res.status(200).json(data); } else { res.status(200).json({ dataExists: "false", }); } }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(500).json({ dbError: "db error", }); }); }; // Get Individual Customer Data const getData = (req, res, db) => { const { _id } = req.params; db.collection("table") .findOne({ _id: ObjectId(_id) }) .then((data) => { res.status(200).json(data); }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(500).json({ dataExists: "false", }); }); }; // Add a Customer const postTableData = (req, res, db) => { const { cust_name, cust_email, cust_phn, cust_address, cust_gst, rem_freq, } = req.body; const timestamp = new Date().toISOString(); const cust_comm = []; db.collection("table") .insertOne({ cust_name, cust_email, cust_phn, cust_address, cust_gst, rem_freq, timestamp, cust_comm, }) .then((data) => { const { _id } = data.ops[0]; db.collection("table") .updateOne( { _id: ObjectId(_id) }, { $set: { cust_id: _id }, } ) .then((item) => { res.status(200).json(data.ops[0]); }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(400).json({ dbError: "db error" }); }); }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(400).json({ dbError: "db error" }); }); }; // Add new Communication const addComm = (req, res, db) => { const { timestamp, details, cust_id } = req.body; db.collection("table") .updateOne( { _id: ObjectId(cust_id) }, { $push: { cust_comm: { $each: [{ timestamp, details }], $position: 0, }, }, } ) .then((data) => { res.status(200).json({ dbUpdate: "true" }); }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(400).json({ dbError: "db error" }); }); }; // Update Customer Data const putTableData = (req, res, db) => { const { cust_id, cust_name, cust_email, cust_phn, cust_address, cust_gst, rem_freq, } = req.body; db.collection("table") .updateOne( { _id: ObjectId(cust_id) }, { $set: { cust_name, cust_email, cust_phn, cust_address, cust_gst, rem_freq, }, } ) .then((item) => { console.log(item); db.collection("table") .findOne({ _id: ObjectId(cust_id), }) .then((data) => { console.log(data); res.status(200).json(data); }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(500).json({ dataExists: "false", }); }); }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(400).json({ dbError: "db error" }); }); }; // Delete a customer const deleteTableData = (req, res, db) => { const { cust_id } = req.body; db.collection("table") .deleteOne({ _id: ObjectId(cust_id) }) .then((data) => { console.log(data); res.status(200).json({ delete: "true" }); }) .catch((err) => { logger.log({ level: "error", message: err, }); res.status(400).json({ dbError: "db error" }); }); }; // Send mail const mailer = (req, res, db) => { const { cust_email, subject, body } = req.body; sendMail( { email: cust_email, subject, body, }, res ); }; // Schedule Mail to be send at a delayed time const scheduleMail = (req, res, db) => { const { cust_email, subject, body, delay } = req.body; scheduleJob({ email: cust_email, subject, body }, delay, res); }; module.exports = { getTableData, postTableData, putTableData, deleteTableData, getData, addComm, mailer, scheduleMail, };
var count = 0, result = 0; function init() { setInterval(function() { result = count; count = 0; }, 1000); } function request() { count++; } function get() { return result; } exports.init = init; exports.request = request; exports.get = get;
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/flairevents', {useNewUrlParser: true}); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function(){ console.log('Connected to databse succesfully'); }); var connectionSchema = new mongoose.Schema({ connectionId:String, cname:String, ctopic:String, cdetail:String, ctime:String, chost: String, clocation: String, cimg:String, userId: String}); var connectionModel = mongoose.model('connectionModel', connectionSchema, "connections"); module.exports.connectionModel = connectionModel;
((win, doc) => { const tableAluno = doc.querySelector('#alu'); const tableCola = doc.querySelector('#cola'); const idAluno = doc.querySelector('#idAluno'); const idColaborador = doc.querySelector('#idColaborador'); tableAluno.addEventListener('click', (e) => { let clickAluno = e.target.classList.contains('aluno'); if (clickAluno) { idAluno.value = e.target.firstElementChild.value; } }); tableCola.addEventListener('click', (e) => { let clickAluno = e.target.classList.contains('cola'); if (clickAluno) { idColaborador.value = e.target.firstElementChild.value; } }); })(window, document);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _from = require('babel-runtime/core-js/array/from'); var _from2 = _interopRequireDefault(_from); exports.default = handleEditorPaste; var _prosemirrorView = require('prosemirror-view'); var _ImageUploadPlaceholderPlugin = require('../ImageUploadPlaceholderPlugin'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // workaround to support ClipboardEvent as a valid type. // https://github.com/facebook/flow/issues/1856 function handleEditorPaste(view, event) { var clipboardData = event.clipboardData; if (!clipboardData) { return false; } var files = clipboardData.files; if (!files || !files.length) { return false; } var filesList = (0, _from2.default)(files); if ((0, _ImageUploadPlaceholderPlugin.uploadImageFiles)(view, filesList)) { event.preventDefault(); return true; } return false; }
define('xstyle/core/Proxy', ['xstyle/core/utils'], function(utils){ var when = utils.when; function Proxy(value){ // just assume everything will be observed, we could change the optimizations later if(value){ this.setSource(value); } } Proxy.prototype = { property: function(key){ var properties = this.hasOwnProperty('_properties') ? this._properties : (this._properties = {}); var proxy = properties[key]; if(proxy){ return proxy; } proxy = properties[key] = new Proxy(this.get(key)); proxy.parent = this; proxy.name = key; return proxy; }, observe: function(listener){ (this._listeners || (this._listeners = [])).push(listener); if(this.source){ listener(this.valueOf()); } // TODO: return handle with remove method }, setSource: function(source){ var proxy = this; if(this.handle && this.handle.remove){ this.handle.remove(); } when(source, function(source){ proxy.source = source; var listeners = proxy._listeners || 0; var value = proxy.valueOf(); for(var i = 0; i < listeners.length; i++){ listeners[i](value); } if(source && source.observe){ proxy.handle = source.observe(function(value){ var listeners = proxy._listeners || 0; for(var i = 0; i < listeners.length; i++){ listeners[i](value); } }); } var properties = proxy._properties; for(i in properties){ proxy.property(i).setSource(source && source.property && source.property(i)); } }); }, valueOf: function(){ var source = this.source; return source && source.observe ? source.valueOf() : source; }, get: function(key){ var source = this.source; return source ? source.get ? source.get(key) : source[key] : this['value-' + key]; }, set: function(key, value){ var source = this.source; if(source){ source[key] = value; }else{ this['value-' + key] = value; } var property = this._properties && this._properties[key]; if(property){ property.put(value); } }, put: function(value){ var source = this.source; if(source && source.put){ return source.put(value); }else if(this.parent){ this.parent[this.name] = value; } return this.setSource(value); } }; return Proxy; });
import express from 'express'; import { fetchJsonByNode, postOption } from '../../../common/common'; import { host } from '../../globalConfig'; const service = 'integration_service'; const URL_LIST = `${host}/${service}/excelModelConfig/listExcelModelByTenantIdModelTypeCode`; const URL_UP = `${host}/${service}/excelModel/importExcelContent`; const URL_DOWN = `${host}/${service}/excelModelConfig/getUrl`; let api = express.Router(); // 根据模板代码返回报表列表 api.get('/list', async (req, res) => { const data = await fetchJsonByNode(req, `${URL_LIST}?modelTypeCode=${req.query.modelTypeCode}`); res.send(data); }); // 上传 api.post('/up', async (req, res) => { res.send(await fetchJsonByNode(req, `${URL_UP}?id=${req.body.id}`, postOption(req.body))); }); // 下载 api.get('/down', async (req, res) => { const data = await fetchJsonByNode(req, `${URL_DOWN}?id=${req.query.id}`); res.send(data); }); export default api;
import {Api} from './api.js'; export {FavoriteApi}; class FavoriteApi { static get url() { return `${Api.baseUrl}/favourites`; } static async add(routineId, controller) { return await Api.post(`${FavoriteApi.url}/${routineId}/`, true, {}, controller); } static async get(data, controller) { return await Api.get(`${FavoriteApi.url}?` + new URLSearchParams({...data}), true, controller); } static async remove(routineId, controller) { return await Api.delete(`${FavoriteApi.url}/${routineId}/`, true, controller); } }
import { AppRegistry, Dimensions } from 'react-native'; import App from './App'; XMLHttpRequest = GLOBAL.originalXMLHttpRequest ? GLOBAL.originalXMLHttpRequest : GLOBAL.XMLHttpRequest; AppRegistry.registerComponent('MobioTV', () => App);
import React from "react"; import styles from "./Header.module.css"; import Button from "../Button/Button"; import RedesSocais from "../Helper/RedesSociais"; import { ReactComponent as TesteWeb } from "../../Assets/Teste web.svg"; const Header = () => { return ( <div className="bgWhite"> <header className={`${styles.header} container`}> <div className={styles.leftContent}> <div className={styles.menuMobile}></div> <TesteWeb /> </div> <nav className={styles.nav}> <Button /> <RedesSocais /> </nav> </header> </div> ); }; export default Header;
const express = require("express"); const morgan = require("morgan"); const Podlet = require("@podium/podlet"); /** * definizione del manifest */ const podlet = new Podlet({ name: "recos", version: "1.0.2", pathname: "/recos", fallback: "/fallback", development: true, }); /** * definizione del css */ podlet.css({ value: "http://localhost:3002/static/fragment.css", }); /** * Init express */ const app = express(); app.use(morgan("dev")); app.use("/recos", podlet.middleware()); app.use("/static", express.static("./static")); /** * Esposizione del manifest json */ app.get("/recos/manifest.json", (req, res) => { res.status(200).json(podlet); }); /** * Film array */ const films = { ace: [{title: "The Adventures of Greyfriars Bobby", cover: "https://m.media-amazon.com/images/M/MV5BNTU0ZmY0YTctNDJjNS00ZjYyLTg2NTUtNzA3Y2Y1M2RmZjgyXkEyXkFqcGdeQXVyMTQ3Njg3MQ@@._V1_SX300.jpg"},{title: "10000 BC", cover: "https://m.media-amazon.com/images/M/MV5BMzc2NDMzNDY4Ml5BMl5BanBnXkFtZTYwNzM2Njk3._V1_SX300.jpg"}], greyfriars: [{title: "10000 BC", cover: "https://m.media-amazon.com/images/M/MV5BMzc2NDMzNDY4Ml5BMl5BanBnXkFtZTYwNzM2Njk3._V1_SX300.jpg"},{title: "Ace Ventura: Pet Detective", cover: "https://m.media-amazon.com/images/M/MV5BYmVhNmFmOGYtZjgwNi00ZGQ0LThiMmQtOGZjMDUzNzJhMGIzXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg"}], bc10000: [{title: "The Adventures of Greyfriars Bobby", cover: "https://m.media-amazon.com/images/M/MV5BNTU0ZmY0YTctNDJjNS00ZjYyLTg2NTUtNzA3Y2Y1M2RmZjgyXkEyXkFqcGdeQXVyMTQ3Njg3MQ@@._V1_SX300.jpg"},{title: "Ace Ventura: Pet Detective", cover: "https://m.media-amazon.com/images/M/MV5BYmVhNmFmOGYtZjgwNi00ZGQ0LThiMmQtOGZjMDUzNzJhMGIzXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg"}] }; app.get("/recos", (req, res) => { const { sku } = req.query; console.log(req.query) res.status(200).podiumSend(` <div class="inspire_fragment"> <h2 class="inspire_headline">Recommendations</h2> <div class="inspire_recommendations"> ${films[sku] .map( reco => ` <a href="http://localhost:3001/product/${reco.title}"> <img src="${reco.cover}" /> </a>` ) .join("\n")} </div> </div> `); }); app.get("/recos/fallback", (req, res) => { res.status(200).podiumSend(` <a href="http://localhost:3002/recos"> Show Recommendations </a> `); }); app.listen(3002);
import Comment from '../models/Comment.js'; export default { async index(req, res) { const { id } = req.params; const comments = await Comment.findAll({ attributes: ['id', 'text', 'updated_at'], where: { idea_id: id, }, include: { association: 'user', attributes: ['id', 'name'] }, }); return res.json(comments); }, async add(req, res) { const { id } = req.params; const { text } = req.body; const { user_id } = req; const comment = await Comment.create({ text, user_id, idea_id: id }); comment.idea_id = parseInt(comment.idea_id); return res.json(comment); }, };
var main = require('./handlers/main'); var newsletter = require('./handlers/newsletter'); var test = require('./handlers/test'); var email = require('./handlers/email'); var cart = require('./handlers/cart'); var vacation = require('./handlers/vacation'); var api = require('./handlers/api'); var extensions = require('./handlers/extensions'); var error = require('./handlers/error'); module.exports = function (app) { /*====================================================================================================*/ /** * main */ /*====================================================================================================*/ app.get('/', main.Home); app.get('/headers', main.Headers); app.get('/about', main.About); app.get('/thank-you', main.ThankYou); /*====================================================================================================*/ /** * newsletter */ /*====================================================================================================*/ app.get('/newsletter', newsletter.GetNewsLetter); app.post('/newsletter', newsletter.PostNewsLetter); app.get('/newsletter/archive', newsletter.Archive); /*====================================================================================================*/ /** * test */ /*====================================================================================================*/ app.get('/jquerytest', test.JqueryTest); /*====================================================================================================*/ /** * email */ /*====================================================================================================*/ app.get('/email', email.GetEmail); app.post('/send-email', email.SendEmail); /*====================================================================================================*/ /** * cart */ /*====================================================================================================*/ app.get('/cart', cart.GetCart); app.get('/cart/add', cart.GetAddCart); app.post('/cart/add', cart.PostAddCart); /*====================================================================================================*/ /** * vacation */ /*====================================================================================================*/ app.get('/vacations', vacation.GetVacations); app.post('/vacations', vacation.PostVacations); app.get('/notify-me-when-in-season', vacation.GetNotifyMeInSeason); app.post('/notify-me-when-in-season', vacation.PostNotifyMeInSeason); app.get('/nursery-rhyme', vacation.GetNurseryRhyme); /*====================================================================================================*/ /** * api */ /*====================================================================================================*/ app.get('/api/tours', api.GetTours); app.put('/api/tour/:id', api.UpdateTourById); app.delete('/api/tour/:id', api.DeleteTourById); /*====================================================================================================*/ /** * extensions */ /*====================================================================================================*/ app.get('/contest/vacation-photo', extensions.GetUploadPhoto); app.post('/contest/vacation-photo/:year/:month', extensions.PostUploadPhoto); app.post('/process', extensions.PostProcess); ; /*====================================================================================================*/ /** * 错误处理,理应放在最后 */ /*====================================================================================================*/ app.use(error.Error_404); app.use(error.Error_500); };
// Dependencies import React from 'react'; import { Redirect } from 'react-router-dom'; // UserSignOut export default (props) => { // context const { context } = props; // signout context.actions.signOut(); // redirect return ( <Redirect to='/' /> ); };
/** * Created by mimi on 7/5/17. */ var gulp = require('gulp'); var nodemon = require('gulp-nodemon'); gulp.task('default',function () { nodemon({ script: 'reportServer.js', ext:'js', env:{ PORT:5000 }, ignore:['./node_modules/**'] }) .on('restart', function(){ console.log('Report Server Has Restarted: Port 5000 ') }); });
$(function () { $(".btn_reload").click(function () { var url = $(".btn_reload").data("url"); console.log(url); $.dialog({ title: "温馨提示", content: "亲,重新加载权限可能需要耗费很长的时间,你确定加载吗?", ok: function () { $.post(url, function (data) { $.dialog({ title: "温馨提示", content: data, ok: function () { window.location.reload(); } }) }) }, cancel: true }); }); });
const http = require('http'); const proveRoutes = require('./routes/prove01-routes'); const server = http.createServer(proveRoutes.hander); server.listen(3000);
/** * Created by cl-macmini-63 on 1/18/17. */ 'use strict'; //create logger var log = require('../../Utils/logger.js'); var logger = log.getLogger(); var mongoose = require('mongoose'); var joi = require('joi'); //mongoose schema var phoneotpSchema = mongoose.Schema({ phone : String, countryCode : String, email : String, otp : String, is_verified : {type : Boolean , default :false} }, { collection : 'phoneotp' } ); module.exports.PhoneOtp = mongoose.model('PhoneOtp', phoneotpSchema,'phoneotp');
'use strict'; /*jshint esnext: true */ // this variable is defined in the global scope, // but it will be wrapped in an AMD requirejs define statement // creating a file local scope, making 'self' global only in this file. let self; let authenticationInterceptor = class AuthenticationInterceptor { /*@ngInject*/ constructor($q, $window, $location, EXTERNAL_SERVICES) { self = this; self.$q = $q; self.$window = $window; self.$location = $location; self.EXTERNAL_SERVICES = EXTERNAL_SERVICES; } login(rejection) { let redirect_uri_template; for(let i=0,len = rejection.data.errors.length; i < len && !redirect_uri_template; i++) { let error = rejection.data.errors[i]; if (error.data && error.data.authenticationUrl) { redirect_uri_template = error.data.authenticationUrl; } } let [baseUrl, view] = self.$location.absUrl().split('#'); // now inject the {{redir}}_path back to us and the current state into the template let redirect_uri = self.EXTERNAL_SERVICES.resources.admin.authentication_params .replace('{client-host}',baseUrl) .replace('{view}', view); let authentication_url = redirect_uri_template.replace('{{redir}}', encodeURIComponent(redirect_uri)); // TODO: When I am mocking, how do I not redirect console.out("--> redirect to: ", authentication_url); self.$window.location.replace(authentication_url); return self.$q.defer(rejection); } request(config) { if (config.url.indexOf('.tpl') < 0 ) { console.out( `request sent: [METHOD:"${config.method}", url:"${config.url}", headers:"${JSON.stringify(config.headers)}"]` ); } return config; } responseError(rejection) { console.out(`request denied: [ status:${rejection.status}, errors:${JSON.stringify(rejection.data.errors)}]` ); switch(rejection.status) { case 401: if (!rejection.headers.Authentication && rejection.data.errors && rejection.data.errors.length > 0) { return self.login(rejection); } break; case 503: console.out(JSON.stringify(rejection)); break; default: return self.$q.reject(rejection); break; } return self.$q.reject(rejection); } }; authenticationInterceptor.$inject = ['$q', '$window', '$location', 'EXTERNAL_SERVICES']; export default authenticationInterceptor;
import {FaReact, FaNodeJs, FaHtml5, FaCss3Alt, FaSass, FaBootstrap, FaAws} from 'react-icons/fa'; import {DiMysql, DiMongodb, DiJavascript1} from 'react-icons/di'; import {GrHeroku} from 'react-icons/gr'; import {SiAdobephotoshop, SiAdobepremiere} from 'react-icons/si'; const skill_items = [ { name: 'REACT', icon: FaReact }, { name: 'SQL', icon: DiMysql }, { name: 'MONGODB', icon: DiMongodb }, { name: 'JS ES6', icon: DiJavascript1 }, { name: 'NODE.JS', icon: FaNodeJs }, { name: 'HTML 5', icon: FaHtml5 }, { name: 'CSS 3', icon: FaCss3Alt }, { name: 'SASS', icon: FaSass }, { name: 'BOOTSTRAP', icon: FaBootstrap }, { name: 'AWS', icon: FaAws }, { name: 'HEROKU', icon: GrHeroku }, { name: 'PHOTOSHOP', icon: SiAdobephotoshop }, { name: 'PREMIERE', icon: SiAdobepremiere } ]; export default skill_items;
// Filename: snips/binders.js // This is the place for rivets binders
import React from 'react'; import Dashboard from './Dashboard'; import cossDashboardData from './cossDashboardData.json'; import Spacer from './Spacer'; export default class Coss extends React.Component { constructor(props) { super(props); this.state = ""; } render() { return ( <div> <h1>Clinical Operations Services & eSystems (COSS) Homepage</h1> <Spacer /> <Dashboard data={cossDashboardData} /> </div> ); } }
const Register = require('./../lib/register'); const requestIdPool = new Register(); function getId(compassname) { let id = requestIdPool.get(compassname); if( typeof id === 'undefined'){ id = 0; } id++; if (id > 0xFFFFFF) { id = 1; } requestIdPool.set(compassname, id); return id; } let Request = function Request(compassname, handler, message) { let _id = getId(compassname); let _handler = handler; let _message = new Buffer(0); if (message && message.length > 0) { _message = new Buffer.from(message); } this.getId = function () { return _id; }; this.getHandler = function () { return _handler; }; this.getMessage = function () { return _message; }; }; let Response = function Request(id, handler, message) { let _id = id; let _handler = handler; let _message = new Buffer(0); if (message && message.length > 0) { _message = new Buffer.from(message); } this.getId = function () { return _id; }; this.getHandler = function () { return _handler; }; this.getMessage = function () { return _message; }; }; exports.request = function (compassname, handler, message) { return new Request(compassname, handler, message); }; exports.response = function (id, handler, message) { return new Response(id, handler, message); };
#!/usr/bin/env node /** * Module dependencies. */ var app = require("../app"); var debug = require("debug")("mailprobe:server"); var http = require("http"); var db = require("../db/authdb"); var crypto = require("crypto"); const readline = require("readline"); /** Check if there is a command to create user */ var args = process.argv.slice(2); if (args.length > 0 && args[0] === "createuser") { var salt = crypto.randomBytes(16); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // Read Username and password from console rl.question(`Enter the user name: `, function(name) { rl.question(`Enter the password: `, function(password) { crypto.pbkdf2(password, salt, 310000, 32, 'sha256', function(err, hashedPassword) { if (err) { console.log(err) }; db.run('INSERT INTO users (username, hashed_password, salt, name) VALUES (?, ?, ?, ?)', [ name, hashedPassword, salt, "webuser" ], function(err) { if (err) { console.log(err); } else { console.log("User is created"); } process.exit(); }); }); }); }); } else { /* Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || "3000"); app.set("port", port); /** * Create HTTP server. */ var server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on("error", onError); server.on("listening", onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== "listen") { throw error; } var bind = typeof port === "string" ? "Pipe " + port : "Port " + port; // handle specific listen errors with friendly messages switch (error.code) { case "EACCES": console.error(bind + " requires elevated privileges"); process.exit(1); break; case "EADDRINUSE": console.error(bind + " is already in use"); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port; debug("Listening on " + bind); } }
const rpn = require('request-promise-native') const host = 'ecki.ceair.com' const origin = `http://${host}` const m = [/^\d{15}(\d{2}[\dXx])?$/, /^\w{3,12}$/, /^\d{3}-?\d{10}$/, /^[a-zA-Z]{3}\d{12}$/] const p = ['NI', 'PP', 'TN', 'NI'] let options = { uri: `${origin}/WebCheckin/uniEnter/query.shtml`, method: 'POST', headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': host, 'Origin': origin, 'Referer': `${origin}/server/cuss.html`, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36' } } // http://www.ceair.com/resource/js/cuss/index.js const checkIdCard = idCard => { let a = '' for (let e = 0; e < m.length; e++) { if (m[e].test(idCard)) { a = p[e] break } } return a || !1 } module.exports = async user => { try { let certType = checkIdCard(user.card) options.form = { 'certNo': user.card, 'certType': certType, 'certName': user.name } const res = await rpn(options) const arr = res.split('var segList = eval(\'') if (arr.length === 1) { user.status = { message: '未提取到您2天内订妥座位的东航行程' } } else { const flights = JSON.parse(arr[1].split('\');')[0]) let flightArr = [] for (let i = 0, len = flights.length; i < len; i++) { let flight = flights[i] let flightDate = flight.depDateTime.substr(0, 10) // let flightStatus = getFlightStatus(flight.type || 0) // statusArr.push(`${flightDate}: ${flightStatus}(票号: ${flight.tktNo})`) flightNo // statusArr.push(`${flightDate} 票号: ${flight.tktNo}`) flightArr.push({ date: flightDate, flightNum: flight.flightNo, ticket: flight.tktNo }) } user.status = { flights: flightArr } } return user } catch (error) { console.log('------- error:') console.log(error) user.status = { message: error.message || '未知1' } return user } } // http://ecki.ceair.com/WebCheckin/uniEnter/query.shtml // function getFlightStatus (type) { // switch (type) { // case 1: // case 4: // case 5: // return '未办理' // case 2: // return '已办理' // case 3: // return '不能办理' // } // return '待定' // } // module.exports = datas => { // return new Promise(resolve => { // let count = 0 // const len = datas.length // for (let i = 0; i < len; i++) { // (function (i) { // let data = datas[i] // let certType = checkIdCard(data.card) // options.form = { // 'certNo': data.card, // 'certType': certType, // 'certName': data.name // } // rpn(options).then(res => { // // const $scripts = $('head').find('script') // // const $flightList = $('.flight_list').find('table') // // if ($flightList.length === 0) { // // datas[i].status = '未提取到您2天内订妥座位的东航行程' // // } else { // // let statusArr = [] // // for (let i = 0, len = $flightList.length; i < len; i++) { // // let $flight = $flightList.eq(i) // // // console.log($flight.text()) // // let flightDate = $flight.find('tbody td').eq(0).text().replace('航班日期:', '') // // let $theadtds = $flight.find('thead td') // // let flightStatus = $theadtds.eq(2) // // let flightTktNum = $theadtds.eq(1).text() // // statusArr.push(`${flightDate}: ${flightStatus}(票号: ${flightTktNum})`) // // } // // datas[i].status = statusArr.join(', ') // // } // const arr = res.split('var segList = eval(\'') // if (arr.length === 1) { // datas[i].status = '未提取到您2天内订妥座位的东航行程' // } else { // const flights = JSON.parse(arr[1].split('\');')[0]) // let statusArr = [] // for (let i = 0, len = flights.length; i < len; i++) { // let flight = flights[i] // let flightDate = flight.depDateTime.substr(0, 10) // // let flightStatus = getFlightStatus(flight.type || 0) // // statusArr.push(`${flightDate}: ${flightStatus}(票号: ${flight.tktNo})`) // statusArr.push(`${flightDate} 票号: ${flight.tktNo}`) // } // datas[i].status = statusArr.join(', ') // } // count++ // if (count === len) { // resolve(datas) // } // }).catch(error => { // console.log('-------- ' + i) // console.log(error) // datas[i].status = 'system error' // count++ // if (count === len) { // resolve(datas) // } // }) // })(i) // } // }) // } // [ { status: '客票已使用,请联系售票点或使用其他客票。(P103_5)', // departure: 'SZX', // arrival: 'KMG', // depEn: 'SHENZHEN', // arrEn: 'KUNMING', // depCityName: '深圳', // arrCityName: '昆明', // tktNo: '7812431890358', // flightNo: 'MU5758', // cabin: 'V', // depDateTime: '2018-02-22 16:50', // type: 2, // cancelAction: 0, // printAction: 1, // checkinAction: 0, // seatAction: 0, // canAsr: 0, // depDate: '2018-02-22', // depTime: '16:50', // isStop: 0, // isToAF: 0, // isToDL: 0, // mkt: 'CN', // carrAirlineCode: '', // carrFlightNumber: 'MU5758' } ] // let certNo = 'H60286267' // let certType = checkIdCard(certNo) // options.form = { // 'certNo': certNo, // 'certType': certType, // 'certName': '徐瑞敏' // } // rpn(options).then(res => { // console.log(res) // }).catch(error => { // console.log('------ error') // console.log(error) // })
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $(function () { $("#savePerBtn").click(function() { var server = $("#savePerMailForm select[name=sid]").val(); if(server==0||server ==="") { alert("请选择服务器"); return false; } // 表情包ID /* var faceid = $("#faceid").val(); $("#savePerMailForm select[name=faceid]").val(faceid); // 装备 var equipid = $("#equipid").val(); $("#savePerMailForm select[name=equipid]").val(equipid); // 套装 suitId var suitId = $("#suitId").val(); $("#savePerMailForm select[name=suitId]").val(suitId); // 道具ID1 var propid1 = $("#propid1").val(); $("#savePerMailForm select[name=propid1]").val(propid1); // 道具ID2 var propid2 = $("#propid2").val(); $("#savePerMailForm select[name=propid2]").val(propid2); // 道具ID3 var propid3 = $("#propid3").val(); $("#savePerMailForm select[name=propid3]").val(propid3); // 道具ID4 var propid4 = $("#propid4").val(); $("#savePerMailForm select[name=propid4]").val(propid4);*/ var form = $("#savePerMailForm").serializeArray(); $.ajax({ type: 'POST', url: "/cdk/Add_Gift", data: form, dataType: 'json', success: function(result) { if (result.errcode == 0) { alert('礼包添加成功!'); window.location.href = '/cdk/giftlist?giftid='+result.msg; }else{ alert(result.msg); } } }); }); //显示模态框 $("#addName").click(function(){ $("#state").val(''); $("#hidput").attr("value",1); //初始化 $('#listsheet').html(""); $("#addFileModalLabel").text("选择文件"); $("#selector").css("visibility","visible"); $("#addFiletestBtn").remove(); $("#addFileModal").modal({backdrop:"static"}).modal('show'); }); $("#cancelBtn").click(function(){ history.go(0); }); // 创建一个上传参数(提交至本控制层的函数addExecl进行处理上传其次判断是否成功,成功返回) var uploadOption = { // 提交目标 action: "uploadfile", // 服务端接收的名称 name: "myfile", // 自动提交 autoSubmit: false, // 选择文件之后… onChange: function (file, ext) { // if (!(ext && /^(xml|XML|txt)$/.test(ext))) { if (!(ext && /^(xls)$/.test(ext))) { alert("您上传的文档格式不对,不是正确的xls文件,请重新选择!"); return false; } $("#state").val( file); }, // 开始上传文件 onSubmit: function (file, extension) { //$("#state").val("正在上传" + file + ".."); $("#addFileModalLabel").text("正在上传" + file + ".."); }, // 上传完成之后 onComplete: function (file, response) { //$("#state").val("上传完成"); $("#addFileModalLabel").text("上传完成"); $("#addFileModalLabel").text("请完成附加文件选项,开始进行添加"); $("#selector").css("visibility","hidden"); //$("#addFileBtn").css("visibility","hidden"); $("#addFileBtn").detach(); var data = JSON.parse(response); /** * 这个地方判断的是在控制器里面的$this->outputJson目录在(\framework\system\libraries\controller.lib) * 找到这个函数里面的设置所引用的参数进行判断 **/ if(data.errcode == 0 ) { //处理接收到的数据 GetPage(data.msg); $("#addFiletestBtn").click(function () { $("#formm").submit(); }); }else{ /** * 其实在$this->outputJson 本身的echo json_encode($rs); * 是不会提示的调用js进行把在控制器里面传入的第一个变量值所做的引用如果是非0就会进行提示相关错误的信息 * */ alert(data.msg); } } }; //添加数据 $("#confirmBtn").click(function() { var param = $("#forbidAccountForm").serialize(); $.ajax({ type: 'POST', url: 'add', data: param, dataType: 'json', success: function(result) { alert(result.msg); if (result.errcode == 0) { history.go(0); //window.location.href = window.location.href; } } }); }); // /*** * (点击确定按钮执行-》执行控制层函数-》addExecl()进行处理上传文件其次进行读取相关数据进行解析然后在进行返回结果集) * */ var oAjaxUpload = new AjaxUpload('#selector', uploadOption); // 给上传按钮增加上传动作 $("#addFileBtn").click(function () { oAjaxUpload.submit(); }); //接收数据 function GetPage(data) { $('#listsheet').html(""); $("#summodel").prepend("<button type='submit' class='btn btn-success' id='addFiletestBtn' name='addFiletestBtn'>开始</button> "); var pagehtml = '表:<pre class="prettyprint linenums" style="pading:1px"><form id="formm" name="formm" action="loadfile" method="post">' pagehtml +='<input type="hidden" name="filepath" value='+data[0].filepath+'><table border =0>'; for(var i = 0; i< data.length;++i) { //data[i].id pagehtml += '<tr><td><input style="margin:0px" type="checkbox" value = "'+data[i].id+'" name="checkboxid"/></td><td>'+data[i].name+'</td></tr>'; } pagehtml += "<tr><td>栏位行:</td><td><input type='text' value='2' style='width:30px;height:10px;margin:0px' name='row'/></<td></tr>" + "<tr><td>数据行 :</td><td><input type='text' value='1' style='width:30px;height:10px;margin:0px' name='clos'/></<td></tr></table>"; pagehtml +='</form></pre>'; $('#listsheet').html(pagehtml); } // 选中数据是否录入(预览数据层) $("#checkAll").click(function(){ if(this.checked){ $("#list :checkbox").attr("checked", true); }else{ $("#list :checkbox").attr("checked", false); } }); // $(selector).submit() $("#packageBtn").click(function(){ $("#package").submit(); }); /** * 修改数据 * **/ $("#tableExcel tr").each(function() { var _this = $(this); var text =null; _this.find(".editMenu").click(function() { var form = $("#editMenuForm").serializeArray(); var trs = null; for(var i=0;i<form.length;i++){ var name = form[i].name; var value = _this.find("."+name).text(); if(name=='ItemList') { var jsonData = _this.find("."+name).text(); var resultobj = $.parseJSON(jsonData); $.each(resultobj, function(n, value) { if(trs==null){ trs = value.ItemId + "," + value.ItemNumber; }else{ trs += "&" + value.ItemId + "," + value.ItemNumber; } }); $("#editMenuForm [name="+name+"]").val(trs); } else { $("#editMenuForm [name="+name+"]").val(value); } //value = value.replace(/(^\s*)|(\s*$)/g, ""); } //$("#editMenuModal input[name=id]").val(_this.attr("id")); $("#editMenuModal").modal({backdrop:"static"}).modal('show'); }); }); // AND EIDT $("#editMenuBtn").click(function(){ //alert('da'); var param = $("#editMenuForm").serialize(); $.ajax({ type: 'POST', url: 'gifedit', data: param, dataType: 'json', success: function(result) { alert(result.msg); if (result.errcode == 0) { history.go(0); //window.location.href = window.location.href; } } }); }); // AND EIDT 录入码 $("#AddCDKBtn").click(function(){ var param = $("#setcdkForm").serialize(); $.ajax({ type: 'POST', url: 'setcode', data: param, dataType: 'json', success: function(result) { if (result.errcode == 0) { alert(result.msg); history.go(0); //window.location.href = window.location.href; }else{ alert(result.msg); $("#AddCDKBtn").removeAttr("disabled"); $("#AddCDKBtn").removeAttr("data-loading"); //location.reload( true ); return false; } } }); }); // 删除 $(".delUser").each(function() { var _this = $(this); _this.click(function() { var id = $(this).attr('data-value'); if (confirm("确定删除礼包Id"+id+"么?")) { if (id == '' || id == 'undefined') { alert("礼包id不能为空!"); return false; } $.ajax({ type: 'POST', url: 'gifdel', data: 'id='+id, dataType: 'json', success: function(result) { alert(result.msg); if (result.errcode == 0) { window.location.reload(); } } }); } }); }); $("#platformid").click(function() { var cdkServerRuleType = $("#setcdkForm select[name=rule]").val(); if(cdkServerRuleType!="" && cdkServerRuleType == 2) { setCdkRuleVerify(); } }); }); function CdkAccountVerify() { $('#cdknumber').removeAttr("readonly"); //("#setcdkForm input[name=number]").val(""); var type = $("#setcdkForm select[name=type]").val(); if(type==1) { $("#setcdkForm input[name=number]").val(1); $('#cdknumber').attr("readonly",true); } else { $('#cdknumber').removeAttr("readonly"); $("#setcdkForm input[name=number]").val(''); } } function setCdkRuleVerify() { $("#ServerId").empty(); $('#ServerInfo').css('display','none'); //$("#serverIdms2side__sx").empty(); //$("select[name='serverIdms2side__dx[]']").empty(); // 根据平台遍历出子类区服信息 var platid = $("#setcdkForm select[name=platformid]").val(); var cdkServerRuleType = $("#setcdkForm select[name=rule]").val(); if(!platid ||platid<0 || platid=="") { alert('指定区服规则,请确认平台类型!'); } if(cdkServerRuleType==2 && platid>0) { var param ='platid='+platid; $.ajax({ type:'POST', url:"/System/plat_server", data:param, dataType:'json', success: function(result) { if (result.errcode != 0) { alert('-1'+result.msg); location.reload( true ); return false; } sidSelectList(cdkServerRuleType,result.serverlist); }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(errorThrown); alert(textStatus); // paser error; } }); } else{ $("#ServerId").empty(); $('#ServerInfo').css('display','none'); //$("#ServerInfo").empty(); //$("select[name='serverIdms2side__dx[]']").empty(); return false; } } /*function platformReset() { var cdkServerRuleType = $("#setcdkForm select[name=rule]").val(); if(cdkServerRuleType!="" && cdkServerRuleType == 2) { alert(12321); setCdkRuleVerify(); } }*/ function sidSelectList(type,serverlist){ // //var serverlist = null; // 平台区服信息 var serverlistHtml= "";//平台区服html //alert(typeof(serverlist)); if(type==2) { // 已经选的 + 初始默认区更改状态的 $.each(serverlist, function(index, value) { serverlistHtml +="<option value="+value+">"+value+"区</option>"; //serverlistHtml+="<option value="+value+">"+value+"区</option>"; }); $('#ServerInfo').css('display','block'); // 【默认展示列表信息主控制】 根据平台 不存在的进行赋值如果已经存在的进行设置 selected='selected' $("#ServerId").append(serverlistHtml); //$("#liOption").append(serverlistHtml); //$("select[name='ServerId']").append(serverlistHtml); // 【待选区设置还没有选择的区配置】 //$("#serverIdms2side__sx").append(wait_SelectList); // 【已选区控制】已经选区设置 根据平台设置已经存在的进行打印赋值 //$("select[name='serverIdms2side__dx[]']").append(been_SelectedList); }else{ $('#ServerInfo').css('display','none'); $("#ServerId").empty(); //$("#serverIdms2side__sx").empty(); //$("select[name='serverIdms2side__dx[]']").empty(); } } function cdkVerify(obj) { var giftid = $(obj).find('select[name=giftid]').val(); giftid = parseInt(giftid); if(giftid == 0 || giftid === null) { alert("礼包Id不能为空!"); location.reload( true ); return false; } }
"use strict"; angular.module("mushroom").factory("factory",function($q,$http){ let getShrooms = ()=>{ return $q((resolve,reject)=>{ $http .get("https://mushroom-mania-67f25.firebaseio.com/mushrooms.json") .then((mushrooms)=>{ resolve(mushrooms); console.log("fb data",mushrooms) }) .catch((err)=>{ reject(err); }); }); }; return { getShrooms }; });
/* Copyright 2016-2018 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import fs from 'fs'; import path from 'path'; export const memoryStoreInfo = JSON.parse( fs.readFileSync(path.join(__dirname, 'memoryStoreInfo.json')) ); export const segment1 = JSON.parse( fs.readFileSync(path.join(__dirname, 'segment1.json')) ); export const segment2 = JSON.parse( fs.readFileSync(path.join(__dirname, 'segment2.json')) ); export const segment3 = JSON.parse( fs.readFileSync(path.join(__dirname, 'segment3.json')) );
#target Illustrator #targetengine main if ( app.documents.length > 0 ) { var curDoc = app.activeDocument; }else{ Window.alert("You must open at least one document."); } #include "color-conversion-algorithms.jsx" #include "hueMe.jsx" increment = -0.025; var sel = curDoc.selection; // get selection for (var i = 0; i < sel.length; i++) { recurseHelper(sel[i]); }
/** * Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license * * CKFinder 2.x - sample "dummy" plugin. * * To enable it, add the following line to config.js: * config.extraPlugins = 'dummy'; */ /** * See http://docs.cksource.com/ckfinder_2.x_api/symbols/CKFinder.html#.addPlugin */ CKFinder.addPlugin( 'hidehelp', { appReady : function( api ) { api.removeTool(12); } });
import axios from "axios" import env from "react-dotenv" const TimKiemLichTrinh = (param)=>{ console.log(param) return axios.post(env.API_ADMIN_LOCAL + "lichtrinh/date", param) } const GetDanhSachNhaGa = ()=>{ return axios.get(env.API_ADMIN_LOCAL + "nhaGa") } const GetNhaGa = (id)=>{ return axios.get(env.API_ADMIN_LOCAL + "nhaGa/id=" + id) } const DangKyKhachHang = (param)=>{ return axios.post(env.API_ADMIN_LOCAL + "signupKH", param) } const DangNhapKhachHang=(SoDienThoai, MatKhau)=>{ let param={ SoDienThoai: SoDienThoai, MatKhau: MatKhau } return axios.post(env.API_ADMIN_LOCAL +"loginKH", param) } const GetDanhSachTau_FollowLichTrinh = (param) => { return axios.post(env.API_ADMIN_LOCAL + "tau/lichtrinh", param) } const GetDSGheDaDat = (param) => { return axios.post(env.API_ADMIN_LOCAL + "tau/gheDaDat", param) } const GetDSToa_Of_Tau = (MaTau) => { return axios.post(env.API_ADMIN_LOCAL + "tau/dsToa", {MaTau:MaTau}) } const GetChiTietToa_Of_Tau = (MaTau) => { return axios.post(env.API_ADMIN_LOCAL + "tau/chitiettoa", {MaTau:MaTau}) } const GetDSGhe_Of_ToaTau = (MaToaTau) => { return axios.get(env.API_ADMIN_LOCAL + "Ghe/MaToa=" + MaToaTau) } //Dat Ve const DatVe = (param, token) => { return axios.post(env.API_ADMIN_LOCAL + "datve", param, { headers: {Authorization: "Bearer " + token} }) } const CapNhatThongTin= (param)=>{ return axios.post(env.API_ADMIN_LOCAL + "CapNhatKH", param) } const GetDSVeDaMua = (token)=>{ return axios.post(env.API_ADMIN_LOCAL + "dsVeDaMua", null,{ headers: {Authorization: "Bearer " + token} }) } const TraVe = (MaVe, token)=>{ return axios.patch(env.API_ADMIN_LOCAL + "chiTietVe/huyVe", {MaVe: MaVe},{ headers: {Authorization: "Bearer " + token} }) } const SendEmailTraVe = (ChiTietVeTra, token)=>{ return axios.post(env.API_ADMIN_LOCAL + "email/thongbaohuyve", ChiTietVeTra, { headers: {Authorization: "Bearer " + token} }) } const SendEmailDatVe = (DSDatVe, token)=>{ return axios.post(env.API_ADMIN_LOCAL + "email/thongbaodatve", DSDatVe, { headers: {Authorization: "Bearer " + token} }) } export default { TimKiemLichTrinh, GetDanhSachNhaGa, GetNhaGa, DangKyKhachHang, DangNhapKhachHang, GetDanhSachTau_FollowLichTrinh, GetDSGheDaDat, GetDSToa_Of_Tau, GetChiTietToa_Of_Tau, GetDSGhe_Of_ToaTau, DatVe, CapNhatThongTin, GetDSVeDaMua, TraVe, SendEmailTraVe, SendEmailDatVe }
// require.config({ // The shim config allows us to configure dependencies for // scripts that do not call define() to register a module shim: { 'underscore': { exports: '_' }, 'socketio': { exports: 'io' }, 'backbone': { deps: [ 'underscore', 'jquery' ], exports: 'Backbone' } }, paths: { socketio: 'lib/socketio', jquery: 'lib/jquery', underscore: 'lib/underscore', backbone: 'lib/backbone' } }); //todo: enotni config fajli var URL = 'ws://rgti.bigbuckduck.com'; var DEBUG = 'ws://localhost'; var PORT = 9999; define(["underscore", "backbone"], function(_, Backbone) { var socket = null; var id = null; var cbck = null; return { connect: function(_cbck){ socket = new WebSocket(DEBUG+':'+PORT+'/'); if(_cbck===undefined){ cbck = function(e,p){}; }else{ cbck = _cbck; } socket.onopen = function(evt) { console.log("OnOpen "+evt); socket.send(JSON.stringify({'type':'remote'})); cbck("open"); }; socket.onclose = function(evt) { console.log("OnClose "+evt); cbck("close"); }; socket.onmessage = function(evt) { console.log("MSG: "+evt.data); payload = JSON.parse(evt.data); if(payload.id!==undefined){ id = payload.id; console.log("Connected as "+id); cbck("connected"); }else{ console.log("Error, bad type"); } }; socket.onerror = function(evt) { console.log("Error: "+evt); cbck("error"); }; }, action: function(type){ if(socket!==null){ console.log("action "+type); socket.send(JSON.stringify({'action':type, 'id':id})); } } }});
import React, { Component } from 'react'; import BarNavigation from './../../components/BarNavigation' import Footer from './../../components/Footer' import Divider from '@material-ui/core/Divider' import mainLogo from './../../img/footer/mainLogoWhite.png' import './styles.css' class LoginE extends Component { render() { return ( <div className='divLogin'> <header className='loginHeader'> <BarNavigation className='bar' classBar='barNavigation2' mainLogo={mainLogo}/> </header> <section className='mainLogin'> <form className='formLogin'> <h2 className='session'>Iniciar sesión</h2> <input type="email" required placeholder='Correo electrónico' ></input> <input type='password' required placeholder='Contraseña'></input> <input type='submit' value='Ingresar' href="#"></input> <hr/> <p>¿No tienes una cuenta? <a href="#/registroEstudiante"> Crea una</a></p> <a href="#/recuperarCuenta">Olvide mi contraseña</a> </form> </section> <div className='divider'> <Divider /> </div> <section className='footerMain'> <Footer classColor='transparent'/> </section> </div> ); } } export default LoginE;
import React, { Component } from 'react'; import './Card.css'; import { withStatus, NavContext } from "./Navbar"; //const NavbarWithStatus = withStatus(Card); class Card extends Component { // state = { // activities: [] // } render() { let label1=""; let label2=""; if (this.props.inCart === false ) { label1='Add to Cart'; } else label1='Remove from Cart'; if (this.props.isFav) label2='Remove from Favorites'; else label2='Add to Favorites' return ( <div className="card"> <img src={this.props.image} width="350px" height="250px" alt="cover"/> <h3>{this.props.title}</h3> <p>{this.props.description}</p> <p>{this.props.price}</p> <button onClick={this.props.favsInc} type="submit">{label1} </button> <button onClick={NavContext.handleFavsInc} type="submit">{label2} </button> </div> ); } } export default Card;
import { renderString } from '../../src/index'; describe(`Renders an image tag`, () => { it(`unnamed case 0`, () => { const html = renderString(`{% image "image" %}`); }); it(`unnamed case 1`, () => { const html = renderString(`{% image "executive_image", label="Executive photo", alt="Photo of Brian Halligan", src="//cdn2.hubspot.net/hub/53/file-733888619-jpg/assets/hubspot.com/about/management/brian-home.jpg", width="300", loading="lazy" %}`); }); });
var pony = {}; pony.image = new Image(800,600); pony.init = function(){ pony.coord = new Object(); pony.vel = new Object(); pony.coord.x = -10; pony.coord.y = -201; pony.vel.x = 1.9; pony.vel.y = -0.9; pony.rotation = 0; pony.width = pony.height = 200; pony.frame = 0; pony.touchGround = true; pony.touchGround2 = true; pony.touchGround3 = false; pony.keyDown = false; } pony.startMoving = false; pony.draw = function() { // TRANSFORM ctx.save(); ctx.translate(0,pony.coord.y); ctx.rotate(pony.rotation); if(HUD.timer>0){ if(pony.touchGround2){ if(pony.keyDown){ ctx.drawImage( pony.image, 202, Math.floor(pony.frame)*200+2,196,196, -200/2, -200+20, 200, 200); }else{ ctx.drawImage( pony.image, 2, Math.floor(pony.frame)*200+2,196,196, -200/2, -200+20, 200, 200); } }else{ if(HUD.timer>0 && pony.keyDown){ ctx.drawImage( pony.image, 602, Math.floor(pony.frame)*200+2,196,196, -200/2, -200+20, 200, 200); }else{ ctx.drawImage( pony.image, 402, Math.floor(pony.frame)*200+2,196,196, -200/2, -200+20, 200, 200); } } }else{ if(!pony.touchGround3){ if(pony.touchGround2){ pony.touchGround3 = true; PWG.shake = 100; } } if(pony.touchGround3){ ctx.drawImage( pony.image, 800, Math.floor(pony.frame)*200,200,200, -200/2, -200+20, 200, 200); }else{ ctx.drawImage( pony.image, 400, Math.floor(pony.frame)*200,200,200, -200/2, -200+20, 200, 200); } } // RESTORE ctx.restore(); } pony.enterFrame = function() { // KEY pony.keyDown = kCont.down; if(!pony.startMoving){ pony.startMoving = pony.keyDown; // Play music if not mobile and upon starting game if(pony.keyDown){ if( !gameIsMobile && music.paused ){ //music.currentTime = 0; menu.toggleAudio(); } } } // FRAME pony.frame += (2+pony.vel.x)/60; if(pony.keyDown){ pony.frame += 0.2; } pony.frame %= 3; if(pony.startMoving){ // Velocity Addition if(HUD.timer<=0){ pony.vel.x*=0.98; } if(HUD.timer>0 && pony.keyDown){ if(pony.touchGround2){ if(pony.vel.y>0){ pony.vel.y += 0.3 * Config.power; //pony.vel.x += 0.05; }else{ //pony.vel.y -= 0.05; pony.vel.x += 0.2 * Config.power; //pony.vel.x += 0.1; //Should just be pushing fwd } }else{ pony.vel.y += 0.25 * Config.power; } }else{ if(HUD.timer>0 && pony.touchGround2){ if(pony.vel.y<0 && pony.vel.x<3){ pony.vel.x += 0.05; } } if(HUD.timer<=0 && !pony.touchGround2){ pony.vel.y+=0.2; } pony.vel.y += 0.08; } // Move coords pony.coord.x += pony.vel.x; var terrY = terrain.funct(pony.coord.x); if(pony.touchGround3){ pony.coord.y += terrY; }else{ pony.coord.y += pony.vel.y; } // Terrain Update terrain.updateX(pony.coord.x); // Correct coords /*pony.touchGround = ( ( pony.vel.y>0 && pony.coord.y>terrY-2 ) || ( pony.vel.y<0 && pony.coord.y>terrY-0.5 ) );*/ //pony.touchGround3 = pony.coord.y>terrY-100; pony.touchGround2 = pony.coord.y>terrY-5; pony.touchGround = pony.coord.y>terrY; if(pony.touchGround) { pony.coord.y = terrY; // Slope & Projection var terrSlope = terrain.functDiff(pony.coord.x); var terrLength = Math.sqrt(1*1+terrSlope*terrSlope); var dotProduct = pony.vel.x*1 + pony.vel.y*terrSlope; dotProduct = dotProduct/terrLength; pony.vel.x = dotProduct/Math.sqrt(1+terrSlope*terrSlope); if(pony.vel.x<0.1){ pony.vel.x=0.1; } pony.vel.y = pony.vel.x*terrSlope; pony.vel.x *= Config.friction; pony.vel.y *= Config.friction; }else{ //pony.coord.y += pony.vel.y; } pony.rotation = Math.atan2(pony.vel.y,pony.vel.x); if(pony.rotation>Math.PI*0.3){ pony.rotation*=3; pony.rotation+=Math.PI*0.3; pony.rotation*=0.25; } } }
const express = require('express') const mongoose = require('mongoose') const bodyParser = require('body-parser') const app = express() mongoose.connect('mongodb://localhost:27017/userApp'); //Middleware app.use(bodyParser.json()) //Routes const routes = require('./routes') routes(app) app.listen('3000', () => { console.log('Server started at 3000') })
import React, { Component } from "react"; import Navigation from './components/Navigation'; import Landing from './components/Landing'; import About from './components/About'; import Portfolio from './components/Portfolio'; import { Router } from 'react-router-dom'; export default class Home extends Component { render() { return ( <div> <Navigation /> <Landing /> <Portfolio /> <About /> </div> ); } }
import SideMenu from '@/components/SideMenu/index.vue' import moduleMenu from './views/children/menu/index.vue' export default () => ( { path: '/module1/menu2', component: SideMenu, redirect: '/module1/menu2/moduleMenu1', meta: { title: '实有房屋', }, children: [ { path: '/module1/menu2/moduleMenu1', component: moduleMenu, } ] } )
import get from 'simple-get'; import initDebug from 'debug'; const debug = initDebug('torrent-http-bridge:chunkstore'); export default class HTTPChunkStore { constructor(pieceLength, opts) { this.pieceLength = pieceLength; this.file = opts.file; this.url = opts.url; debug('created chunk store for %s', this.url); } get(index, { offset, length }, cb) { return this._httpRequest(index, offset, length, cb); } // Taken from bittorrent-swarm webconn.js _httpRequest(pieceIndex, offset, length, cb) { const pieceOffset = pieceIndex * this.pieceLength; const start = pieceOffset + offset; const end = start + length - 1; debug('Requesting pieceIndex=%d offset=%d length=%d start=%d end=%d', pieceIndex, offset, length, start, end); const opts = { url: this.url, method: 'GET', headers: { 'user-agent': 'WebTorrent-HTTP-Bridge (http://webtorrent.io)', 'range': 'bytes=' + start + '-' + end, }, }; get.concat(opts, (err, data, res) => { if (err) return cb(err); if (res.statusCode < 200 || res.statusCode >= 300) { return cb(new Error('Unexpected HTTP status code ' + res.statusCode)); } debug('Got data of length %d', data.length); cb(null, data); }); } close(cb) { process.nextTick(cb); } }
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/iC5'); var AVs = require('../models/AV.js'); var BVs = require('../models/BV.js'); const bvList = [ { title: 'BV10', description: 'Старт Установки', readOnly: false, value: false }, { title: 'BV1', description: 'Работа ККБ', readOnly: true, value: true }, { title: 'BV2', description: 'ТЭН', readOnly: true, value: true }, { title: 'BV3', description: 'ТЭН', readOnly: true, value: true }, { title: 'BV4', description: 'Насос Отопления', readOnly: true, value: false }, { title: 'BV11', description: 'Теплый Пол', readOnly: false, value: true }, ]; const avList = [ { title: 'AV0', description: 'Температура в канале', status: 'norm', units: 'deg C', readOnly: true, value: 22.5 }, { title: 'AV1', description: 'Влажность в помещении', status: 'norm', units: '%', readOnly: true, value: 22.5 }, { title: 'AV2', description: 'Температура в помещении', status: 'norm', units: 'deg C', readOnly: true, value: 24.5 }, { title: 'AV3', description: 'Температура наружная', status: 'norm', units: 'deg C', readOnly: true, value: -5 }, { title: 'AV4', description: 'Температура Теплого Пола', status: 'norm', units: 'deg C', readOnly: true, value: 24 }, { title: 'AV12', description: 'Уставка ГВС', status: 'norm', units: 'deg C', readOnly: false, value: 55 }, { title: 'AV10', description: 'Клапан Тепло', status: 'norm', units: '%', readOnly: false, value: 100 }, { title: 'AV11', description: 'Клапан Холод', status: 'norm', units: '%', readOnly: false, value: 20 } ]; avList.forEach(element => { AVs.create(element, function(err, av) { if (err) { console.log('MongoError', err); throw err; } console.log('\nSAVE AV\n', av); }); }); bvList.forEach(element => { BVs.create(element, function(err, bv) { if (err) { console.log('MongoError', err); throw err; } console.log('\nSAVE AV\n', bv); }); });
/** * Creates A, B, C... blocks for exercise order. * 1 for each exercise (though they may not all be used if circuits exist). */ P.views.workouts.order.Blocks = function(exercises) { var blocks = [], index = {}, letter = "A".charCodeAt(0), prev, block, i; for (i = 0; i < exercises.length; i++) { block = { order: String.fromCharCode(letter), exercises: [], prev: prev }; index[block.order] = block; blocks.push(block); if (prev) { prev.next = block; } prev = block; letter++; } this.index = index; this.blocks = blocks; this.init(exercises); }; _.extend(P.views.workouts.order.Blocks.prototype, { /** * Given the cid of the exercise object, return the block it is in and it's index in that block. * @return object */ find: function(cid) { var block, index; this.blocks.forEach(function(b) { b.exercises.forEach(function(e, i) { if (e.cid == cid) { block = b; index = i; } }); }); return { block: block, index: index }; }, /** * Add the exercises. */ init: function(exercises) { exercises.each(function(exercise) { var block = this.index[exercise.get('order').charAt(0)]; block.exercises.push({ name: exercise.get('name'), cid: exercise.cid, _mdl: exercise }); }.bind(this)); }, /** * Find exercise by cid and remove it from the blocks. * @return {Object} */ detach: function(cid) { var location = this.find(cid); if (location && location.block) { return location.block.exercises.splice(location.index, 1).pop(); } return null; }, /** * Add exercise to block at specified position. * @param {Object} exercise Reference * @param {String} order Block order e.g. "A", "B"... * @param {Number} index Position in the block. */ insert: function(exercise, order, index) { this.index[order].exercises.splice(index, 0, exercise); }, /** * Update exercises with their new order. */ save: function() { this.blocks.forEach(function(block) { block.exercises.forEach(function(exercise, index) { var order = block.order; if (block.exercises.length > 1) { order += '.' + (index + 1); } exercise._mdl.set('order', order); }); }); }, toJSON: function() { var blocks = []; this.blocks.forEach(function(block) { block.isCircuit = block.exercises.length > 1; blocks.push(block); }); return blocks; } });
"use strict" console.log('Hello People!'); console.warn('Hello Warning!'); console.error('This is Error!'); console.info('Information'); alert('Hello ALERT!');
import React from "react"; import { useDispatch } from "react-redux"; import Button from "./Shared/Button"; import Section from "./Shared/Section"; import { create } from "../slices/game"; import { useHistory } from "react-router"; import Center from "./Shared/Center"; import styled from "styled-components"; const Start = () => { const dispatch = useDispatch(); const history = useHistory(); return ( <Center> <Buttons> <Section size={4}> <Button fullWidth color="primary" onClick={() => dispatch(create({ history }))} > Create game </Button> </Section> <Section size={4}> <Button fullWidth onClick={() => history.push("/local")} color="success" > Play local </Button> </Section> </Buttons> </Center> ); }; const Buttons = styled.div` max-width: 32rem; margin-top: 10vh; `; export default Start;
const _ = require('lodash'); const fs = require('fs'); const parse = require('csv-parse'); const { loadFileContent } = require('./util.js'); const preparePortfolio = (entries) => { return _.map(entries, (entry) => { return { title: _.get(entry, 'Produkt'), ISIN: _.get(entry, 'Symbol/ISIN'), amount: parseInt(_.get(entry, 'Anzahl', 0)), currency: _.get(entry, 'Wert'), value: parseFloat(_.get(entry, '').replace(',', '.')), }; }); }; const getPortfolio = (filepath) => { return loadFileContent(filepath) .then(parseContent({ columns: true })) .then(preparePortfolio) }; const parseContent = _.curry((options, content) => { return new Promise((resolve, reject) => { parse(content, options, (err, output) => { err ? reject(err) : resolve(output); }) }); }); const TRANSACTION_COLUMNS = [ 'date', 'time', 'title', 'ISIN', 'exchange', 'amount', 'local_share_price_currency', 'local_share_price', 'local_total_price_currency', 'local_total_price', 'target_total_price_after_fee_currency', 'target_total_price_after_fee', 'exchange_rate', 'exchange_fee_currency', 'exchange_fee', 'target_total_price_currency', 'target_total_price', ]; const TRANSACTION_FLOATS = [ 'local_share_price', 'local_total_price', 'target_total_price_after_fee', 'exchange_rate', 'exchange_fee', 'target_total_price', ]; const getTransactions = (filepath) => { return loadFileContent(filepath) .then(parseContent({ columns: TRANSACTION_COLUMNS })) .then(prepareTransactions) }; const prepareTransactions = (entries) => { return _.map(entries, (entry) => { entry.amount = parseInt(_.get(entry, 'amount', 0)); TRANSACTION_FLOATS.forEach((property) => { entry[property] = parseFloat(_.get(entry, property).replace(',', '.')); }); return entry; }); }; const explore = (filepath, prepare) => { loadFileContent(filepath) .then((content) => { return new Promise((resolve, reject) => { parse(content, { columns: true }, (err, output) => { err ? reject(err) : resolve(output); }) }); }) .then((entries) => { return prepare ? prepare(entries) : entries; }) .then(console.log) .catch(console.log); }; module.exports = { explore, getPortfolio, preparePortfolio, getTransactions, };
import React from 'react'; import Todo from './todo'; const todo_output= ({todos, setTodos}) => { console.log(todos); return ( <div className="todo-container"> <ul className="todo-list"> { todos.map( (todo) => ( <Todo todo={todo} setTodos={setTodos} /> ))} </ul> </div> ); } export default todo_output;
var Framework = function() { } Framework.prototype.preload = function() { } Framework.prototype.setup = function() { } Framework.prototype.draw = function() { } Framework.prototype.onMouseClicked = function() { } Framework.prototype.onMousePressed = function() { } Framework.prototype.onMouseMoved = function() { } Framework.prototype.onMouseDragged = function() { } Framework.prototype.onMouseReleased = function() { } Framework.prototype.onKeyPressed = function() { }
import authTypes from "src/redux/auth/types"; import { createAction } from "redux-actions"; import authBackend from "src/services/backend/auth"; export const authRequest = () => { return { type: authTypes.authRequest }; }; export const logIn = user => ({ type: authTypes.logInResponse, payload: user }); export const logOut = user => async dispatch => { let payload; dispatch(authRequest()); try { payload = await authBackend.logOut(); } catch (error) { payload = error; } dispatch(createAction(authTypes.logOutResponse)(payload)); }; export const checkLogIn = () => async dispatch => { let payload; dispatch(authRequest()); try { payload = await authBackend.checkLogIn(); } catch (error) { payload = error; } dispatch(createAction(authTypes.checkResponse)(payload)); };
$(document).ready(function() { // Загрузчик $('.preloader').delay(100).fadeOut(300); // ============================= // Анимация $(window).scroll( function () { // Классы var priceBlock = $('.price-box'); // Неизменны var $winTop = $(this).scrollTop(); var $winHeight = $(this).height(); var $winBottom = ($winTop + $winHeight); // Подстановки классов var $priceBlock = priceBlock.offset().top; var $pospriceBlock = ($priceBlock - $winHeight / 1.2); if ($winTop > $pospriceBlock) { priceBlock.addClass('animated'); }; }); // ============================= });
/********************************************************************************************* /** * Grand Central ajax call (everything goes in POST, but current GET is rerooted) * @author mvd@hands.agency **#******************************************************************************************/ (function($) { // Here we go! $.ajx = function(options, callbacks, element) { // Use "plugin" to reference the current instance of the object var plugin = this; // this will hold the merged default, and user-provided options plugin.settings = {} var $element = $(element), // reference to the jQuery version of DOM element element = element; // reference to the actual DOM element // Plugin's variables var vars = { } // The "constructor" plugin.init = function() { // the plugin's final properties are the merged default and user-provided options (if any) plugin.settings = $.extend({}, vars, options); // Some vars mime = (typeof(plugin.settings.mime) != 'undefined') ? plugin.settings.mime : 'html'; async = (typeof(plugin.settings.async) != 'undefined') ? plugin.settings.async : true; url = SITE_URL+'/ajax.'+mime; // Reroute the _GET (currently declared in the master) if (typeof(_GET) != 'undefined') plugin.settings._GET = _GET; // Call $.ajax( { type:'POST', url:url, async:async, context:this, data:plugin.settings, }) .done(function(html) { // Return HTML if ($element.length) $element.html(html); // Execute callback (make sure the callback is a function) if ((typeof(callbacks) != 'undefined') && (typeof(callbacks['done']) == "function")) callbacks['done'].call($element, html); }) .fail(function( jqXHR, textStatus ) { // console.log( "Request failed: " + textStatus ); console.log( "Request failed: " + jqXHR.responseText ); }); } // Fire up the plugin! plugin.init(); } // Add the plugin to the jQuery.fn object $.fn.ajx = function(options, callbacks) { return this.each(function() { // if (undefined == $(this).data('ajx')) // { var plugin = new $.ajx(options, callbacks, this); $(this).data('ajx', plugin); // } }); } /********************************************************************************************* /** * Lazyload * @author @mvdandrieux **#******************************************************************************************/ // Get rid of the original image in javascript (leave it in the DOM for SEO) $('[data-original]').attr('src', '').css('background-image', ''); // Lasyload ! $('[data-original]').lazyload( { effect : "fadeIn" }); })( jQuery );
const liteSchema = "https://vega.github.io/schema/vega-lite/v5.json"; const url = "https://vega.github.io/editor"; const geourl = 'https://vega.github.io/vega-lite'; export const vegaLitePieSpec = { $schema: liteSchema, data: { name: "table" }, transform: [ { aggregate: [{ op: "sum", field: "value", as: "value" }], groupby: ["symbol"], }, ], mark: "arc", encoding: { theta: { field: "value", type: "quantitative" }, color: { field: "symbol", type: "nominal", legend: true }, }, view: { stroke: null }, }; export const vegaLiteSeriseSpec = (list) => { console.log(list); return { $schema: "https://vega.github.io/schema/vega-lite/v5.json", description: "Stock prices of 5 Tech Companies over Time.", data: { name: "table" }, encoding: { x: { field: "date", type: "temporal", title: null }, }, layer: [ { mark: { type: "area", line: true, }, encoding: { y: { field: "value", type: "quantitative", axis: { format: "s" }, title: null, }, color: { field: "symbol", type: "nominal", legend: null, }, }, }, { transform: [{ pivot: "symbol", value: "value", groupby: ["date"] }], mark: "rule", encoding: { opacity: { condition: { value: 0.3, param: "hover", empty: false }, value: 0, }, tooltip: list.map((l) => ({ field: l, type: "quantitative" })), }, params: [ { name: "hover", select: { type: "point", fields: ["date"], nearest: true, on: "mouseover", clear: "mouseout", }, }, ], }, ], }; }; export const vegaErrorBand = { $schema: "https://vega.github.io/schema/vega-lite/v5.json", data: { url: `${url}/data/cars.json` }, encoding: { x: { field: "Year", timeUnit: "year", title: null, }, }, layer: [ { mark: { type: "errorband", extent: "ci" }, encoding: { y: { field: "Miles_per_Gallon", type: "quantitative", title: null, }, }, }, { mark: "line", encoding: { y: { aggregate: "mean", field: "Miles_per_Gallon", }, }, }, ], }; export const vegaHitmap = { $schema: "https://vega.github.io/schema/vega-lite/v5.json", data: { url: `${url}/data/seattle-weather.csv`, }, config: { view: { strokeWidth: 0, step: 13, }, axis: { domain: false, }, }, mark: "rect", encoding: { x: { field: "date", timeUnit: "date", type: "ordinal", title: null, axis: { labelAngle: 0, format: "%e", }, }, y: { field: "date", timeUnit: "month", type: "ordinal", title: null, }, color: { field: "temp_max", aggregate: "max", type: "quantitative", legend: null, }, }, }; export const vegaThreshold = { $schema: "https://vega.github.io/schema/vega-lite/v5.json", description: "The PM2.5 value of Beijing observed 15 days, highlighting the days when PM2.5 level is hazardous to human health. Data source https://chartaccent.github.io/chartaccent.html", layer: [ { data: { values: [ { Day: 1, Value: 54.8 }, { Day: 2, Value: 112.1 }, { Day: 3, Value: 63.6 }, { Day: 4, Value: 37.6 }, { Day: 5, Value: 79.7 }, { Day: 6, Value: 137.9 }, { Day: 7, Value: 120.1 }, { Day: 8, Value: 103.3 }, { Day: 9, Value: 394.8 }, { Day: 10, Value: 199.5 }, { Day: 11, Value: 72.3 }, { Day: 12, Value: 51.1 }, { Day: 13, Value: 112.0 }, { Day: 14, Value: 174.5 }, { Day: 15, Value: 130.5 }, ], }, layer: [ { mark: "bar", encoding: { x: { field: "Day", type: "ordinal", axis: { labelAngle: 0 } }, y: { field: "Value", type: "quantitative" }, }, }, { mark: "bar", transform: [ { filter: "datum.Value >= 300" }, { calculate: "300", as: "baseline" }, ], encoding: { x: { field: "Day", type: "ordinal", title: null }, y: { field: "baseline", type: "quantitative", title: null, }, y2: { field: "Value" }, color: { value: "#e45755" }, }, }, ], }, { data: { values: [{}], }, encoding: { y: { datum: 200 }, }, layer: [ { mark: "rule", }, { mark: { type: "text", align: "right", baseline: "bottom", dx: -2, dy: -2, x: "width", text: "hazardous", }, }, ], }, ], }; export const vegaGeo = { $schema: "https://vega.github.io/schema/vega-lite/v5.json", width: 500, height: 300, data: { url: `${geourl}/data/us-10m.json`, format: { type: "topojson", feature: "counties", }, }, transform: [ { lookup: "id", from: { data: { url: `${geourl}/data/unemployment.tsv`, }, key: "id", fields: ["rate"], }, }, ], projection: { type: "albersUsa", }, mark: "geoshape", encoding: { color: { field: "rate", type: "quantitative", }, }, };