text
stringlengths
7
3.69M
// ==UserScript== // @name Udacity Plus // @namespace https://udacityplus.appspot.com // @description Enhances Udacity lessons // @match http*://udacityplus.appspot.com/* // @match http*://*.udacity.com/* // @match http*://udacity.com/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js // @download https://udacityplus.appspot.com/static/udacityplus.user.js // @version 0.1.1145 // ==/UserScript== // Looking at the udacity.com html code there is already a bunch of material there // that was removed for launch var path = String(window.location); // full url var host = window.location.host; // subdomain.domain.tld // Create an overlay for articles var article_overlay_html = '<div class="udacity-plus" id="article-overlay"></div>'; GM_addStyle("div.udacity-plus#article-overlay {"+ "display:none; "+ "position: absolute; "+ // absoulte creates an overlay "margin-left: -1px; margin-top: 0px; z-index:100; "+ "background: #FFFFFF; border: solid 1px #1C78AA; "+ "font-size: 12px; "+ "color: black; "+ "width: 500px; height: 600px;} "+ "span.udacity-plus-score {color: #1C78AA; font-weight:bold;} "+ "a.udacity-plus-link {padding: 0px; border: none;} "); GM_addStyle("a.uplus-upvote {"+ "font-size: 18px;"+ "border:2px solid #1C78AA;"+ "background: #FFF no-repeat 4px 5px;"+ "text-decoration: none;"+ "border-radius: 5px;"+ "}\n"+ "a.uplus-upvote:hover, a.uplus-upvote:focus, a.uplus-upvote.selected {"+ //"border:2px solid #000000;"+ "background: #00FF00;}"); // Function to set the content, both in the overlay, if already created, // and in the overlay filler html var setContent = function(content) { if (typeof content !== "string") { content = "<p>An error occurred retrieving the articles."+ "Please try again or contact the Udacity Plus author</p>"; } article_overlay_html = '<div class="udacity-plus" id="article-overlay">'+content+'</div>'; jQuery("div.udacity-plus#article-overlay").html(content); } // Articles should be cached for an hour // Get content (via ajax or from storage) and put it into the article overlay var retrieval = GM_getValue('udacity plus articles', false); if (retrieval) { try { var asJSON = JSON.parse(retrieval); if ((asJSON["timestamp"] + 3600*1000) < new Date().getTime()) { // Cache expires after 1 hour retrieval = false; } else { setContent(asJSON["content"]); } } catch(e) { // In case **** happens, e.g. corrupted cache retrieval = false; } } // Retrieve user token and settings, if stored var local_data = GM_getValue("udacity plus settings", false); var settings = false; var token = false; if (local_data) { local_data = JSON.parse(local_data); if ("settings" in local_data) { settings = local_data["settings"]; } else { settings = {}; } if ("token" in local_data) { token = local_data["token"]; } } else { settings = {}; } var updateSettings = function() { // I know, globals are sub-ideal var storage = {"token": token, "settings": settings}; GM_setValue('udacity plus settings', JSON.stringify(storage)); } var upvote = function(link){ settings[link] = true; GM_xmlhttpRequest({ method: "POST", url: "https://udacityplus.appspot.com/api/articles/upvote", data: "link="+link+"&token="+token, headers: { "Content-Type": "application/x-www-form-urlencoded" }, onload: function(response) { response = JSON.parse(response.responseText); // Check that it worked console.log("Upvoted: "+link); updateSettings(); } }); } var devote = function(link){ settings[link] = false; GM_xmlhttpRequest({ method: "POST", url: "https://udacityplus.appspot.com/api/articles/devote", data: "link="+link+"&token="+token, headers: { "Content-Type": "application/x-www-form-urlencoded" }, onload: function(response) { response = JSON.parse(response.responseText); console.log(response["content"]); // Check that it worked updateSettings(); } }); } var isSelected = function(link){ if (link in settings && settings[link]) { return true; } else { return false; } } // Retrieve articles from server if (!retrieval && host.indexOf("udacity.com") != -1) { // Retrieve data via XHR GM_xmlhttpRequest({ method: "POST", url: "https://udacityplus.appspot.com/api/articles/get", data: "token="+token, headers: { "Content-Type": "application/x-www-form-urlencoded" }, onload: function(response) { var response = JSON.parse(response.responseText); var content = response["content"] if (!token || token !== response["token"]) { token = response["token"]; updateSettings(); } var storage = {"content": content, "timestamp": new Date().getTime()}; GM_setValue('udacity plus articles', JSON.stringify(storage)); setContent(content); } }); } jQuery(document).mouseup(function (event) { var container = jQuery("div.udacity-plus#article-overlay"); if (container.has(event.target).length === 0) { container.hide(); } }); // Wait for everything to be loaded window.addEventListener("load", function(e) { // Site is udacityplus.appspot.com: if (host.indexOf("udacityplus.appspot.com") != -1) { jQuery("a.install_button").html("Udacity Plus is already installed!"); jQuery("div#install_script").removeAttr("id"); } // Site is udacity.com: if (host.indexOf("udacity.com") != -1) { // Make the U+ additions more obvious GM_addStyle("li.udacity-plus {border: solid 1px #1C78AA;}"); // SECTION articles var progress_link = jQuery("li.topnav").last(); // Clicking default tabs must remove the active state from U+ tabs jQuery("a", jQuery("li.topnav")).click(function(event){ jQuery("li.topnav.udacity-plus").removeClass("selected"); }); // Create new topnav for articles var article_link = progress_link.clone(); article_link.html('<a href="#">Articles</a>');//article_link.html('<a href="#article-overlay">Articles</a>'); article_link.addClass("udacity-plus"); progress_link.after(article_link); article_link.append(article_overlay_html); article_overlay = jQuery("div.udacity-plus#article-overlay"); // Add click events: article_link.click(function(event){ article_overlay.show(); }); // Add U+ upvote functionality if (host.indexOf("forums.udacity.com") != -1) { var insert = '<a class="uplus-upvote" href="#" title="Upvote on Udacity Plus! (Click again to undo)">&nbsp;+&nbsp;</a><br/>&nbsp;<br/>'; var questionUpVote = jQuery(insert); // Create a new DOM element jQuery("div#favorite-count").after(questionUpVote); if (isSelected(path)) { jQuery(questionUpVote).addClass("selected"); } questionUpVote.click(function(event){ event.preventDefault(); if (jQuery(this).hasClass("selected")) { jQuery(this).removeClass("selected"); devote(path); } else { jQuery(this).addClass("selected"); upvote(path); } this.blur(); }); jQuery("div.answer").each(function(index){ var answerUpVote = jQuery(insert); jQuery("a.post-vote.down", this).after(answerUpVote); var answerID = jQuery(this).prev("a").attr("name"); var link = path+"#"+answerID if (isSelected(link)) { answerUpVote.addClass("selected"); } answerUpVote.click(function(event){ event.preventDefault(); if (jQuery(this).hasClass("selected")) { jQuery(this).removeClass("selected"); devote(link); } else { jQuery(this).addClass("selected"); upvote(link); } this.blur(); }); }); } // SECTION materials var tab_supplementary = jQuery('a[href="#tab-follow"]'); // Create a <LI> for Udacity Plus Materials var uplus_materials_tab = tab_supplementary.parent().clone(); uplus_materials_tab.addClass("udacity-plus"); var uplus_notes_tab = uplus_materials_tab.clone(); // Clicking default tabs must remove the active state from U+ tabs // and also hide U+ panels jQuery("a", jQuery("li.ui-state-default")).click(function(event){ jQuery("li.ui-state-default.udacity-plus").removeClass( "ui-tabs-selected ui-state-active"); jQuery("div.udacity-plus.ui-tabs-panel").addClass("ui-tabs-hide"); }); // Change text and link binding for U+ Materials jQuery("a", uplus_materials_tab).html("U+ Materials"); jQuery("a", uplus_materials_tab).attr("href", "#tab-uplus-materials"); // Add tab: tab_supplementary.parent().after(uplus_materials_tab); // Create a div area for the content jQuery("div#tab-follow").after('<div id="tab-uplus-materials" '+ 'class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide udacity-plus">\n'+ '<div>\n'+ '<span class="pretty-format"><p>Some sample materials here</p></span>\n'+ '</div>\n'+ '</div>\n') // Add click events: jQuery("a", uplus_materials_tab).click(function(event){ event.preventDefault(); jQuery("li.ui-tabs-selected.ui-state-active"). // Deselects current active tab removeClass("ui-tabs-selected ui-state-active"); jQuery("div.ui-tabs-panel").addClass("ui-tabs-hide"); // Hide all panels jQuery(uplus_materials_tab).addClass("ui-tabs-selected ui-state-active"); jQuery("div#tab-uplus-materials").removeClass("ui-tabs-hide"); // Show materials panel }); // Change text and link binding for U+ Notes jQuery("a", uplus_notes_tab).html("U+ Notes"); jQuery("a", uplus_notes_tab).attr("href", "#tab-uplus-notes"); // Add tab: jQuery(uplus_materials_tab).after(uplus_notes_tab); // Create a div area for the content jQuery("div#tab-uplus-materials").after('<div id="tab-uplus-notes" '+ 'class="ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide udacity-plus">\n'+ '<div>\n'+ '<span class="pretty-format"><p>Enter notes here</p></span>\n'+ '</div>\n'+ '</div>\n') // Add click events: jQuery("a", uplus_notes_tab).click(function(event){ event.preventDefault(); jQuery("li.ui-tabs-selected.ui-state-active"). // Deselects current active tab removeClass("ui-tabs-selected ui-state-active"); jQuery("div.ui-tabs-panel").addClass("ui-tabs-hide"); // Hide all panels jQuery(uplus_notes_tab).addClass("ui-tabs-selected ui-state-active"); jQuery("div#tab-uplus-notes").removeClass("ui-tabs-hide"); // Show notes panel }); } }, false);
import * as React from 'react'; import { View,ActivityIndicator } from 'react-native'; import firebase from 'firebase'; export default class LoadingScreen extends React.Component { toCheckUserLoggedIn=()=>{ firebase.auth().onAuthStateChanged((user)=>{ if(user){ this.props.navigation.navigate('DashBoardScreen') } else{ this.props.navigation.navigate('LoggingScreen')} }) } componentDidMount(){ this.toCheckUserLoggedIn() } render(){ return ( <View style={{ flex:1, justifyContent:'center', alignItems:'center' }}> <ActivityIndicator size="large"/> </View> ); } }
import express from 'express'; import expressAsyncHandler from 'express-async-handler'; import Data from '../Data.js'; import Product from '../models/productModel.js'; const productRouter=express.Router(); productRouter.get('/',expressAsyncHandler(async(req,res)=>{ const products=await Product.find({}); // this will find all the data and send it to us (fetching data from monogdb database) // console.log(products); res.send(products); })); productRouter.get('/seed', expressAsyncHandler(async(req,res)=>{ // await Product.remove({}); //this removes all the data from database const createdProducts=await Product.insertMany(Data.products); res.send({createdProducts}); })); productRouter.get('/:id',expressAsyncHandler(async(req,res)=>{ const product=await Product.findById(req.params.id); // console.log(product); if(product) res.send(product); else res.status(404).send({message: "Product Not Found"}) })); export default productRouter;
function fetchData() { const url = window.location.href; return { url: url } }; const sendData = (data) => { // const site_url = window.location.href; const url = 'http://127.0.0.1:3000/api/v1/audios'; fetch(url, { method: 'POST', headers: { "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({ "audio": { "text_url": `${data.url}` } } ) }) } sendData(fetchData());
import React, { Component } from "react"; import Form from "./Form"; import TweetCard from "./TweetCard"; import Trend from "./Trend"; import Header from "./Header"; import Notification from "./Notification"; import { connect } from "react-redux"; import { fetchTweets, notifyPortals, fetchTrends } from "../actions"; import moment from "moment"; class TwitterHistory extends Component { state = { username: "", startDate: "", endDate: "" }; handleChange = event => { const { name, value } = event.target; this.setState({ [name]: value }); }; handleSubmission = event => { event.preventDefault(); if (this.state.username.length < 3) { this.props.notifyPortals( "Enter a Username with 3 or more characters", "bg-red-500" ); return; } let from = moment(this.state.startDate); let to = moment(this.state.endDate); if (!from.isValid()) { this.props.notifyPortals("Enter a valid Start Date", "bg-red-500"); return; } if (!to.isValid()) { this.props.notifyPortals("Enter a valid End Date", "bg-red-500"); return; } if (to.isBefore(from)) { this.props.notifyPortals( "Start Date must be less than End Date", "bg-red-500" ); return; } this.props.fetchTweets(this.state); }; renderListOfTweets() { const { tweets } = this.props; if (!tweets.results) return; const tweetCards = tweets.results.map(tweet => ( <TweetCard key={tweet.id} tweet={tweet} /> )); return tweetCards; } componentDidMount() { this.props.fetchTrends(); } renderListOfTrends(){ const { trends } = this.props; if (trends.length < 1) return; return trends[0].trends.map(trend => <Trend key={trend.name} trend={trend} />) } render() { return ( <div> <Header title="Twitter Today in History" /> <main className="px-12 py-5 "> <div className="py-4"> <h2 className="text-blue-500 text-2xl"> Fetch Twitter History on Specific Dates </h2> </div> <div className="flex flex-wrap"> <div className="w-full lg:w-3/4"> <Form data={this.state} handleChange={this.handleChange} handleSubmission={this.handleSubmission} /> {this.props.notify ? ( <Notification content={this.props.notify.message} style={this.props.notify.style} /> ) : null} <div className="flex flex-wrap w-full mt-4"> {this.renderListOfTweets()} </div> </div> <div className="w-full lg:w-1/4"> <div className="shadow-lg md:mt-4 sm:mt-4 lg:ml-4 py-4 px-2"> <p className="text-blue-500 text-lg">Latest Trends</p> <p className="text-gray-400 text-sm"> Checkout What is Trending </p> <div className="flex flex-wrap pt-4"> { this.renderListOfTrends() } </div> </div> </div> </div> </main> </div> ); } } const mapStateToProps = state => { return { tweets: state.tweets, notify: state.notify, trends: state.trends }; }; export default connect(mapStateToProps, { fetchTweets, notifyPortals, fetchTrends })(TwitterHistory);
//实现验证开始时间必须小于结束时间 Ext.apply(Ext.form.field.VTypes, { daterange: function (val, field) { var date = field.parseDate(val); if (!date) { return false; } this.dateRangeMax = null; this.dateRangeMin = null; if (field.startDateField && (!this.dateRangeMax || (date.getTime() != this.dateRangeMax.getTime()))) { var start = field.up('form').down('#' + field.startDateField); start.setMaxValue(date); //start.validate(); this.dateRangeMax = date; } else if (field.endDateField && (!this.dateRangeMin || (date.getTime() != this.dateRangeMin.getTime()))) { var end = field.up('form').down('#' + field.endDateField); end.setMinValue(date); //end.validate(); this.dateRangeMin = date; } /* * Always return true since we're only using this vtype to set the * min/max allowed values (these are tested for after the vtype test) */ return true; }, daterangeText: '開始時間必須小於結束時間' }); //品牌Model Ext.define("gigade.Brand", { extend: 'Ext.data.Model', fields: [ { name: "Brand_Id", type: "string" }, { name: "Brand_Name", type: "string" }] }); //品牌store var brandStore = Ext.create('Ext.data.Store', { model: 'gigade.Brand', autoLoad: true, //filterOnLoad: true, proxy: { type: 'ajax', url: "/Product/GetVendorBrand", actionMethods: 'post', reader: { type: 'json', root: 'data' } } }); //商品館別Store var ProdClassfyStore = Ext.create('Ext.data.Store', { fields: ['txt', 'value'], data: [ { "txt": '全部', "value": "0" }, { "txt": '食品館', "value": "10" }, { "txt": '用品館', "value": "20" }] }); Ext.define("gigade.paraModel", { extend: 'Ext.data.Model', fields: [ { name: 'parameterCode', type: 'string' }, { name: 'parameterName', type: 'string' } ] }); var statusStore = Ext.create("Ext.data.Store", { model: 'gigade.paraModel', autoLoad: true, proxy: { type: 'ajax', url: '/Parameter/QueryPara?paraType=product_status', noCache: false, getMethod: function () { return 'get'; }, actionMethods: 'post', reader: { type: 'json', root: 'items' } } }); //查询 Query = function () { //ProductClickStore.removeAll(); var type = Ext.getCmp('type').getValue(); switch (type.type) { case "b": Ext.getCmp('year').show(); Ext.getCmp('month').show(); Ext.getCmp('day').show(); break; case "y": Ext.getCmp('year').show(); Ext.getCmp('month').hide(); Ext.getCmp('day').hide(); break; case "m": Ext.getCmp('year').hide(); Ext.getCmp('month').show(); Ext.getCmp('day').hide(); break; case "d": Ext.getCmp('year').hide(); Ext.getCmp('month').hide(); Ext.getCmp('day').show(); break; } Ext.getCmp("gdProductClick").store.loadPage(1, { params: { product_status: Ext.getCmp('product_status').getValue(), brand_id: Ext.getCmp('brand_id').getValue(), prod_classify: Ext.getCmp('prod_classify').getValue(), product_id: Ext.getCmp('product_id').getValue(), type: Ext.getCmp('type').getValue(), startdate: Ext.getCmp('startdate').getValue(), enddate: Ext.getCmp('enddate').getValue() } }); } function TheMonthFirstDay() { var times; times = new Date(); return new Date(times.getFullYear(), times.getMonth(), 1); } function Tomorrow(month) { var d; d = new Date(); // 创建 Date 对象。 //d.setDate(d.getDate() + days); d.setMonth(d.getMonth() - 1); return d; } var frm = Ext.create('Ext.form.Panel', { id: 'frm', layout: 'anchor', flex: 1.8, border: 0, bodyPadding: 10, width: document.documentElement.clientWidth, items: [ { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'combobox', //status fieldLabel: '商品狀態', editable: false, id: 'product_status', margin: '0 5px', store: statusStore, displayField: 'parameterName', valueField: 'parameterCode', typeAhead: true, forceSelection: false, allowBlank: true, emptyText: '請選擇' //, //listeners: { // "select": function (combo, record) // { // var z = Ext.getCmp("product_status"); // if (z.getValue() == "0" || z.getValue() == "20") // {//新建立商品和供應商新建商品 // Ext.Msg.alert(INFORMATION, "不存在該狀態的商品"); // z.setValue(""); // } // } //} }, {//品牌 xtype: 'combobox', fieldLabel: '品牌', labelWidth: 40, defaultListConfig: { //取消loading的Mask loadMask: false, loadingHeight: 70, minWidth: 70, maxHeight: 300, shadow: "sides" }, id: 'brand_id', name: 'brand_id', colName: 'brand_id', editable: true, store: brandStore, queryMode: 'local', displayField: 'Brand_Name', valueField: 'Brand_Id', typeAhead: true, triggerAction: 'all', forceSelection: true, emptyText: '請選擇' }, { xtype: 'combobox', id: 'prod_classify', name: 'prod_classify', margin: '0 5px', fieldLabel: '商品館別', queryMode: 'local', editable: false, store: ProdClassfyStore, displayField: 'txt', valueField: 'value', value: 0 } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'displayfield', margin: '0 0 0 5', fieldLabel: '查詢日期' }, { xtype: 'datefield', id: 'startdate', name: 'startdate', margin: '0 5 0 0', editable: false, value: Tomorrow(1), format: 'Y/m/d', width:110, vtype: 'daterange', endDateField: 'enddate', listeners: { select: function (a, b, c) { var start = Ext.getCmp("startdate"); var end = Ext.getCmp("enddate"); if (end.getValue() == null) { end.setValue(setNextMonth(start.getValue(), 1)); } else if (end.getValue() < start.getValue()) { Ext.Msg.alert(INFORMATION, DATA_TIP); start.setValue(setNextMonth(end.getValue(), -1)); } else if (end.getValue() > setNextMonth(start.getValue(), 1)) { // Ext.Msg.alert(INFORMATION, DATE_LIMIT); end.setValue(setNextMonth(start.getValue(), 1)); } }, specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } } } }, { xtype: 'displayfield', value: '~' }, { xtype: 'datefield', id: 'enddate', name: 'enddate', margin: '0 5px', width: 110, editable: false, value: new Date(), format: 'Y/m/d', vtype: 'daterange', startDateField: 'startdate', listeners: { select: function (a, b, c) { var start = Ext.getCmp("startdate"); var end = Ext.getCmp("enddate"); if (start.getValue() != "" && start.getValue() != null) { if (end.getValue() < start.getValue()) { Ext.Msg.alert(INFORMATION, DATA_TIP); end.setValue(setNextMonth(start.getValue(), 1)); } else if (end.getValue() > setNextMonth(start.getValue(), 1)) { // Ext.Msg.alert(INFORMATION, DATE_LIMIT); start.setValue(setNextMonth(end.getValue(), -1)); } } else { start.setValue(setNextMonth(end.getValue(), -1)); } }, specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } } } } ] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'textfield', id: 'product_id', name: 'product_id', margin: '0 5px', fieldLabel: '商品編號', listeners: { specialkey: function (field, e) { if (e.getKey() == e.ENTER) { Query(); } } } }, { xtype: 'radiogroup', hidden: false, id: 'type', name: 'type', fieldLabel: '統計類型', width: 400, margin: '0 5px', columns: 4, vertical: true, items: [ { boxLabel: '不分', name: 'type', id: 'bufen', checked: true, inputValue: "b" }, { boxLabel: '年', name: 'type', inputValue: "y" }, { boxLabel: '月', name: 'type', inputValue: "m" }, { boxLabel: '日', name: 'type', inputValue: "d" }, ] }] }, { xtype: 'fieldcontainer', combineErrors: true, layout: 'hbox', items: [ { xtype: 'button', margin: '0 10 0 10', iconCls: 'icon-search', text: "查詢", handler: Query }, { xtype: 'button', text: '重置', id: 'btn_reset', iconCls: 'ui-icon ui-icon-reset', listeners: { click: function () { Ext.getCmp('product_status').setValue(""); Ext.getCmp('prod_classify').setValue(0); Ext.getCmp('brand_id').setValue(""); Ext.getCmp('product_id').setValue(""); Ext.getCmp('bufen').setValue(true); Ext.getCmp('startdate').reset();//開始時間--time_start--delivery_date Ext.getCmp('enddate').reset();//結束時間--time_end--delivery_date Ext.getCmp('startdate').setValue(Tomorrow(1));//開始時間--time_start--delivery_date Ext.getCmp('enddate').setValue(new Date());//結束時間--time_end--delivery_date } } } ] } ] }); setNextMonth = function (source, n) { var s = new Date(source); s.setMonth(s.getMonth() + n); if (n < 0) { s.setHours(0, 0, 0); } else if (n > 0) { s.setHours(23, 59, 59); } return s; }
"use strict"; const newImage = new Image(); const imageCanvas = document.querySelector("#imageCanvas"); const ctx = imageCanvas.getContext("2d"); const zoomCtx = zoomCanvas.getContext("2d"); const imageWidth = ctx.canvas.width; const imageHeight = ctx.canvas.height; let imageData; const zoomWidth = zoomCtx.canvas.width; let zoomData; window.addEventListener("DOMContentLoaded", init); function init() { console.log("init"); crateAndLoadImage(); } function crateAndLoadImage() { console.log("crateAndLoadImage"); // image path newImage.src = "cat.jpg"; // when image is loaded newImage.addEventListener("load", drawImage); } function drawImage() { // draw image in canvas ctx.drawImage(newImage, 0, 0); getImageData(); } function getImageData() { // get pixel data from image imageData = ctx.getImageData(0, 0, imageWidth, imageHeight); console.log(imageData); createZoomData(); } function createZoomData() { // create an empty imageData for the zoom canvas console.log("createZoomData"); zoomData = zoomCtx.createImageData(10, 10); console.log(zoomData); } function copyPixel(startX, startY) { console.log("copyPixel"); // loop for x and y content i zoomCtx (10x10px grid) for (let y = 0; y < 10; y++) { for (let x = 0; x < 10; x++) { // calculate pixelIndex position (loop x & y) const pixelIndex = (x + y * 10) * 4; // use mouse position (startX & startY) with (loop x & y) const imageX = startX + x + -5; const imageY = startY + y + -5; // calculate where in the imageData to copy from imageIndex = (imageX + imageY * imageWidth) * 4; // copy each pixel (4 colors) data from imageData to zoomData zoomData.data[pixelIndex + 0] = imageData.data[imageIndex + 0]; zoomData.data[pixelIndex + 1] = imageData.data[imageIndex + 1]; zoomData.data[pixelIndex + 2] = imageData.data[imageIndex + 2]; zoomData.data[pixelIndex + 3] = imageData.data[imageIndex + 3]; // fill with red test // zoomData.data[pixelIndex + 0] = 255; //r // zoomData.data[pixelIndex + 1] = 0; //g // zoomData.data[pixelIndex + 2] = 0; //b // zoomData.data[pixelIndex + 3] = 255; //a } drawZoomData(); } } function drawZoomData() { // put zoomData in zoom canvas (zoomCtx) zoomCtx.putImageData(zoomData, 0, 0); } // get mouse position on every move on the canvas imageCanvas.addEventListener("mousemove", getPosition, false); function getPosition(event) { // get mouse position let x = event.x; let y = event.y; x -= imageCanvas.offsetLeft; y -= imageCanvas.offsetTop; console.log("x:" + x + " y:" + y); // put image data in ctx ctx.putImageData(imageData, 0, 0); drawRectangle(x, y); copyPixel(x, y); getColor(x, y); } function drawRectangle(x, y) { // draw rectangle with 5 px offset for centering ctx.strokeRect(x - 5, y - 5, 10, 10); ctx.strokeStyle = "green"; ctx.moveTo = (x, y); } function getColor(x, y) { // color info from a pixel - return {r,g,b} const pixelIndex = 4 * (x + y * imageWidth); const r = imageData.data[pixelIndex]; const g = imageData.data[pixelIndex + 1]; const b = imageData.data[pixelIndex + 2]; console.log(`r: ${r} g: ${g} b: ${b}`) const rgb = { r, g, b } showColorInfo(rgb); } // 🎁 Here you go! 🎁 - thanks!! function showColorInfo(rgb) { document.querySelector("#r").textContent = rgb.r; document.querySelector("#g").textContent = rgb.g; document.querySelector("#b").textContent = rgb.b; const hex = "#" + rgb.r.toString(16).padStart(2, "0") + rgb.g.toString(16).padStart(2, "0") + rgb.b.toString(16).padStart(2, "0"); document.querySelector("#hex").textContent = hex; document.querySelector("#colorbox").style.backgroundColor = hex; }
export default function () { console.log("我是foo") }
// You are trying to put a hash in ruby or an object in javascript or java into an array, but it always returns error, solve it and keep it as simple as possible! // items = [] // items.push{a: "b", c: "d"} // I wasn't sure what was exactly wrong with this solution so I had to do research. I realized that it was a simple punctuation error. items = [] items.push({a: "b", c: "d"})
import styled from "styled-components"; export const Button = styled.button` min-width: 100px; margin: 5px; padding: 5px 20px; color: #ffffff; background-color: #2EA44F; border: 1px solid lightgrey; border-radius: 5px; outline: none; cursor: pointer; &:hover { background-color: #2b8444; } &:active { background-color: #2EA44F; } `
import React from 'react'; import VerifyCode from 'component/verify-code/index.jsx'; import BaseUtil from 'util/base-util.jsx'; import User from 'service/user-service.jsx'; import './index.css'; const _baseUtil = new BaseUtil(); const _user = new User(); class VerifyPage extends React.Component{ constructor(props){ super(props); this.state = { key: 1, verify: '', verifyCode: _baseUtil.getStorage('vc') || '1234', redirect: _baseUtil.getUrlParam('redirect') || '/' } } componentWillMount(){ document.title = '创易汇'; } onInputChange(e){ let inputName = e.target.name; let inputValue = e.target.value; this.setState({ [inputName]: inputValue }); } onInputKeyup(e){ if(e.keyCode === 13){ this.onSubmit(); } } onSubmit(){ if(this.state.verify === ''){ _baseUtil.errorTips('请输入验证码'); return false; } if(this.state.verifyCode !== this.state.verify){ _baseUtil.errorTips('验证码输入错误'); return false; } _baseUtil.successTips('验证通过'); this.props.history.push(this.state.redirect); // _user.verify(this.state.verify).then((res)=>{ // _baseUtil.saveToken(res.token); // this.props.history.push(this.state.redirect); // },(errMsg)=>{ // _baseUtil.errorTips(errMsg); // }); } // onVerify(verifyCode){ // this.setState({ // verifyCode: verifyCode // }); // } render(){ return ( <div className="verify-body"> <div className="verify-page"> <VerifyCode key={this.state.key} verifyCode={this.state.verifyCode}/><br/><br/> <input type="text" className="form-control" name="verify" value={this.state.verify} placeholder="请输入验证码" onChange={e=>this.onInputChange(e)} onKeyUp={e=>this.onInputKeyup(e)}/> <button id="btn-verify" className="btn btn-primary" onClick={()=>{this.onSubmit()}}>确定</button> </div> </div> ); } } export default VerifyPage;
/** * @param {number} num * @return {string} */ var convertToBase7 = function(num) { if( num === 0) return "0"; var res = ""; var positive = num > 0; while (num !== 0) { res = Math.abs(num %7).toString() + res; if (num > 0) { num = Math.floor( num / 7); } else { num = Math.ceil( num / 7); } } return positive ? res: "-"+res; }; console.log(convertToBase7(100)); console.log(convertToBase7(-7));
module.exports.createServiceLocator = function() { var self = {}; /** * Registers a service but make it read only * @param {String} name To get the service by * @param {Object} service What you want to register */ function register(name, service) { if (self[name] !== undefined) { throw new Error('Service \'' + name + '\' already registered'); } Object.defineProperty(self, name, { get: function(){ return service; } }); return self; } self.register = register; return self; };
function Awake(){ if(!networkView.isMine){ enabled = false; } } function OnCollisionEnter(collision : Collision){ transform.parent.GetComponent("BoxMove").collisionEnterProxy(collision); } function OnCollisionExit(collision : Collision){ transform.parent.GetComponent("BoxMove").collisionExitProxy(collision); }
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { getUser } from 'actions/user' import { Map } from 'immutable' import styles from './ChatMessage.css' class ChatMessage extends Component { static propTypes = { message: PropTypes.instanceOf(Map).isRequired, getUser: PropTypes.func.isRequired } componentDidMount () { const userId = this.props.message.get('userId') this.props.getUser(userId) } render () { const { userStore, message } = this.props const user = userStore.find((user) => { return user.get('id') === message.get('userId') }) return ( <div> { user && <div className={ styles.message }> <img className={ styles.avatar } src={ user.get('avatar') } /> { message.get('text') } </div> } </div> ) } } const mapStateToProps = (state) => { return { userStore: state.user.get('store') } } export default connect(mapStateToProps, { getUser })(ChatMessage)
import React, { useState } from "react"; import { Grid } from "@material-ui/core"; import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown'; import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp'; import { connect } from "react-redux"; function Process(props) { const [processReadMores, setProcessReadMores] = useState([false, false, false]) const onProcessReadMore = (index) => { const temp = [...processReadMores]; temp[index] = !temp[index]; setProcessReadMores(temp); } return ( <div className="grants-process text-center"> <div className="title border pb-sm-10">GRANT APPLICATION PROCESS</div> <div className="description mt-16">An accurate business proposal that outlines the requirements to achieve a large specific project</div> <div className="process-card-container"> <Grid container spacing={6}> <Grid item lg={6} md={6} xs={12}> <div className="card-wrapper"> <div className="circle">1</div> <div className="card-text"> <div className="process-title">Research</div> <div className={`text ${processReadMores[0] ? 'full' : null}`}>Grants are available from government agencies, state associations, and private corporations. The government website grants.gov, the local Business Development Center, and charities like the Local, State, or nationwide Initiatives Support Corp are all places venture plans starts byresearching and finding the top eligible choices that fit well with your entity and for your application.</div> <div onClick={() => onProcessReadMore(0)} className="flex flex-middle flex-center mt-20 btnReadMore"> read more {!processReadMores[0] && <ArrowDropDownIcon />} {processReadMores[0] && <ArrowDropUpIcon />} </div> </div> </div> </Grid> <Grid item lg={6} md={6} xs={12}> <div className="card-wrapper"> <img src="/assets/images/grants/process-1.png" alt="process" /> </div> </Grid> <Grid item lg={6} md={6} xs={12}> <div className="card-wrapper"> <img src="/assets/images/grants/process-2.png" alt="process" /> </div> </Grid> <Grid item lg={6} md={6} xs={12}> <div className="card-wrapper"> <div className="circle">2</div> <div className="card-text"> <div className="process-title">Guidelines & Requirements</div> <div className={`text ${processReadMores[1] ? 'full' : null}`}>After the initial research phase, we dive deeper in disecting the guidelines of the top compatible grants that match your venture’s needs. We start looking at the requirements and checklist of the stated guidelines, to see how we are going to create a compelling business model, sustainability plan for a proper budgeting strategy for a ongoing long term funding portal.</div> <div onClick={() => onProcessReadMore(1)} className="flex flex-middle flex-center mt-20 btnReadMore"> read more {!processReadMores[1] && <ArrowDropDownIcon />} {processReadMores[1] && <ArrowDropUpIcon />} </div> </div> </div> </Grid> <Grid item lg={6} md={6} xs={12}> <div className="card-wrapper"> <div className="circle">3</div> <div className="card-text"> <div className="process-title">Grant Proposal and Submission </div> <div className={`text ${processReadMores[2] ? 'full' : null}`}>Our team of grant experts draft a grant proposal that is straightforward, precise document written for a specific institution or funding agency with the intention of influencing the supporters to help you because: (1) you have a significant and well-thought-out strategy to pursue a viable cause, and (2) you are accountable and capable of carrying out that plan.</div> <div onClick={() => onProcessReadMore(2)} className="flex flex-middle flex-center mt-20 btnReadMore"> read more {!processReadMores[2] && <ArrowDropDownIcon />} {processReadMores[2] && <ArrowDropUpIcon />} </div> </div> </div> </Grid> <Grid item lg={6} md={6} xs={12}> <div className="card-wrapper"> <img src="/assets/images/grants/process-3.png" alt="process" /> </div> </Grid> </Grid> </div> </div> ); } const mapStateToProps = state => ({ }); export default connect( mapStateToProps, { } )(Process);
function esPrimo(numero) { if (numero > 0 && numero < 4 || numero === 5) { return true; } if ( (numero % 2 === 0) || (numero % 3 === 0) || (numero % 5 === 0) ) { return false; } return true; } function cantidadPrimos(cantidad) { const primos = []; let count = 1; while ( primos.length < cantidad ) { if ( esPrimo(count)) primos.push(count); count++; } return primos; } const numero = 7; const numerosPrimos = cantidadPrimos(numero); console.log(`los primeros ${numero} numeros primos son ${numerosPrimos}`);
const secret = "@@n@nl@jnlk-02r-9i0uq4ohifuho9UEF0-I9@$@%@#!$-20-9U#$#$@$OUFHIFO-0EIF9H" exports = module.exports = { secret }
import styles from "../styles/hands.module.scss"; const Hands = ({ setUserHand }) => { return ( <div className={styles.hands}> <div className={styles.paper} onClick={() => setUserHand("paper")}> <img src="./images/Paper.png" /> </div> <div className={styles.scissor} onClick={() => setUserHand("scissors")}> <img src="./images/Scissors.png" /> </div> <div className={styles.rock} onClick={() => setUserHand("rock")}> <img src="./images/Rock.png" /> </div> </div> ); }; export default Hands;
function load_wysiwyg($par){ $par.find('textarea:not(.no_wysiwyg)').tinymce({ // Location of TinyMCE script script_url : '/site_media/static/tinymce/jscripts/tiny_mce/tiny_mce_src.js', // relative_urls are awful. I want to never, ever see them. relative_urls : false, // General options valid_elements: '*[*]', theme : 'advanced', plugins: 'paste,media,autoresize', fix_list_elements : true, // Theme options, empty on purpose theme_advanced_buttons1 : '', theme_advanced_buttons2 : '', theme_advanced_buttons3 : '', //Paste Options paste_create_paragraphs : false, paste_create_linebreaks : false, paste_use_dialog : true, paste_auto_cleanup_on_paste : true, paste_convert_middot_lists : false, paste_convert_headers_to_strong : true, // Example content CSS (should be your site CSS) // This is a convention, if you need to override // wysiwyg.css location, you'll have to override this // entire file.. or symlink. content_css : "/site_media/static/css/wysiwyg.css", //Auto resize theme_advanced_resizing_min_width : 50, theme_advanced_resizing_min_height : 350, setup: function (ed) { ed.onPostRender.add(function(ed,evt){ $(ed.getBody()).addClass(ed.id); $(ed.getBody()).css({'backgroundColor':'transparent'}); $(ed.getWin()).focus(function(e) { $('#srv_wysiwyg_tools').addClass('out'); }); $par.find("input, textarea").focus(function(e) { $('#srv_wysiwyg_tools, .srv_adminBox').removeClass('out'); }); a = ed; }); } }); } function srv_wysiwyg_insert_html_at_cursor(h){ tinyMCE.execCommand('mceInsertContent', false, h); return; } function srv_get_content(){ return tinyMCE.activeEditor.getContent({format:'raw'}); } function srv_set_content(h){ tinyMCE.activeEditor.setContent(h,{format:'raw'}); return } function srv_put_link(){ var inst = tinyMCE.activeEditor; var elm, elementArray, i; elm = inst.selection.getNode(); elm = inst.dom.getParent(elm, "A"); // Remove element if there is no href if (($("#srv_link_url").val() == '' )|| ($('#srv_link_url').val() == 'http://')) { tinyMCE.execCommand("mceBeginUndoLevel"); i = inst.selection.getBookmark(); inst.dom.remove(elm, 1); inst.selection.moveToBookmark(i); tinyMCE.execCommand("mceEndUndoLevel"); alert('You must put a link in the box'); return false; } if(tinyMCE.activeEditor.selection.isCollapsed()) { if($("#srv_link_title").val().length > 0) { inst.selection.setContent('<span class="servee-auto-place">'+$("#srv_link_title").val()+'</span>'); } else { inst.selection.setContent('<span class="servee-auto-place">'+$("#srv_link_url").val())+'</span>'; } elementArray = tinymce.grep(inst.dom.select("span"), function(n) {return inst.dom.getAttrib(n, 'class') == 'servee-auto-place';}); inst.dom.removeClass(elementArray,'servee-auto-place'); inst.selection.select(elementArray[0]); } tinyMCE.execCommand("mceBeginUndoLevel"); // Create new anchor elements if (elm == null) { tinyMCE.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1}); elementArray = tinymce.grep(inst.dom.select("a"), function(n) {return inst.dom.getAttrib(n, 'href') == '#mce_temp_url#';}); for (i=0; i<elementArray.length; i++) srv_setAllAttribs(elm = elementArray[i]); } else srv_setAllAttribs(elm); tinyMCE.execCommand("mceEndUndoLevel"); return false; } function srv_setAllAttribs(elm) { var inst = tinyMCE.activeEditor; inst.dom.setAttrib(elm, 'href', $("#srv_link_url").val()) if($("#srv_link_title").val().length > 0) { inst.dom.setAttrib(elm, 'title', $("#srv_link_title").val()); } if($("#srv_link_new_window:checked").length == 1) { inst.dom.setAttrib(elm, 'target', '_blank'); } } $("a.srv_bold").click(function(e){ tinyMCE.activeEditor.execCommand("Bold"); e.preventDefault(); return false; }); $("a.srv_italic").click(function(e){ tinyMCE.activeEditor.execCommand("Italic"); e.preventDefault(); return false; }); $("a.srv_underline").click(function(e){ tinyMCE.activeEditor.execCommand("underline"); e.preventDefault(); return false; }); $("a.srv_blockquote").click(function(e){ tinyMCE.activeEditor.execCommand("formatblock",false,"blockquote");; e.preventDefault(); return false; }); $("a.srv_bullet").click(function(e){ tinyMCE.activeEditor.execCommand("insertunorderedlist");; e.preventDefault(); return false; }); $("a.srv_number").click(function(e){ tinyMCE.activeEditor.execCommand("insertorderedlist");; e.preventDefault(); return false; }); $("a.srv_unlink").click(function(e){ tinyMCE.activeEditor.execCommand("unlink"); e.preventDefault(); return false; }); $("a.srv_undo").click(function(e){ tinyMCE.activeEditor.execCommand("undo"); e.preventDefault(); return false; }); $("a.srv_redo").click(function(e){ tinyMCE.activeEditor.execCommand("redo"); e.preventDefault(); return false; }); $("a.srv_hr").click(function(e){ tinyMCE.activeEditor.execCommand("inserthorizontalrule");; e.preventDefault(); return false; }); $("a.srv_word").click(function(e){ pasteWord() e.preventDefault(); return false; }); $("a.srv_spell").click(function(e){ tinyMCE.activeEditor.execCommand("mceWritingImprovementTool"); e.preventDefault(); return false; }); $('a.f-block').click(function(e){ var p = $(this).parent()[0].nodeName.toLowerCase(); tinyMCE.activeEditor.execCommand('formatblock',false,p); e.preventDefault(); return true; });
import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import MoviesApp from './moviesApp/moviesApp.js'; render(( <BrowserRouter > <MoviesApp /> </BrowserRouter> ), document.getElementById('movies-app'));
const db = require('../../core/config/sequalize'), Crypto = require('crypto-js'), crypto = require('crypto'); exports.mapUserToResponseModel = (user) => { const userTypes = []; if (user.is_expert) { userTypes.push('expert'); } userTypes.push('user'); return { id: user.id, firstName: user.first_name, lastName: user.last_name, email: user.email, isExpert: user.is_expert, userTypes } }; exports.getUser = async (email, raw) => { const user = await db.user.findOne({ where: { email } }); if(!raw) { return exports.mapUserToResponseModel(user); } return user; } exports.saveUser = async (user) => { const salt = crypto.randomBytes(16).toString('hex'); const passwordAndSalt = user.password + salt; const password = Crypto.SHA256(passwordAndSalt).toString(); const createdUser = await db.user.create({ first_name: user.firstName, last_name: user.lastName, salt: salt, email: user.email, password: password, is_expert: false }); return exports.mapUserToResponseModel(createdUser.dataValues) }
var express = require('express'); var mongoose = require('mongoose'); var db = require('./config.js') var Inventory = require('./inventory.js'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.json()); app.use(express.static('public')); app.post('/api/inventory', function(req, res, next) { var myInventory = new Inventory({ light: req.body.jacket }) myInventory.save(function (err, jacket) { if (err) { return next(err) } res.json(201, jacket) }) }); app.get('/api/inventory', function(req, res, next) { Inventory.findOne({light: 'A\'s Letterman'}, function (err, jacket) { if (err) return handleError(err); res.json(200, jacket); console.log('got here'); }) }) app.listen(3000);
var assert = require("assert") describe(' basic mocha test', () => { it ('thorw some errors', () => { assert.equal(3,3) // try { // assert.equal(2,3) // } // catch(e){ // console.log(e) // } // throw({message: 'some error'}) }) })
// HunterDouglas Platinum Shades plugin for HomeBridge // // Remember to add platform to config.json. Example: // "platforms": [ // { // "platform": "HunterDouglas", // "name": "Hunter Douglas", // "ip_address": "127.0.0.1", // "port": 522 // } // ], // // If you do not know the IP address of your Bridge, open the "Platinum Shade Controller" app // and navgate to Settings within the app and look for "Bridge IP". // // // When you attempt to add a device, it will ask for a "PIN code". // The default code for all HomeBridge accessories is 031-45-154. // "use strict"; var hd = require("node-hunterdouglas"); var Service, Characteristic, UUIDGen; module.exports = function(homebridge) { Service = homebridge.hap.Service; Characteristic = homebridge.hap.Characteristic; UUIDGen = homebridge.hap.uuid; homebridge.registerPlatform("homebridge-hunterdouglas", "HunterDouglas", HunterDouglasPlatform); } function HunterDouglasPlatform(log, config) { this.log = log; this.ip_address = config["ip_address"]; this.port = config["port"]; if (typeof this.port === "undefined") { this.port = 522; } } function HunterDouglasAccessory(log, device, hd, platform) { this.id = UUIDGen.generate(device.name); this.name = device.name; this.blinds = device.blinds; this.hd = hd; this.log = log; this.platform = platform; this.currentPosition = this.blinds[0].position; this.targetPosition = this.blinds[0].position; this.positionState = 2; // Stopped } HunterDouglasPlatform.prototype = { lastUpdated: new Date(), accessories: function (callback) { this.log("Fetching Hunter Douglas Blinds..."); var that = this; let blindController = hd({ ip: this.ip_address, port: this.port }); blindController.setup().then(function (blinds) { let foundAccessories = []; Object.keys(blinds).forEach(function (key) { let blind = blinds[key]; var accessory = new HunterDouglasAccessory(that.log, blind, blindController, that); foundAccessories.push(accessory); }); callback(foundAccessories); }); }, updateValues: function () { let that = this; blindController.setup().then(function (blinds) { Object.keys(blinds).forEach(function (key) { let blind = blinds[key]; let id = UUIDGen.generate(blind.name); let index = that.accessories.map(a => a.id).indexOf(id); if (index !== -1) { let accessory = that.accessories[index]; accessory.currentPosition = blind.blinds[0].position; accessory.targetPosition = blind.blinds[0].position; accessory.positionState = 2; // Stopped } }); }); } }; HunterDouglasAccessory.prototype = { // Convert 0-100 to 0-1 posToPercent: function (value) { value = value / 100 return value; }, percentToPos: function (value) { value = value * 100; value = Math.round(value); return value; }, getValue: function (characteristic) { switch(characteristic.toLowerCase()) { case 'pos': return this.percentToPos(this.currentPosition); case 'target': return this.percentToPos(this.targetPosition); case 'state': return this.positionState; default: return null; } }, // Set blind state executeChange: function (characteristic, value, callback) { var that = this; switch (characteristic.toLowerCase()) { case 'pos': this.currentPosition = this.posToPercent(value); callback(); break; case 'target': this.targetPosition = this.posToPercent(value); this.hd.move(this.name, this.targetPosition).then(function () { setTimeout(function () { that.currentPosition = that.targetPosition; that.positionState = 2; // Not moving callback(); }, 500); }); break; case 'state': this.positionState = value; callback(); break; } }, // Read blind state getState: function (characteristic, callback) { callback(null, this.getValue(characteristic)); }, // Respond to identify request identify: function(callback) { this.log(this.name, "Identify"); callback(); }, // Get Services getServices: function() { var that = this; // Use HomeKit types defined in HAP node JS var blindService = new Service.WindowCovering(this.name); blindService .getCharacteristic(Characteristic.CurrentPosition) .on('get', function(callback) { that.getState("pos", callback);}) .on('set', function(value, callback) { that.executeChange("pos", value, callback);}) .value = this.getValue("pos"); blindService .getCharacteristic(Characteristic.PositionState) .on('get', function(callback) { that.getState("state", callback);}) .on('set', function(value, callback) { that.executeChange("state", value, callback);}) .value = this.getValue("state"); blindService .getCharacteristic(Characteristic.TargetPosition) .on('get', function(callback) { that.getState("target", callback);}) .on('set', function(value, callback) { that.executeChange("target", value, callback);}) .value = this.getValue("target"); var informationService = new Service.AccessoryInformation(); informationService .setCharacteristic(Characteristic.Manufacturer, "HunterDouglas") .setCharacteristic(Characteristic.SerialNumber, this.name); return [informationService, blindService]; } };
import { shuffleArray } from "./utils"; export const URLS = shuffleArray([ "https://findtheinvisiblecow.com/", "https://www.mapcrunch.com/", "https://theuselessweb.com/", "http://hackertyper.com/", "http://papertoilet.com/", "https://pointerpointer.com/", "http://www.staggeringbeauty.com/", "https://screamintothevoid.com/", "http://www.shadyurl.com/", "https://archive.org/web/", "http://dontevenreply.com/", "https://stellarium-web.org/", "http://www.shutupandtakemymoney.com/", "https://play2048.co/", "https://en.wikipedia.org/wiki/List_of_individual_dogs", "https://zoomquilt.org/", "https://mlh.io/", "https://freerice.com/categories/english-vocabulary", "https://apod.nasa.gov/apod/astropix.html", "https://www.duolingo.com/", "https://www.internetlivestats.com/", "https://thisissand.com/", "https://lizardpoint.com/", "https://www.musictheory.net/", "https://radiooooo.com/", "https://sleepyti.me/", "https://trypap.com/", "https://www.codecademy.com/", "https://29a.ch/sandbox/2011/neonflames/#", "https://explore.org/livecams/cats/kitten-rescue-cam", "https://myfridgefood.com/", "https://www.onread.com/", "https://www.omfgdogs.com/#", "http://weavesilk.com/", "https://eyebleach.me/", "https://en.wikipedia.org/wiki/List_of_conspiracy_theories", "http://sanger.dk/", "https://pokemonshowdown.com/", "https://www.sporcle.com/", "https://www.poptropica.com/", "https://koalabeast.com/", "http://orteil.dashnet.org/cookieclicker/", "https://habitica.com/static/front", "http://www.foddy.net/2010/10/qwop/", "http://www.flashbynight.com/", "https://xkcd.com/", "http://youarelistening.to/", "https://www.incredibox.com/", "https://asoftmurmur.com/", "https://www.rainymood.com/", "http://flashbynight.com/drench/", "https://quickdraw.withgoogle.com/", "https://www.dafont.com/", "https://spacejam.com/", "https://www.mint.com/", "https://tastedive.com/", "https://www.addictivetips.com/", "https://archive.org/details/msdos_Oregon_Trail_The_1990", "https://www.instructables.com/", "https://www.snopes.com/", "http://themagicipod.com/", "https://lifehacker.com/", "https://mix.com/", "https://localhackday.mlh.io/", "https://www.wizardingworld.com/", "https://www.lego.com/en-us/kids", "https://www.marvel.com/comics", "https://www.dccomics.com/comics", "https://www.darkhorse.com/Comics/", "https://www.cbr.com/", "https://comicbook.com/comics/", "https://screenrant.com/", "https://bleedingfool.com/", "https://www.penny-arcade.com/", "https://www.adastrasteammedia.com/intergalacticacademy", "https://mara-comic.com/", "https://dilbert.com/", "https://comicsverse.com/", "https://victoriatb123adoba.wixsite.com/website-1", "https://www.reddit.com/r/comics/", "https://www.reddit.com/r/comicbooks/", "https://www.dailykos.com/blog/Comics", "https://bleedingcool.com/comics/", "https://questionablecontent.net/", "https://killsixbilliondemons.com/comic/", "https://blog.comicspriceguide.com/", "https://www.comiccrusaders.com/", "https://undercovercapes.com/", "https://aiptcomics.com", "https://sdccblog.com/", "http://www.9mood.com/", "https://www.comicbookaddicts.com/", "https://www.howtolovecomics.com/", "https://thegww.com/category/comics-3/", "https://comicyears.com/", "http://westfieldcomics.com/blog/", "https://geeksofdoom.com/", "http://www.tcj.com/", "https://joshreads.com/", "https://comichron.com/blog/", "https://attackongeek.com/", "https://www.supermansupersite.com/index.php", "https://www.youdontreadcomics.com/", "http://berkeleyplaceblog.com/", "https://www.dorkaholics.com/", "https://www.animatedapparelcompany.com/a/blog", "https://thanley.wordpress.com/", "https://www.weirdsciencedccomics.com/", "https://thebatmanuniverse.net/", "https://comicstrove.com/", "https://thecomicvault.wordpress.com/", "https://www.spidermancrawlspace.com/", "http://thehorrorsofitall.blogspot.com/", "http://talkingcomicbooks.com/", "http://www.twogag.com/", "http://michelfiffe.com/", "https://marvel-dc-art.tumblr.com/", "https://fourcolorapocalypse.wordpress.com/", "http://studygroupcomics.com/main/", "https://50yearoldcomics.com/", "http://www.spartantown.net/", "https://www.blogofoa.com/", "https://xmen-supreme.blogspot.com/", "http://doctordcpodcast.ca/", "https://duckcomicsrevue.blogspot.com/", "https://martinohearn.blogspot.com/", "https://davescomicheroes.blogspot.com/", "https://fuzzypoet.com/", "https://psychostick.com/comics", "http://phoenixseattle.com/category/comics/", "http://lewstringercomics.blogspot.com/", "http://www.lanterncast.com/", "http://edgosney.com/", "https://comicstalkblog.com/", "https://comicsforever.tumblr.com/", "http://highlowcomics.blogspot.com/", "http://www.thepcg.uk/", "https://tapas.io/", "http://fromearthsend.blogspot.com/", "https://mrjarvis98.blogspot.com/", "https://pappysgoldenage.blogspot.com/", "http://oldcomicsworld.blogspot.com/", "https://forbiddenplanet.co.uk/category/comics/", "https://comicboxcommentary.blogspot.com/", "http://libraryofamericancomics.com/blog/", "https://thejadegiant.wordpress.com/", "https://paintedcomic.wordpress.com/", "https://longboxjunk.blogspot.com/", "https://classicxmen.tumblr.com/", "https://retcon-punch.com/", "https://www.superchum.com/updates", "https://thebrownbagaeccb.blogspot.com/", "https://drunkencatcomics.com/", "https://comicspectrumblog.wordpress.com/", "https://www.comicart.tips/blog/", "https://www.comicsreporter.com/", "https://alteregocomics.com/blog/", "http://www.unsungsuperheroes.com/blog/", "https://www.comicbookherald.com/", "https://socialmomus.com/", "https://www.suficomics.com/blog/", "https://www.bizarro.com/", "https://playvalorant.com/en-us/", "https://www.epicgames.com/fortnite/en-US/home?sessionInvalidated=true", "https://na.leagueoflegends.com/en-us/", "https://www.ubisoft.com/en-gb/game/rainbow-six/siege", "https://www.ubisoft.com/en-gb/game/watch-dogs/legion", "https://store.ubi.com/ie/assassin-s-creed-franchise-all-games", "https://www.cyberpunk.net/in/en/", "https://osu.ppy.sh/home", "https://www.minecraft.net/en-us", "https://www.rockstargames.com/V/", "https://worldofwarcraft.com/", "https://www.animal-crossing.com/new-horizons/", "https://www.rockstargames.com/reddeadredemption2/", "https://www.roblox.com/", "https://www.residentevil.com/village/", "https://www.pubg.com/", "https://godofwar.playstation.com/", "https://playoverwatch.com/", "https://pokemongolive.com/", "https://www.half-life.com/", ]);
import Link from 'next/link' export default ({ sideNav, children }) => ( <nav className='blue darken-4'> <div className='nav-wrapper'> <a href='#' data-activates='mobile-nav' className='button-collapse'><i className='material-icons'>menu</i></a> <ul className='left hide-on-med-and-down'> <li><Link href='/'><a>Home</a></Link></li> </ul> { children } </div> </nav> )
// @flow import React, { Component } from "react"; import { Container, Button, Text, Input, Item, Icon, Spinner, List, ListItem, Body // $FlowFixMe } from "native-base"; import store from "../store/store"; import type { Repo } from "./Repo"; type GitReposState = { repos: Repo[], filterByStr: string, projectsToCompare: Repo[], fetchFailed: boolean, fetchError: string, org: string }; type GitRepoProps = { navigation: any }; class GitRepos extends Component<GitRepoProps, GitReposState> { constructor(props: GitRepoProps) { super(props); this.state = { repos: [], filterByStr: "", projectsToCompare: [], fetchFailed: false, fetchError: "", org: "" }; } componentDidMount() { // this.unsubscribe = store.subscribe(() => { store.subscribe(() => { const storeState = store.getState(); this.setState({ repos: storeState.projects, projectsToCompare: storeState.projectsToCompare, fetchFailed: storeState.fetchFailed, fetchError: storeState.fetchError, org: storeState.organizationName }); }); this.fetchReposByOrg(store.getState().organizationName); } componentWillUnmount() { store.dispatch({ type: "REMOVE_ALL_PROJECTS_FROM_COMPARE_LIST" }); // this.unsubscribe(); } generateGetReposByOrgUrl(org: string) { return `https://api.github.com/orgs/${org}/repos`; } fetchReposByOrg(org: string) { // eslint-disable-next-line no-undef fetch(this.generateGetReposByOrgUrl(org)) .then(async resp => { if (resp.status !== 200) { throw Error((await resp.json()).message); } else { return resp; } }) .then(resp => resp.json()) .then((repos: Repo[]) => { store.dispatch({ type: "SET_PROJECTS", payload: repos }); }) .catch(e => { this.setState({ fetchFailed: true, fetchError: e.message }); }); } addToCompare(repo: Repo) { store.dispatch({ type: "ADD_REPO_TO_COMPARE_LIST", payload: repo }); store.dispatch({ type: "REMOVE_PROJECT_FOCUS", payload: repo }); } projectBriefInfoOnClick = (repo: Repo) => { store.dispatch({ type: "SET_PROJECT_FOCUS", payload: repo }); }; projectFullInfoOnClick = (repo: Repo) => { store.dispatch({ type: "REMOVE_PROJECT_FOCUS", payload: repo }); }; renderBriefRepoInfo(repo: Repo) { return <Text onPress={() => this.projectBriefInfoOnClick(repo)}>{repo.name}</Text>; } toggleProjectListItem = (repo: Repo) => { const { projectsToCompare } = this.state; if (projectsToCompare.includes(repo)) { store.dispatch({ type: "REMOVE_REPO_FROM_COMPARE_LIST", payload: repo }); } else { store.dispatch({ type: "ADD_REPO_TO_COMPARE_LIST", payload: repo }); } }; renderRepos(repos: Repo[]) { const selectedRepos = this.state.projectsToCompare; const notSelected = repos.filter(r => selectedRepos.indexOf(r) === -1); return ( <List dataArray={notSelected} renderRow={(repo: Repo) => ( <ListItem onPress={() => this.toggleProjectListItem(repo)}> <Body> <Text>{repo.name}</Text> </Body> </ListItem> )} /> ); } filterReposByStr(repos: Repo[], substr: string) { const subStrLowerCase = substr.toLowerCase(); return repos.filter(repo => repo.name.toLowerCase().includes(subStrLowerCase)); } renderCompareButton() { const selectedReposAmount = this.state.projectsToCompare.length; if (selectedReposAmount < 2) { return null; } return ( <Button bordered success active={false} style={{ alignSelf: "center", bottom: 20 }} onPress={() => this.props.navigation.navigate("Comparator")} > <Text>Compare {selectedReposAmount}</Text> </Button> ); } render() { const { repos, filterByStr, org, fetchFailed, fetchError } = this.state; if (repos.length === 0 && fetchFailed === false) { return ( <Container style={{ flex: 1, justifyContent: "center", alignItems: "center" }} > <Text>Loading repos...</Text> ; <Spinner color="green" /> </Container> ); } if (fetchFailed === true) { return ( <Container style={{ flex: 1, justifyContent: "center", alignItems: "center" }} > <Text>{`Error during fetch: ${fetchError}`}</Text> ; </Container> ); } const filteredRepos = this.filterReposByStr(repos, filterByStr); return ( <Container> <Item> <Icon name="ios-search" /> <Input placeholder="Project name" onChangeText={(text: string) => this.setState({ filterByStr: text })} /> </Item> <Text style={{ textAlign: "center" }}>Repos by {org}</Text> {this.renderRepos(filteredRepos)} {this.renderCompareButton()} </Container> ); } } export default GitRepos;
const User = require('./user'); const john = new User('John Doe'); console.log(john.getUser());
/** * 全局动画配置 * @author: terry <jfengsky@gmail.com> * @date: 2013-10-21 10:47 */ define(function(require, exports, module) { var $ = require('jquery'); $('.tableTh, .saletable').delegate('a.del', 'click', function(){ $(this).parents('tr').fadeOut(); }); // module.exports = Move; });
const express = require("express"); const router = express.Router(); const getProjectSummary = require("../library/getProjectSummary"); const getProteoform = require("../library/getProteoform"); /** * Express router for /seqQuery * * Query proteoform by projectCode and scan, * send back proteoform result to user */ const seqQuery = router.get('/seqQuery', function (req, res) { let projectDir = req.query.projectDir; let projectCode = req.query.projectCode; let scanNum = req.query.scanID; getProjectSummary(projectCode,function (err,row) { let seqStatus = row.sequenceStatus; if(seqStatus === 1) { let proteoform = getProteoform(projectDir, scanNum); if (proteoform !== 0) { //console.log(proteoform) res.write(JSON.stringify(proteoform)); res.end(); } else { res.write('0'); res.end(); } } else { res.write('0'); res.end(); } }); }); module.exports = seqQuery;
import { createStore, applyMiddleware } from "redux"; import { persistReducer } from "redux-persist"; import { composeWithDevTools } from 'redux-devtools-extension' import storage from "../redux/storage"; import rootReducers from "./reducers/index"; import thunk from "redux-thunk"; const persistConfig = { timeout: 0, key: "root", storage, }; const persistedReducer = persistReducer(persistConfig, rootReducers); export const initializeStore = () => { return createStore( persistedReducer, composeWithDevTools(applyMiddleware(thunk)) ); };
// Created by Boris Schneiderman. // Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. define(function() { /** * Used to report pagination state back to the host application * * @class Models.CurrentPagesInfo * * @constructor * * @param {Models.Spine} spine * @param {boolean} isFixedLayout is fixed or reflowable spine item * @return CurrentPagesInfo */ var CurrentPagesInfo = function(spine, isFixedLayout) { /** * The reading direction * * @property isRightToLeft * @type bool */ this.isRightToLeft = spine.isRightToLeft(); /** * Is the ebook fixed layout or not? * * @property isFixedLayout * @type bool */ this.isFixedLayout = isFixedLayout; /** * Counts the number of spine items * * @property spineItemCount * @type number */ this.spineItemCount = spine.items.length /** * returns an array of open pages, each array item is a data structure (plain JavaScript object) with the following fields: spineItemPageIndex, spineItemPageCount, idref, spineItemIndex (as per the parameters of the addOpenPage() function below) * * @property openPages * @type array */ this.openPages = []; /** * Adds an page item to the openPages array * * @method addOpenPage * @param {number} spineItemPageIndex * @param {number} spineItemPageCount * @param {string} idref * @param {number} spineItemIndex */ this.addOpenPage = function(spineItemPageIndex, spineItemPageCount, idref, spineItemIndex) { this.openPages.push({spineItemPageIndex: spineItemPageIndex, spineItemPageCount: spineItemPageCount, idref: idref, spineItemIndex: spineItemIndex}); this.sort(); }; /** * Checks if navigation to the page on the left is possible (depending on page-progression-direction: previous page in LTR mode, next page in RTL mode) * * @method canGoLeft * @return bool true if turning to the left page is possible */ this.canGoLeft = function () { return this.isRightToLeft ? this.canGoNext() : this.canGoPrev(); }; /** * Checks if navigation to the page on the right is possible (depending on page-progression-direction: next page in LTR mode, previous page in RTL mode) * * @method canGoRight * @return bool true if turning to the right page is possible */ this.canGoRight = function () { return this.isRightToLeft ? this.canGoPrev() : this.canGoNext(); }; /** * Checks if navigation to the next page is possible (depending on page-progression-direction: right page in LTR mode, left page in RTL mode) * * @method canGoNext * @return bool true if turning to the next page is possible */ this.canGoNext = function() { if(this.openPages.length == 0) return false; var lastOpenPage = this.openPages[this.openPages.length - 1]; // TODO: handling of non-linear spine items ("ancillary" documents), allowing page turn within the reflowable XHTML, but preventing previous/next access to sibling spine items. Also needs "go back" feature to navigate to source hyperlink location that led to the non-linear document. // See https://github.com/readium/readium-shared-js/issues/26 // Removed, needs to be implemented properly as per above. // See https://github.com/readium/readium-shared-js/issues/108 // if(!spine.isValidLinearItem(lastOpenPage.spineItemIndex)) // return false; return lastOpenPage.spineItemIndex < spine.last().index || lastOpenPage.spineItemPageIndex < lastOpenPage.spineItemPageCount - 1; }; /** * Checks if navigation to the previous page is possible (depending on page-progression-direction: left page in LTR mode, right page in RTL mode) * * @method canGoPrev * @return bool true if turning to the previous page is possible */ this.canGoPrev = function() { if(this.openPages.length == 0) return false; var firstOpenPage = this.openPages[0]; // TODO: handling of non-linear spine items ("ancillary" documents), allowing page turn within the reflowable XHTML, but preventing previous/next access to sibling spine items. Also needs "go back" feature to navigate to source hyperlink location that led to the non-linear document. // See https://github.com/readium/readium-shared-js/issues/26 // Removed, needs to be implemented properly as per above. // //https://github.com/readium/readium-shared-js/issues/108 // if(!spine.isValidLinearItem(firstOpenPage.spineItemIndex)) // return false; return spine.first().index < firstOpenPage.spineItemIndex || 0 < firstOpenPage.spineItemPageIndex; }; /** * Sorts the openPages array based on spineItemIndex and spineItemPageIndex * * @method sort */ this.sort = function() { this.openPages.sort(function(a, b) { if(a.spineItemIndex != b.spineItemIndex) { return a.spineItemIndex - b.spineItemIndex; } return a.spineItemPageIndex - b.spineItemPageIndex; }); }; }; return CurrentPagesInfo; });
/* Write a function that accepts two arguments: an array of integers and another integer n. Determine the number of times where two integers in the array have a difference of n. For example: int_diff([1, 1, 5, 6, 9, 16, 27], 4) # 3 ([1, 5], [1, 5], [5, 9]) int_diff([1, 1, 3, 3], 2) # 4 ([1, 3], [1, 3], [1, 3], [1, 3]) Note: your code should not modify the input array. */ function intDiff(nums, n) { let counter = 0; for (let i = 0; i < nums.length; i++) { let currNum = nums[i]; for (let j = i + 1; j < nums.length; j++) { let otherNum = nums[j]; if (Math.abs(currNum - otherNum) === n) counter++; } } return counter; }
import React, { useState, useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import { Input, Button, List, ListItem } from '@material-ui/core' import { postMessageAction, getMessagesAction, } from 'Utilities/redux/messageReducer' const MessageComponent = () => { const dispatch = useDispatch() const [message, setMessage] = useState('') const messages = useSelector(({ messages }) => messages.data.sort((a, b) => a.body.localeCompare(b.body)), ) const postMessage = () => { dispatch(postMessageAction({ message })) setMessage('') } useEffect(() => { dispatch(getMessagesAction()) }, [messages.length]) return ( <div style={{ paddingTop: '1em' }}> <Input id="message" value={message} onChange={(e) => setMessage(e.target.value)} /> <Button variant="contained" color="primary" onClick={() => postMessage()}> Send! </Button> <List> {messages.map((m) => ( <ListItem key={m.id}>{m.body}</ListItem> ))} </List> </div> ) } export default MessageComponent
import React, { useState, useEffect } from "react"; import axios from "axios"; function SearchInput({ searchHandler }) { return ( <div> find countries: <br /> <input onChange={searchHandler} /> </div> ); } function CountryDisplay({ country }) { const languages = country.languages; const countryUrl = country.flag; return ( <> <h1>{country.name}</h1> <p>Capital: {country.capital}</p> <p>Population: {country.population}</p> <h2>Languages</h2> <ul> {languages.map((language) => ( <li key={language.name}>{language.name}</li> ))} </ul> <img src={countryUrl} alt="flag img" /> </> ); } function WeatherDisplay(props) { console.log("In weather display"); console.log(props.weather); if (props.weather === undefined) { return <p>Loading ...</p>; } else { console.log("In component:"); console.log(props.weather); const weather_img = props.weather.current.weather_icons[0]; return ( <div> <h2>Weather in {props.weather.location.name}</h2> <p> <b>temperature</b>: {props.weather.current.temperature} Celcius </p> <img src={weather_img} alt="" /> <p> <b>wind:</b> {props.weather.current.wind_speed} mph, direction{" "} {props.weather.current.wind_dir} </p> </div> ); } } function CountriesDisplay({ filteredCountries, setShowCountry, showCountry, getWeather, weather, }) { if (filteredCountries.length > 10) { return ( <> <p>Too many results, be more specific</p> </> ); } else if (filteredCountries.length === 1) { const country = filteredCountries[0]; <CountryDisplay country={country} />; } else { return ( <div> {filteredCountries.map((country) => ( <div key={country.name} style={{ display: "flex", alignItems: "center", }} > <p>{country.name}</p> <button country={country.name} onClick={() => { setShowCountry(country); getWeather(country.capital); }} > show </button> </div> ))} {showCountry.name && <CountryDisplay country={showCountry} />} {showCountry.name && <WeatherDisplay weather={weather} />} </div> ); } } function App() { const [countries, setCountries] = useState([]); const [weather, setWeather] = useState(); const [searchFilter, setSearchFilter] = useState(""); const [showFiltered, setShowFiltered] = useState(false); const [showCountry, setShowCountry] = useState({}); const api_key = process.env.REACT_APP_WEATHER_API_KEY; const getCountries = () => { axios.get("https://restcountries.eu/rest/v2/all").then((response) => { console.log("countries promise fulfilled"); setCountries(response.data); }); }; const getWeather = (countryName) => { const urlCountry = countryName.replace(" ", "_"); axios .get( `http://api.weatherstack.com/current?access_key=${api_key}&query=${urlCountry}` ) .then((response) => { console.log("weather promise fulfilled"); const weatherData = response.data; console.log(response.data); setWeather(weatherData); }); }; useEffect(getCountries, []); const filteredCountries = showFiltered ? countries.filter((country) => country.name.toLowerCase().includes(searchFilter.toLowerCase()) ) : countries; const searchHandler = (event) => { setSearchFilter(event.target.value); if (searchFilter.length !== 0) { setShowFiltered(true); } else { setShowFiltered(false); } }; return ( <> <SearchInput searchHandler={searchHandler} /> <CountriesDisplay filteredCountries={filteredCountries} setShowCountry={setShowCountry} showCountry={showCountry} getWeather={getWeather} weather={weather} /> </> ); } export default App;
import Vue from 'vue' import VueSemantic from 'croud-vue-semantic' import Loader from '../../../src/components/shared/misc/ProfileHeader' import CroudImageUploader from '../../../src/components/shared/misc/ImageUploader' import CroudAvatar from '../../../src/components/shared/misc/Avatar' import '../../../semantic/dist/semantic' Vue.use(VueSemantic) Vue.component('CroudImageUploader', CroudImageUploader) Vue.component('CroudAvatar', CroudAvatar) const Constructor = Vue.extend(Loader) const vm = new Constructor({ propsData: { user: { name: 'test', first_name: 'test', last_name: 'test', avatar: '', email: 'test', }, readOnly: false, }, }).$mount() describe('Profile header', () => { it('should match the snapshot', () => { expect(vm.$el).toMatchSnapshot() }) describe('read only', () => { beforeEach(() => { vm.readOnly = true }) it('should match the snapshot', () => { expect(vm.$el).toMatchSnapshot() }) }) })
import React, { Fragment } from "react"; import "./css/style.css" const Portafolio = () => { return( <Fragment> <div id="notfound"> <div className="notfound"> <div className="notfound-404"> <h1>404</h1> </div> <h2>Oops! No se pudo encontrar esta página</h2> <p>Lo sentimos, pero la página que busca no existe, ha sido eliminada. el nombre ha cambiado o no está disponible temporalmente</p> <a href="/">Ir a la página de inicio</a> </div> </div> </Fragment> ); }; export default Portafolio
/*global ODSA,MathJax */ // Written by Mohammed Farghally and Cliff Shaffer // Expanding a Divide and Conquer Recurrence $(document).ready(function() { "use strict"; var av_name = "ExpandRecurrenceCON"; // Load the config object with interpreter and code created by odsaUtils.js var config = ODSA.UTILS.loadConfig({av_name: av_name}), interpret = config.interpreter; // get the interpreter var av; var tree; var leftAlign = 10; var topAlign = 20; var nodeGap = 25; var nodeHeight = 33; var nodeWidth = 45; var labelShift = 50; var labelSet; av = new JSAV(av_name); labelSet = new Array(); MathJax.Hub.Config({tex2jax: {inlineMath: [["$", "$"], ["\\(", "\\)"]]}}); $(".avcontainer").on("jsav-message", function() { // invoke MathJax to do conversion again MathJax.Hub.Queue(["Typeset", MathJax.Hub]); }); // Slide 1 av.umsg(interpret("sc1")); av.displayInit(); // Slide 2 av.umsg(interpret("sc2.1")); av.umsg(interpret("sc2.2"), {preserve: true}); tree = av.ds.binarytree({left: leftAlign, top: topAlign, nodegap: nodeGap}); var root = tree.newNode("$n$"); tree.root(root); var nOverTwo1 = tree.newNode("$n/2$"); var nOverTwo2 = tree.newNode("$n/2$"); root.addChild(nOverTwo1); root.addChild(nOverTwo2); tree.layout(); var workLabel = av.label("<b><u>Amount of Work</u></b>", {top: topAlign - 15, left: leftAlign + 250, After: root}); labelSet.push(workLabel); var dashLabel_n = av.label("----------------------------------", {top: topAlign + 0.25 * nodeHeight, left: leftAlign + nodeWidth + labelShift}); labelSet.push(dashLabel_n); var valueLabel_1 = av.label("$5n^2$", {top: topAlign + 0.25 * nodeHeight, left: leftAlign + nodeWidth + labelShift * 5}); labelSet.push(valueLabel_1); av.step(); // Slide 3 av.umsg(interpret("sc3.1")); av.umsg(interpret("sc3.2"), {preserve: true}); displaceLabels(2 * nodeWidth); var dashLabel_n2 = av.label("----------------------", {top: topAlign + 1.25 * nodeHeight + nodeGap, left: leftAlign + nodeWidth + labelShift * 4}); labelSet.push(dashLabel_n2); var valueLabel_2 = av.label("$\\frac{5n^2}{2}$", {top: topAlign + 1.25 * nodeHeight + nodeGap, left: leftAlign + 3 * nodeWidth + labelShift * 5}); labelSet.push(valueLabel_2); var nOverFour1 = tree.newNode("$n/4$"); var nOverFour2 = tree.newNode("$n/4$"); var nOverFour3 = tree.newNode("$n/4$"); var nOverFour4 = tree.newNode("$n/4$"); nOverTwo1.addChild(nOverFour1); nOverTwo1.addChild(nOverFour2); nOverTwo2.addChild(nOverFour3); nOverTwo2.addChild(nOverFour4); tree.layout(); av.step(); // Slide 4 av.umsg(interpret("sc4.1")); av.umsg(interpret("sc4.2"), {preserve: true}); displaceLabels(5 * nodeWidth); labelSet.push(av.label("----------", {top: topAlign + 2.25 * nodeHeight + 2 * nodeGap, left: leftAlign + 7.5 * nodeWidth + labelShift * 4})); labelSet.push(av.label("$\\frac{5n^2}{4}$", {top: topAlign + 2.25 * nodeHeight + 2 * nodeGap, left: leftAlign + 8 * nodeWidth + labelShift * 5})); var nOverEight1 = tree.newNode("$n/8$"); var nOverEight2 = tree.newNode("$n/8$"); var nOverEight3 = tree.newNode("$n/8$"); var nOverEight4 = tree.newNode("$n/8$"); var nOverEight5 = tree.newNode("$n/8$"); var nOverEight6 = tree.newNode("$n/8$"); var nOverEight7 = tree.newNode("$n/8$"); var nOverEight8 = tree.newNode("$n/8$"); nOverFour1.addChild(nOverEight1); nOverFour1.addChild(nOverEight2); nOverFour2.addChild(nOverEight3); nOverFour2.addChild(nOverEight4); nOverFour3.addChild(nOverEight5); nOverFour3.addChild(nOverEight6); nOverFour4.addChild(nOverEight7); nOverFour4.addChild(nOverEight8); tree.layout(); av.step(); // Slide 5 av.umsg(interpret("sc5.1")); av.umsg(interpret("sc5.2"), {preserve: true}); //displaceLabels(2 * nodeWidth); labelSet.push(av.label("------", {top: topAlign + 4.25 * nodeHeight + 4 * nodeGap, left: leftAlign + 8 * nodeWidth + labelShift * 4})); labelSet.push(av.label("$7n$", {top: topAlign + 4.25 * nodeHeight + 4 * nodeGap, left: leftAlign + 8 * nodeWidth + labelShift * 5})); labelSet.push(av.label("---------------------------------------------------------------------------", {top: topAlign + 4.25 * nodeHeight + 4 * nodeGap, left: leftAlign + nodeWidth})); var one1 = tree.newNode("$1$"); var one2 = tree.newNode("$1$"); nOverEight1.left(one1); nOverEight8.right(one2); var edge1 = one1.edgeToParent(); var edge2 = one2.edgeToParent(); edge1.addClass("dashed"); edge2.addClass("dashed"); tree.layout(); av.step(); // Slide 6 av.umsg(interpret("sc6")); labelSet.push(av.label("|------------ $\\log{n + 1}$ ------------|", {top: topAlign + 3 * nodeHeight + nodeGap, left: leftAlign + 8.5 * nodeWidth + labelShift * 4 - 20}).addClass("rotated")); av.step(); // Slide 7 av.umsg(interpret("sc7")); av.step(); // Slide 8 av.umsg(interpret("sc8")); av.step(); // Slide 9 av.umsg(interpret("sc9")); av.recorded(); function displaceLabels(offset) { $.each(labelSet, function(index, value) { var current = value.css("left"); var currentPos = current.match(/\d+/); value.css({left: parseInt(currentPos, 10) + offset}); }); } });
import React from 'react'; import styled from 'styled-components'; //import Nabvar from './Navbar/Navbar' import Login from './Login/Login' import firebase from 'firebase'; firebase.initializeApp({ apiKey: "AIzaSyD6dwZetB7GNS528bQhV4lgB-pl34_n2X0", authDomain: "test-firebase-app-c039f.firebaseapp.com", databaseURL: "https://test-firebase-app-c039f.firebaseio.com", projectId: "test-firebase-app-c039f", storageBucket: "test-firebase-app-c039f.appspot.com", messagingSenderId: "4892780509" }); import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faHome } from '@fortawesome/free-solid-svg-icons' import { faIgloo } from '@fortawesome/free-solid-svg-icons' import { faKeyboard } from '@fortawesome/free-solid-svg-icons' import { faAddressCard } from '@fortawesome/free-solid-svg-icons' library.add(faHome) library.add(faIgloo) library.add(faKeyboard) library.add(faAddressCard) const App = () => ( <Login></Login> //<Nabvar name="asd"></Nabvar> ); export default App;
import { f, s } from "./helpers/index"; export default function Nonpreemptive({ processes, comparator, criteria }) { let uncompleted = processes.length; let readyQueue = processes.map((e) => ({ ...e })).sort(comparator); let clock = 0; let frames = []; let frame = null; let findCurrent = () => { let tPrIndex = readyQueue.findIndex((e) => { return e.arrivalTime <= clock; }); if (tPrIndex < 0) { clock += 1; return null; } for (let pId = 0; pId < readyQueue.length; pId++) { if (readyQueue[pId].arrivalTime <= clock) { if (readyQueue[pId][criteria] < readyQueue[tPrIndex][criteria]) { tPrIndex = pId; } } else { break; } } return tPrIndex; }; while (uncompleted) { const curIndex = findCurrent(); if (curIndex === null) { continue; } let running = readyQueue[curIndex]; // responseTime running.responseTime = clock - running.arrivalTime; frame = s(clock, running); clock += running.cpuTime; running.cpuTimeLeft = 0; // turnaroundTime running.turnaroundTime = clock - running.arrivalTime; // waitingTime running.waitingTime = running.turnaroundTime - running.cpuTime; // exitTime running.exitTime = clock; frames.push(f(frame, clock, "Finished", running)); readyQueue = readyQueue.filter((e, i) => { return i !== curIndex; }); uncompleted -= 1; } return { frames }; }
var Promise = require('bluebird'); var router = require('express').Router(); var activityModel = require('../../models/activity') router.get('/', function (req, res, next) { activityModel.findAll() .then(res.json.bind(res)) .catch(next) }) module.exports = router;
var searchData= [ ['orientation',['orientation',['../classRobot.html#affc0c754c8dc2133cb6171e9a34579fd',1,'Robot']]] ];
ejs.zip.Deflate = function(){ } ejs.zip.Deflate.prototype.MAX_BITS = 15; ejs.zip.Deflate.prototype.MAX_LITERAL_CODES = 286; ejs.zip.Deflate.prototype.MAX_LENGTH = 258; ejs.zip.Deflate.prototype.MIN_LENGTH = 3; ejs.zip.Deflate.prototype.MAX_DISTANCE = 32768; ejs.zip.Deflate.prototype.lengths = [ { bits : 0, lengthBase : 3, code : 257 }, { bits : 0, lengthBase : 4, code : 258 }, { bits : 0, lengthBase : 5, code : 259 }, { bits : 0, lengthBase : 6, code : 260 }, { bits : 0, lengthBase : 7, code : 261 }, { bits : 0, lengthBase : 8, code : 262 }, { bits : 0, lengthBase : 9, code : 263 }, { bits : 0, lengthBase : 10, code : 264 }, { bits : 1, lengthBase : 11, code : 265 }, { bits : 1, lengthBase : 13, code : 266 }, { bits : 1, lengthBase : 15, code : 267 }, { bits : 1, lengthBase : 17, code : 268 }, { bits : 2, lengthBase : 19, code : 269 }, { bits : 2, lengthBase : 23, code : 270 }, { bits : 2, lengthBase : 27, code : 271 }, { bits : 2, lengthBase : 31, code : 272 }, { bits : 3, lengthBase : 35, code : 273 }, { bits : 3, lengthBase : 43, code : 274 }, { bits : 3, lengthBase : 51, code : 275 }, { bits : 3, lengthBase : 59, code : 276 }, { bits : 4, lengthBase : 67, code : 277 }, { bits : 4, lengthBase : 83, code : 278 }, { bits : 4, lengthBase : 99, code : 279 }, { bits : 4, lengthBase : 115, code : 280 }, { bits : 5, lengthBase : 131, code : 281 }, { bits : 5, lengthBase : 163, code : 282 }, { bits : 5, lengthBase : 195, code : 283 }, { bits : 5, lengthBase : 227, code : 284 }, { bits : 0, lengthBase : 258, code : 285 } ]; ejs.zip.Deflate.prototype.distances = [{ bits : 0, distanceBase : 1, code : 0 }, { bits : 0, distanceBase : 2, code : 1 }, { bits : 0, distanceBase : 3, code : 2 }, { bits : 0, distanceBase : 4, code : 3 }, { bits : 1, distanceBase : 5, code : 4 }, { bits : 1, distanceBase : 7, code : 5 }, { bits : 2, distanceBase : 9, code : 6 }, { bits : 2, distanceBase : 13, code : 7 }, { bits : 3, distanceBase : 17, code : 8 }, { bits : 3, distanceBase : 25, code : 9 }, { bits : 4, distanceBase : 33, code : 10 }, { bits : 4, distanceBase : 49, code : 11 }, { bits : 5, distanceBase : 65, code : 12 }, { bits : 5, distanceBase : 97, code : 13 }, { bits : 6, distanceBase : 129, code : 14 }, { bits : 6, distanceBase : 193, code : 15 }, { bits : 7, distanceBase : 257, code : 16 }, { bits : 7, distanceBase : 385, code : 17 }, { bits : 8, distanceBase : 513, code : 18 }, { bits : 8, distanceBase : 769, code : 19 }, { bits : 9, distanceBase : 1025, code : 20 }, { bits : 9, distanceBase : 1537, code : 21 }, { bits : 10, distanceBase : 2049, code : 22 }, { bits : 10, distanceBase : 3073, code : 23 }, { bits : 11, distanceBase : 4097, code : 24 }, { bits : 11, distanceBase : 6145, code : 25 }, { bits : 12, distanceBase : 8193, code : 26 }, { bits : 12, distanceBase : 12289, code : 27 }, { bits : 13, distanceBase : 16385, code : 28 }, { bits : 13, distanceBase : 24577, code : 29 } ]; // 0 - 15 = codelengths // 16 copy prev 3 - 6, 2 bits // 17 copy prev 3 - 10 // 18 copy prev 11 - 138 ejs.zip.Deflate.prototype.order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; ejs.zip.Deflate.prototype.inflate = function(stream){ var outputStream = new ejs.zip.BitStream(); var blockPosition = stream.read(1); var method = stream.read(2); if (method === 1){ // Fixed } else if (method === 2) {// dynamic var hlit = stream.read(5) + 257; var hdist = stream.read(5) + 1; var hclen = stream.read(4) + 4; console.log(hlit, hdist, hclen); var lengths = []; var literals = []; // Code lengths code lengths for (var i = 0; i < hclen; i++){ lengths[this.order[i]] = stream.read(3); } for (;i<19;i++){ lengths[this.order[i]] = 0; } var ranges = []; for (var i = 0; i < lengths.length; i++){ if (lengths[i] !== 0){ ranges.push({ code : i, length : lengths[i]}); } } ranges.sort(function(a, b){ var d = a.length - b.length; if (d === 0) return a.code - b.code; else return d; }); var huff = new ejs.zip.Huffman(); var codes = huff.canonicalize(ranges); var lengthKey = huff.toKey(codes); // With codes read stream var val = null; var i = 0; while (i < hlit + hdist){ var sym = this.decode(stream, lengthKey); if (sym < 0){ console.log("sym error < 0"); } if (sym < 16){ literals[i++] = sym; continue; } len = 0; if (sym === 16){ len = literals[i - 1]; sym = 3 + stream.read(2); } else if(sym === 17){ sym = 3 + stream.read(3); } else{ sym = 11 + stream.read(7); } while(sym--){ literals[i++] = len; } } var usedLiterals = []; var distances = []; for (var i = 0; i < literals.length && i < literals.length; i++){ if (literals[i] !== 0) { if (i < hlit){ usedLiterals.push({ code : i, length : literals[i]}); }else { distances.push({ code : i - hlit, length : literals[i]}); } } } usedLiterals.sort(function(a, b){ var d = a.length - b.length; if (d === 0) return a.code - b.code; else return d; }); var codes = huff.canonicalize(usedLiterals); var literalKey = huff.toKey(codes); var dop = {}; codes.forEach(function(d){ dop[d.code] = d.bs; }); distances.sort(function(a, b){ var d = a.length - b.length; if (d === 0) return a.code - b.code; else return d; }); var codes = huff.canonicalize(distances); var distanceKey = huff.toKey(codes); var sym = 0; var count = 0; // Decode content while (sym !== 256 && count < 1000){ // To avoid infinite sym = this.decode(stream, literalKey); var length = 0; var distance = 0; if (sym < 256){ // literal outputStream.writeByte(sym); }else if (sym > 256){ // length var l = this.lengths[sym - 257]; length = l.lengthBase + stream.read(l.bits); sym = this.decode(stream, distanceKey); var d = this.distances[sym]; distance = d.distanceBase + stream.read(d.bits); } while (length--){ outputStream.writeByte(outputStream.getByteAtPosition(outputStream.position - distance)); } count++; } } return outputStream; } ejs.zip.Deflate.prototype.deflate = function(stream){ var outputStream = new ejs.zip.BitStream(); outputStream.write(1, 1, true); // Block position outputStream.write(2, 2, true); // Dynamic for the moment // Get LZ77 coding var view = new Uint8Array(stream.buffer); var literals = {}; var lengths = {}; var distances = {}; var rawDistances = []; var rawLengths = []; var content = []; var cursor = 0; var d = { d: 1, l : 1 }; for (var i = 0; i < view.length; i++){ var len = 0; // Look for match before but not including current position var maxl = 0; var maxP = 0; for (var j = i - 1; j > 0; j--){ var k = j; var l = i; var len = 0; while (view[k] === view[l] && len < this.MAX_LENGTH){ k++; l++; len++; } if (len > maxl){ maxl = len; maxP = j; } // Short circuit if we've found a max match already if (maxl === this.MAX_LENGTH) j = -1; } if (maxl >= this.MIN_LENGTH){ // encode as distance length pair var d = i - maxP; l = maxl; content.push({ d : d, l : l }); i += maxl - 1; var leng = this.getLengthCode(l); literals[leng.code] = literals[leng.code] || 0; literals[leng.code]++; var dist = this.getDistCode(d); distances[dist.code] = distances[dist.code] || 0; distances[dist.code]++; } else { // write character to stream var literal = view[i]; literals[literal] = literals[literal] || 0; literals[literal]++; content.push(literal); } } // Add end literals[256] = 1; content.push(256); var huffman = new ejs.zip.Huffman(); var lengths = huffman.getLengths(literals); var distLengths = huffman.getLengths(distances); var contentCodes = huffman.canonicalize(lengths); var distCodes = huffman.canonicalize(distLengths); var codeLengthLengths = {}; var codeDict = {}; var distDict = {}; var hlit = 0, hdist = 0; for (var i = 0; i < lengths.length; i++){ var l = lengths[i].length; codeLengthLengths[l] = codeLengthLengths[l] || 0; codeLengthLengths[l]++; codeDict[lengths[i].code] = lengths[i]; hlit = hlit > lengths[i].code ? hlit : lengths[i].code; } hlit++; // Need to know how many distcodes to encode var hdist = 0; // for (var i = 0; i < distCodes.length; i++){ // distDict[distCodes[i].code] = distCodes[i]; // hdist = distCodes[i].code > hdist ? distCodes[i].code : hdist; // } for (var i = 0; i < distLengths.length; i++){ var l = distLengths[i].length; codeLengthLengths[l] = codeLengthLengths[l] || 0; codeLengthLengths[l]++; distDict[distLengths[i].code] = distLengths[i]; hdist = distLengths[i].code > hdist ? distLengths[i].code : hdist; } hdist++; // Contruct alphabet. Iterate 0 - 255, see what codes are needed var alphabet = []; for (var i = 0; i < (hlit + hdist); i++){ if (codeDict[i]){ alphabet.push(codeDict[i].length); }else if (i > hlit && distDict[i - hlit]){ alphabet.push(distDict[i - hlit].length); } else{ alphabet.push(0); } } // run-length encode alphabet var ac = []; var n = 1; for (var i = 1; i <= alphabet.length; i++) { if (alphabet[i] === alphabet[i - 1]){ n++; } else { if (n > 3) { ac.push({ l : n, v : alphabet[i - 1] }); } else if (n > 0) { while(n--){ ac.push(alphabet[i - 1]); } } else { ac.push(alphabet[i - 1]) } n = 1; } } // Get frequency of other codes from alphabet for (var i = 0; i < ac.length; i++){ if (ac[i].l) { if (ac[i].v === 0){ // use 17 or 18 if (ac[i].l > 10){ codeLengthLengths[18] = codeLengthLengths[18] || 0; codeLengthLengths[18]++; } else { codeLengthLengths[17] = codeLengthLengths[17] || 0; codeLengthLengths[17]++; } } else { codeLengthLengths[16] = codeLengthLengths[16] || 0; codeLengthLengths[16]++; } } else if (ac[i] == 0){ codeLengthLengths[0] = codeLengthLengths[0] || 0; codeLengthLengths[0]++; } } var alpha = huffman.getLengths(codeLengthLengths); huffman.canonicalize(alpha); codeLengthDict = {}; var maxI = 0; for (var i = 0; i < alpha.length; i++){ codeLengthDict[alpha[i].code] = alpha[i]; } for (var i = 0; i < this.order.length; i++){ var code = this.order[i]; if (codeLengthDict[code]){ maxI = i + 1; } } outputStream.write(hlit - 257, 5, true); // # of literals outputStream.write(hdist - 1, 5, true); // # of distances outputStream.write(maxI - 4, 4, true); // # of bit length codes // Write bit length codes for (i = 0; i < maxI; i++){ if (codeLengthDict[this.order[i]]){ outputStream.write(codeLengthDict[this.order[i]].length, 3, true); }else{ outputStream.write(0, 3, true); } } //var lCount = 0; // Write out alphabet for (var i = 0; i < ac.length; i++){ var len = 0; var b = 0; var code = null; if (ac[i].l){ if (ac[i].v === 0){ if (ac[i].l > 10){ code = codeLengthDict[18]; len = ac[i].l - 11; // lCount += len + 11; b = 7; }else{ code = codeLengthDict[17]; len = ac[i].l - 3; //lCount += len + 3; b = 3; } }else{ code = codeLengthDict[16]; len = ac[i].l - 3; //lCount += len + 3; b = 2; } }else{ var code = codeLengthDict[ac[i]]; //lCount++; } outputStream.write(outputStream.reverse(code.value, code.length), code.length, true); if (b) outputStream.write(len, b, true); } // Write out content for (var i = 0; i < content.length; i++){ if (content[i].l){ // Use lengths var c = this.getLengthCode(content[i].l); var code = codeDict[c.code]; outputStream.write(outputStream.reverse(code.value, code.length), code.length, true); if (c.bits){ outputStream.write(content[i].l - c.lengthBase, c.bits, true); } // Write distance var d = this.getDistCode(content[i].d); var code = distDict[d.code]; outputStream.write(outputStream.reverse(code.value, code.length), code.length, true); if (d.bits){ outputStream.write(content[i].d - d.distanceBase, d.bits, true); } }else{ var code = codeDict[content[i]]; outputStream.write(outputStream.reverse(code.value, code.length), code.length, true); } } outputStream.flush(); console.log(outputStream.asBinaryString()); console.log(outputStream.asHexString()); return outputStream; } ejs.zip.Deflate.prototype.getLengthCode = function(length){ var i = 0; while (this.lengths[i + 1] && length >= this.lengths[i + 1].lengthBase){ i++; } return this.lengths[i]; } ejs.zip.Deflate.prototype.getDistCode = function(dist){ var i = 0; while (this.distances[i + 1] && dist >= this.distances[i + 1].distanceBase){ i++; } return this.distances[i]; } ejs.zip.Deflate.prototype.decode = function(stream, huffman){ var code = 0, index = 0; for (var i = 0; i < this.MAX_BITS; i++){ code |= stream.read(1); if (huffman[code] && huffman[code][i + 1]) { return huffman[code][i + 1].code; } code <<= 1; } console.log(code, 'not found'); } ejs.zip.Huffman = function(){ } /** * Get the code lengths given a <code, frequency> dictionary */ ejs.zip.Huffman.prototype.getLengths = function(freqDict){ var keys = Object.keys(freqDict); var nodes = []; for (var i = 0; i < keys.length; i++){ var node = new ejs.zip.HuffmanNode(); node.isLeaf = true; node.value = +keys[i]; node.f = freqDict[keys[i]]; nodes.push(node); } while (nodes.length > 1){ nodes = nodes.sort(function(a, b){ return a.f - b.f; }); var node = new ejs.zip.HuffmanNode(); node.zero = nodes.shift(); node.one = nodes.shift(); node.f = node.zero.f + node.one.f; nodes.push(node); } var lengths = this.getDepth(nodes[0]); lengths.sort(function(a, b){ if (a.length === b.length){ return a.code - b.code; } else return a.length - b.length; }); return lengths; } ejs.zip.Huffman.prototype.getDepth = function(node, depth){ var depths = []; depth = depth || 0; if (node.zero) depths = depths.concat(this.getDepth(node.zero, depth + 1)); if (node.one) depths = depths.concat(this.getDepth(node.one, depth + 1)); if (node.value !== undefined){ depths.push({ length : depth, code : node.value }); } return depths; } ejs.zip.Huffman.prototype.encode = function(source){ var key = {}; for (var i = 0; i < source.length; i++){ key[source[i]] = key[source[i]] || 0; key[source[i]]++; } var freq = Object.keys(key).map(function(d){ var node = new ejs.zip.HuffmanNode(); node.isLeaf = true; node.value = d; node.f = key[d]; return node; }); while (freq.length > 1){ freq = freq.sort(function(a, b){ return a.f - b.f; }); var node = new ejs.zip.HuffmanNode(); node.zero = freq.shift(); node.one = freq.shift(); node.f = node.zero.f + node.one.f; freq.push(node); i++; } var root = freq[0]; function getCodeLengths(node, depth){ depth = depth === undefined ? 0 : depth; var codes = [], ones = [], zeroes = []; if (node.zero){ zeroes = getCodeLengths(node.zero, depth + 1); }if (node.one){ ones = getCodeLengths(node.one, depth + 1); } if(node.value){ codes.push({ length : depth, code : node.value}); } return codes.concat(zeroes).concat(ones); } function getCodes(node, prefix){ prefix = prefix === undefined ? '' : prefix; var codes = [], ones = [], zeroes = []; if (node.zero){ zeroes = getCodes(node.zero, prefix + '0'); }if (node.one){ ones = getCodes(node.one, prefix + '1'); } if(node.value){ codes.push({ prefix : prefix, code : node.value}); } return codes.concat(zeroes).concat(ones); } //var codes = getCodes(root); var codes = getCodeLengths(root); codes.sort(function(a, b){ if (a.length === b.length){ return a.code.localeCompare(b.code); } else return a.length - b.length; }); this.codes = this.canonicalize(codes); } ejs.zip.Huffman.prototype.canonicalize = function(codes){ var N = [0]; var max = 0; var code = 0, nextCode = []; for(var i = 0; i < codes.length; i++){ N[codes[i].length] = N[codes[i].length] || 0; N[codes[i].length]++; max = Math.max(max, codes[i].length); } for (bits = 1; bits <= max; bits++){ var n = N[bits - 1]; n = n === undefined ? 0 : n; code = (code + n) << 1; nextCode[bits] = code; } for(var i = 0; i < codes.length; i++){ var len = codes[i].length; if (len != 0){ codes[i].value = nextCode[len]; codes[i].bs = codes[i].value.toString(2); while(codes[i].bs.length < codes[i].length){ codes[i].bs = '0' + codes[i].bs; } nextCode[len]++; } } if (codes.length === 1){ codes[0].value = 0; codes[0].length = 1; codes[0].bs = '0'; } return codes; } ejs.zip.Huffman.prototype.toKey = function(codes){ var key = {}; for (var i = 0; i < codes.length; i++){ var code = codes[i]; key[code.value] = key[code.value] === undefined ? {} : key[code.value]; key[code.value][code.length] = code; } return key; } ejs.zip.HuffmanNode = function(){ this.code; // int this.zero; // Node this.one; // Node } ejs.zip.HuffmanRange = function(end, length){ this.end = end; this.length = length; } ejs.zip.LZ77 = function(){ } ejs.zip.LZ77.prototype.compress = function(input){ var i, length, p, l, c, buffer, nextChar, previous, windowLength = 32768, bufferLength = 16384; var output = ''; var lengthLimit = 258; var ot = new Uint8Array(); // 0 0000000 1 000000000000 0000 // Data in Uint8Array // var blob = new Blob(data, {type : 'application/octet-stream'}); for (var i = 0; i < input.length; i++){ // Form window buffer = input.slice(i, i + bufferLength); dictionary = input.slice(Math.max(i - bufferLength, 0), i); nextSequence = input.slice(i, i + 1); var found = dictionary.indexOf(nextSequence); var pre = found; var testSequence = nextSequence; var cursor = i; while (found > -1 && cursor < 500){ pre = found; nextSequence = testSequence; dictionary = input.slice(Math.max(cursor - bufferLength, 0), cursor); cursor++; testSequence += input[cursor]; found = dictionary.indexOf(testSequence); } var offset = i - pre; var length = nextSequence.length; var nextCharacter = input[cursor] || '$'; var result = ''; if (pre === -1) result = input[cursor]; else result = '<' + offset + ',' + length + ',' + nextCharacter + '>'; i = cursor; output += result; } return output; } ejs.zip.LZ77.prototype.decompress = function(input){ }
/*const comportamiento = document.querySelectorAll('[name=comportamiento') //! OBTENIENDO EL VALOR DE UN RADIOBUTTON CON UN FOR console.log(comportamiento) let resultado= "" function obtenerRadio(){ for(let i = 0;i<comportamiento.length;i++){ if(comportamiento[i].checked){ console.log(comportamiento[i].value) resultado = comportamiento[i].value } } return resultado } let resultadoFinal = obtenerRadio() alert(resultadoFinal)*/ function validarNombre(nombre) { if (nombre.length === 0) { return "Este campo debe tener al menos 1 caracter"; } if (nombre.length >= 50) { return "Este campo debe tener menos de 50 caracteres"; } if (!/^[a-z]+$/i.test(nombre)) { return "El campo nombre solo acepta letras"; } return ""; } function validarDescripcionRegalo(descripcionRegalo) { if (descripcionRegalo.length >= 100) { return "El texto que ingresaste es muy largo"; } else if (descripcionRegalo.length === 0) { return "Por favor ingresa un texto valido"; } else if (!/^[a-z0-9,\._ ]+$/i.test(descripcionRegalo)) { return "Por favor ingrese un caracter valido"; } return ""; } function validarCiudad(ciudad) { if (ciudad === "") { return "Por Favor ingrese una provincia"; } return ""; } const $form = document.querySelector("#carta-a-santa"); function validarFormulario(event) { event.preventDefault(); const nombre = $form.nombre.value; const ciudad = $form.ciudad.value; const descripcionRegalo = $form["descripcion-regalo"].value; const errorNombre = validarNombre(nombre); const errorCiudad = validarCiudad(ciudad); const errorDescripcionRegalo = validarDescripcionRegalo(descripcionRegalo); const objetoErrores = { nombre: errorNombre, ciudad: errorCiudad, "descripcion-regalo": errorDescripcionRegalo, }; const esExito = manejarErrores(objetoErrores) === 0; //! COMPARO, SI TIENE ERRORES != EXITO, SI ES === 0 ESTONCES ES EXITOSO Y EN 5 SEGUNDOS LO MANDO A WISHLIST if (esExito) { document.querySelector("#carta-a-santa").remove(); const $divExito = document.querySelector("#exito"); $divExito.className = ""; setTimeout(() => { window.location.assign("wishlist.html"); }, 5000); } } function manejarErrores(errores) { let contadorErrores = 0; const $errores = document.querySelector("#errores"); const keys = Object.keys(errores); while ($errores.hasChildNodes()) { $errores.removeChild($errores.firstChild); } keys.forEach(function (key) { const error = errores[key]; if (error) { contadorErrores++; $form[key].className = "error"; let liErrores = document.createElement("li"); liErrores.textContent = error; $errores.appendChild(liErrores); } else { console.log("Exito!"); $form[key].className = ""; } }); return contadorErrores; } $form.onsubmit = validarFormulario;
var state = { menuList: [ {msg: '全部事项', count: 14, icon: 'glyphicon glyphicon-list-alt'}, {msg: '完成事项', count: 14, icon: 'glyphicon glyphicon-ok'}, {msg: '在忙事项', count: 14, icon: 'glyphicon glyphicon-option-horizontal'}, {msg: '清除事项', count: 14, icon: 'glyphicon glyphicon-remove'} ], menuShowFlag: false, doneList: [], deletedList: [], doingList: [ { date: '', list: [ { msg: '' } ] } ] }; module.exports = state;
import React ,{useEffect,useState} from 'react'; import Webcam from "react-webcam" ; import Container from '@material-ui/core/Container'; import Grid from '@material-ui/core/Grid'; import { Button } from '@material-ui/core'; const videoConstraints = { width: 300, height: 300, facingMode: "user" }; export default function WebcamCapture() { const [imageSrc, setImageSrc] = useState('') const webcamRef = React.useRef(null); const capture = (event) => { event.preventDefault(); setImageSrc(webcamRef.current.getScreenshot()) }; return ( <> <Grid xs={12} container spacing={2}> <Grid item xs={6} spacing={2}> <Webcam audio={false} height={300} ref={webcamRef} screenshotFormat="image/jpeg" width={300} videoConstraints={videoConstraints} /> </Grid><Grid item xs={6} spacing={2}> <img margin="10px" src={imageSrc} /> </Grid></Grid> <Button variant="contained" color="secondary" onClick={capture}>Capturar Nova Foto</Button> <Button variant="contained" color="primary" onClick={capture}>Salvar</Button> </> ); };
module.exports = (function() { // Constructor var robotCls = function() { }; // Fields robotCls.statusCode = -1, robotCls.error = null, // Should be refactored to a custom object robotCls.pass = true, robotCls.domBase = null, robotCls.asserts = []; robotCls.open = function (title, url, callback) { var request = require('request'), cheerio = require('cheerio'), result = this; result.title = title; request({ uri:url, headers : { 'user-agent': 'Site Robot 0.1' } // I have checked this }, function (error, response, body) { // This is the wrapping call to log the request. var finish = function (finishResult) { result.assertDate = Date.now(); result.url = url; callback(result); }; // Setup the robot object result.error = error; // General Error if(error !== null) { result.assert("request error", error, false); } var finishResponse = "valid"; if(typeof response === 'undefined') { result.assert("response null error", null, false); finishResponse = "response null error"; } else { // Valid response result.statusCode = response.statusCode; if (response.statusCode == 200) { result.pass = true; // set this as the default result.domBase = cheerio.load(body); result.currentElement = robotCls.domBase; result.assertPass("valid web request", "statusCode:" + response.statusCode); } else { result.assertFail("invalid status code", response.statusCode); finishResponse = "unhandled response.statusCode: \n" + response.statusCode; result.error = "invalid status code: " + response.statusCode; } } // Make sure we call finish with every response finish(finishResponse); }); }; // Return a list of elements to perform validations on. robotCls.check = function (selector) { if(robotCls.error === null) { robotCls.element._source = robotCls.domBase(selector); robotCls.element._selector = selector; robotCls.element._length = selector = robotCls.element._source.length; } return robotCls.element; }; robotCls.element = { _source: null, val: function(expected) { if(robotCls.error !== null) return null; if(typeof expected !== 'undefined') { robotCls.assert('ele:val', 'val:' + robotCls.element._selector + ' ele.length:' + robotCls.element._length, function () { return robotCls.element._source.text() === expected; }); } return this._source.text(); }, noVal: function() { if(robotCls.error !== null) return null; robotCls.assert('ele:val', 'noVal: ' + robotCls.element._selector + ' ele.length:' + robotCls.element._length, function () { return robotCls.element._source.text().trim().length === 0; }); return this._source.text(); }, attr: function() { return this._source.attr(); } }; // Asserts robotCls.assert = function (name, message, pass) { var passResult = false; try { passResult = pass(); } catch(e) { robotCls.pass = false; pass = false; message = e; } if(!passResult) robotCls.pass = false; robotCls.asserts.push({'name': name, 'pass': passResult, 'message': message}); // ** TODO return add more info into the robot object ** }; robotCls.assertPass = function (name, message) { robotCls.asserts.push({'name': name, 'pass': true, 'message': message}); }; robotCls.assertFail = function (name, message) { robotCls.pass = false; robotCls.asserts.push({'name': name, 'pass': false, 'message': message}); }; return robotCls; })(); //exports.open = robot.open; //exports.check = robot.check; //// exports.element = robot.element; //exports.asserts = robot.asserts;
var tokki = angular.module("pedidoController", []); tokki.controller("Pedido", ['$scope', '$rootScope', '$state', '$filter', 'tokkiData', 'tokkiApi', 'Notification', function($scope, $rootScope, $state, $filter, tokkiData, tokkiApi, Notification) { $rootScope.navigation = 'pedido'; $scope.sucursales = tokkiData[0]; $scope.formas = tokkiData[1]; $scope.pedido = {}; $scope.pedido.sucursal = $filter('filter')(tokkiData[0], {id: $rootScope.sucursalId}, true)[0]; $scope.pedido.forma = 1; $scope.save = function() { $scope.sending = true; if($scope.pedido.forma != 2){ $scope.tipoDte = 39; } else{ $scope.tipoDte = 139; } savedte = tokkiApi.save({ action: 'pedidos', dte: $scope.tipoDte, pedido: $scope.pedido, user_id: $scope.currentUserId, }) .$promise.then(function(response) { $state.go('system.viewboleta', {dte: $scope.tipoDte, id: response.id}); }, function(response){ Notification.error(response.data); $scope.sending = false; }); } } ]); tokki.controller("FinalizarPedido", ['$scope', '$rootScope', '$state', '$filter', 'tokkiData', 'tokkiApi', 'Notification', function($scope, $rootScope, $state, $filter, tokkiData, tokkiApi, Notification) { $rootScope.navigation = 'finalizar'; $scope.pedido = tokkiData[0]; $scope.sucursales = tokkiData[1]; $scope.formas = tokkiData[2]; $scope.pedido.sucursal = $filter('filter')(tokkiData[1], {id: $rootScope.sucursalId}, true)[0]; $scope.pedido.forma = 1; $scope.save = function() { $scope.sending = true; if($scope.pedido.forma != 2){ $scope.tipoDte = 39; } else{ $scope.tipoDte = 139; } savedte = tokkiApi.save({ action: 'pedidos', control: 'finalizar', dte: $scope.tipoDte, pedido: $scope.pedido, user_id: $scope.currentUserId, }) .$promise.then(function(response) { $state.go('system.viewboleta', {dte: $scope.tipoDte, id: response.id}); }, function(response){ Notification.error(response.data); $scope.sending = false; }); } } ]); tokki.controller("ViewPedido", ['$scope', '$rootScope', '$state', '$filter', 'tokkiData', 'tokkiApi', function($scope, $rootScope, $state, $filter, tokkiData, tokkiApi) { $scope.pedido = tokkiData[0]; } ]);
import auth_reducer from './auth_reducer.js'; import project_reducer from './project_reducer.js'; import dom_elements_reducer from './dom_elements_reducer.js'; import { combineReducers } from 'redux'; const root_reducer = combineReducers({ auth: auth_reducer, project: project_reducer, dom_elements: dom_elements_reducer }); export default root_reducer;
// Implement a function called, areThereDuplicates which accepts a // variable number of arguments, and checks whether there are any // duplicates among the arguments passed in. You can solve this using the // frequency counter pattern OR the multiple pointers pattern // frequency counter pattern function areThereDuplicates1(...args) { if (args.length === 0) return false; let lookup = {}; let result = false; for (let item of args) { lookup[item] = ++lookup[item] || 1; if (lookup[item] > 1) { result = true; console.log(result); break; } } return result; } //areThereDuplicates Solution (Multiple Pointers) function areThereDuplicates2(...args) { // Two pointers args.sort((a, b) => a > b); let start = 0; let next = 1; while (next < args.length) { if (args[start] === args[next]) { return true; } start++; next++; } return false; } // areThereDuplicates One Liner Solution function areThereDuplicates3() { return new Set(arguments).size !== arguments.length; } areThereDuplicates1(1, 2, 3); areThereDuplicates1(1, 2, 2); areThereDuplicates1("a", "b", "c", "a");
///** // * Service // */ //angular.module('ngApp.profile').factory('ProfileService', function ($http, config, SessionService) { //});
import React from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux' import { updateImg } from '../../../ducks/reducer'; function Step2(props) { const { img, updateImg } = props return ( <div> <div> <h2>Image URL</h2> <input type="text" value={img} onChange={(e) => updateImg(e.target.value)} /> </div> <Link to='1'> <button>Back</button> </Link> <Link to='3' > <button>Next</button> </Link> </div> ) } function mapStateToProps(state) { const { img } = state; return { img } } export default connect(mapStateToProps,{updateImg})(Step2);
class Random { constructor (seed) { if (typeof seed === 'string') { seed = parseInt(seed.toLowerCase().replace(/[^a-z0-9]/,''), 36); } this._seed = seed; this._rnd = new MersenneTwister(seed); } random (a, b) { var min = 0; var max = 1; if (arguments.length === 1) { max = a; } else if (arguments.length === 2){ min = a; max = b; } var scale = max-min; return min + scale * this._rnd.random(); } // Compute the random number generated on the nth iteration of this seed randomItr (iteration) { var rnd = new MersenneTwister(this._seed); var val; for (var i = 0; i < iteration; i++) { val = rnd.random(); } return val; } choose (arr) { return arr[ Math.floor(this.random(arr.length)) ]; } }
var activeTurn = false, actives = []; var square = {}, allSquares = $(".grid-square"); square.validate = function(){ var self = {}; //candidate = $(this); console.log("validate starting"); //console.log(this); //console.log(square.current); //$( candidate ).on('mouseenter', this.activeTurn()); self.activeTurn = function( candidate ){ console.log("activeTurn"); //console.log(candidate); if( activeTurn ){ self.backtracking( candidate ); } else { //don't select anything, not dragging }; }; self.backtracking = function( candidate ){ console.log("backtracking"); console.log(candidate); if ( candidate.hasClass('selected') ){ self.firstSquare(); } else { self.lessThanMax( candidate ); }; // if square already selected // this.firstSquare(); // else // this.adjacency(); }; self.firstSquare = function(){ console.log("firstSquare"); if ( actives.length > 1 ){ actives.pop().removeClass('selected'); } else { // don't remove the first square }; }; self.lessThanMax = function( candidate ){ console.log("lessThanMax"); if ( actives.length < 3 ){ self.adjacency( candidate ); } else { // don't select any more }; // if active nodes < 3 // this.backtracking(); // else // don't select anymore }; self.adjacency = function( candidate ){ console.log("adjacency"); console.log(actives.length < 1); var isAdjacent, lastActive = $( actives.slice(0).pop() ); function directNeighbor(side1, side2){ if ( lastActive.data(side1) == candidate.data(side1) ){ if ( lastActive.data(side2) == (candidate.data(side2) + 1) || lastActive.data(side2) == (candidate.data(side2) - 1) ) isAdjacent = true; } else { // not directly adjacent }; return isAdjacent; } // if this is the first square if ( actives.length < 1 ){ self.done.success( candidate ); // if square is directly adjacent in either direction } else if (directNeighbor("row", "column") || directNeighbor("column", "row")){ self.done.success( candidate ); } else { //don't add! }; // if new is same row as lastActive // if new == lastActive col +/-1 // true // if new is same col as lastActive // if new == lastActive row +/-1 // true // if isAdjacent // this.success(); }; self.done = { success: function( candidate ){ console.log("done.success!!!"); candidate.addClass('selected'); //candidate.data('arrayIndex', actives.length); actives.push( candidate ); // update ui // add to array } }; // init self.activeTurn( $(this) ); }; square.reset = function(){ console.log("done.reset"); allSquares.removeClass('selected'); actives = []; }; // start turn when user clicks any square allSquares.on('mousedown', function(){ console.log("turn start"); activeTurn = true; allSquares.on( "mousedown", square.validate); }); // end turn when player stops dragging anywhere on screen $(window).on('mouseup', function(){ console.log("turn end"); activeTurn = false; //allSquares.off( "mouseenter", square.validate); square.reset(); }); allSquares.on( "mouseenter", square.validate);
// Criação do Formulário let formulario = document.createElement('form'); formulario.setAttribute('class','formulario'); document.body.appendChild(formulario); // Seleçao do Formulário let form = document.querySelector('.formulario'); // Inserção do Título let titulo = document.createElement('h1'); let tituloTexto = document.createTextNode("Login"); // Adicionando elementos titulo.appendChild(tituloTexto); formulario.appendChild(titulo); // Inserção do Input E-mail let email = document.createElement('input'); email.setAttribute('placeholder',"E-mail"); email.setAttribute('type',"email"); form.appendChild(email); // Inserção do Input Senha let senha = document.createElement('input'); senha.setAttribute('placeholder',"senha"); senha.setAttribute('type',"password"); form.appendChild(senha); // Inserção do Botão Enviar let enviar = document.createElement('button'); enviar.setAttribute('type',"submit"); enviar.innerText = "Enviar"; form.appendChild(enviar); // Inserção do Botão Cancelar let cancelar = document.createElement('button'); cancelar.setAttribute('type',"reset"); cancelar.innerText = "Cancelar"; form.appendChild(cancelar); // Manipulação de Atributos // email.setAttribute("disabled",true); // Sugestão de Estilização formulario.style.display = "flex"; formulario.style.maxWidth = "300px"; formulario.style.margin = "10% auto"; formulario.style.margin = "center"; formulario.style.flexDirection = "column"; formulario.style.gap = "10px"; // Carregamento da tela window.onload = alert("Seu formulário está pronto para o preenchimento"); // Função de validação function validar(){ confirm("Você tem certeza que deseja canvelar o envio?"); } // Cancela o envio cancelar.onclick = validar; // Função function desabilitar(event){ event.preventDefault(); } // Cancelar a ação Enviar do botão enviar.addEventListener('click',desabilitar);
// == Copy == function Copy(target, { onOk = () => {}, onErr = () => {} } = {}){ if(!navigator.clipboard){ console.warn('navigator.clipboard not support.'); return; } if(!target){ console.warn('Text to copy or target DOM is required.'); return; } let txt; if(typeof target === 'string' && !target.tagName) txt = target; else txt = target.textContent; // target.innerText.trim() // console.log(txt.replace(/\n/gm, '')); navigator.clipboard.writeText(txt).then(() => onOk(txt)) .catch(err => onErr(err)); } // For npm export {Copy};
import BaseDisplay from './BaseDisplay'; import Rms from '../../common/operator/Rms'; const log10 = Math.log10; const definitions = { offset: { type: 'float', default: -14, metas: { kind: 'dyanmic' }, }, min: { type: 'float', default: -80, metas: { kind: 'dynamic' }, }, max: { type: 'float', default: 6, metas: { kind: 'dynamic' }, }, width: { type: 'integer', default: 6, metas: { kind: 'dynamic' }, } } /** * Simple VU-Meter to used on a `signal` stream. * * @memberof module:client.sink * * @param {Object} options - Override defaults parameters. * @param {Number} [options.offset=-14] - dB offset applied to the signal. * @param {Number} [options.min=-80] - Minimum displayed value (in dB). * @param {Number} [options.max=6] - Maximum displayed value (in dB). * @param {Number} [options.width=6] - Width of the display (in pixels). * @param {Number} [options.height=150] - Height of the canvas. * @param {Element|CSSSelector} [options.container=null] - Container element * in which to insert the canvas. * @param {Element|CSSSelector} [options.canvas=null] - Canvas element * in which to draw. * * @example * import * as lfo from 'waves-lfo/client'; * * const audioContext = new window.AudioContext(); * * navigator.mediaDevices * .getUserMedia({ audio: true }) * .then(init) * .catch((err) => console.error(err.stack)); * * function init(stream) { * const source = audioContext.createMediaStreamSource(stream); * * const audioInNode = new lfo.source.AudioInNode({ * audioContext: audioContext, * sourceNode: source, * }); * * const vuMeter = new lfo.sink.VuMeterDisplay({ * canvas: '#vu-meter', * }); * * audioInNode.connect(vuMeter); * audioInNode.start(); * } */ class VuMeterDisplay extends BaseDisplay { constructor(options = {}) { super(definitions, options, false); this.rmsOperator = new Rms(); this.lastDB = 0; this.peak = { value: 0, time: 0, } this.peakLifetime = 1; // sec } /** @private */ processStreamParams(prevStreamParams) { this.prepareStreamParams(prevStreamParams); this.rmsOperator.initStream(this.streamParams); this.propagateStreamParams(); } /** @private */ processSignal(frame) { const now = new Date().getTime() / 1000; // sec const offset = this.params.get('offset'); // offset zero of the vu meter const height = this.canvasHeight; const width = this.canvasWidth; const ctx = this.ctx; const lastDB = this.lastDB; const peak = this.peak; const red = '#ff2121'; const yellow = '#ffff1f'; const green = '#00ff00'; // handle current db value const rms = this.rmsOperator.inputSignal(frame.data); let dB = 20 * log10(rms) - offset; // slow release (could probably be improved) if (lastDB > dB) dB = lastDB - 6; // handle peak if (dB > peak.value || (now - peak.time) > this.peakLifetime) { peak.value = dB; peak.time = now; } const y0 = this.getYPosition(0); const y = this.getYPosition(dB); const yPeak = this.getYPosition(peak.value); ctx.save(); ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, width, height); const gradient = ctx.createLinearGradient(0, height, 0, 0); gradient.addColorStop(0, green); gradient.addColorStop((height - y0) / height, yellow); gradient.addColorStop(1, red); // dB ctx.fillStyle = gradient; ctx.fillRect(0, y, width, height - y); // 0 dB marker ctx.fillStyle = '#dcdcdc'; ctx.fillRect(0, y0, width, 2); // peak ctx.fillStyle = gradient; ctx.fillRect(0, yPeak, width, 2); ctx.restore(); this.lastDB = dB; } } export default VuMeterDisplay;
const axios = require("axios"); const db = require("../../models/"); module.exports ={ findAll:function(req,res){ axious.get("https://arxiv.org/find/grp_cs/1/ti:+Encryption/0/1/0/2009,2010/0/1?per_page=10").then(response=>{ console.log(response); } }, findAll:function(req,res){ db.eprint .find(req.query) .sort({date:-1}) .then(dbEprint=>res.json(dbEprint)) .catch(err=>res.status(422).json(err)); }, findById:function(req,res){ db.eprint .findById(req.params.id) .then(dbEprint=>res.json(dbEprint)) .catch(err=>res.status(422).json(err)); }, create:function(req,res){ const newEprint={ _id:req.body._id, title: req.body.headline.main, url:req.body.link, }; db.eprint .create(newEprint) .then(dbEprint=>res.json(dbEprint)) .catch(err=>res.status(422).json(err)); }, update:function(req,res){ .sort({date:-1}) .then(dbEprint=>res.json(dbEprint)) .catch(err=>res.status(422).json(err)); }, remove:function(req,res){ .sort({date:-1}) .then(dbEprint=>res.json(dbEprint)) .catch(err=>res.status(422).json(err)); }, }
import React, { useState, createContext } from "react" // module retrieves maintenance events from the DB in various ways to be utilized differently export const LotNoteContext = createContext() export const LotNoteProvider = (props) => { const [lotNotes, setLotNotes] = useState([]) //const user = localStorage.getItem("MaintenanceMinder_user") //gets events using user ID and expanded to vehicle to attach specific vehicle to specific event const getLotNotes = () => { return fetch("http://localhost:8000/lotnotes", { headers: { Authorization: `Token ${localStorage.getItem("PF_token")}`, }, }) .then((response) => response.json()) .then(setLotNotes); }; const getLotNoteById = lotNoteId => { return fetch(`http://localhost:8000/lotnotes/${lotNoteId}`, { headers: { Authorization: `Token ${localStorage.getItem("PF_token")}` } }) .then(res => res.json()) } //uses the add maintenance form to add a new event to the DB const addLotNote = (lotNoteObj) => { return fetch("http://localhost:8000/lotnotes", { method: "POST", headers: { Authorization: `Token ${localStorage.getItem("PF_token")}`, "Content-Type": "application/json" }, body: JSON.stringify(lotNoteObj) }) .then(getLotNotes) } //retrieves the event by its ID //uses the maintenance form to edit an event and update the DB const updateLotNote = lotNote => { return fetch(`http://localhost:8000/lotnotes/${lotNote.id}`, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: `Token ${localStorage.getItem("PF_token")}` }, body: JSON.stringify(lotNote) }) .then(getLotNotes) } //uses the event ID to delete the event from the DB const deleteLotNote = lotNoteId => { return fetch(`http://localhost:8000/lotnotes/${lotNoteId}`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Token ${localStorage.getItem("PF_token")}` }, }) .then(getLotNotes) } // exports the function fetch calls via MaitenanceContext to be used throughout the modules return ( <LotNoteContext.Provider value={{ lotNotes, getLotNotes, addLotNote, getLotNoteById, updateLotNote, deleteLotNote }}> {props.children} </LotNoteContext.Provider> ) }
import React from "react"; class Counter extends React.Component { changeColor() { let h2ClassName = { color: "blue" }; if (this.props.count > 0) h2ClassName = { color: "green" } if (this.props.count < 0) h2ClassName = { color: "red" } return h2ClassName }; render() { const h2ClassName = this.changeColor() console.log(this.props) return ( <> <h2 style={h2ClassName}>{this.props.count}</h2> <button className="btn btn-danger mx-2" onClick={() => this.props.substract() } > -1 </button> <button className="btn btn-success" onClick={() => this.props.increment() }>+1</button> </> ) } } export default Counter
angular.module("myApp").controller("DeliveryListCtrl",["$scope","$rootScope","DeliveryService",function ($scope,$rootScope,DeliveryService) { var page,time,status; $scope.changeStatus = function(newStatus){ page = 0; time = 0; status = newStatus; status = newStatus; if(status.id=='0'){ $scope.isSuccess = false; $scope.isNo = true; $scope.isPending=false; }else if(status.id=='1'){ $scope.isNo = false; $scope.isSuccess = true; $scope.isPending=false; }else{ $scope.isNo = false; $scope.isSuccess = false; $scope.isPending = true; } $scope.deliverys = loadDeliverys(status,page,time); }; $scope.changeTime = function(newTime){ page = 0; time = newTime; $scope.deliverys= loadDeliverys(status,page,newTime); }; $scope.refreshPage = function () { $scope.deliverys = loadDeliverys(status,page,time); }; $scope.loadMore = function () { page = page+1; var deliverys = loadDeliverys(status,page,time); if(deliverys.length>0) for(var i=0,len=deliverys.length; i<len; i++){ $scope.deliverys.push(deliverys[i]); } }; function loadDeliverys(status,page,time) { return DeliveryService.getDeliveryList(status,page,time); } function initPage(){ page =0;time=0; var deliveryStatusArray = DeliveryService.getDeliveryStatusArray(); $scope.deliveryStatusArray = deliveryStatusArray; status = deliveryStatusArray[0]; $scope.deliverys = loadDeliverys(status,page,time); } //初始化 initPage(); }]); myApp.controller("DeliveryDetailCtrl",["$scope","$rootScope",'$stateParams','DeliveryDetailService',function ($scope,$rootScope,$stateParams,DeliveryDetailService) { //取得传过来的参数 var deliveryId = $stateParams.deliveryId; $scope.delivery = DeliveryDetailService.getDeliveryDetail(deliveryId); //var deliveryNum = $stateParams.deliveryNum; //$scope.delivery = DeliveryDetailService.getDeliveryDetail(deliveryId,deliveryNum); // 我的订单详情 // function loadOrderDetail(status,page,time) { // return OrderDetailService.getOrderDetail(status,page,time); // } }]);
(function () { 'use strict'; angular .module('DivineChMS') .factory('DivineFactory', factory) .service('LoggerApi', LoggerApi); function LoggerApi() { return { createLogger : create }; function create() { var page = window.location.href; var url = "http://divinelog.azurewebsites.net/api/Logger"; return new Logger(url, logObj.serverName, page, logObj.siteId); } } factory.$inject = ['$http']; function factory($http) { //TODO break this factory service object into: //service.attendance //service.lookup //service.members //service.message var service = {}; service.attendanceService = { getAllRecords: attendanceList, getById: attendanceRecord, post: submitAttendance, delete: removeAttendance, }; service.lookupService = { getAll: lookupData, post: submitLookupData, getStatistics: siteStatistics //TODO: change to current usage }; service.memberService = { getAll: members, getById: memberById, getEventsByMonth: monthlyEvents, find: findMembers, post: submitMember, getDemographicStats: demographicStats, }; service.messageService = { post: sendMessage, getAll: messages, getTwilioConfigData: twilioConfigData, }; /* var service = { getMembers: members, getMemberById: memberById, getLookupData: lookupData, getMembersEventsByMonth: monthlyEvents, findMembers: findMembers, postMember: submitMember, postMessage: sendMessage, getMessages: messages, getAttendanceList: attendanceList, getAttendanceRecord: attendanceRecord, postAttendance: submitAttendance, deleteAttendance: removeAttendance, getDemographicStats: demographicStats, getTwilioConfigData: twilioConfigData, postLookupData: submitLookupData, getStatistics: siteStatistics };*/ return service; function siteStatistics() { return $http({ method: "get", url: "/api/Lookup/GetStatistics" }); } function submitLookupData(data) { return $http({ method: "post", url: "/api/Lookup/UpdateLookupData", data: data }); } function twilioConfigData() { return $http({ method: "get", url: "/api/Message/GetConfigData" }); } function members() { var request = $http({ method: "get", url: "/api/Members" }); return request; } function memberById(id) { var request = $http({ method: "get", url: "/api/Members/" + id }); return request; } function lookupData() { var request = $http({ method: "get", url: "/api/Lookup/GetLookupData", cache: true }); return request; } function monthlyEvents(monthNbr) { var request = $http({ method: "get", url: "/api/Members/MonthlyLifeEvents/" + monthNbr }); return request; } function findMembers(searhMember) { var request = $http({ method: "post", data: searhMember, url: "/api/Members/SearchMembers" }); return request; } function submitMember(member) { return $http({ method: "post", data: member, url: "/api/Members" }); } function sendMessage(message) { return $http({ method: "post", data: message, url: "/api/Message" }); } function messages() { return $http({ method: "get", url: "/api/Message" }); } function attendanceList() { return $http({ method: "get", url: "/api/Attendance" }); } function attendanceRecord(id) { return $http({ method: "get", url: "/api/Attendance/" + id }); } function submitAttendance(record) { return $http({ method: "post", data: record, url: "api/Attendance" }); } function removeAttendance(id) { return $http({ method: "delete", url: "api/Attendance/" + id }); } function demographicStats() { return $http({ method: "get", url: "api/Members/DemographicStatistics" }); } } })();
function displayData() { var displayArea = document.getElementById("displayArea"); var username = document.getElementById("username").value; var email = document.getElementById("email").value; var password = document.getElementById("password").value; var firstName = document.getElementById("firstName").value; var lastName = document.getElementById("lastName").value; displayArea.innerHTML = "Username : "+username +" <br>Pasword : "+password+" <br>Email"+email+" <br>First Name : "+firstName+" <br>Last name : "+lastName; }
(function () { angular.module('OnePushApp.portfolios.services',[]) .factory('PortfoliosService', PortfoliosService); PortfoliosService.$inject = ["$timeout", "$q", "$http", "$timeout", "appConstants"]; function PortfoliosService($timeout, $q, $http, $timeout, appConstants) { var PortfoliosService = { fetchPortfolios: fetchPortfolios, pushPortfolio: pushPortfolio }; return PortfoliosService; function fetchPortfolios(params) { var def = $q.defer(); var req = { method: 'GET', url: appConstants.OnePushBaseURL, headers: {}, params: { type: 'json', query: 'list_websites' } } $http(req).then(function (response) { def.resolve({ portfolios: response.data.websites }); }, function (arg) { def.reject(arg.data); }); return def.promise; } function pushPortfolio(params) { var def = $q.defer(); var req = { method: 'GET', url: appConstants.OnePushBaseURL, headers: {}, params: { type:'json', query:'push', title: params.title, url: params.url, tag: params.tag } } $http(req).then(function (response) { if(response.status==200&&response.data.status==403){ def.reject({ portfolio: "Error!" + response.data.message }); }else if(response.status==200&&response.data.status==200) { def.resolve({ portfolio: "Success!"+ response.data.message }); }else { def.resolve({ portfolio: response.data }); } }, function (arg) { def.reject({ portfolio: response.data }); }); return def.promise; } } })();
const submitBtn = document.querySelector("#submit"); const resetBtn = document.querySelector("#reset"); const timer = document.querySelector(".timer"); let seconds; submitBtn.addEventListener("click", () => { seconds = 60; let minutes = document.querySelector("#minutes").value; minutes--; console.log(minutes); const startWatch = () => { seconds--; if (seconds < 0 && !minutes) { return; } else if (!seconds && minutes) { seconds = 60; return seconds--, minutes--; } if (minutes > 10 && seconds >= 10) { timer.textContent = `${minutes} : ${seconds}`; } else if (minutes < 10 && seconds >= 10) { timer.textContent = `0${minutes} : ${seconds}`; } else if (minutes > 10 && seconds < 10) { timer.textContent = `${minutes} : 0${seconds}`; } else timer.textContent = `0${minutes} : 0${seconds}`; }; setInterval(startWatch, 1000); }); resetBtn.addEventListener("click", () => { location.reload(); return false; });
define('/static/script/lib/json/jsonToStr', [], function(require, exports, module) { function jsonToStr(json) { var arr = []; var str = ""; if(Object.prototype.toString.apply(json)=='[object Array]') { var num=json.length; for (var i=0;i<num;i++) { arr.push(jsonToStr(json[i])); str='['+arr.join(',')+']'; } } if(Object.prototype.toString.apply(json)==='[object Date]') { str="new Date("+json.getTime()+")"; } if(Object.prototype.toString.apply(json)==='[object Function]'||Object.prototype.toString.apply(json)==='[object RegExp]') { str=json.toString(); } if(Object.prototype.toString.apply(json)==='[object Number]') { str=json; } if(Object.prototype.toString.apply(json)==='[object String]') { str='"'+json+'"'; } if(Object.prototype.toString.apply(json)==='[object Object]') { for (var i in json) { if(typeof (json[i]) === 'string') { json[i]='"' + json[i] + '"'; } else { if(typeof (json[i]) === 'object') { json[i]=jsonToStr(json[i]); } else { json[i]=json[i]; } } arr.push(i + ':' + json[i]); } str = '{' + arr.join(',') + '}'; } return str; } return jsonToStr; });
/* * @Author: HuYanan * @Date: 2022-08-26 14:00:24 * @LastEditTime: 2022-08-30 19:01:13 * @LastEditors: HuYanan * @Description: 时间相关操作 * @Version: 0.0.1 * @FilePath: /HynScript/src/time/index.js * @Contributors: [HuYanan, other] */ import { fillZero } from "../String/numberFormat"; /** * 输入一个时间点,获取其最近15分钟的时间点 * 例如输入 10:10分 应返回 10:15 * @param {*} timestamp 时间戳 * @param {*} findNearMinute 查找最近的15分钟的倍数的分钟数 * 例如 设置此值15 * 则 0 -> 0, 7 -> 0, 8 -> 15, 14 -> 15, 16 -> 15, 22 -> 15, 23 -> 30 */ export function getNearTime (timestamp, findNearMinute = 15) { let resTime = ''; let resMinute = ''; const intTimestamp = parseInt(timestamp); let date = ''; let hour = 0; let minute = 0; let minuteRate = 0; let startTime = 0; let endTime = 0; let startTimeDistance = 0; let endTimeDistance = 0; try { if (!isNaN(intTimestamp)) { date = new Date(intTimestamp); // 获取分钟 // 获取小时 hour = date.getHours(); minute = date.getMinutes(); minuteRate = Math.floor(minute / findNearMinute); startTime = minuteRate * findNearMinute; endTime = (minuteRate + 1) * findNearMinute; startTimeDistance = minute - startTime; endTimeDistance = endTime - minute; console.log(minute, minuteRate, startTime, endTime, startTimeDistance, endTimeDistance); if (startTimeDistance <= endTimeDistance) { resMinute = startTime; } else if (startTimeDistance > endTimeDistance) { resMinute = endTime; } // 边界处理 // 边界1 如果分钟计算为60,则小时进一位,分钟置为00 if (resMinute === 60) { hour++; resMinute = 0; } // 边界2 如果分钟为60,小时进一位后等于24,则相当于第二天的凌晨,故应该返回00:00 if (hour === 24) { hour = 0; } resTime = `${fillZero(hour)}:${fillZero(resMinute)}`; } } catch (error) { } if (!resTime) { resTime = this.getNearTime(Date.now(), findNearMinute); } return resTime; } const param = Date.now()+40 * 60 * 1000 const date = new Date(param); const paramFormat = `${date.getHours()}:${date.getMinutes()}`; console.log(paramFormat, getNearTime(param, 15)) // console.log(paramFormat, getNearTime('1661744252931', 15))
import styled from "styled-components"; const LinksBackground = styled.div` background-color: ${props => props.theme.colors.purple.primaryPurple}; `; const LinkName = styled.span` font-size: ${props => props.theme.fontSizes.sizeFour}; padding-left: 10px; `; const SocialLink = styled.a` color: ${props => props.theme.colors.purple.tertiaryPurple}; text-decoration: none; display: flex; align-items: center; margin: 40px 30px; &:hover { color: ${props => props.theme.colors.black.quaternaryBlack}; } transition: color .2s linear; `; const SocialLinks = styled.div` display: flex; justify-content: center; `; const StyledFooter = styled.footer` position: absolute; bottom: 0; width: 100%; height: 235px; `; export { LinksBackground, LinkName, SocialLink, SocialLinks, StyledFooter };
import Vue from 'vue' import App from '@/App.vue' import store from '@/common/store.js' import mixins from '@/common/mixins.js' import moment from 'moment' Vue.mixin(mixins) moment.locale('zh-cn') import WxdocDesc from '@/components/learun-app/desc.vue' Vue.component('wxdoc-desc', WxdocDesc) import LButton from '@/components/learun-ui-wx/button.vue' import LIcon from '@/components/learun-ui-wx/icon.vue' import LTag from '@/components/learun-ui-wx/tag.vue' import LAvatar from '@/components/learun-ui-wx/avatar.vue' import LProgress from '@/components/learun-ui-wx/progress.vue' import LLoading from '@/components/learun-ui-wx/loading.vue' import LInput from '@/components/learun-ui-wx/input.vue' import LSelect from '@/components/learun-ui-wx/select.vue' import LDatePicker from '@/components/learun-ui-wx/date-picker.vue' import LTimePicker from '@/components/learun-ui-wx/time-picker.vue' import LDatetimePanel from '@/components/learun-ui-wx/datetime-panel.vue' import LDateTimePicker from '@/components/learun-ui-wx/datetime-picker.vue' import LRegionPicker from '@/components/learun-ui-wx/region-picker.vue' import LSwitch from '@/components/learun-ui-wx/switch.vue' import LRadio from '@/components/learun-ui-wx/radio.vue' import LCheckbox from '@/components/learun-ui-wx/checkbox.vue' import LCheckboxPicker from '@/components/learun-ui-wx/checkbox-picker.vue' import LUpload from '@/components/learun-ui-wx/upload.vue' import LTextarea from '@/components/learun-ui-wx/textarea.vue' import LCard from '@/components/learun-ui-wx/card.vue' import LList from '@/components/learun-ui-wx/list.vue' import LListItem from '@/components/learun-ui-wx/list-item.vue' import LModal from '@/components/learun-ui-wx/modal.vue' import LBar from '@/components/learun-ui-wx/bar.vue' import LBarItem from '@/components/learun-ui-wx/bar-item.vue' import LBarItemButton from '@/components/learun-ui-wx/bar-item-button.vue' import LTitle from '@/components/learun-ui-wx/title.vue' import LBanner from '@/components/learun-ui-wx/banner.vue' import LTimeline from '@/components/learun-ui-wx/timeline.vue' import LTimelineItem from '@/components/learun-ui-wx/timeline-item.vue' import LStep from '@/components/learun-ui-wx/step.vue' import LNav from '@/components/learun-ui-wx/nav.vue' import LLabel from '@/components/learun-ui-wx/label.vue' import LChat from '@/components/learun-ui-wx/chat.vue' import LChatMsg from '@/components/learun-ui-wx/chat-msg.vue' import LChatInput from '@/components/learun-ui-wx/chat-input.vue' import LCustomItem from '@/components/learun-ui-wx/custom-item.vue' import LCustomAdd from '@/components/learun-ui-wx/custom-add.vue' Vue.component('l-button', LButton) Vue.component('l-icon', LIcon) Vue.component('l-tag', LTag) Vue.component('l-avatar', LAvatar) Vue.component('l-progress', LProgress) Vue.component('l-loading', LLoading) Vue.component('l-input', LInput) Vue.component('l-select', LSelect) Vue.component('l-date-picker', LDatePicker) Vue.component('l-time-picker', LTimePicker) Vue.component('l-datetime-panel', LDatetimePanel) Vue.component('l-datetime-picker', LDateTimePicker) Vue.component('l-region-picker', LRegionPicker) Vue.component('l-switch', LSwitch) Vue.component('l-radio', LRadio) Vue.component('l-checkbox', LCheckbox) Vue.component('l-checkbox-picker', LCheckboxPicker) Vue.component('l-upload', LUpload) Vue.component('l-textarea', LTextarea) Vue.component('l-card', LCard) Vue.component('l-list', LList) Vue.component('l-list-item', LListItem) Vue.component('l-modal', LModal) Vue.component('l-bar', LBar) Vue.component('l-bar-item', LBarItem) Vue.component('l-bar-item-button', LBarItemButton) Vue.component('l-title', LTitle) Vue.component('l-banner', LBanner) Vue.component('l-timeline', LTimeline) Vue.component('l-timeline-item', LTimelineItem) Vue.component('l-step', LStep) Vue.component('l-nav', LNav) Vue.component('l-label', LLabel) Vue.component('l-chat', LChat) Vue.component('l-chat-msg', LChatMsg) Vue.component('l-chat-input', LChatInput) Vue.component('l-custom-item', LCustomItem) Vue.component('l-custom-add', LCustomAdd) Vue.config.productionTip = process.env.NODE_ENV === 'development' Vue.prototype.$store = store new Vue({ ...App, mpType: 'app', store }).$mount() //--add //adddksfiwkefie
/** * Created by michael on 6/12/2017. */ import React, {PureComponent} from "react"; import { StyleSheet, Image, Text, TouchableOpacity, TouchableWithoutFeedback, View, Dimensions } from "react-native"; import PropTypes from "prop-types"; import FontAwesome from "react-native-vector-icons/FontAwesome"; export default class NotifInListItem extends PureComponent { constructor(props) { super(props); } _onTitlePressed = () => { this.props.onTitlePress(this.props.item.caseId); }; _onImagePressed = () => { this.props.onImagePress(this.props.item.caseId); }; _onLikePressed = () => { this.props.onLikePress(this.props.item.caseId); }; _onCommentPressed = () => { this.props.onCommentPress(this.props.item.caseId); }; _onSharePressed = () => { this.props.onSharePress(this.props.item.caseId); }; render() { let likeIcon = null; if (this.props.item.likeState === '1') { likeIcon = "heart"; } else { likeIcon = "heart-o"; } return ( <View style={{flex: 1}}> {/* Bar Header */} <TouchableWithoutFeedback onPress={this._onTitlePressed}> <View style={[ styles.layout, { flexDirection: 'row', height: 60, alignItems: 'center', justifyContent: 'space-between', } ]}> <View style={{flexDirection: 'row', flex: 1}}> <Image style={styles.profilePicture} source={{uri: this.props.item.userPictureUrl}}/> <Text style={styles.title}>{this.props.item.caseTitle}</Text> </View> {/*<Image style={{width: 40, height: 40, borderRadius: 20, marginRight: 20}}*/} {/*source={{uri: 'http://placehold.it/100x100'}}/>*/} </View> </TouchableWithoutFeedback> {/* Image */} <TouchableWithoutFeedback onPress={this._onImagePressed}> <Image style={styles.image} source={{uri: this.props.item.attachments.attachmentUrlThumb}} /> </TouchableWithoutFeedback> {/* Bar Actions */} <View style={[styles.layout, {flexDirection: 'row', height: 60, alignItems: 'center'}]} > <TouchableOpacity onPress={this._onLikePressed}> <FontAwesome name={likeIcon} size={25}/> </TouchableOpacity> <View style={styles.space}/> <TouchableOpacity onPress={this._onCommentPressed}> <FontAwesome name="comment-o" size={25}/> </TouchableOpacity> <View style={styles.space}/> <TouchableOpacity onPress={this._onSharePressed}> <FontAwesome name="share" size={25}/> </TouchableOpacity> </View> {/* Bar Description */} <View style={[styles.layout, {paddingBottom: 20}]}> <Text numberOfLines={4} style={styles.description}> {this.props.item.caseDetails} </Text> <Text style={{paddingTop: 5}}>15 May 2017</Text> </View> </View> ); } } NotifInListItem.propTypes = { item: PropTypes.object.isRequired, onTitlePress: PropTypes.func.isRequired, onImagePress: PropTypes.func.isRequired, onLikePress: PropTypes.func.isRequired, onCommentPress: PropTypes.func.isRequired, onSharePress: PropTypes.func.isRequired, selected: PropTypes.bool.isRequired, }; const styles = StyleSheet.create({ profilePicture: { width: 40, height: 40, borderRadius: 20 }, title: { flex: 1, marginLeft: 10, fontSize: 24, color: 'black', }, image: { height: Dimensions.get('window').width, }, actionIcon: { width: 35, height: 35, }, description: { color: 'black', }, space: { width: 15, }, layout: { paddingLeft: 15, paddingRight: 15, } });
/* * var menu_selector = "nav"; function onScroll(){ var scroll_top = $(document).scrollTop(); $(menu_selector + " a").each(function(){ var hash = $(this).attr("href"); var target = $(hash); if (target.position().top <= scroll_top && target.position().top + target.outerHeight() > scroll_top) { $(menu_selector + " a.active").removeClass("active"); $(this).addClass("active"); } else { $(this).removeClass("active"); } }); } */ function isVisible(tag) { var t = $(tag); var w = $(window); var wt = w.scrollTop(); console.log('window.scrollTop()='+wt); var tt = t.offset().top; console.log('services.offset().top='+tt); var tb = tt + t.height(); return ((tb <= wt + w.height()) && (tt <= wt)); } function isScrolledIntoView(elem) { var docViewTop = $(window).scrollTop(); console.log('docViewTop='+docViewTop); var docViewBottom = docViewTop + $(window).height(); //console.log('docViewBottom='+docViewBottom); var elemTop = $(elem).offset().top; console.log('elemTop='+elemTop); var elemBottom = elemTop + $(elem).height(); //console.log('elemBottom='+elemBottom); return ((elemTop <= docViewTop) && (elemBottom >= docViewBottom)); } $(document).ready(function () { //slow-scroll var $page = $('html, body'); $('a[href*="#"]').click(function () { $page.animate({ scrollTop:$($.attr(this, 'href')).offset().top }, 1500); //$(this).css('color', '#aa0019'); return false; }); //menu-colore $(window).scroll(function () { var docViewTop = $(window).scrollTop(); //var elemTop = $(elem).offset().top; //var a = $("#about"); //var s = $("#services"); //var c = $("#contact_us"); var aboutTop = $("#about").offset().top-20; var servicesTop = $("#services").offset().top-20; var contact_usTop = $("#contact_us").offset().top-20; if ($(window).scrollTop() > 0) { $('nav').css('position', 'fixed').css('top', '0').css('width', '100%'); } else { $('header').css('margin-top', '4em'); } if(docViewTop >= aboutTop && docViewTop < servicesTop) { $('.about').css('color', '#aa0019'); $('.serv').css('color', '#484047'); $('.contacts').css('color', '#484047'); } else if (docViewTop >= servicesTop && docViewTop < contact_usTop) { $('.serv').css('color', '#aa0019'); $('.about').css('color', '#484047'); $('.contacts').css('color', '#484047'); } else if (docViewTop >= contact_usTop) { $('.contacts').css('color', '#aa0019'); $('.about').css('color', '#484047'); $('.serv').css('color', '#484047'); } else { $('.about').css('color', '#484047'); $('.serv').css('color', '#484047'); $('.contacts').css('color', '#484047'); } /* працює, але з мертвими зонами між розділами if (isScrolledIntoView(a)) { $('.about').css('color', '#aa0019'); } else { $('.about').css('color', '#484047'); } if (isScrolledIntoView(s)) { $('.serv').css('color', '#aa0019'); } else { $('.serv').css('color', '#484047'); } if (isScrolledIntoView(c)) { $('.contacts').css('color', '#aa0019'); } else { $('.contacts').css('color', '#484047'); } */ // if ($(window).scrollTop() > 800 && $(window).scrollTop() < 2450) { // $('.about').css('color', '#aa0019'); // } else { // $('.about').css('color', '#484047'); // } // if ($(window).scrollTop() > 2449 && $(window).scrollTop() < 4800) { // $('.serv').css('color', '#aa0019'); // } else { // $('.serv').css('color', '#484047'); // } // if ($(window).scrollTop() > 4799) { // $('.contacts').css('color', '#aa0019'); // } else { // $('.contacts').css('color', '#484047'); // } }); /* //menu-scroll color $(document).on("scroll", onScroll); $("a[href^=#]").click(function(e){ e.preventDefault(); $(document).off("scroll"); $(menu_selector + " a.active").removeClass("active"); $(this).addClass("active"); var hash = $(this).attr("href"); var target = $(hash); $("html, body").animate({ scrollTop: target.offset().top }, 500, function(){ window.location.hash = hash; $(document).on("scroll", onScroll); }); }); */ //Mobile-nav showMobileMenu = false; //$('.mobile').hide(); $('.bar').click(function (event) { //$('.mobile_navPhone').hide(); //$('.fa-phone').css('color', '#aa0019'); //$('nav').css('position', 'fixed'); showMobileMenu = !showMobileMenu; if (showMobileMenu == true) { $('.mobile').show(); $('nav').css('padding-bottom', '0'); } else { $('.mobile').hide(); $('nav').css('padding-bottom', '16px'); } }); $('.mobile .menu-link').click(function (event) { showMobileMenu = !showMobileMenu; $('.mobile').hide(); $('nav').css('padding-bottom', '16px'); }); //Mobile-Phone if ($(window).width() < 992) { showMobile_navPhoneMenu = false; $('.mobile_navPhone').hide(); $('.i-phone').click(function (event) { $('.mobile').hide(); showMobile_navPhoneMenu = !showMobile_navPhoneMenu; if (showMobile_navPhoneMenu == true) { $('.mobile_navPhone').show(); $('.fa-phone').css('color', '#a67c52'); $('nav').css('padding-bottom', '0'); } else { $('.mobile_navPhone').hide(); $('.fa-phone').css('color', '#aa0019'); $('nav').css('padding-bottom', '16px'); } }); } // MODAL // Get the modal var modal = document.getElementById('myModal'); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function () { modal.style.display = "none"; } // Promko var myImages = new Array(); var picturesCount = 40; for (i = 0; i < picturesCount; i++) { myImages[i] = {}; } myImages[0].src = "img/girl-bride_dress.jpg"; myImages[0].alt = "1/40"; myImages[1].src = "img/girl-bride_dress2.jpg"; myImages[1].alt = "2/40"; myImages[2].src = "img/blue_glossy_dress.jpg"; myImages[2].alt = "3/40"; myImages[3].src = "img/blue_glossy_dress2.jpg"; myImages[3].alt = "4/40"; myImages[4].src = "img/baby-bride_dress.jpg"; myImages[4].alt = "5/40"; myImages[5].src = "img/baby-bride_dress2.jpg"; myImages[5].alt = "6/40"; myImages[6].src = "img/red_crystals_dress.jpg"; myImages[6].alt = "7/40"; myImages[7].src = "img/red_crystals_dress2.jpg"; myImages[7].alt = "8/40"; myImages[8].src = "img/bride_dress.jpg"; myImages[8].alt = "9/40"; myImages[9].src = "img/bride_dress2.jpg"; myImages[9].alt = "10/40"; myImages[10].src = "img/blue_dress.jpg"; myImages[10].alt = "11/40"; myImages[11].src = "img/blue_dress2.jpg"; myImages[11].alt = "12/40"; myImages[12].src = "img/pink_dress.jpg"; myImages[12].alt = "13/40"; myImages[13].src = "img/pink_dress2.jpg"; myImages[13].alt = "14/40"; myImages[14].src = "img/white_jacket.jpg"; myImages[14].alt = "15/40"; myImages[15].src = "img/white_jacket2.jpg"; myImages[15].alt = "16/40"; myImages[16].src = "img/bride_dress3.jpg"; myImages[16].alt = "17/40"; myImages[17].src = "img/ball_pair.jpg"; myImages[17].alt = "18/40"; myImages[18].src = "img/white_dress.jpg"; myImages[18].alt = "19/40"; myImages[19].src = "img/white_dress1.jpg"; myImages[19].alt = "20/40"; myImages[20].src = "img/red_dress.jpg"; myImages[20].alt = "21/40"; myImages[21].src = "img/red_dress2.jpg"; myImages[21].alt = "22/40"; myImages[22].src = "img/white_dress_.jpg"; myImages[22].alt = "23/40"; myImages[23].src = "img/white_dress_2.jpg"; myImages[23].alt = "24/40"; myImages[24].src = "img/tailoring_v.jpg"; myImages[24].alt = "25/40"; myImages[25].src = "img/bride_crystals.jpg"; myImages[25].alt = "26/40"; myImages[26].src = "img/wd.jpg"; myImages[26].alt = "27/40"; myImages[27].src = "img/bride_crystals1.jpg"; myImages[27].alt = "28/40"; myImages[28].src = "img/jacket.jpg"; myImages[28].alt = "29/40"; myImages[29].src = "img/jacket1.jpg"; myImages[29].alt = "30/40"; myImages[30].src = "img/overcoat.jpg"; myImages[30].alt = "31/40"; myImages[31].src = "img/overcoat1.jpg"; myImages[31].alt = "32/40"; myImages[32].src = "img/halloween_costume.jpg"; myImages[32].alt = "33/40"; myImages[33].src = "img/halloween_costume2.jpg"; myImages[33].alt = "34/40"; myImages[34].src = "img/chervona_lyce.jpg"; myImages[34].alt = "35/40"; myImages[35].src = "img/chervona_spyna.jpg"; myImages[35].alt = "36/40"; myImages[36].src = "img/synya_lyce.jpg"; myImages[36].alt = "37/40"; myImages[37].src = "img/synya_spyna.jpg"; myImages[37].alt = "38/40"; myImages[38].src = "img/red_v.jpg"; myImages[38].alt = "39/40"; myImages[39].src = "img/blue_crystals.jpg"; myImages[39].alt = "40/40"; var i = 0; var current; $('img', 'div.gal').each(function () { $(this).click(function () { current = parseInt(this.id.substring(3)); modal.style.display = "block"; modalImg.src = this.src; captionText.innerHTML = this.alt; }); i++; }); $('.nextSlide').click(nextSlide); function nextSlide() { current++; if (current == picturesCount) { current = 0; } modalImg.src = myImages[current].src; captionText.innerHTML = myImages[current].alt || ''; } $('.prevSlide').click(prevSlide); function prevSlide() { current--; if (current < 0) { current = picturesCount - 1; } modalImg.src = myImages[current].src; captionText.innerHTML = myImages[current].alt || ''; } $(document).keydown(function (e) { switch (e.which) { case 37: // left prevSlide(); break; case 39: // right nextSlide(); break; case 27: // Esc modal.style.display = "none"; break; default: return; // exit this handler for other keys } e.preventDefault(); // prevent the default action (scroll / move caret) }); // END GALLERY MODAL });
import React, { Component, Fragment } from 'react'; export default class ErrorCatch extends Component { constructor(props) { super(props) this.state = { hasError: null } } static getDerivedStateFromError(error) { return { hasError: true } } componentDidCatch(error, errorInfo) { console.log(error.stack) console.log(error.error) } render() { if (this.state.hasError) { return ( <Fragment> <section class="icon-list"> <i class="nes-mario" style={{width: "60%"}}></i> </section> <h1>Mammamia! Something went wrong!</h1> <button onClick={this.setState({ hasError: null })} >Try Again!</button> </Fragment> ) } else { return this.props.children } } }
var facebookConnect; function onDeviceReady(){ // After device ready, create a local alias facebookConnect = window.plugins.facebookConnect; } loginCallback = function(result){ alert(result); } logoutCallback = function(result){ alert(result); } meCallback = function(result){ alert(JSON.stringify(result)); } statusCallback = function(result){ alert(result); } $("#index").live("pageinit", function(){ $("#login").on("click", function(){ facebookConnect.login(loginCallback, true); }); $("#logout").on("click", function(){ facebookConnect.logout(logoutCallback); }); $("#me").on("click", function(){ facebookConnect.me(meCallback); }); $("#status").on("click", function(){ facebookConnect.status(statusCallback); }); }) document.addEventListener('deviceready', onDeviceReady, false);
( function (){ angular .module('app.maps.controllers') .controller('MapsController',MapsController); MapsController.$inject = ['$scope']; function MapsController($scope){ console.log('init map'); }; })();
import React, { useEffect } from "react"; import { ReactComponent as Ok } from "../images/ok.svg"; import { useHistory } from "react-router-dom"; import "../Styles/ok.css"; function Thankyou() { const history = useHistory(); useEffect(() => { setTimeout(() => { history.push("/"); }, 3000); }); return ( <div className="ok"> <Ok /> <h3>Thanks Successfull. </h3> </div> ); } export default Thankyou;
var $extend = require('extend'); const $promise = require("bluebird"); module.exports = function restfulErrors(req,res){ var self = this; this._errors = []; this._req = req; this._res = res; this.$init = function(){}; this.error = function(status,code,msg,field,obj){ // console.log('log error'); if(!status) status = 400; if(!code) code = 215; if(!msg) msg = "unknown error"; if(!field) field = undefined; var error = {status:status,code:code,message:msg,field:field}; if(typeof obj!=='undefined'){ error = $extend(true, error, obj); } self._errors.push(error); return false; }; this.hasErrors = function(){ return (self._errors.length>0); }; this.clear = function(){ self._errors = []; }; this.response = function(){ return new $promise((resolve, reject) => { if (self._errors.length === 0) self.error(200, 1, 'unknown response'); let statusCode = self._errors[0].status; var lngErrors = self._errors.length; for (var i = 0; i < lngErrors; i++) { delete self._errors[i].status; } var errors = {errors: self._errors}; resolve([statusCode, errors]); self.clear(); }); }; this.$init(); };
var React = require("react"); class Newlistsong extends React.Component { render() { let formAction; if (this.props.message.includes("Favorites")) { formAction = '/favorites/new'; } else { formAction = '/playlists/' + this.props.id + '/newsong'; } let song = this.props.songs.map(song => { return ( <option value={song.id}>{song.title}</option> ); }); return ( <html> <head /> <body> <h3>{this.props.message}</h3> <form method="POST" action={formAction}> Song: <select name="song_id"> {song} </select> <input type="submit" value="Submit"/> </form> </body> </html> ); } } module.exports = Newlistsong;
/** * 微信公众号信息, 需设置IP名单 */ module.exports = { appid: '', secret: '', url: '', // 签名url, 需设置JSAPI安全域名 };
$(document).ready( function () { $('#tabel_nonpemakalah').DataTable({ "paging": true, "lengthChange": true, "searching": true, "ordering": true, "info": false, "responsive": true, "autoWidth": false, "pageLength": 10, "ajax": { "url": "data_nonpemakalah.php", "type": "POST" }, "columnDefs":[ { "targets":[], "orderable":false, }, ], "columns": [ { "data": "nama_lengkap" }, { "data": "instansi" }, ] }); });
const express = require('express'); const path = require('path'); const indexRouter = require('./routes/index'); const epd_tool = require('./modules/app_tools'); const log = require('./modules/log'); // 初始化模板 epd_tool.initAllTemplate(path.join(__dirname, 'public', 'rules')); // 启动应用 const app = express(); // 设置access日志 log.useLogger(app) // 设置全局日志 global.LOG = log.getLogger('info'); // 支持json的body app.use(express.json({ limit: '20mb' })); app.use(express.urlencoded({ limit: '20mb', extended: true })); // 设置静态文件路径 app.use(express.static(path.join(__dirname, 'public'))); // 装载路由,统一设置 / 到indexRouter路由处理器 app.use('/', indexRouter); module.exports = app;
import Mixin from '@ember/object/mixin'; import { debounce } from '@ember/runloop'; export default Mixin.create({ attributeBindings: ['data-toggle', 'data-placement'], tooltipValuesObserver: [], init() { this._super(...arguments); this.tooltipValuesObserver.forEach((key) => { this.addObserver(key, this._rebuildTooltip); }); }, _buildTooltip() { let $els = this.$('[data-toggle="tooltip"]') || []; if ($els.length > 0) { $els.tooltip('fixTitle'); } }, _rebuildTooltip() { debounce(this, this._buildTooltip, 200); }, didRender() { this._super(); this.$('[data-toggle="tooltip"]').tooltip(); } });
import React, { useEffect, useRef, useState } from "react"; import { useDispatch,useSelector } from "react-redux"; import { PostControlsNav, PostControlsOverlay, HiddenInput } from "./style"; import { Link } from "react-router-dom"; import { Button, Form, Modal } from "react-bootstrap"; import { deletePost, togglePinPost,pinningPostReset } from "../../actions/postActions"; export default function PostControls({ onCancel, post }) { const dispatch = useDispatch(); const {pinning, pinningSuccess} = useSelector(state => state.posts) const authenticatedUser = localStorage.getItem("loggedUser"); const [show, setShow] = useState(false); const copyLink = useRef(null); useEffect(()=>{ if(pinningSuccess){ dispatch(pinningPostReset()); onCancel(false); } },[dispatch, onCancel, pinningSuccess]) const handleClose = () => { onCancel(false); setShow(false); }; const handleShow = () => {setShow(true); }; const handleDelete = (e) => { e.preventDefault(); e.stopPropagation(); dispatch(deletePost(post._id)) setShow(false); }; return ( <div> <PostControlsOverlay onClick={e => {e.stopPropagation(); onCancel(false)}}></PostControlsOverlay> <div className="position-relative"> <PostControlsNav className="border d-flex flex-column shadow-lg bg-white"> <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title>Confirm delete</Modal.Title> </Modal.Header> <Modal.Body>Proceed to delete?</Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleClose}> Cancel </Button> <Form method="POST" onSubmit={handleDelete}> <Button variant="primary" type="submit"> Delete </Button> </Form> </Modal.Footer> </Modal> {authenticatedUser === post.user.username && ( <div> <Link to={`/edit-post?postId=${post._id}`} className="border-bottom bg-white" > Edit </Link> {/* If pinning is successfull, useEffect will handle the overlay closing */} <Form method="POST" className="border-bottom" onSubmit={(e) => { dispatch(togglePinPost(post._id)); e.stopPropagation(); e.preventDefault(); }}> <button type="submit" className="bg-white" > {!pinning && post.isPinned ? 'Unpin post' : !pinning && !post.isPinned ? 'Pin post' : 'Pinning'} </button> </Form> <Form method="POST" className="border-bottom" onSubmit={(e) => { e.stopPropagation(); e.preventDefault(); handleShow(); }}> <button type="submit" className="bg-white" > Delete </button> </Form> </div> )} <Form onSubmit={async(e) => { e.preventDefault(); e.stopPropagation(); copyLink.current.select(); if(typeof document.execCommand === "function"){ document.execCommand('copy'); return onCancel(false); } else if(navigator.clipboard && typeof document.execCommand !== "function"){ await navigator.clipboard.writeText(`${window.location.host}/comments?postId=${post._id}`) .then(()=>onCancel(false)) } }}> {/* Don't put hidden attribute to allow copying */} <HiddenInput type="text" ref={copyLink} readOnly value={`${window.location.host}/comments?postId=${post._id}`}/> <button className="bg-white" role="link">Copy link</button> </Form> </PostControlsNav> </div> </div> ); }
// Game objects - will probably separate this out when I get an idea what's actually // going to be in the game // Coordinates explained: // X = angle with respect to north pole // y = height above surface // vx = speed with respect to x, which is X * (r + y) var ClipsToCamera = { init: function (r) { this.clipr = r || 0 this.setmethodmode("draw", "any") }, draw: function () { return !camera.isvisible(this.X, this.y, this.clipr) }, } var Lives = { init: function () { this.alive = true }, die: function () { this.alive = false }, } // For objects that have transitions in/out - don't want to disappear immediately var AppearsDisappears = { init: function (tappear, tdisappear) { this.alive = true this.tappear = typeof tappear == "number" ? tappear : 0.5 this.tdisappear = typeof tdisappear == "number" ? tdisappear : tappear this.appearing = true this.disappering = false this.fappear = 0 }, think: function (dt) { if (this.appearing) { this.fappear = this.tappear ? this.fappear + dt / this.tappear : 1 if (this.fappear >= 1) { this.fappear = 1 this.appearing = false if (this.onappear) this.onappear() } } else if (this.disappearing && this.alive) { this.fappear = this.tdisappear ? this.fappear - dt / this.tdisappear : 0 if (this.fappear <= 0) { this.fappear = 0 this.alive = false } } }, die: function () { this.appearing = false this.disappearing = true }, } var WorldBound = { init: function (X, y) { this.X = X || 0 this.y = y || 0 this.vx = 0 this.vy = 0 this.facingright = true }, think: function () { this.oldX = this.X this.oldy = this.y this.xfactor = Math.max(gamestate.worldr + this.y, 1) }, draw: function () { if (Twondy.wobblet) { var theta = this.x + Twondy.phi var C = Math.cos(theta), S = Math.sin(theta) var r = gamestate.worldr context.rotate(Twondy.beta + Twondy.phi) context.translate(r * (Twondy.cprimex + Twondy.a * S), r * (Twondy.cprimey + Twondy.b * C)) context.rotate(-Math.atan2(Twondy.b * S, Twondy.a * C)) context.translate(0, this.y) } else { context.rotate(-this.X) context.translate(0, this.xfactor) } }, } // States for a state machine var HasStates = { init: function (methodnames) { // Or, how I learned to stop worrying and love JavaScript function notation var methods = {} methodnames.forEach(function (methodname) { methods[methodname] = function () { return this.state && this.state[methodname].apply(this, arguments) } }) this.addcomp(methods) }, // Call this to set the state immediately. // For state changes that should be set at the end of the think cycle, assign to this.nextstate setstate: function (state) { if (this.state && this.state.exit) { this.state.exit.call(this) } if (state instanceof Array) { this.state = state[0] if (this.state.enter) { this.state.enter.apply(this, state.slice(1)) } } else { this.state = state if (this.state && this.state.enter) { this.state.enter.call(this) } } this.think(0) }, // this.nextstate can either be a state object or an Array of [stateobj, arg1, arg2], where // the args will be passed to stateobj.enter. updatestate: function () { if (this.nextstate) { this.setstate(this.nextstate) this.nextstate = null } }, } // Has a velocity and an acceleration, and updates position based on that var BasicMotion = { init: function () { this.vx = this.vx || 0 this.vy = this.vy || 0 this.ax = this.ax || 0 this.ay = this.ay || 0 }, think: function (dt) { this.X += (this.vx + 0.5 * this.ax * dt) * dt / this.xfactor this.y += (this.vy + 0.5 * this.ay * dt) * dt this.vx += this.ax * dt this.vy += this.ay * dt // Last ax and ay are the acceleration for the purposes of animation this.lastax = this.ax ; this.lastay = this.ay this.ax = this.ay = 0 }, } var IsBall = { init: function (size, color) { this.ballsize = size || 10 this.ballcolor = color || "orange" }, draw: function () { context.beginPath() context.arc(0, 0, this.ballsize, 0, tau) context.strokeStyle = this.ballcolor context.lineWidth = 1 context.stroke() } } var IsBox = { init: function (size, color) { this.boxsize = size || 10 this.boxcolor = color || "purple" }, draw: function () { context.strokeStyle = this.boxcolor context.strokeRect(-this.boxsize/2, 0, this.boxsize, this.boxsize) } } var IsBlob = { init: function (size, color0, color1) { this.blobsize = size || 10 this.blobcolor0 = color0 || "purple" this.blobcolor1 = color1 || "purple" this.tspin = 0 }, think: function (dt) { this.tspin += dt }, draw: function () { context.rotate(this.tspin) context.strokeStyle = "black" context.lineWidth = 1 var s = this.blobsize function circ(x, y, r) { context.beginPath() context.arc(x*s, y*s, r*s, 0, tau) context.stroke() context.fill() } context.fillStyle = this.blobcolor0 circ(0, 0.8, 0.5) circ(0, -0.8, 0.5) context.fillStyle = this.blobcolor1 circ(0, 0, 0.8) context.fillStyle = this.blobcolor0 circ(0.8, 0, 0.5) circ(-0.8, 0, 0.5) }, } var Wobbles = { init: function (wspeed, wmag) { this.wobblet = 0 this.wspeed = wspeed || 4 this.wmag = wmag || 0.3 }, wobble: function () { this.wobblet = 0 }, think: function (dt) { this.wobblet += dt }, draw: function () { var w = this.wobblet * this.wspeed if (w < 50) { var s = 1 + this.wmag * Math.sin(w) * Math.exp(-0.1 * w) context.scale(s, 1/s) } }, } var Drifts = { init: function (vx, vy) { this.vx = vx || 0 this.vy = vy || 0 }, think: function (dt) { this.X += this.vx * dt / this.xfactor this.y += this.vy * dt }, } var SeeksOrbit = { init: function (ymax) { this.ymax = ymax || 200 }, think: function (dt) { this.X += this.vx * dt / this.xfactor if (this.y < this.ymax) { this.y += this.vy * dt if (this.y >= this.ymax) { this.y = this.ymax this.vy = 0 } } else if (this.y > this.ymax) { this.y -= this.vy * dt if (this.y <= this.ymax) { this.y = this.ymax this.vy = 0 } } if (this.y != this.ymax) { this.vy += 40 * dt } }, } var Crashes = { think: function (dt) { this.alive = this.alive && this.y > 0 }, } var FadesUpward = { init: function (ymax) { this.ymax = ymax }, think: function (dt) { this.alive = this.alive && this.y < this.ymax }, draw: function () { var a = Math.max(0, Math.min(1, (this.ymax - this.y) / 50)) context.globalAlpha *= a }, } var FadesOutward = { init: function (smax, vs, s0, color) { this.smax = smax this.vs = vs || 400 this.s = s0 || 0 this.color = color || "blue" }, think: function (dt) { this.s += this.vs * dt if (this.s > this.smax) this.alive = false }, draw: function () { var a = Math.max(0, Math.min(1, 1 - (this.smax - this.s) / this.smax / 3)) context.strokeStyle = this.color context.fillStyle = this.color context.lineWidth = 1.5 context.beginPath() context.arc(0, 0, this.s, 0, tau) context.stroke() context.globalAlpha *= 0.3 context.fill() }, } var HitsWithin = { init: function (dhp) { this.dhp = dhp }, hit: function (objs) { for (var j = 0 ; j < objs.length ; ++j) { var dx = getdX(this.X, objs[j].X) * this.xfactor var dy = this.y - objs[j].y if (dx * dx + dy * dy < this.s * this.s) { objs[j].takedamage(this.dhp) } } }, } var GivesMoney = { init: function (money) { this.money = money || 1 }, benabbed: function (nabber) { if (this.alive) { this.alive = false gamestate.bank += this.money effects.push(new MoneyBox(this.money, this.X, this.y)) } }, } var ExplodesOnTouch = { benabbed: function (nabber) { if (this.alive) { this.alive = false ehitters.push(new Wave(this.X, this.y, 300, 500)) } }, } var GivesBoost = { init: function (boostvy) { this.boostvy = boostvy }, benabbed: function (nabber) { if (this.alive && nabber.y > 0) { this.alive = false nabber.vy = Math.max(nabber.vy, 0) + this.boostvy nabber.jumps = 1 } }, } var HasHealth = { init: function (hp) { this.hp = hp || 1 }, die: function () { this.alive = false }, takedamage: function (dhp) { this.hp -= dhp if (this.hp <= 0) this.die() } } function Token(X, y) { this.X = X this.y = y this.vx = UFX.random.choice([-50, 50]) this.vy = -30 this.alive = true this.think(0) } Token.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(IsBall, 5, "yellow") .addcomp(Drifts) .addcomp(Crashes) .addcomp(GivesMoney) function Bubble(X, y) { this.X = X this.y = y this.vx = UFX.random(-20, 20) this.vy = 20 this.alive = true this.think(0) } Bubble.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(FadesUpward, 200) .addcomp(Wobbles, 4, 0.3) .addcomp(IsBall, 20, "#AAF") .addcomp(Drifts) .addcomp(GivesBoost, 360) function Bomb(X, y) { this.X = X this.y = y this.vx = UFX.random.choice([-40, 40]) this.vy = 60 this.alive = true this.think(0) } Bomb.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(SeeksOrbit, 200) .addcomp(IsBlob, 10, "pink") .addcomp(ExplodesOnTouch) function Wave (X0, y0, smax, vs) { this.X = X0 this.y = y0 if (smax) this.smax = smax if (vs) this.vs = vs this.alive = true this.think(0) } Wave.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(FadesOutward, 100, 200) .addcomp(HitsWithin, 1)
import React, { useState, useEffect } from "react"; import axios from "axios"; import { Card, CardTitle, CardText, } from "reactstrap"; import FormModal from './FormModal' function Event () { const [info, setInfo] = useState({ events: [] }); useEffect(() => { const fetch = async () => { try { const result = await axios("http://localhost:4100/events"); setInfo({ ...info, events: result.data }); } catch (e) { console.log(e) } } fetch() },[]); const event = info.events.map((item) => ( <div key={item.id}> <Card body inverse style={{ backgroundColor: "#333", borderColor: "#333" }} > <CardTitle sm="5" tag="h5"> {item.name} </CardTitle> <CardText>{item.venue}</CardText> <CardText> <small className="text-muted">{item.date}</small> </CardText> <FormModal/> </Card> </div> )); return ( <div className="Container"> <div className="event"> {event} </div> </div> ); } export default Event;
const express = require('express') const bodyParser = require('body-parser') const { Author, Book } = require('./sequelize') const app = express() app.use(bodyParser.json()) app.get('', (req, res) => res.status(200).send({ message: 'Welcome to the beginning of nothingness.', })); // Create a restaurant app.post('/rest', (req, res) => { console.log(req.body) restaurant.create(req.body) .then(restaurants => res.json(restaurants)) }) // create an employee app.post('/emp', (req, res) => { console.log("employee", req.body) employee.create(req.body) .then(employee => res.json(employee)) }) // get all books app.get('/allrest', (req, res) => { restaurant.findAll().then(restaurant => res.json(restaurant)) }) // get all authors app.get('/allemp', (req, res) => { employee.findAll().then(employees => res.json(employees)) }) // get book by bookId app.get('/rest/:id', (req, res) => { restaurant.findOne( { where: { id: req.params.storeID, }, } ).then(restaurant => res.json(restaurant)) }) // get author by id app.get('/emp/:id', (req, res) => { employee.findOne( { where: { id: req.params.employeeID, }, } ).then(employee => res.json(employee)) }) const port = 12000 app.listen(port, () => {console.log(`Running on http://localhost:${port}`) })
app.activeDocument.activeLayer.locked ^= 1;
class Developer { askQuestions() { console.log('Asking about design patterns!') } } class CommunityExecutive { askQuestions() { console.log('Asking about community building') } } module.exports = { Developer, CommunityExecutive }
/** * Inserts an element after another element. * @param {Node Element} newNode Node to insert. * @param {Node Element} referenceNode Reference of insert. * @return {void} */ function insertAfter(newNode, referenceNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } /** * AJAX call, much like how jQuery AJAX works. * @param {object} o Holds information * @return {void} */ function ajax(o){ let xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { if (o.success && xmlhttp.responseText.indexOf('Error') == -1) { o.success(xmlhttp.responseText); } else if (o.error) { o.error(xmlhttp.responseText); } } let url = ""; if (o.data) { let i = 0; for (var k in o.data){ if (o.data.hasOwnProperty(k)) { if (i > 0) url += "&"; url += k + '=' + encodeURIComponent(o.data[k]); i++; } } } let method = "GET"; if (o.method) { method = o.method.toUpperCase(); } if (method == "GET" || method == "POST") { try { xmlhttp.open(method, o.url, true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(encodeURI(url)); } catch(err) { console.log(err); } } } /** * UI modifications for liking a post * @param {DOM Element} heart The heart icon * @return {void} */ function applyLike(heart) { heart.classList.remove('btn-like'); heart.classList.remove('fa-heart-o'); heart.classList.add('btn-liked'); heart.classList.add('fa-heart'); } /** * UI modifications for unliking a post * @param {DOM Element} heart The heart icon * @return {void} */ function applyUnlike(heart) { heart.classList.remove('btn-liked'); heart.classList.remove('fa-heart'); heart.classList.add('btn-like'); heart.classList.add('fa-heart-o'); } /** * Likes or unlikes a post * @param {DOM Element} heart The heart icon * @return {void} */ function like(heart) { let url = document.getElementById("like-action").value; let isLiking = true; let postId = heart.getAttribute('post-id'); if (heart.classList.contains('btn-liked')) { applyUnlike(heart); isLiking = false; } else { applyLike(heart); } ajax({ method: 'post', url: url, data: { post_id: postId, is_liking: isLiking }, success: function(res) { if (res >= 1) { let spanNumLikes = document.getElementById('num-likes-' + postId); let numLikes = parseInt(spanNumLikes.innerHTML); numLikes += isLiking ? 1 : -1; spanNumLikes.innerHTML = numLikes; } else { if (heart.classList.contains('btn-liked')) { applyUnlike(heart); } else { applyLike(heart); } alert("Please log in to like this post."); } }, error: function(err) { console.log(err); } }); } /** * Deletes a post * @param {number} id Id of the post * @return {void} */ function deletePost(id) { let yes = confirm("Are you sure?"); if (yes) { ajax({ method: 'post', url: actionDir + 'delete_post.php', data: { post_id: id }, success: function(res) { let post = document.getElementById('upload-box-' + id); if (!post) post = document.getElementById('post-box-' + id); post.style.opacity = '0'; setTimeout(function() { post.parentNode.removeChild(post); appendLastPost(); }, 400); }, error: function(err) { alert(err); } }); } } var imgDir; var actionDir; var postDir; (function() { imgDir = document.getElementById('img-dir').getAttribute('value'); actionDir = document.getElementById('action-dir').getAttribute('value'); postDir = document.getElementById('post-dir').getAttribute('value'); }());
exports.up = function(knex, Promise) { return knex.schema.createTable('action_log', function(table) { table.increments(); table.string('method').defaultTo(null); table.string('action').defaultTo(null); table.string('name').defaultTo(null); table.string('value').defaultTo(null); table.string('ip').defaultTo(null); table.integer('userId').defaultTo(null).unsigned().references('id').inTable('users'); table.integer('clientId').defaultTo(null).unsigned().references('id').inTable('clients'); table.timestamp('createdAt').defaultTo(knex.fn.now()); table.timestamp('updatedAt').defaultTo(knex.fn.now()); }); }; exports.down = function(knex, Promise) { knex.schema.dropTable('action_log'); };
import React from 'react'; import { View, StyleSheet, TextInput } from 'react-native'; import Icon from 'react-native-vector-icons/Entypo'; const IconTextInput = ({ icon, value, placeholder, name, onKeyPress, width = 145 }) => ( <View style={styles.searchSection}> <Icon style={styles.searchIcon} name={icon} size={20} color="rgb(102,22,173)" /> <TextInput style={[styles.input, { width }]} placeholder={placeholder} underlineColorAndroid="transparent" value={value} onChangeText={text => onKeyPress(text, name)} /> </View> ); const styles = StyleSheet.create({ searchSection: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgb(241,241,241)', borderWidth: 2, borderColor: '#ccc' }, searchIcon: { padding: 10 }, input: { height: 55, paddingTop: 10, paddingRight: 10, paddingBottom: 10, paddingLeft: 0, backgroundColor: 'rgb(241,241,241)', color: '#424242', fontSize: 18 } }); export default IconTextInput;
'use strict'; const fs = require('fs'); const buffer = fs.readFileSync('input.txt'); const file = String(buffer); // Part 1 function part1() { let list = file.split('\n'), /*list = [ 'aaaaa-bbb-z-y-x-123[abxyz]', 'a-b-c-d-e-f-g-h-987[abcde]', 'not-a-real-room-404[oarel]', 'totally-real-room-200[decoy]' ],*/ sectorIDs = []; list.forEach(line => { let sectorID = line.match(/[0-9]+/)[0], split = line.split(/[0-9]+/), name = split[0].replace(/-/g, ''), checksum = split[1].replace(/(\[|\])/g, ''), letters = {}, letterList = [], ordered = '', i; for (i = 0; i < name.length; i++) { if (letters[name[i]] !== undefined) { letterList[letters[name[i]]].count++; } else { letterList.push({ key: name[i], count: 1 }); letters[name[i]] = letterList.length - 1; } } letterList = letterList.sort((a, b) => { if (b.count > a.count) return 1; if (a.count > b.count) return -1; if (a.count === b.count) { if (a.key > b.key) return 1; if (b.key > a.key) return -1; } return 0; }); for (i = 0; i < 5; i++) { ordered += letterList[i].key; } if (checksum === ordered) sectorIDs.push(sectorID); }); return sectorIDs.reduce((memo, value) => { return memo += parseInt(value, 10); }, 0); } console.log(part1()); const alphabet = 'abcdefghijklmnopqrstuvwxyz' // Part 2 function getAlphaNumber(letter) { let number = 0, i; for (i = 0; i < 26; i++) { if (letter === alphabet[i]) { number = i; i = 26; } } return number; } function decrypt(name, shift) { let decrypted = '', i; for (i = 0; i < name.length; i++) { if (name[i] === '-') { decrypted += ' '; } else { decrypted += alphabet[((getAlphaNumber(name[i]) + shift) % 26)]; } } return decrypted; } function part2() { let list = file.split('\n'), storageSector; list.forEach(line => { let sectorID = parseInt(line.match(/[0-9]+/)[0], 10), split = line.split(/[0-9]+/), name = split[0], checksum = split[1].replace(/(\[|\])/g, ''), letters = {}, letterList = [], ordered = '', i; for (i = 0; i < name.length; i++) { if (name[i] !== '-') { if (letters[name[i]] !== undefined) { letterList[letters[name[i]]].count++; } else { letterList.push({ key: name[i], count: 1 }); letters[name[i]] = letterList.length - 1; } } } letterList = letterList.sort((a, b) => { if (b.count > a.count) return 1; if (a.count > b.count) return -1; if (a.count === b.count) { if (a.key > b.key) return 1; if (b.key > a.key) return -1; } return 0; }); for (i = 0; i < 5; i++) ordered += letterList[i].key; if (checksum === ordered && decrypt(name, sectorID).indexOf('northpole object storage') >= 0) storageSector = sectorID; }); return storageSector; } console.log(part2());
/** * 公共JS处理类库 **/ var _init_serachform_name='searchfrom'; var _init_listform_name='listfrom'; //---查找---// function searchList(fname){ if("undefined" == typeof fname) fname=_init_serachform_name; alert(fname); var pro =document.getElementById(fname); pro.method = "post"; pro.submit(); } //搜索 function search(url,fname){ if(fname=='') fname=_init_form_name; var pro =document.getElementById(fname); pro.action = url; pro.method = "post"; pro.submit(); } /*****删除--批量排序*****/ /*****列表专用:listform*****/ function doOrder(url){ var formObj = document.getElementById(_init_listform_name); formObj.action = url; formObj.method = "post"; formObj.submit(); } /*****审核-批量删除*****/ function docheck(url,ckbid){ if (!hasChecked(ckbid)){ jAlert('请先选中要审核的项!', '提示框'); return; } jConfirm('您确定要审核吗?', '提示对话框', function(r) { if(r){ var formObj = document.getElementById(_init_listform_name); formObj.action = url; formObj.method = "post"; formObj.submit(); } return ; }); } /*****删除--批量删除*****/ function dodel(url,ckbid){ if (!hasChecked(ckbid)){ jAlert('请先选中要删除的项!', '提示框'); return; } jConfirm('您确定要删除吗?', '提示对话框', function(r) { if(r){ var formObj = document.getElementById(_init_listform_name); //formObj.action = url +"?"+id+"="+ getCheckedValue(ckbid); formObj.action = url; formObj.method = "post"; formObj.submit(); } return ; }); } /*****删除--删除一条*****/ function del(url,ckbid,id){ setChecked(ckbid,id) dodel(url,ckbid); } /*****直接挑战的某一页面******/ /*****编辑,添加等*****/ function gourl(url){ window.location.href=url; } /*****根据ID选择某个checkbox*****/ function setChecked(itemName,id){ var items = document.getElementsByName(itemName); if(items){ if(items.length){ for(var i=0;i<items.length;i++){ if(items[i].value==id) { items[i].checked=true; }else{ items[i].checked=false; } } } } return false; } /*****检查有没有被选中*****/ function hasChecked(itemName){ var items = document.getElementsByName(itemName); if(items){ if(items.length){ for(var i=0;i<items.length;i++){ if(items[i].checked){ return true; } } }else{ return items.checked; } } return false; } /*****取选中的多选框*****/ function getCheckedValue(itemName){ var items = document.getElementsByName(itemName); var ids = ""; if(items){ if(items.length){ for(var i=0;i<items.length;i++){ if(items[i].checked){ if(ids == ""){ ids = items[i].value; }else{ ids += "," +items[i].value; } } } }else{ if(items.checked){ ids= items.value; } } } return ids; }
// eslint-disable-next-line no-unused-vars import styles from './styles.scss'; const defaultTheme = () => `<div class="mstr-container" data-mstr-directive="autoHideShow,togglePlayPauseClick"> <div class="mstr-centerbar"> <span data-mstr-standard="spinner"></span> </div> <div class="mstr-bottombar"> <div class="mstr-items"> <div class="mstr-item"> <span data-mstr-standard="playbutton"></span> </div> <div class="mstr-item"> <span data-mstr-standard="playlistpreviousbutton"></span> </div> <div class="mstr-item mstr-item--fill"> <span data-mstr-standard="seekbar"></span> </div> <div class="mstr-item"> <span data-mstr-standard="timedisplay"></span> </div> <div class="mstr-item"> <span data-mstr-standard="playlistnextbutton"></span> </div> <div class="mstr-item"> <span data-mstr-standard="fullscreenbutton"></span> </div> <div class="mstr-item"> <span data-mstr-standard="volumeslider"></span> </div> <div class="mstr-item"> <span data-mstr-standard="qualitybutton"></span> </div> </div> </div> </div>`; export default defaultTheme;
function randomBodyColour(){ document.body.style.backgroundColor=bodyColour (); } function bodyColour () { var getColour = Math.floor(Math.random() * 0xFFFFFF); return "#" + (getColour.toString(16)).substr(-6); } function randomBtnColour(){ document.getElementById("btn").style.backgroundColor =btnColour(); } function btnColour () { var getColour = Math.floor(Math.random() * 0xFFFFFF); return "#" + (getColour.toString(16)).substr(-6); }
import React from "react"; import { makeStyles, useTheme } from '@material-ui/core/styles'; import { useRouter } from 'next/router'; import Typography from '@material-ui/core/Typography'; import Button from 'components/Button'; import Grid from '@material-ui/core/Grid'; import { cdnURL } from 'utils/constants'; const useStyles = makeStyles((theme) => ({ })); const List = () => { // Get the data of the current list. const router = useRouter(); const classes = useStyles(); const theme = useTheme(); return ( <Grid container direction="row" justify="center" spacing={6} alignItems="center"> <Grid item md> <Typography variant="h3" color="secondary" style={{ lineHeight: '0.8em', fontWeight: 400 }}> About </Typography> <Typography variant="h1" color="secondary" style={{ lineHeight: '0.8em', fontWeight: 700, marginBottom: '4rem' }}> SAMAHAN </Typography> <Button variant="contained" color="secondary" disableElevation onClick={() => router.push('/samahan')}> Learn More </Button> </Grid> <Grid item md> <center> <img src={`${cdnURL}/21-22/samahan asset.png`} style={{ width: '100%', }} /> </center> </Grid> </Grid> ); }; export default List;
var stylist = angular.module('stylistCtrl', []); stylist.controller('stylist', ['$scope', 'Stylist', 'Message', function($scope, Stylist, Message) { Stylist.all().success(function(data) { $scope.stylists = data; }); $scope.showAddForm = function() { if($(".top .form").is(':visible')) { $(".top .form").fadeOut(); } else { $(".top .form").fadeIn(); } }; $scope.addStylist = function() { Stylist.add($scope.stylist).success(function(data) { Message.send([data['type'], data['msg']]); $scope.stylist = ''; if(data['type'] == 'SUCCESS') { Stylist.all().success(function (data) { $scope.stylists = data; }) } }); }; $scope.stylistDel = function(id) { Stylist.del(id).success(function(data) { Message.send([data['type'], data['msg']]); if(data['type'] == 'SUCCESS') { Stylist.all().success(function(data) { $scope.stylists = data; }); } }); }; }]);
 // document ready starts here $(document).ready(function () { //PopOver for selecting voucher type $('#changeType').popover({ placement: 'right', html: true, content: $('#typeWrap').html() }).on('click', function () { //inititalize select 2 ddl $("#ddlChangeType").select2({ width: '100%' }); // Apply Filter Click $('#btnChangeType').click(function () { var Vouchertype = $("#ddlChangeType").select2('data').id; $('#hdnVoucherType').val(Vouchertype); //Filter Logic Here if (Vouchertype == "0") { errorAlert('Select Type of voucher'); } else { var Voucherno = $("#ddlChangeType").select2('data').text;//Get text to Change Main Title $('#hdnVoucherTypeName').val(Voucherno); GetVoucherNo();//Get voucher Number $('#lblTitle').text(Voucherno);//Changes The Main title } $('#changeType').popover('hide'); $('body').on('hidden.bs.popover', function (e) { $(e.target).data("bs.popover").inState = { click: false, hover: false, focus: false }; }); }) // Cancel Filter Click $('#btnChangeCancel').click(function () { $('#changeType').popover('hide'); $('body').on('hidden.bs.popover', function (e) { $(e.target).data("bs.popover").inState = { click: false, hover: false, focus: false }; }); }) }); $('#datepicker').datepicker(); $('select.form-select').select2(); //Used to add new rows to the table $('#addRow').click(function () { //Removes the select2 property of dummy table row $('#dummy .dummyRow .account-heads').select2('destroy'); $('#dummy .dummyRow .CostCenter').select2('destroy'); $('#dummy .dummyRow .Job').select2('destroy'); //Clones the dummyRow with normal select $('#dummy .dummyRow').clone(true).appendTo('.journal-table > tbody'); //Add select2 property to the cloned Select $('#VoucherTable').find('.dummyRow .account-heads').select2(); $('#VoucherTable').find('.dummyRow .CostCenter').select2(); $('#VoucherTable').find('.dummyRow .Job').select2(); //Removes the dummyrow class from the cloned row $('#VoucherTable').find('.dummyRow').removeClass('dummyRow'); //Functionality to get serial number for the added row var tr = $('#VoucherTable>tbody').children('tr') $('.slno').text(parseInt(tr.length)); $('#VoucherTable').find('.slno').removeClass('slno'); }); $('body').on('click', '.remove-row', function () { var tbllength = $('#VoucherTable tbody').children('tr').length; if (tbllength <= 2) { errorAlert('Atleast Two lines should be in the table'); } else { $(this).closest('tr').hide('slow', function () { $(this).closest('tr').remove(); calculateDebit(); $('.credit-total').text($('.debit-total').text()); var tr = $('#VoucherTable>tbody').children('tr'); $(tr[0]).children('td:nth-child(3)').find('.credit-Amount').val($('.debit-total').text()); GetSeriallNo(); }); } }); //Function to add serial number in the table function GetSeriallNo() { var tr = $('#VoucherTable>tbody').children('tr'); var length = tr.length; for (var i = 0; i < length; i++) { $(tr[i]).eq(0).children('td:nth-child(1)').text(i + 1); } } var apiurl = $('#hdApiUrl').val(); //GetVoucherNo(); $('#ddlCreditHead').select2(); $('.account-heads').select2(); $('.CostCenter').select2(); $('.Job').select2(); //This Function is used to get the URL parameters and to get the data from the database var Params = getUrlVars(); if (Params.ID != undefined && !isNaN(Params.ID)) { reset(); $('#btnSave').html('<i class="md md-archive"></i>&nbsp;Update'); $('#btnSavePrint').html('<i class="md md-print"></i>&nbsp;Update & Print'); var GroupID = Params.ID; $.ajax({ url: apiurl + 'api/VoucherEntry/GetVoucherDataforEdit', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(GroupID), success: function (response) { var tr = $('#VoucherTable>tbody').children('tr'); for (var i = 0; i < response.Table.length; i++) { var CostCenter = response.Table[i].CostCenter.split("`");; var NewCost = CostCenter[0]; var selected = ""; $(tr[i]).find('.entry-desc').val(response.Table[i].Fve_ExpenseDesc); if (i >= 5) { //$('#addRow').trigger('click'); //Adds a new row if the edit data has more than 5 rows //Removes the select2 property of dummy table row $('#dummy .dummyRow .account-heads').select2('destroy'); $('#dummy .dummyRow .CostCenter').select2('destroy'); $('#dummy .dummyRow .Job').select2('destroy'); //Clones the dummyRow with normal select $('#dummy .dummyRow').clone(true).appendTo('.journal-table > tbody'); //Add select2 property to the cloned Select $('#VoucherTable').find('.dummyRow .account-heads').select2(); $('#VoucherTable').find('.dummyRow .CostCenter').select2(); $('#VoucherTable').find('.dummyRow .Job').select2(); //Removes the dummyrow class from the cloned row $('#VoucherTable').find('.dummyRow').removeClass('dummyRow'); //Functionality to get serial number for the added row var tr = $('#VoucherTable>tbody').children('tr'); $('.slno').text(parseInt(tr.length)); $('#VoucherTable').find('.slno').removeClass('slno'); selected = response.Table[i].ParticularsID + "|" + response.Table[i].CostHead; $(tr[i]).find('.CostCenter').select2('val', NewCost); if (response.Table[i].CreditOrDebit == 0) { $(tr[i]).find('.account-heads-Credit').select2('val', selected); } else { $(tr[i]).find('.account-heads').select2('val', selected); } if (response.Table[i].Fve_ExpenseDesc != null || response.Table[i].Fve_ExpenseDesc != "") { $(tr[i]).find('.entry-desc').val(response.Table[i].Fve_ExpenseDesc); } //alert(response.Table[i].Fve_ExpenseDesc); $(tr[i]).find('.Job').select2("val", response.Table[i].Job_ID); if (response.Table[i].DebitAmt == 0) { $(tr[i]).find('.debit-Amount').val(""); } else { $(tr[i]).find('.debit-Amount').val(response.Table[i].DebitAmt); } if (response.Table[i].creditAmt == 0) { $(tr[i]).find('.credit-Amount').val(""); } else { $(tr[i]).find('.credit-Amount').val(response.Table[i].creditAmt); } calculateDebit(); calculateCredit(); } else { selected = response.Table[i].ParticularsID + "|" + response.Table[i].CostHead; $(tr[i]).find('.CostCenter').select2('val', NewCost); $(tr[i]).find('.Job').select2("val", response.Table[i].Job_ID); if (response.Table[i].CreditOrDebit == 0) { $(tr[i]).find('.account-heads-Credit').select2('val', selected); } else { $(tr[i]).find('.account-heads').select2('val', selected); } if (response.Table[i].DebitAmt == 0) { $(tr[i]).find('.debit-Amount').val(""); } else { $(tr[i]).find('.debit-Amount').val(response.Table[i].DebitAmt); } if (response.Table[i].creditAmt == 0) { $(tr[i]).find('.credit-Amount').val(""); } else { $(tr[i]).find('.credit-Amount').val(response.Table[i].creditAmt); } calculateDebit(); calculateCredit(); } if (response.Table[0].Fve_IsCheque == true) { var date = new Date(response.Table[0].Fve_ChequeDate); var dateString = date.getDate() + '/' + getmonth(date.getMonth() + 1) + '/' + date.getFullYear(); $('#chkIsCheque').prop('checked', true); $('#dvCheque').fadeIn('slow'); $('#dvCheque').removeClass('hidden'); $('#txtChequeNumber').val(response.Table[0].Fve_ChequeNo); $('#txtChequeDate').val(dateString); $('#txtDrawOn').val(response.Table[0].Fve_Drawon); } else { $('#chkIsCheque').prop('checked', false); $('#dvCheque').fadeOut('slow'); $('#dvCheque').addClass('hidden'); $('#txtChequeNumber').val(""); $('#txtChequeDate').val(""); $('#txtDrawOn').val(""); } $('#hdnVoucherNumber').val(response.Table[0].Fve_Number); $('#hdnGroupID').val(response.Table[0].Fve_GroupID); $('#VoucherNumber').text(response.Table[0].Voucher); $('#txtVoucherDate').datepicker("update", new Date(response.Table[0].Fve_Date)); $('.Narration').val(response.Table[0].Fve_Description); $('#btnSave').html('<i class="md md-archive"></i>&nbsp;Update'); $('#btnSavePrint').html('<i class="md md-print"></i>&nbsp;Update & Print'); } }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } //Voucher Save function call without print $('#btnSave').click(function () { save(false); }); $('body').on('click', '#chkIsCheque', function () { if ($('#chkIsCheque').prop('checked')) { $('#dvCheque').fadeIn('slow'); $('#dvCheque').removeClass('hidden'); $('#txtChequeDate').datepicker('setDate', today); } else { $('#dvCheque').fadeOut('slow'); $('#dvCheque').removeClass('hidden'); $('#txtChequeNumber').val(""); $('#txtChequeDate').val(""); $('#txtDrawOn').val(""); } }); //Voucher Save function call with print $('#btnSavePrint').click(function () { save(true); }); //Save Function Definition function save(print) { var voucher = {}; var Heads = "";//Stores the head ID seperated by | symbol var child = "";//Stores the Child ID seperated by | symbol var amount = ""; var costcenter = ""; var JobString = ""; var tempData = "";//Data Used to Store The Select2 value; var creditorDebit = "";//Flag used to identify credit or debit.1 if Debit 0 if Credit.Seperated by | symbol var creditorDebitTemp = "";//Flag used to identify credit or debit.1 if Debit 0 if Credit. var EntryDesc = ""; var tr = $('#VoucherTable>tbody').children('tr'); var debitTotal = $('.debit-total').text();//Final debit total(Sum of debit amounts) var creditTotal = $('.credit-total').text();//Final Credit total(Sum of credit amounts) var flag = 0; if ($('.debit-total').text() != $('.credit-total').text()) { if (isNaN($('.debit-total').text()) || isNaN($('.credit-total').text())) { errorAlert('Enter valid Amount'); } else { errorAlert('Credit And Debit Amount Are Not Equal'); } } else if (debitTotal != "0" && creditTotal != "0") { for (var i = 0; i < tr.length; i++) { var debit = $(tr[i]).children('td:nth-child(4)').find('.debit-Amount').val(); var credit = $(tr[i]).children('td:nth-child(3)').find('.credit-Amount').val(); var Head = $(tr[i]).children('td').children('.account-heads').select2('data').id; var ddlCostCenter = $(tr[i]).children('td').children('.CostCenter').select2('data').id; //Cost Center ddlvalue if (debit == "" && credit == "" && Head != "0" || isNaN(debit) || isNaN(credit)) { errorAlert('Enter Valid Amount'); flag = 1; return false; } else if ($(tr[i]).children('td').children('.account-heads').select2('data').id == 0 && (debit != "" || credit != "")) { errorAlert('Head is Not Selected'); flag = 1; return false; } else if ($(tr[i]).children('td').children('.account-heads').select2('data').id != 0 && (debit != "" || credit != "")) { tempData = $(tr[i]).children('td').children('.account-heads').select2('data').id + "|"; var Job = $(tr[i]).children('td').children('.Job').select2('data').id; var Desc = $(tr[i]).children('td').children('.entry-desc').val(); if (EntryDesc == "") { EntryDesc = Desc; } else { EntryDesc += '|' + Desc; } if ($(tr[i]).children('td').children('.account-heads').select2('data').id == undefined) { tempData = $(tr[i]).children('td').children('.account-heads-Credit').select2('data').id + "|"; } var headstring = tempData.split("|"); if (Heads == "") { Heads = headstring[0]; } else { Heads += "|" + headstring[0]; } if (child == "") { child = headstring[1]; } else { child += "|" + headstring[1]; } if (JobString == "") { JobString += Job; } else { JobString += "|" + Job; } if (debit != "") { creditorDebitTemp = "1"; //Debit then creditOrDebit is One //Appends Debit Amount if Debit if (amount == "") { amount = debit; } else { amount += "|" + debit; } if (costcenter == "") { if (ddlCostCenter == "0") { costcenter = "1`" + debit; } else { costcenter += ddlCostCenter + "`" + debit; } } else { if (ddlCostCenter == "0") { costcenter += "|1`" + debit; } else { costcenter += "|" + ddlCostCenter + "`" + debit; } } //if (costcenter == "") { // costcenter = ddlCostCenter + "`" + debit; //} //else { // costcenter += "|" + ddlCostCenter + "`" + debit; //} } else if (credit != "") { creditorDebitTemp = "0"; //Credit Then CreditorDebit is zero //Appends Credit Amount if Credit if (amount == "") { amount = credit; } else { amount += "|" + credit; } if (costcenter == "") { if (ddlCostCenter == "0") { costcenter = "1`" + credit; } else { costcenter += ddlCostCenter + "`" + credit; } } else { if (ddlCostCenter == "0") { costcenter += "|1`" + credit; } else { costcenter += "|" + ddlCostCenter + "`" + credit; } } } //Appends Credit or Debit if (creditorDebit == "") { creditorDebit = creditorDebitTemp; } else { creditorDebit += "|" + creditorDebitTemp; } } } if (debitTotal != "0" && creditTotal != "0" && flag != 1) { voucher.AccountHead = Heads; voucher.AccountChild = child; voucher.Amount = amount; voucher.VoucherType = creditorDebit; voucher.Description = $('.Narration').val(); voucher.IsVoucher = 1; if ($('#chkIsCheque').prop('checked')) { voucher.IsCheque = 1; voucher.ChequeNo = $('#txtChequeNumber').val(); voucher.ChequeDate = $('#txtChequeDate').val(); voucher.Drawon = $('#txtDrawOn').val(); } else { voucher.IsCheque = 0; voucher.ChequeNo = null; voucher.ChequeDate = null; voucher.Drawon = null; } voucher.VoucherTypeID = $('#hdnVoucherType').val(); voucher.ReceiptNo = null; voucher.CostCenter = costcenter; voucher.username = $.cookie('bsl_3'); voucher.ID = $('#hdnGroupID').val();//groupID for updation in Entities voucher.groupID = $('#hdnGroupID').val();//groupID for updation in Controllers voucher.VoucherNo = $('#hdnVoucherNumber').val(); voucher.CreatedBy = $.cookie('bsl_3'); voucher.ModifiedBy = $.cookie('bsl_3'); voucher.Date = $('#txtVoucherDate').val(); voucher.Jobs = JobString; voucher.EntryDesc = EntryDesc; $.ajax({ url: apiurl + 'api/VoucherEntry/Save', method: 'POST', datatype: 'JSON', data: JSON.stringify(voucher), contentType: 'application/json;charset=utf-8', success: function (response) { if (response.Success) { successAlert(response.Message); reset(); GetVoucherNo(); $('#hdnGroupID').val("0"); $('#hdnVoucherNumber').val("0"); $('.entry-desc').val(""); if (print) { var url = "/Finance/Print/Voucher?id=" + response.Object; PopupCenter(url, 'VoucherPrint', 800, 700); } } else { errorAlert(response.Message); } }, error: function (xhr) { errorAlert("Something went wrong.Please try Again Later"); }, beforeSend: function () { miniLoading('start'); $('#btnSave').attr('disabled', 'disabled'); $('#btnSavePrint').attr('disabled', 'disabled'); }, complete: function () { miniLoading('stop'); $('#btnSave').removeAttr('disabled'); $('#btnSavePrint').removeAttr('disabled'); } }); } else { errorAlert('Enter a valid information'); } } else { errorAlert('Enter valid information'); } } //Loads the Account heads according to the voucher Types selected function LoadHeads(voucher) { var Company = $.cookie("bsl_1"); $.ajax({ url: apiurl + 'api/VoucherEntry/GetHeads?CompanyId=' + Company + '&Credit=0', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(voucher), success: function (response) { $('.account-heads').children('option').remove(); $('.account-heads').select2('destroy'); $('.account-heads').append('<option value=0>--Select--</option>'); for (var i = 0; i < response.length; i++) { $('.account-heads').append('<option value=' + response[i].parent + '|' + response[i].ID + '>' + response[i].Name + '</option>'); } $('.account-heads').select2(); $.ajax({ url: apiurl + 'api/VoucherEntry/GetHeads?CompanyId=' + Company + '&Credit=1', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(voucher), success: function (response) { $('.account-heads-Credit').children('option').remove(); $('.account-heads-Credit').select2('destroy'); $('.account-heads-Credit').append('<option value=0>--Select--</option>'); for (var i = 0; i < response.length; i++) { $('.account-heads-Credit').append('<option value=' + response[i].parent + '|' + response[i].ID + '>' + response[i].Name + '</option>'); } $('.account-heads-Credit').select2(); }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } //Loads CostCenter for dropdown list function LoadCostCenter() { var Company = $.cookie("bsl_1"); $.ajax({ url: apiurl + 'api/VoucherEntry/GeCostCenter', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(Company), success: function (response) { $('.CostCenter').append('<option value="0">--Select--</option>'); for (var i = 0; i < response.length; i++) { $('.CostCenter').append('<option value=' + response[i].ID + '>' + response[i].name + '</option>'); } $('.CostCenter').select2(); }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } //Loads CostCenter for dropdown list function LoadJobs() { var Company = $.cookie("bsl_1"); $.ajax({ url: apiurl + 'api/Jobs/GetJobForVoucher', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(Company), success: function (response) { $('.Job').empty(); $('.Job').append('<option value="0">--Select--</option>'); for (var i = 0; i < response.length; i++) { $('.Job').append('<option value=' + response[i].Job_Id + '>' + response[i].Job_Name + '</option>'); } $('.Job').select2(); }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } //following two event handlers are used to target the credit and debit amount any one of the exet box are allowed for one entry $('.credit-Amount').on('keyup', function () { var crAmount = $(this).closest('td').next('td').find('input').val(); if (crAmount != "") { $(this).closest('td').next('td').find('input').val(""); } calculateDebit(); calculateCredit(); }); $('.debit-Amount').on('keyup', function () { var crAmount = $(this).closest('td').prev('td').find('input').val(); if (crAmount != "") { if (crAmount != "") { var attr = $(this).closest('td').prev('td').find('input').attr('readonly'); //Added to reset the text box when focus to debit amount textbox(Only reset when it is not read only) if (typeof attr !== undefined && attr !== false) { } else { $(this).closest('td').prev('td').find('input').val(""); } } } calculateDebit(); //Added to Maintain the debit and credit amount equal var tr = $('#VoucherTable>tbody').children('tr'); $(tr[0]).children('td:nth-child(3)').find('.credit-Amount').val($('.debit-total').text()); $('.credit-total').text($('.debit-total').text()); }); //Function to Calculate Debit Amount function calculateDebit() { var tr = $('#VoucherTable>tbody').children('tr'); var debit = 0; for (var i = 0; i < tr.length; i++) { var amount = $(tr[i]).children('td:nth-child(4)').find('.debit-Amount').val(); if (amount == "") { amount = 0; } debit += parseFloat(amount); } $('.debit-total').text(debit); } //Function to Calculate Credit Amount function calculateCredit() { var tr = $('#VoucherTable>tbody').children('tr'); var credit = 0; for (var i = 0; i < tr.length; i++) { var amount = $(tr[i]).children('td:nth-child(3)').find('.credit-Amount').val(); if (amount == "") { amount = 0; } credit += parseFloat(amount); } $('.credit-total').text(credit); } //Datepicker Functions $('#txtVoucherDate').datepicker({ autoClose: true, format: 'dd/M/yyyy', todayHighlight: true }); $('#txtChequeDate').datepicker({ autoClose: true, format: 'dd/M/yyyy', todayHighlight: true }); var date = new Date(); var today = new Date(date.getFullYear(), date.getMonth(), date.getDate()); $('#txtVoucherDate').datepicker('setDate', today); $('#txtVoucherDate').datepicker() .on('changeDate', function (ev) { $('#txtVoucherDate').datepicker('hide'); }); $('#txtChequeDate').datepicker() .on('changeDate', function (ev) { $('#txtChequeDate').datepicker('hide'); }); //Loads the voucher Types for dropdown list function LoadVoucherTypes() { var Company = $.cookie("bsl_1"); $.ajax({ url: apiurl + 'api/VoucherSettings/GetVoucherTypes', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify($.cookie("bsl_1")), success: function (response) { $('.VoucherType').append('<option value="0">--Select--</option>'); $(response).each(function () { $('.VoucherType').append('<option value=' + response[i].ID + '>' + response[i].Name + '</option>'); }); $("#ddlChangeType").select2({ width: '100%' }); }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } //Function is used to get the voucher number function GetVoucherNo() { var voucher = $('#hdnVoucherType').val(); $.ajax({ url: apiurl + 'api/VoucherEntry/GeVoucherNumber?voucher=' + voucher, method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify($.cookie("bsl_1")), success: function (response) { var VoucherType = response.Table1[0].Fvt_TypeName; var Number = response.Table[0].Column1; $('#VoucherNumber').html(VoucherType + ':' + Number); $('#hdnVoucherTypeName').val(VoucherType); $('#lblTitle').text(VoucherType); var vouchertypeid = $('#hdnVoucherType').val(); LoadHeads(vouchertypeid); }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } //Reset Function function reset() { var Voucher = $('#hdnVoucherType').val(); $('.debit-Amount').val(""); $('.credit-Amount').val(""); $('.debit-total').text("0"); $('.credit-total').text("0"); $('.account-heads').select2('data', { id: "0", text: '--Select--' }); $('.account-heads-Credit').select2('data', { id: "0", text: '--Select--' }); $('.CostCenter').select2('data', { id: "0", text: '--Select--' }); $('.Job').select2('data', { id: "0", text: '--Select--' }); //$('.CostCenter').select2("val", "1"); $('#txtVoucherDate').datepicker('setDate', today); $('#txtChequeNumber').val(""); $('#txtChequeDate').val(""); $('#txtDrawOn').val(""); $('#btnSave').html('<i class="md md-archive"></i>&nbsp;Save'); $('#btnSavePrint').html('<i class="md md-print"></i>&nbsp;Save & Print'); var tr = $('#VoucherTable>tbody').children('tr'); for (var i = tr.length; i > 5; i--) { $(tr[i - 1]).remove(); } $('#chkIsCheque').prop('checked', false); $('#dvCheque').fadeOut('slow'); $('#dvCheque').addClass('hidden'); $('.Narration').val(""); } function getmonth(month) { if (month == 0) { month = 12; } switch (month) { case 1: return 'Jan'; case 2: return 'Feb'; case 3: return 'Mar'; case 4: return 'Apr'; case 5: return 'May'; case 6: return 'June'; case 7: return 'July'; case 8: return 'Aug'; case 9: return 'Sep'; case 10: return 'Oct'; case 11: return 'Nov'; case 12: return 'Dec'; } } //Find Button Click event handler $('#btnFind').click(function () { $('#findModal').modal('show'); refreshTable(); function refreshTable() { reset(); var html = ''; var fin = {}; var date = new Date(); var toDate = date.getMonth(); var FromdateString = date.getDate() + "/" + getmonth(toDate) + "/" + (date.getFullYear() - 1); fin.filterType = 0; fin.fromdatestring = FromdateString; fin.todatestring = date.getDate() + "/" + getmonth(toDate) + "/" + (date.getFullYear() + 1); fin.VoucherType = $('#hdnVoucherType').val(); fin.CompanyId = $.cookie('bsl_1'); fin.FromAccount = 0; $.ajax({ url: apiurl + 'api/VoucherEntry/GetVoucherData', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(fin), success: function (response) { $(response).each(function (index) { html += '<tr>'; html += '<td style="display:none">' + this.TrnID + '</td>'; html += '<td>' + this.TrnDesc + '</td>'; html += '<td>' + this.TrnVchType + '</td>'; html += '<td>' + this.TrnVchNo + '</td>'; html += '<td>' + this.TrnAmount + '</td>'; html += '<td>' + this.TrnChequeNo + '</td>'; html += '<td>' + this.TrnChequeDate + '</td>'; html += '<td style="display:none">' + this.TrnGroupID + '</td>'; html += '<td><a class="edit-register" title="edit" href="#"><i class="fa fa-edit"></i></a></td>' html += '</tr>'; }); $('#tblRegister').DataTable().destroy(); $('#tblRegister tbody').children().remove(); $('#tblRegister tbody').append(html); $('#tblRegister').dataTable({ destroy: true, aaSorting: [] }); //binding event to row $('#tblRegister').off().on('click', '.edit-register', function () { var GroupID = $(this).closest('tr').children('td').eq(7).text(); $.ajax({ url: apiurl + 'api/VoucherEntry/GetVoucherDataforEdit', method: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'Json', data: JSON.stringify(GroupID), success: function (response) { var tr = $('#VoucherTable>tbody').children('tr'); if (response.Table[0].Fve_IsCheque == true) { var date = new Date(response.Table[0].Fve_ChequeDate); var dateString = date.getDate() + '/' + getmonth(date.getMonth() + 1) + '/' + date.getFullYear(); $('#chkIsCheque').prop('checked', true); $('#dvCheque').fadeIn('slow'); $('#dvCheque').removeClass('hidden'); $('#txtChequeNumber').val(response.Table[0].Fve_ChequeNo); $('#txtChequeDate').val(dateString); $('#txtDrawOn').val(response.Table[0].Fve_Drawon); } else { $('#chkIsCheque').prop('checked', false); $('#dvCheque').fadeOut('slow'); $('#dvCheque').addClass('hidden'); $('#txtChequeNumber').val(""); $('#txtChequeDate').val(""); $('#txtDrawOn').val(""); } for (var i = 0; i < response.Table.length; i++) { var CostCenter = response.Table[i].CostCenter.split("`");; var NewCost = CostCenter[0]; var selected = ""; $(tr[i]).find('.entry-desc').val(response.Table[i].Fve_ExpenseDesc); if (i >= parseInt($('#VoucherTable>tbody').children('tr').length)) { //$('#addRow').trigger('click'); //Adds a new row if the edit data has more than 5 rows //Removes the select2 property of dummy table row $('#dummy .dummyRow .account-heads').select2('destroy'); $('#dummy .dummyRow .CostCenter').select2('destroy'); $('#dummy .dummyRow .Job').select2('destroy'); //Clones the dummyRow with normal select $('#dummy .dummyRow').clone(true).appendTo('.journal-table > tbody'); //Add select2 property to the cloned Select $('#VoucherTable').find('.dummyRow .account-heads').select2(); $('#VoucherTable').find('.dummyRow .CostCenter').select2(); $('#VoucherTable').find('.dummyRow .Job').select2(); //Removes the dummyrow class from the cloned row $('#VoucherTable').find('.dummyRow').removeClass('dummyRow'); //Functionality to get serial number for the added row var tr = $('#VoucherTable>tbody').children('tr'); $('.slno').text(parseInt(tr.length)); $('#VoucherTable').find('.slno').removeClass('slno'); selected = response.Table[i].ParticularsID + "|" + response.Table[i].CostHead; if (response.Table[i].CreditOrDebit == 0) { $(tr[i]).find('.account-heads-Credit').select2('val', selected).trigger("change"); } else { //$(tr[i]).find('.account-heads').select2('val', selected); $(tr[i]).find('.account-heads').val(selected).trigger("change"); } $(tr[i]).find('.CostCenter').select2("val", NewCost); $(tr[i]).find('.Job').select2("val", response.Table[i].Job_ID); $(tr[i]).find('.entry-desc').val(response.Table[i].Fve_ExpenseDesc); if (response.Table[i].DebitAmt == 0) { $(tr[i]).find('.debit-Amount').val(""); } else { $(tr[i]).find('.debit-Amount').val(response.Table[i].DebitAmt); } if (response.Table[i].creditAmt == 0) { $(tr[i]).find('.credit-Amount').val(""); } else { $(tr[i]).find('.credit-Amount').val(response.Table[i].creditAmt); } calculateDebit(); calculateCredit(); } else { selected = response.Table[i].ParticularsID + "|" + response.Table[i].CostHead; if (response.Table[i].CreditOrDebit == 0) { $(tr[i]).find('.account-heads-Credit').select2('val', selected); } else { $(tr[i]).find('.account-heads').select2('val', selected); } $(tr[i]).find('.CostCenter').select2("val", NewCost); $(tr[i]).find('.Job').select2("val", response.Table[i].Job_ID); if (response.Table[i].DebitAmt == 0) { $(tr[i]).find('.debit-Amount').val(""); } else { $(tr[i]).find('.debit-Amount').val(response.Table[i].DebitAmt); } if (response.Table[i].creditAmt == 0) { $(tr[i]).find('.credit-Amount').val(""); } else { $(tr[i]).find('.credit-Amount').val(response.Table[i].creditAmt); } calculateDebit(); calculateCredit(); } $('#hdnVoucherNumber').val(response.Table[0].Fve_Number); $('#hdnGroupID').val(response.Table[0].Fve_GroupID); $('#VoucherNumber').text(response.Table[0].Voucher); //$('#txtVoucherDate').val(response.Table[0].Fve_Date); $('#txtVoucherDate').datepicker("update", new Date(response.Table[0].Fve_Date)); $('#btnSave').html('<i class="md md-archive"></i>&nbsp;Update'); $('#btnSavePrint').html('<i class="md md-print"></i>&nbsp;Update & Print'); $('.Narration').val(response.Table[0].Fve_Description); } }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); $('#findModal').modal('hide'); //binding delete $('.delete-row').click(function () { $(this).closest('tr').hide('slow', function () { $(this).closest('tr').remove(); }); }); }); }, error: function (xhr) { alert(xhr.responseText); console.log(xhr); } }); } }); //Print Functionality Requires GroupID of the voucher. $('#btnPrint').click(function () { var id = $('#hdnGroupID').val(); if (id == "0") { errorAlert('Select a voucher to print'); } else { var url = "/finance/Print/Voucher?id=" + id; PopupCenter(url, 'VoucherPrint', 800, 700); } }); //Added for generate new row when focus comes to last row var tr = $('#VoucherTable>tbody').children('tr'); $('body').on('blur', '.credit-Amount', function () { if ($(this).parent().parent().next('tr').html() == undefined) { $('#addRow').trigger('click'); } }); //Added for generate new row when focus comes to last row $('body').on('blur', '.debit-Amount', function () { if ($(this).parent().parent().next('tr').html() == undefined) { $('#addRow').trigger('click'); } }); $('#btnNew').click(function () { reset(); GetVoucherNo(); }); });//Document Ready function end
var bgColor = localStorage.getItem('userTheme'); $(function(){ /*将皮肤选中默认选中缓存中的值*/ //$("input[value="+bgColor+"]")[0].setAttribute("checked",'true'); $("input[value="+bgColor+"]").attr('checked',true); if(bgColor){ $("#bgBox").removeClass().addClass(bgColor); } //背景色切换选框 $('input[type=radio][name=setBackground]').bind('change',function() { localStorage['userTheme']=this.value; $("#bgBox").removeClass().addClass(this.value); }); /*执行I18n翻译*/ execI18n(); /*将语言选择默认选中缓存中的值*/ //$("input[value="+i18nLanguage+"]")[0].setAttribute("checked",'true'); $("input[value="+i18nLanguage+"]").attr('checked',true); /* 选择语言 */ $("input[name='setLangue']").bind('change',function(){ var language = getRadioButtonCheckedValue("setLangue"); getCookie("userLanguage",language,{ expires: 30, path:'/coinTrading' }); location.reload(); }); //设置下拉框 $("#setting").on('click',function(){ $(".setBox").toggle('slow'); }); //radio beauty $("span.radioInput").on('click',function(){ $(this).parent().children("label").click(); }); //dataTable $('#dataTable').DataTable( { "ajax": "js/objects.txt", "columns": [ { "data": "id" }, { "data": "name" }, { "data": "position" }, { "data": "salary" }, { "data": "start_date" }, { "data": "office" }, { "data": "extn" } ] } ); //$.ajax({ // type:"get", // url:"http://news.at.zhihu.com/api/4/news/before/20131119", // success:function(data){ // console.log(data); // } //}) });
import React from 'react' import styles from './Post.module.scss' const Post = (props) => { const renderMedia = (media = {}) => { if (Object.keys(media).length) { return ( <div styleName="post-thumb-wrap"> <img src={media.file} alt={media.alt_text} title={media.title.rendered} className={(media.vertical) ? "portrait" : "landscape"} styleName="feat-image"/> </div> ); } return ''; } return ( <article styleName="post-detail" key={props.id}> {renderMedia(props.media)} {props.children} </article> ) } export default Post