text
stringlengths
7
3.69M
/** * @file 默认的FontEditor设置 * @author mengke01(kekee000@gmail.com) */ define( function (require) { var setting = { saveSetting: true, // 是否保存setting // 查看器选项 viewer: { color: '', // 查看器颜色 shapeSize: 'normal', // 字形大小 pageSize: 100 // 翻页大小 }, // 编辑器选项 // see : editor/options.editor editor: { sorption: { enableGrid: false, enableShape: true }, fontLayer: { strokeColor: '#999', fill: true, fillColor: '#555' }, referenceline: { style: { strokeColor: '#0FF' } }, axis: { showGrid: true, gapColor: '#A6A6FF', metricsColor: 'red', graduation: { gap: 100 } } } }; return setting; } );
var maxnumber = 0; var arrPickRowId = new Array(); var arrPickInfo = new Array(); var pickCount = 0; var ff = []; var deliver_id; //庫存Model Ext.define('gigade.Stock', { extend: 'Ext.data.Model', fields: [ { name: 'row_id', type: 'int' }, { name: 'item_id', type: 'int' }, { name: 'cde_dt', type: "string" }, { name: 'made_date', type: "string" }, { name: 'prod_qty', type: 'int' }, { name: 'vendor_id', type: 'int' }, { name: 'cde_dt_shp', type: 'int' }//允出天數 ] }); //庫存Store var StockStore = Ext.create('Ext.data.Store', { pageSize: 25, model: 'gigade.Stock', proxy: { type: 'ajax', url: '/WareHouse/GetStockByProductId', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); //庫存信息載入之前添加查詢條件 StockStore.on('beforeload', function () { Ext.apply(StockStore.proxy.extraParams, { loc_id: Ext.getCmp("loc_id").getValue() }); }); StockStore.on('load', function () { $.get('/WareHouse/GetStockByProductId', { 'loc_id': Ext.getCmp("loc_id").getValue() }, function (data) { //var datadata = data.parseJSON(); var datadata = eval('(' + data + ')'); if (datadata.islock != "0") { Ext.getCmp('presentation').show(); } if (datadata.totalCount > 0) { //Ext.getCmp('presentation').show(); Ext.getCmp('deliver').hide(); } }); }); function refushthis() { StockStore.load(); } //寄倉流程 Ext.onReady(function () { //庫存信息grid var gdStock = Ext.create('Ext.grid.Panel', { id: 'gdStock', title: '庫存信息', store: StockStore, columnLines: true, width: 600, height: 300, columnLines: true, frame: true, hidden: true, columns: [ { header: '製造日期', dataIndex: 'made_date', width: 100, align: 'center', renderer: Ext.util.Format.dateRenderer('Y-m-d'), editor: { xtype: 'datefield', format: 'Y-m-d', allowBlank: false } }, { header: '有效日期', dataIndex: 'cde_dt', width: 100, align: 'center', renderer: Ext.util.Format.dateRenderer('Y-m-d'), editor: { xtype: 'datefield', format: 'Y-m-d', allowBlank: false } }, { header: '庫存數量', dataIndex: 'prod_qty', width: 100, align: 'center' }, { header: '撿貨數量',id: 'pick_num',dataIndex: 'pick_num', width: 100,align: 'center', editor: {xtype: 'numberfield', id: 'pnum',minValue: 0} } ], selType: 'cellmodel', plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 }) ], viewConfig: { emptyText: '<span>暫無數據!</span>' }, listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManageListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } }, edit: function (editor, e) { //修改製造日期 if (e.field == "made_date" || e.field == "cde_dt") { //如果有效日期更改的話,就更新有效時間 var i = 0; if (e.field == "made_date") { i = 1;//1表示編輯的是cde_dt_make } else { i = 2;//1表示編輯的是cde_dt } if (e.record.data.row_id != "" && e.record.data.row_id != "0") { if (Ext.Date.format(e.value, 'Y-m-d') != e.originalValue) { Ext.Ajax.request({ url: "/WareHouse/selectproductexttime", params: { item_id: e.record.data.item_id }, success: function (response) { var result = Ext.decode(response.responseText); var datetimes = 0; datetimes = result.msg; Ext.Ajax.request({ url: "/WareHouse/aboutmadetime", params: { cde_dtormade_dt: e.value, y_cde_dtormade_dt: e.originalValue, row_id: e.record.data.row_id, prod_qtys: e.record.data.prod_qty, type_id: i, datetimeday: datetimes, sloc_id: Ext.htmlEncode(Ext.getCmp('loc_id').getValue()), prod_id: e.record.data.item_id }, success: function (response) { var result = Ext.decode(response.responseText); var message; switch (result.msg) { case 1: message = " 製造日期不能大於當前時間!"; Ext.Msg.alert(INFORMATION, message); break; case 3: message = " 修改失敗!"; Ext.Msg.alert(INFORMATION, message); break; } StockStore.load(); } }); } }); } else { StockStore.load(); } } } if (e.field === "pick_num") { if (e.value !== e.originalValue) { var gdStock = Ext.getCmp("gdStock").store.data.items; var pickNum = Ext.getCmp("out_qty").getValue(); var prod_qty = e.row.children[2].textContent;//選中行的庫存量 var pnum = e.value;//選中行的撿貨量 var made_date = e.row.children[0].textContent;//選中行的製造日期 Ext.getCmp('deliver').show(); pickCount = 0; //重置實際撿貨量 for (var i = 0; i < gdStock.length; i++) { if (gdStock[i].get("pick_num") !== 0 && !isNaN(gdStock[i].get("pick_num"))) { pickCount += gdStock[i].get("pick_num"); } } Ext.getCmp("act_pick_qty").setValue(pickCount); //顯示當前撿貨數量 ////////////////////魚下方更換位置////////////////////////////// //撿貨數量與庫存數量作比較 var row_id = e.record.data.row_id; var inputValue = e.value; arrPickRowId.push(row_id); arrPickInfo.push(inputValue); var message = ""; if (inputValue != "0" && inputValue != null) { /*判斷先進先出*/ var istip = false; if (Ext.Array.contains(ff, e.rowIdx)) { var index = Ext.Array.indexOf(ff, e.rowIdx, 0); if (e.value == e.record.data.prod_qty) { Ext.Array.splice(ff, parseInt(index + 1), 1, "true"); } else if (e.value < e.record.data.prod_qty) { Ext.Array.splice(ff, parseInt(index + 1), 1, "false"); } } else { //不存在就添加 ff.push(e.rowIdx); if (e.value == e.record.data.prod_qty) { ff.push("true"); } else if (e.value < e.record.data.prod_qty) { ff.push("false"); } } if (e.rowIdx != 0) { if (ff.length > 2) { for (var i = 0; i < ff.length; i = i + 2) { if (parseInt(ff[i]) < parseInt(e.rowIdx)) { if (ff[i + 1] == "false") { istip = true; } } } } else { istip = true; } } if (istip == true) { message += "請遵守先進先出原則!"; //Ext.getCmp("act_pick_qty").setValue(0); } /*檢查日期是否過期開始*/ Ext.Ajax.request({ url: "/WareHouse/JudgeDate", method: 'post', type: 'text', params: { dtstring: 2, item_id: e.record.data.item_id, startTime: e.record.data.cde_dt }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { if (result.msg == "3") { message += "超過允出天數!"; //editFunction(message + "超過允出天數!"); //return; } else if (result.msg == "4") { message += "有效期為" + result.dte + "的商品已超過有效日期!!"; //editFunction(message + "有效期為" + result.dte + "的商品已超過有效日期!"); //return; } //else if (message.length > 0) { // Ext.Msg.alert(INFORMATION, message); //} } //else { // if (message.length > 0) { // Ext.Msg.alert(INFORMATION, message); // } //} }, failure: function (form, action) { Ext.Msg.alert(INFORMATION, "該商品日期驗證出問題!請聯繫管理員~"); } });/*檢查日期是否過期結束*/ } ////////////////////魚下方更換位置////////////////////////////// ////////////////////魚上方更換位置////////////////////////////// if (pickNum >= pickCount) { Ext.getCmp("act_pick_qty").setValue(pickCount); //顯示當前撿貨數量 var R = 0; var S = 0; Ext.Ajax.request({ url: "/WareHouse/GetSum", method: 'post', async: true, type: 'text', params: { item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value), lcat_id: "S" }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { S = result.S; R = result.R; //if (parseInt(S) < parseInt(pnum)) { // if (parseInt(R) > 0) { // Ext.getCmp("pnum").setValue(0); // Ext.getCmp("act_pick_qty").setValue(0); // Ext.Msg.alert(INFORMATION, message+"請補貨主料位!"); // } // else { // Ext.MessageBox.confirm("提示",message + "該項目庫存不夠,是否庫調?", function (btn) { // if (btn == "yes") { // onAddClick(); // } // else { // Ext.getCmp("pnum").setValue(0); // Ext.getCmp("act_pick_qty").setValue(0); // return false; // } // }); // } //} //else if (parseInt(pnum) > parseInt(prod_qty)) { //2015-08-17 庫調邏輯變更:直接庫調 if (Ext.getCmp("loc_id").getValue() == "YY999999") { Ext.getCmp("act_pick_qty").setValue(0); Ext.Msg.alert(INFORMATION, "該商品沒有主料位,不能庫調!"); setTimeout('refushthis()', 4000) } else { Ext.MessageBox.confirm("提示", "該商品庫存不夠,確認直接進行商品數量庫調?", function (btn) { if (btn == "yes") { Ext.Ajax.request({ url: "/WareHouse/RFKT", method: 'post', type: 'text', params: { item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value), prod_qty: prod_qty, pnum: pnum, made_date: made_date, order_id: Ext.getCmp("ord_id").getValue(), loc_id: Ext.getCmp("loc_id").getValue() }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { if (result.msg == "100") { Ext.getCmp("act_pick_qty").setValue(0); StockStore.load(); } if (result.msg == "2") { Ext.Msg.alert("提示", "今日的庫存已鎖,不能庫調"); Ext.getCmp("act_pick_qty").setValue(0); Ext.getCmp("pnum").setValue(0); StockStore.load(); } } else { Ext.Msg.alert(INFORMATION, "系統故障,內部庫調失敗!"); } } }); } else { Ext.getCmp("pnum").setValue(0); Ext.getCmp("act_pick_qty").setValue(0); StockStore.load(); return false; } }) } //撿貨數量大於庫存判斷1.該輔料為沒有庫存進行庫調.2.輔料位有庫存可以去進行補貨. //Ext.Ajax.request({ // url: "/WareHouse/GetSum", // method: 'post', // type: 'text', // params: { // item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value), // lcat_id: "R", // made_date: made_date // }, // success: function (form, action) { // var result = Ext.decode(form.responseText); // if (result.success) { // S = result.S; // R = result.R; // if (parseInt(R) > 0) { // Ext.Msg.alert(INFORMATION,message+ "請補貨主料位!"); // } // else { // //Ext.MessageBox.confirm("提示", message+"該項目庫存不夠,是否庫調?", function (btn) { // // if (btn == "yes") { // // onAddClick(); // // } // // else { // // Ext.getCmp("pnum").setValue(0); // // Ext.getCmp("act_pick_qty").setValue(0); // // return false; // // } // //}); // } // Ext.getCmp("act_pick_qty").setValue(0); // }else { // if (message.length > 0) { // Ext.Msg.alert(INFORMATION, message); // } // } // } //}); } else { if (message.length > 0) { Ext.Msg.alert(INFORMATION, message); } } }else { if (message.length > 0) { Ext.Msg.alert(INFORMATION, message); } } } }); } else { e.record.set("pick_num", 0); pickCount = 0;//重新獲取當前撿貨數量 for (var i = 0; i < gdStock.length; i++) { if (gdStock[i].get("pick_num") !== 0 && !isNaN(gdStock[i].get("pick_num"))) { pickCount += gdStock[i].get("pick_num"); } } Ext.getCmp("act_pick_qty").setValue(pickCount); Ext.Msg.alert(INFORMATION, "實際撿貨量不能大於撿貨數量!"); } ////////////////////魚上方更換位置////////////////////////////// } //alert('edit:end'); } } } }); var addTab = Ext.create('Ext.form.Panel', { layout: 'anchor', width: 900, url: '/WareHouse/GETMarkTallyWD', defaults: { labelWidth: 100, width: 250, margin: '5 0 0 10' }, border: false, plain: true, id: 'AddUserPForm', items: [ { xtype: 'displayfield', fieldLabel: '工作代號', id: 'assg_id', name: 'assg_id' }, { xtype: 'displayfield', fieldLabel: '出貨單號', id: 'deliver_code', name: 'deliver_code' }, { xtype: 'fieldcontainer', combineErrors: true, width: 1000, layout: 'hbox', items: [ { xtype: 'displayfield', fieldLabel: '訂單號', id: 'ord_id', width: 250, name: 'ord_id' }, { xtype: 'displayfield', fieldLabel: '備註', id: 'note_order', name: 'note_order', hidden: true } ] }, { xtype: 'displayfield', fieldLabel: '撿貨料位', id: 'loc_id', name: 'loc_id' }, { xtype: 'displayfield', fieldLabel: 'Hash撿貨料位', id: 'hash_loc_id', name: 'hash_loc_id' , hidden:true }, { xtype: "textfield", id: 'upc_id', name: 'upc_id', fieldLabel: '料位條碼', submitValue: true, hidden: true, listeners: { change: function () { var loc_id = Ext.getCmp("loc_id").getValue(); var loc_id_Input = Ext.getCmp("upc_id").getValue().toUpperCase().trim(); var hash_loc_id = Ext.getCmp("hash_loc_id").getValue().toUpperCase(); if (loc_id == loc_id_Input || (hash_loc_id == loc_id_Input&&hash_loc_id.length>15)) { Ext.getCmp("product_name").show(); Ext.getCmp("upc").show(); Ext.getCmp("upc").focus(); Ext.getCmp("upc_id").setValue(loc_id_Input); Ext.getCmp("err").hide(); } else { if (loc_id_Input.length == 8) { Ext.getCmp("upc_id").setValue(""); Ext.getCmp("upc_id").focus(); Ext.getCmp("err").show(); } Ext.getCmp("product_name").hide(); Ext.getCmp("upc").hide(); Ext.getCmp("out_qty").hide(); Ext.getCmp("act_pick_qty").hide(); Ext.getCmp("upc").setValue(""); Ext.getCmp("act_pick_qty").setValue("");//清空實際撿貨量 Ext.getCmp("gdStock").hide(); Ext.getCmp("deliver").hide(); Ext.getCmp("deliver").setValue("");//清空輸入用於驗證的定單編號 Ext.getCmp("presentation").hide(); Ext.getCmp("err2").hide(); } } } }, { id: 'err', border: false, html: '<div style="color:red;">提示:這個料位不存在,請重新掃描!</div>', hidden: true }, { xtype: 'displayfield', fieldLabel: '品名', id: 'product_name', name: 'product_name', hidden: true }, { xtype: 'textfield', fieldLabel: '產品條碼/商品細項編號', id: 'upc', name: 'upc', hidden: true, listeners: { change: function () { //判斷該商品item對應的條碼 if (Ext.getCmp('upc').getValue().length > 5) { Ext.Ajax.request({ url: "/WareHouse/Judgeupcid", method: 'post', type: 'text', params: { item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value), upc_id: Ext.getCmp("upc").getValue() }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { Ext.getCmp("err1").hide(); Ext.getCmp("out_qty").show(); Ext.getCmp("act_pick_qty").show(); //載入庫存信息 Ext.getCmp("gdStock").show(); Ext.getCmp('gdStock').store.loadPage(1, { params: { item_id: document.getElementById('hid_item_id').value } }); Ext.getCmp("deliver").show(); } else { if (result.msg == 1) { Ext.getCmp("err1").setValue("<div style='color:red;'>這個條碼對應到" + result.itemid + "品號,請重新掃描正確商品!</div>"); } else if (result.msg == 2) { Ext.getCmp("err1").setValue("<div style='color:red;'>這個條碼不存在,請重新掃描!</div>"); } Ext.getCmp("err1").show(); Ext.getCmp("upc").setValue("");//清空輸入用於驗證的定單編號 Ext.getCmp("out_qty").hide(); Ext.getCmp("act_pick_qty").hide(); Ext.getCmp("gdStock").hide(); Ext.getCmp("deliver").hide(); Ext.getCmp("deliver").setValue("");//清空輸入用於驗證的定單編號 Ext.getCmp("upc").focus(); } }, failure: function (form, action) { Ext.Msg.alert(INFORMATION, "條碼錯誤,請稍后再試,如有重複出錯請聯繫管理員!!"); Ext.getCmp("upc").focus(); } }); } } } }, { xtype: 'displayfield', fieldLabel: '提示', id: 'err1', name: 'err1', style: 'color:red;', width: 600, hidden: true }, { xtype: 'fieldcontainer', combineErrors: true, width: 600, layout: 'hbox', items: [ { xtype: 'displayfield', fieldLabel: '撿貨數量', id: 'out_qty', name: 'out_qty', hidden: true }, { xtype: 'textfield', id: 'deliver', fieldLabel: '出貨單號', margin: '0 0 0 20', allowBlank: false, submitValue: true, hidden: true, listeners: { change: function () { Ext.getCmp("btn_sure").setDisabled(true); var deliver = Ext.getCmp("deliver").getValue(); if (deliver == Ext.getCmp("deliver_code").getValue()) { Ext.getCmp("err2").hide(); Ext.getCmp("btn_sure").setDisabled(false); Ext.getCmp("amsure").setDisabled(false); Ext.getCmp("amsure").show(); } else { if (deliver.length == 9) { Ext.getCmp("err2").show(); Ext.getCmp("err2").setValue("<div style='color:red;'>不是該出貨單的單號,請重新輸入!</div>"); Ext.getCmp("deliver").setValue(); Ext.getCmp("deliver").focus(); } Ext.getCmp("amsure").hide(); } } } } ] }, { xtype: 'fieldcontainer', combineErrors: true, width: 800, layout: 'hbox', items: [ { xtype: 'displayfield', fieldLabel: '實際撿貨量統計', id: 'act_pick_qty', name: 'act_pick_qty', margin: '0 20 0 0', hidden: true }, { xtype: 'displayfield', id: 'err2', name: 'err2', width: 400, style: 'color:red;', hidden: true }, { xtype: 'button', margin: '0 0 0 20', text: "確認撿貨", id: 'amsure', hidden:true, disabled:true, handler: JhQuery } ] }, { id: 'presentation', border: false, html: '<div style="color:red;">提示:料位有上鎖的庫存,請注意</div>', hidden: true }, gdStock ], buttonAlign: 'left', buttons: [ { id: 'btn_sure', text: '確認撿貨', hidden:true, formBind: true, disabled: true, handler: function () { } } ], listeners: { afterrender: function () { //獲取工作代號用於顯示并連帶出相關信息 var assg_id = document.getElementById("hid_assg_id").value; Ext.getCmp("assg_id").setValue(assg_id); LoadWorkInfo(assg_id); } } }); Ext.create('Ext.Viewport', { layout: 'anchor', id: 'Mark', items: addTab, autoScroll: true }); }); //初始化頁面加載信息 function LoadWorkInfo(assg_id) { Ext.Ajax.request({ url: '/WareHouse/JudgeAssg', method: 'post', params: { assg_id: assg_id }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { //請求成功,控制下一步的操作 if (result.data.length > 0) { document.getElementById("hid_item_id").value = result.data[0].item_id; document.getElementById("hid_upc_id").value = result.data[0].upc_id; document.getElementById("hid_ordd_id").value = result.data[0].ordd_id; document.getElementById("hid_seld_id").value = result.data[0].seld_id; document.getElementById("hid_ord_qty").value = result.data[0].ord_qty; Ext.getCmp("ord_id").setValue(result.data[0].ord_id); Ext.getCmp("deliver_code").setValue(result.data[0].deliver_code); Ext.getCmp("hash_loc_id").setValue(result.data[0].hash_loc_id); deliver_id = result.data[0].deliver_id; Ext.getCmp("loc_id").setValue(result.data[0].sel_loc); var prod = ""; if (result.data[0].prod_sz != "") { prod = "(" + result.data[0].prod_sz + ")"; } Ext.getCmp("product_name").setValue(result.data[0].description + prod); Ext.getCmp("out_qty").setValue(result.data[0].out_qty); Ext.getCmp("upc_id").show(); Ext.getCmp("amsure").hide(); Ext.getCmp('upc_id').focus(); //20150504 add訂單備註信息 if (result.data[0].note_order.length > 0) { Ext.getCmp("note_order").setValue(result.data[0].note_order); Ext.getCmp("note_order").show(); } else { Ext.getCmp("note_order").hide(); } //Ext.getCmp("act_pick_qty").setMaxValue(result.data[0].out_qty);//實際撿貨數量不能大於缺貨量(實際是定貨數量[因數據插入時定貨量與缺貨量相同,撿貨時撿幾個就扣幾個缺貨量故缺貨量就是每次需要撿貨的數量]) } else { //document.location.href = "/WareHouse/MarkTally"; //商品撿完后轉到輸工作代號與定單號頁面 } } else { //Ext.Msg.alert("提示","您輸入的料位條碼不符,請查找對應的料位!"); } }, failure: function () { //Ext.Msg.alert("提示","您輸入的料位條碼不符,請查找對應的料位!"); } }); } //庫存新增 onAddClick = function () { var loc = Ext.getCmp('loc_id').getValue(); if (loc != 'YY999999' && loc.length == 8) { addFunction(null, StockStore); } else { Ext.Msg.alert(INFORMATION, "該商品無主料位,不能庫調!"); //Ext.getCmp("pick_num").setValue(0); Ext.getCmp("act_pick_qty").setValue(0); } } //新增庫存頁面 function addFunction(row, store) { var cde_dt_shp; var pwy_dte_ctl; var cde_dt_var; var cde_dt_incr; var vendor_id; var editFrm = Ext.create('Ext.form.Panel', { id: 'editFrm', frame: true, plain: true, defaultType: 'textfield', layout: 'anchor', labelWidth: 120, url: '/WareHouse/InsertIinvd', defaults: { anchor: "95%", msgTarget: "side" }, items: [ { xtype: 'numberfield', fieldLabel: "數量", name: 'num', id: 'num', minValue: 0, allowBlank: false }, { xtype: 'fieldcontainer', fieldLabel: "製造日期", combineErrors: true, height: 24, margins: '0 200 0 0', layout: 'hbox', id: 'createtime', //hidden: true, defaults: { flex: 1, hideLabel: true }, items: [ { xtype: 'radiofield', name: 'us', inputValue: "1", id: "us1", checked: true, listeners: { change: function (radio, newValue, oldValue) { var i = Ext.getCmp('startTime');//製造日期 var j = Ext.getCmp('cde_dt'); if (newValue) { j.allowBlank = true; i.setDisabled(false); j.setDisabled(true); j.setValue(null); i.allowBlank = false; } } } }, { xtype: "datefield", fieldLabel: "製造日期", id: 'startTime', name: 'startTime', submitValue: true, listeners: { change: function (radio, newValue, oldValue) { if (Ext.getCmp('startTime').getValue() != "" && Ext.getCmp('startTime').getValue() != null) { Ext.Ajax.request({ url: "/WareHouse/JudgeDate", method: 'post', type: 'text', params: { dtstring: 1, item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value), startTime: Ext.Date.format(Ext.getCmp('startTime').getValue(), 'Y-m-d') }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { if (result.msg == "1") { Ext.Msg.alert(INFORMATION, "該商品製造日期大於今天"); Ext.getCmp('startTime').setValue(null); } else if (result.msg == "3") { editFunction("超過允出天數!"); return; } else if (result.msg == "4") { editFunction("有效期為" + result.dte + "的商品已超過有效日期!"); return; } } } }); } } } } ] }, { xtype: 'fieldcontainer', fieldLabel: "有效日期", combineErrors: true, //hidden: true, layout: 'hbox', height: 24, //margins: '0 200 0 0', id: 'cdttime', defaults: { flex: 1, hideLabel: true }, items: [ { xtype: 'radiofield', name: 'us', inputValue: "2", id: "us2", //disabled: true, listeners: { change: function (radio, newValue, oldValue) { var i = Ext.getCmp('startTime');//製造日期 var j = Ext.getCmp('cde_dt'); if (newValue) { i.setDisabled(true); j.setDisabled(false); i.allowBlank = true; i.setValue(null); j.allowBlank = false; } } } }, { xtype: "datefield", fieldLabel: "有效日期", id: 'cde_dt', name: 'cde_dt', disabled: true, submitValue: true, listeners: { change: function (radio, newValue, oldValue) { if (Ext.getCmp('cde_dt').getValue() != "" && Ext.getCmp('cde_dt').getValue() != null) { Ext.Ajax.request({ url: "/WareHouse/JudgeDate", method: 'post', type: 'text', params: { dtstring: 2, item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value), startTime: Ext.Date.format(Ext.getCmp('cde_dt').getValue(), 'Y-m-d') }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { if (result.msg == "1") { Ext.Msg.alert(INFORMATION, "該商品製造日期大於今天"); Ext.getCmp('startTime').setValue(null); } else if (result.msg == "3") { editFunction("超過允出天數!"); return; } else if (result.msg == "4") { editFunction("有效期為" + result.dte + "的商品已超過有效日期!"); return; } } }, failure: function (form, action) { Ext.Msg.alert(INFORMATION, "保存失敗,請稍后再試,如有重複出錯請聯繫管理員!"); } }); } } } } ] } ] , buttons: [ { text: SAVE, formBind: true, handler: function () { var form = this.up('form').getForm(); Ext.Ajax.request({ url: "/WareHouse/Getprodbyid", method: 'post', async: false, type: 'text', params: { id: Ext.htmlEncode(document.getElementById("hid_item_id").value) }, success: function (form, action) { var result = Ext.decode(form.responseText); if (result.success) { cde_dt_shp = result.cde_dt_shp; pwy_dte_ctl = result.pwy_dte_ctl; cde_dt_var = result.cde_dt_var; cde_dt_incr = result.cde_dt_incr; vendor_id = result.vendor_id; } } }); if (form.isValid()) { form.submit({ params: { //id: Ext.htmlEncode(Ext.getCmp('plas_prdd_id').getValue()),//條碼 iialg: 'Y', item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value),//商品品號 product_name: Ext.htmlEncode(Ext.getCmp('product_name').getValue()),//品名 prod_qty: Ext.htmlEncode(Ext.getCmp('num').getValue()),//數量 startTime: Ext.htmlEncode(Ext.getCmp('startTime').getValue()),//創建時間 cde_dt: Ext.htmlEncode(Ext.getCmp('cde_dt').getValue()),//有效時間 plas_loc_id: Ext.htmlEncode(Ext.getCmp('loc_id').getValue()),//上架料位 loc_id: Ext.htmlEncode(Ext.getCmp('loc_id').getValue()),//主料位 iarc_id:'PC', doc_num: '',//不存值 Po_num: '',//前置單號 remark: '',//備註 cde_dt_var: cde_dt_var, cde_dt_incr: cde_dt_incr, vendor_id: vendor_id }, success: function (form, action) { var result = Ext.decode(action.response.responseText); Ext.Msg.alert(INFORMATION, SUCCESS); if (result.success) { StockStore.load();// editWin.close(); } else { Ext.MessageBox.alert(ERRORSHOW + result.success); } }, failure: function () { Ext.Msg.alert(INFORMATION, "系統異常,請稍后再試,如有重複出錯請聯繫管理員!"); } }); } } }] }); var editWin = Ext.create('Ext.window.Window', { title: "庫存調整", id: 'editWin', iconCls: 'icon-user-edit', width: 550, height: 380, autoScroll: true, // height: document.documentElement.clientHeight * 260 / 783, layout: 'fit', items: [editFrm], closeAction: 'destroy', modal: true, constrain: true, //窗體束縛在父窗口中 resizable: false, labelWidth: 60, bodyStyle: 'padding:5px 5px 5px 5px', closable: false, tools: [ { type: 'close', qtip: CLOSEFORM, handler: function (event, toolEl, panel) { Ext.MessageBox.confirm(CONFIRM, IS_CLOSEFORM, function (btn) { if (btn == "yes") { Ext.getCmp('editWin').destroy(); } else { return false; } }); } }] , listeners: { 'show': function () { if (row == null) { // editFrm.getForm().loadRecord(row); //如果是添加的話 editFrm.getForm().reset(); } else { editFrm.getForm().loadRecord(row); //如果是編輯的 } } } }); editWin.show(); } function JhQuery() { Ext.getCmp("amsure").setDisabled(true); var pickNum = Ext.getCmp("out_qty").getValue(); if (parseInt(pickCount) > parseInt(pickNum)) { Ext.Msg.alert(INFORMATION, "實際撿貨量不能大於撿貨數量!"); return; } if (Ext.getCmp("deliver").getValue() != Ext.getCmp("deliver_code").getValue()) { Ext.Msg.alert(INFORMATION, "出貨單號錯誤!"); return; } var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ params: { commodity_type: 2,//寄倉調度的編號 seld_id: Ext.htmlEncode(document.getElementById("hid_seld_id").value),//aseld的流水號 out_qty: Ext.htmlEncode(Ext.getCmp('out_qty').getValue()),//缺貨數量 ord_qty: Ext.htmlEncode(document.getElementById("hid_ord_qty").value),//訂貨數量 act_pick_qty: Ext.htmlEncode(Ext.getCmp('act_pick_qty').getValue()),//實際揀貨量 item_id: Ext.htmlEncode(document.getElementById("hid_item_id").value),//商品細項編號 ordd_id: Ext.htmlEncode(document.getElementById("hid_ordd_id").value), assg_id: Ext.htmlEncode(Ext.getCmp('assg_id').getValue()),//工作項目編號 ord_id: Ext.htmlEncode(Ext.getCmp('ord_id').getValue()), deliver_id: Ext.htmlEncode(Ext.getCmp('deliver').getValue()), pickRowId: arrPickRowId, pickInfo: arrPickInfo }, success: function (form, action) { var result = Ext.decode(action.response.responseText); if (result.success) { arrPickRowId = new Array(); arrPickInfo = new Array(); pickCount = 0; pickNum = 0; var msg = ""; var fa = 0; if (result.qty > 0) { msg = "該商品缺貨! "; } if (result.ord == 0) { if (result.can == 0) { msg += "該訂單可以封箱! "; } else { if (result.flag == 0) { fa = 1; editFunction("請移交主管處理"); } else { editFunction("請移交主管處理!"); //LoadWorkInfo(Ext.getCmp("assg_id").getValue()); Ext.getCmp("upc_id").setValue(""); //清空料位條碼繼續進行撿貨 } } } if (result.flag == 0&& fa==0) { //不繼續往下循環 Ext.Msg.alert("提示", "該項目已經走完!"); setTimeout('closedthis()', 3000); //Ext.MessageBox.confirm("提示", msg + "該項目已經走完,是否繼續?", function (btn) { // if (btn == "yes") { // document.location.href = "/WareHouse/MarkTally"; // } // else { // document.location.href = "/WareHouse/MarkTally"; // } //}); } else if( fa == 0){//續下一個商品。 if (msg !== "") { Ext.MessageBox.confirm("提示", msg, function (btn) { if (btn == "yes") { return true; } else { return false; } }) } LoadWorkInfo(Ext.getCmp("assg_id").getValue()); Ext.getCmp("upc_id").setValue(""); //清空料位條碼繼續進行撿貨 } } else { Ext.Msg.alert(INFORMATION, "程序運行出錯,請聯繫開發人員!"); } }, failure: function (form, action) { Ext.Msg.alert(INFORMATION, "系統異常,請稍后再試,如有重複出錯請聯繫管理員!"); } }); } } function closedthis() { document.location.href = "/WareHouse/MarkTally"; }
QUnit.config.module = "MODULE b"; QUnit.module( "Module A", () => { QUnit.test( "Test A", assert => { assert.true( false ); } ); } ); QUnit.module( "Module B", () => { QUnit.test( "Test B", assert => { assert.true( true ); } ); } ); QUnit.module( "Module C", () => { QUnit.test( "Test C", assert => { assert.true( false ); } ); } );
console.log("yo"); var user //grab id from session $.get("/api/session").then(function (session) { console.log(session) user = session; $.get(`/api/main/${user.currentUser.id}`).then(function (userData) { for (var i = 0; i < userData.Profile.length; i++) { var cardDiv = $(`<div class="card horizontal"></div>`) var cardImgDiv = $(`<div class="card-image"></div>`).append(`<img src="${userData.Profile[i].photo}">`) var cardStackedDiv = $(`<div class="card-stacked"></div>`) var cardContentDiv = $(`<div class="card-content"></div>`) var cardContentdelete = $(`<i class="material-icons small right tooltipped delete" data-position="top" id="test" data-delay="50" data-tooltip="Delete my Account" data-id="${userData.Profile[i]._id}" >remove_circle</i>`) var cardContentH5 = $(`<h5 class="your-name">${userData.Profile[i].first_name ? userData.Profile[i].first_name : userData.first_name} ${userData.Profile[i].last_name ? userData.Profile[i].last_name : userData.last_name}</h5>`) var cardContentRow = $(`<div class="row"></div>`) var cardContentRowDiv1 = $(`<div class="col s6"></div>`) var cardContentRowDiv1P1 = $(`<p>DOB: ${userData.Profile[i].birthdate}</p>`) var cardContentRowDiv1P2 = $(`<p>Height: ${userData.Profile[i].height}</p>`) var cardContentRowDiv1P3 = $(`<p>Hair: ${userData.Profile[i].hair}</p>`) var cardContentRowDiv2 = $(`<div class="col s6"></div>`) var cardContentRowDiv2P1 = $(`<p>AGE: ${calulateAge(userData.Profile[i].birthdate)}</p>`) var cardContentRowDiv2P2 = $(`<p>Weight: ${userData.Profile[i].weight}</p>`) var cardContentRowDiv2P3 = $(`<p>Eye: ${userData.Profile[i].eyes}</p>`) var cardContentRowDiv2P4 = $(`<p>Relationship: ${userData.Profile[i].relationship ? userData.Profile[i].relationship : "Account Owner"}</p>`) var cardContentLastDiv = $(`<p class="black-text text-darken-4"><a href="profile.html"><i class="material-icons right tooltipped" data-position="top" data-delay="50" data-tooltip="more info" data-id="${userData.Profile[i]._id}">more_horiz</i></a></p>`) cardContentRowDiv1.append(cardContentRowDiv1P1).append(cardContentRowDiv1P2).append(cardContentRowDiv1P3) cardContentRowDiv2.append(cardContentRowDiv2P1).append(cardContentRowDiv2P2).append(cardContentRowDiv2P3).append(cardContentRowDiv2P4) cardContentRow.append(cardContentRowDiv1).append(cardContentRowDiv2) cardContentDiv.append(cardContentdelete).append(cardContentH5).append(cardContentRow) cardStackedDiv.append(cardContentDiv).append(cardContentLastDiv) cardDiv.append(cardImgDiv).append(cardStackedDiv) $(`#cardStuff`).append(cardDiv) } }) }) //query the db Prfile for users id //generate a card with data function calulateAge(dateString) { var today = new Date(); var birthDate = new Date(dateString); var age = today.getFullYear() - birthDate.getFullYear(); var m = today.getMonth() - birthDate.getMonth(); if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; } return age; } //sudo request made to backend for user // var user = { // userData: { // firstName: "ahhhhhh", // lastName: "qoooooo" // }, // _id: "5aac14432e838fa643d51d88", // photo: './images/addform/addformperson.jpg', // birthdate: '12/08/2112', // address: 'qwerqwerqwer', // phone: 'asdfasdfasd', // height: 'vzxcvzxcvzc', // weight: 'sdfgs', // hair: 'qwerqwe', // eyes: 'sfgsdf' // } // < div class="card horizontal" > // <div class="card-image"> // <img src="./images/profile/you.JPG"> // </div> // <div class="card-stacked"> // <div class="card-content"> // <h5 class="your-name">JoEllen D. Giani</h5> // <div class="row"> // <div class="col s6"> // <p>DOB: 12/7/80</p> // <p>Height: 5' 9"</p> // <p>Hair: Brown</p> // </div> // <div class="col s6"> // <p>AGE: 36</p> // <p>Weight: 150 lbs</p> // <p>Eye: Brown</p> // </div> // </div> // </div> // <div class=""> // <p class="black-text text-darken-4">YOU<a href="profile.html"><i class="material-icons right tooltipped" data-position="top" data-delay="50" data-tooltip="more info">more_horiz</i></a></p> // </div> // </div> // </div> // $("#test").on("click", function (event) { // console.log("this clicked"); // // var id = $(this).data("id"); // var id = $(this).attr("data-id"); // // $.delete(`/delete/profile/${sessionUser.currentUser.id} // // Send the DELETE request. // $.ajax({ // type: "DELETE", // url: "/delete/profile/" + id, // }).then( // function () { // console.log("deleted profile", id); // // Reload the page to get the updated list // location.reload(); // } // ); // });
var image_list; var define; var firstview; $(document).ready(function(){ if(firstview == "on") { if(!localStorage.getItem("fade_no_first_view")) { localStorage.setItem("fade_no_first_view","true"); setup(); } } else { localStorage.removeItem("fade_no_first_view"); setup(); } }); function setup() { var html = $("body").html(); $("body").html("<div id='fade-main-content' style='display:none;'>"+html+"</div>"); $("body").prepend("<div id='fade-image'></div>"); for (var i=0 ; i<image_list.length ; i++) { $("#fade-image").append("<div style='background-image:url("+image_list[i]+");'></div>"); } for (i=0;i<image_list.length;i++) { fade_in_out(i); } } function fade_in_out (i) { if(i == 0) { if(1 == image_list.length) { $("#fade-image div").eq(i).fadeIn(deley_time,function(){ $(this).fadeOut(deley_time); $("#fade-main-content").fadeIn(deley_time); }); } else { $("#fade-image div").eq(i).fadeIn(deley_time,function(){ $(this).fadeOut(deley_time); }); } } else if (i+1 == image_list.length) { setTimeout(function() { $("#fade-image div").eq(i).fadeIn(deley_time,function(){ $(this).fadeOut(deley_time); $("#fade-main-content").fadeIn(deley_time); }); }, deley_time*i); } else { setTimeout(function() { $("#fade-image div").eq(i).fadeIn(deley_time,function(){ $(this).fadeOut(deley_time); }); }, deley_time*i); } }
export default (req, schema) => { let headers; if (schema) { const { properties } = schema; for (const property in properties) { if (!headers) { headers = {}; } headers[property] = req.getHeader(property); } // This shit makes all plugins go wrong headers.origin = req.getHeader('origin'); return headers; } if (schema !== false) { req.forEach((key, value) => { if (!headers) { headers = {}; } headers[key] = value; }); } return headers; };
var getCurrBoard = require('../assets/js/getCurrBoard.js') test('gets board from DOM', () => { // Set up our document body document.body.innerHTML = `<div class="container" id="board"> <div class="box box1"> <div class="cell cell1">1</div> <div class="cell cell2">2</div> <div class="cell cell3">3</div> <div class="cell cell4">4</div> <input type="text" class="numberInput cell"> <div class="cell cell6">6</div> <div class="cell cell7">7</div> <div class="cell cell8">8</div> <div class="cell cell9">9</div> </div> </div>` expect(getCurrBoard()).toBeDefined() });
const notes = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b'] const tuning = 400 const noteToString = noteNumber => { if (noteNumber % 1 !== 0) return false const octave = Math.floor((noteNumber - 12) / 12) return `${notes[noteNumber % 12]}${octave}` } const stringToNote = noteString => { for (let i in notes) { if (noteString.includes(notes[i])) { let note = parseInt(i) let octave const parsedRemainder = noteString.split(notes[i])[1] if (parsedRemainder.includes('#')) { octave = parseInt(parsedRemainder.split('#')[1]) note += 1 } else { octave = parseInt(parsedRemainder) } return note + 12 * octave + 12 } } return -1 } const noteToFrequency = noteNumber => { const a4hz = tuning const a4midi = 69 return 2 ** ((noteNumber - a4midi) / 12) * 440 } module.exports = { noteToString, stringToNote, noteToFrequency }
import React, { Component } from "react"; import { BrowserRouter, Route } from "react-router-dom"; // compoents import SearchGithub from "./SearchGithub"; import Header from "./common/Header"; import Footer from "./common/Footer"; const App = () => { return ( <BrowserRouter> <div> <Header /> <Route path="/" exact component={SearchGithub} /> <Footer /> </div> </BrowserRouter> ); }; export default App;
const randomHexaNumber = () => { let hexaChar= '0123456789abcdef' let hexaLen = hexaChar.length //let hexaIndex = Math.floor(Math.random()*hexaLen) let hexaId = '#' for (let i=0; i<6; i++) { hexaId = hexaId + hexaChar[Math.floor(Math.random()*hexaLen)] } return hexaId } const copyHexaId = (value) => { let input = document.createElement('input') document.body.appendChild(input) input.value = value input.select() document.execCommand('copy') input.remove() } const searchResultDiv = document.querySelector('#searchResult') const number = document.querySelector('#number') const generate = document.querySelector('#generate') const stop = document.querySelector('#stop') const homePage = () => { searchResultDiv.textContent = '' for (i=0; i<5;i++) { const divCol = document.createElement('div') const copyButton = document.createElement('button') copyButton.style.margin = '10px' copyButton.textContent= 'Copy' //copyButton.setAttribute('id','copyid-'+i) divCol.setAttribute('class','divCol') const hexaColorId = randomHexaNumber() divCol.append(hexaColorId) divCol.append(copyButton) divCol.style.background = hexaColorId searchResultDiv.append(divCol) copyButton.addEventListener('click', function(event) { let copiedText = divCol.textContent.replace('Copy','') copyHexaId(copiedText) }) } } homePage() const timer = setInterval(homePage,2000) stop.addEventListener('click', function() { clearInterval(timer) }) generate.addEventListener('click', function() { clearTimeout(timer) console.log('inside generator') searchResultDiv.textContent = '' const number = document.querySelector('#number') console.log('Number is',number.value) if ( number.value <5) { divNum1 = document.createElement('div') divNum1.textContent = '*Enter a number greater than or equal to 5' divNum1.style.color = 'red' searchResultDiv.append(divNum1) //searchResultDiv.replaceWith(divNum1) //searchResultDiv.replaceWith(divNum1) const searchResultDiv1 = document.querySelector('#searchResult') console.log('searchResultDiv in the middle',searchResultDiv1) } else { const divNum2 = document.createElement('div') divNum2.setAttribute('id','divNum2') for (i=0; i<number.value;i++) { const divNum3 = document.createElement('div') divNum3.setAttribute('class','divNum3') const hexaColorId = randomHexaNumber() divNum3.append(hexaColorId) console.log('divNum3,',divNum3) divNum3.style.background = hexaColorId divNum2.append(divNum3) console.log('divNum2,',divNum2) } searchResultDiv.append(divNum2) console.log('Final divNum2', divNum2) console.log(divNum2.textContent) console.log('searchResultDiv before appending',searchResultDiv) //searchResultDiv1.append(divNum2) console.log('searchResultDiv after appending',searchResultDiv) } })
import { storiesOf } from '@storybook/vue' import { Heading, Text as KText, Stack, Box } from '..' storiesOf('UI | Stack', module) .add('With vertical stack', () => ({ components: { Heading, KText, Stack, Box }, template: ` <div> <Stack spacing="8"> <Box p="5" shadow="md" border-width="1px"> <Heading font-size="xl">Plan Money</Heading> <KText mt="4">The future can be even brighter but a goal without a plan is just a wish</KText> </Box> <Box p="5" shadow="md" border-width="1px"> <Heading font-size="xl">Save Money</Heading> <KText mt="4">You deserve good things. With a whooping 10-15% interest rate per annum, grow your savings on your own terms with our completely automated process</KText> </Box> </Stack> </div> ` })) .add('With horizontal stack', () => ({ components: { Heading, KText, Stack, Box }, template: ` <div> <Stack is-inline spacing="8"> <Box p="5" shadow="md" border-width="1px"> <Heading font-size="xl">Plan Money</Heading> <KText mt="4">The future can be even brighter but a goal without a plan is just a wish</KText> </Box> <Box p="5" shadow="md" border-width="1px"> <Heading font-size="xl">Save Money</Heading> <KText mt="4">You deserve good things. With a whooping 10-15% interest rate per annum, grow your savings on your own terms with our completely automated process</KText> </Box> </Stack> </div> ` }))
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { BrowserRouter as Router, Switch, Route, Link ,match, Redirect} from "react-router-dom"; import * as action from "../../_redux/actions.js"; import * as acyncActions from "../../_redux/acyncActions.js"; import './Login.css'; import Modal from '../Modal'; import BtnHome from '../Common/Btn/BtnHome.js'; class Login extends Component { constructor(props) { super(props); this.state = { login: '', password:'', a:true }; this.onCancel = this.onCancel.bind(this); this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); this.onError = this.onError.bind(this); } onChange(event) { const target = event.target; const name = target.name; this.setState({ [name]: target.value }); } onCancel() { this.setState({ login: '', password:'' }); } onError() { this.props.errorAction(false); } onSubmit() { let data = { login:this.state.login, password:this.state.password, } for ( let key in data) { if (data[key].length <= 0 ) { return } } this.props.authAction('/auth/login',{ method:'post', body: JSON.stringify(data), headers: { "Accept": "application/json", "Content-Type": "application/json" } },action.LOGIN_SEND); } render () { if ( this.props.isLoading ) { return <p>Loading…</p>; } if (this.props.auth) return <Redirect to="/admin" />; return ( <React.Fragment> {this.props.hasErrored ? <Modal onError={this.onError} errorText={this.props.errText} /> : null} <div className="login"> <BtnHome /> <div className="login-form-block"> <h3 className="login-form-head">Login form</h3> <div className="login-form-wrap"> <form className="login-form" onSubmit={this.onSubmit}> <div className="form-group"> <input type="text" name="login" placeholder="Login" onChange={ (e) => this.onChange(e)} value={this.state.login} className="form-input"/> </div> <div className="form-group"> <input type="password" name="password" placeholder="Password" onChange={ (e) => this.onChange(e)} value={this.state.password} className="form-input"/> </div> <div className="btn-group clearfix"> <input type="button" value="Submit" onClick={this.onSubmit} className="form-btn submit"/> <input type="button" value="Cancel" onClick={this.onCancel} className="form-btn cancel"/> </div> </form> </div> </div> </div> </React.Fragment> )} } export default connect( (store) => {return { auth: store.appState.auth, hasErrored: store.appState.loginHasErrored, isLoading: store.appState.LoginIsLoading, errText: store.appState.errText, }}, (dispatch) => {return { authAction: (url,options,effect) => { dispatch(acyncActions.Auth(url,options,effect)); }, errorAction: (bool) => { dispatch(action.LOGIN_itemsHasErrored(bool)); }, }} )(Login);
/*$(document).ready(function () { /*alert(getCookie("diaSemana")); $(function () { var data = getCookie("diaSemana"); for (var i = 0; i < 6; i++) if (data != i) $("input.col" + i).attr("disabled", true); }); $('#tabela td input').click(function (e) { var horas = $(this).parent().parent().prop('className'); var dia = $(this).parent().parent().children().children().index($(this)); alert(horas + " " + dia); for (var i = 0; i < 6; i++) if (dia != i) $("input.col" + i).attr("disabled", true); $.post('AdicionarReservas/reserva.jsp', { horas: horas, dia: dia }, function (responseText) { $('#reserva').html(responseText); }); }); function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } });*/
import MdRendererBase from "./md-renderer-base"; export default class HeaderAnchorRenderer extends MdRendererBase { constructor() { super(); } apply($content, $) { $content.children('section').find(':header a[href][id]').filter(function() { return `#${$(this).id()}` === $(this).attr('href'); }).each(function() { let $a = $(this), $h = $a.closest(':header'), $padder = $('<a>').addClass('header-anchor').id($a.id()); $padder.insertBefore($h); $a.id(null); }); } }
// Ex6.3-organize_strings // Take 2 strings s1 and s2 including only letters from a to z. // Return a new sorted string, the longest possible, containing distinct letters, each taken only once - coming from s1 or s2. // Examples: // a = "xyaabbbccccdefww" // b = "xxxxyyyyabklmopq" // longest(a, b) -> "abcdefklmopqwxy" // a = "abcdefghijklmnopqrstuvwxyz" // longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" const longest = (s1, s2) => { const joinedStr = s1.concat(s2); let resultStr = []; for (let char of joinedStr) { !resultStr.includes(char) && (resultStr = resultStr.concat(char)); } return resultStr.sort().join(""); }; const a = "xyaabbbccccdefww"; const b = "xxxxyyyyabklmopq"; const c = "abcdefghijklmnopqrstuvwxyz"; console.log(longest(a, b)); console.log(longest(c, c));
const countries= { "Spillian 10.19.2019": { "subtitle": "Kanhar Munshi & Carolyn Dawn Campo, Fleischmann, NY", "description": [ ], "video_url": "https://www.youtube.com/embed/YvGxuIvkIo4", "video_image": "img/videoSpillianShort.jpg" }, "Calcutta 02.19.2020": { "subtitle": "Kanhar Munshi & Carolyn Dawn Campo, Calcutta, India", "description": [ ], "video_url": "https://www.youtube.com/embed/OljW9di0_TY", "video_image": "img/videoCalcuttaPreview.jpg" }, }; // Create Header Links var parentPage = "video.html"; const urlParams = new URLSearchParams(window.location.search); const levelAValue = urlParams.get('levelA'); const levelBValue = urlParams.get('levelB'); var level0Href = '<a href="' + parentPage + '">Video</a>'; var levelAHref = '<a href="' + parentPage + '?levelA=' + levelAValue + '">' + levelAValue +'</a>'; var levelBHref = '<a href="' + parentPage + '?levelA=' + levelAValue + '&levelB='+levelBValue+'">'+levelBValue+'</a>'; var headerOutput; if (levelAValue != null && levelBValue != null) { headerOutput = level0Href + " --> " + levelAHref + " --> " + levelBHref; } else if(levelAValue != null) { headerOutput = level0Href + " --> " + levelAHref; } else { headerOutput = level0Href; } if (!levelAValue) { let output = ''; const datas = Object.entries(countries); datas.forEach(d=> { output += ` <a href="video.html?levelA=${d[0]}" class="item"> <img src="${d[1].video_image}" alt=""> <span>${d[0]}</span> </a> `; }); const div = document.createElement("div"); div.className = 'generic-items'; div.innerHTML= output; document.querySelector(".generic-leaf-container").insertAdjacentElement("beforeend", div); } else { var x= Object.entries(countries); var found= x.find(y => { return y[0] == levelAValue; }); document.querySelector(".generic-description").innerHTML = found[1].subtitle; document.querySelector(".generic-description").style.textTransform = 'capitalize'; const ul = document.createElement("ul"); ul.innerHTML= ` <div style="width: 95%; margin: 3.2rem auto;"> <iframe width="100%" height="550" src="${found[1].video_url}" id="video-player" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> `; document.querySelector("#generic-container .generic-leaf-container").insertAdjacentElement("afterend", ul); } document.querySelector(".generic-header").innerHTML= headerOutput;
module.exports = function(ngModule) { ngModule.factory('bandList', function() { return [{ name: 'Joe', formed: '2000' }, { name: 'Jill', formed: '2001' }]; }); };
var express = require('express'); var app = express(); var db = require('./db'); app.get('/', function(req, res){ res.render('events', { }); }); app.post('/', function(req, res){ var skill; if (req.body.communication){ console.log("Communication event"); skill = "Communication"; } if (req.body.responsibilty){ console.log("Communication event"); skill = "Responsibilty"; } if (req.body.Criticalt){ console.log("Communication event"); skill = "criticalt"; } db.query("SELECT * FROM `activities` WHERE skill = '"+skill+"'", function(request, responce){ if(responce[0] != undefined){ console.log(responce[0]); } res.render('events', { event: responce }); }); }); module.exports = app;
import PageLoading from './page-loading'; export default PageLoading;
/** CONFIG GERAL **/ "use strict"; module.exports = { /** CONEXAO BASE DE DADOS **/ /* config: { host: 'cheff_db.mysql.dbaas.com.br', user : 'cheff_db', password : 'dbzGTL123', database : 'cheff_db' }, */ config: { host: 'localhost', user : 'root', password : '123!@#321#@!', database : 'CHEFF' }, configRemote: { host: 'cheff_db.mysql.dbaas.com.br', user : 'cheff_db', password : 'dbzGTL123', database : 'cheff_db' }, configFtp: { host: 'ftp.cheff.innsere.com.br', user : 'cheff2', password : 'dbzGTL123' }, configMail: { user: 'nao-responda@innsere.com.br', password: 'jesus260389', host: 'email-ssl.com.br', port: 465, ssl: true }, }
import Home from './home'; import PostExample from './postPage'; import BlogExample from './blogPage'; module.exports = { Home, PostExample, BlogExample }
export default class Journey { constructor(p) { this.p = p this.route = [] this.boxSize = 26 this.gHue = Math.random() * 360 this.hueSpeed = 0.8 this.setup() } setup() { const { route, p } = this const length = 50 for (let i = 0; i < length; i += 1) { route.push( new RouteItem(128 - (i / length) * 128, this.boxSize, route, p) ) } } render(x, y, z, rx, ry, rz) { const { hueSpeed, route } = this this.gHue += hueSpeed if (this.gHue > 360) { this.gHue = 0 } // render for (let i = 0; i < route.length; i += 1) { route[i].render(i, x, y, z, rx, ry, rz) } } } class RouteItem { constructor(radius, boxSize, route, p) { this.radius = radius this.cx = 0 this.cy = 0 this.cz = 0 this.boxSize = boxSize this.route = route this.p = p } getY() { return -this.cy } render(i, x, y, z, rx, ry, rz) { const { radius, boxSize, route, p } = this p.push() p.translate(x, y, z) p.rotateX(rx) p.rotateY(ry) p.rotateZ(rz) this.cx = 0 this.cy = (p.noise((p.frameCount * 0.5 + i * 1.2) * 0.006) - 0.5) * p.windowHeight this.cz = -i * boxSize + 400 + boxSize const angleShift = (i / (route.length - 1)) * Math.PI + p.frameCount * 0.015 + p.sin(p.frameCount * 0.01 + i * 0.1) const circum = 2 * Math.PI * radius const numEntities = p.int(circum / boxSize) for (let e = 0; e < numEntities; e += 1) { const angle = (e / (numEntities - 1)) * Math.PI * 2 + angleShift const ex = Math.cos(angle) * radius const ey = Math.sin(angle) * radius const ez = p.sin(p.frameCount * 0.01 + i * 0.1) * boxSize * 0.7 p.push() p.fill( p.noise((p.frameCount * 0.05 + i + angle) * 0.4) * 360, p.map(p.noise(p.frameCount * 0.05 + i, angle), 0, 1, 64, 100), p.map(p.noise(angle, p.frameCount * 0.05 + i), 0, 1, 30, 100) ) p.translate(this.cx + ex, this.cy + ey, this.cz + ez) p.strokeWeight(2) p.box(boxSize) p.pop() } p.pop() } }
function login() { var email = $('#inputEmail').val(); var password = $('#inputPassword').val(); var info = { email: email, password: password } xhr = new XMLHttpRequest(); var url = "http://localhost:8080/login"; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", "application/json"); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { var json = JSON.parse(xhr.responseText); console.log(json.data.key); var userInfo = { email: email, token: json.data.key } $.ajax({ type: 'POST', url: 'http://localhost:8081/userToken', dataType: 'json', data: userInfo }); document.location.href = "/home_page"; } else { console.log(xhr.status, xhr.responseText); alert("error"); } } } var data = JSON.stringify(info); xhr.send(data); }
var searchData= [ ['base_5fpv',['BASE_PV',['../classGardien.html#a1832c02b32c6e47b240536fd6ba47812',1,'Gardien']]], ['box',['BOX',['../Labyrinthe_8h.html#ac14e2c021da59c694d6643dba21a9b7e',1,'Labyrinthe.h']]] ];
document.getElementById('form-email').addEventListener('submit', function (e) { e.preventDefault(); let errorSpan = document.getElementById('error-msg'); let errorIcon = document.getElementsByClassName('error-icon')[0]; const mailFormat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; const mail = e.target[0].value; errorSpan.innerHTML = ''; if (!mail.match(mailFormat)) { errorSpan.innerHTML = 'Oops! Please check your email'; errorIcon.classList.add('flag'); setTimeout(function () { errorIcon.classList.remove('flag'); errorSpan.innerHTML = ''; }, 3000); } });
import faunadb from 'faunadb' const FEEDBACK_INDEX = 'feedback_by_slug' const FEEDBACK_COLLECTION = 'feedback' export default async function handler(req, res) { if (req.method === 'POST') { const db = faunadb.query const client = new faunadb.Client({ secret: process.env.FAUNA_SECRET_KEY, }) const { slug, message, name } = req.query if (!slug) { return res.status(400).json({ message: 'Article slug not provided', }) } const doesDocExist = await client.query( db.Exists(db.Match(db.Index(FEEDBACK_INDEX), slug)) ) if (!doesDocExist) { await client.query( db.Create(db.Collection(FEEDBACK_COLLECTION), { data: { slug, feedback: [], }, }) ) } const doc = await client.query( db.Get(db.Match(db.Index(FEEDBACK_INDEX), slug)) ) await client.query( db.Update(doc.ref, { data: { feedback: [...doc.data.feedback, { message, name }] }, }) ) return res.status(200).json({ feedback: doc.data.feedback }) } return res.status(404).end() }
describe('URLValidator', function () { 'use strict'; var urlValidator; beforeEach(module('WordItApp')); beforeEach(inject(function (_$rootScope_, _UrlValidator_) { urlValidator = _UrlValidator_; })); it('should prepend protocol if url does not contain a protocol', function () { expect(urlValidator.validify('www.google.com')).toBe('http://www.google.com'); expect(urlValidator.validify('www.pivotal.io')).toBe('http://www.pivotal.io'); expect(urlValidator.validify('pivotal.io')).toBe('http://pivotal.io'); }); it('should not prepend if a protocol is potentially added', function () { expect(urlValidator.validify('h')).toBe('h'); expect(urlValidator.validify('ht')).toBe('ht'); expect(urlValidator.validify('htt')).toBe('htt'); }); it('should not prepend empty string', function () { expect(urlValidator.validify('')).toBe(''); }) });
import React from 'react' export default function Start(){ return ( <div className="start-icon iconfont">&#xe60f;</div> ) }
/** * 文件二进制流 */ export default (response, type, fileType, name) => { const blob = new Blob([response], { type }); const downloadElement = document.createElement('a'); const href = window.URL.createObjectURL(blob); const currentName = `${new Date().getTime()}`; downloadElement.href = href; downloadElement.download = name || `${currentName}${fileType}`; document.body.appendChild(downloadElement); downloadElement.click(); document.body.removeChild(downloadElement); // 下载完成移除元素 window.URL.revokeObjectURL(href); // 释放掉blob对象 };
$(document).ready( function () { $('#table_nonpemakalah').DataTable({ "scrollX": true, "paging": true, "lengthChange": true, "searching": true, "ordering": true, "info": false, "responsive": true, "autoWidth": false, "pageLength": 10, "ajax": { "url": "data_admnonpemakalah.php", "type": "POST" }, "columnDefs":[ { "targets":[0], "orderable":false, }, ], "columns": [ { "data": "btnhps" }, { "data": "status_bayar" }, { "data": "nama_lengkap" }, { "data": "instansi" }, { "data": "alamat" }, { "data": "no_hp" }, { "data": "email" }, ] }); }); $(document).on( "click",".btnhapus", function() { var id_np= $(this).attr("id_np"); var nama_lengkap = $(this).attr("nama_lengkap"); swal({ title: "Delete Data?", text: "Delete Data : "+nama_lengkap+" ?", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Delete", closeOnConfirm: true }, function(){ var value = { id_np: id_np }; $.ajax( { url : "delete_nonpemakalah.php", type: "POST", data : value, success: function(data, textStatus, jqXHR) { var data = jQuery.parseJSON(data); if(data.result ==1){ $.notify('Successfull delete data'); var table = $('#table_nonpemakalah').DataTable(); table.ajax.reload( null, false ); }else{ swal("Error","Can't delete data, error : "+data.error,"error"); } }, error: function(jqXHR, textStatus, errorThrown) { swal("Error!", textStatus, "error"); } }); }); });
Communication.OUTGOING_LOGIN = 1; Communication.OUTGOING_REQUEST_MAP = 2; Communication.OUTGOING_REQUEST_MOVEMENT = 7; Communication.OUTGOING_REQUEST_CHAT = 9; Communication.OUTGOING_REQUEST_LOOK_AT = 12; Communication.OUTGOING_REQUEST_WAVE = 13; Communication.OUTGOING_REQUEST_ROOM_DATA = 15; Communication.OUTGOING_REQUEST_ITEM_INTERACT = 18; Communication.INCOMING_LOGIN_OK = 3; Communication.INCOMING_MAP_DATA = 4; Communication.INCOMING_PLAYERS_DATA = 6; Communication.INCOMING_PLAYER_STATUS = 8; Communication.INCOMING_CHAT = 10; Communication.INCOMING_PLAYER_REMOVE = 11; Communication.INCOMING_PLAYER_WAVE = 14; Communication.INCOMING_ROOM_ITEM_DATA = 16; Communication.INCOMING_ITEM_REMOVE = 17; Communication.INCOMING_ITEM_STATE = 19; Communication.INCOMING_WALL_ITEM_DATA = 20; function Communication(game) { this.game = game; } Communication.prototype.doLogin = function(username, look) { var message = new ClientMessage(Communication.OUTGOING_LOGIN); message.appendString(username); message.appendString(look); this.game.connection.sendMessage(message); }; Communication.prototype.requestMap = function() { this.game.connection.sendMessage(new ClientMessage(Communication.OUTGOING_REQUEST_MAP)); }; Communication.prototype.requestRoomData = function() { this.game.connection.sendMessage(new ClientMessage(Communication.OUTGOING_REQUEST_ROOM_DATA)); }; Communication.prototype.requestMovement = function(x, y) { var message = new ClientMessage(Communication.OUTGOING_REQUEST_MOVEMENT); message.appendInt(x); message.appendInt(y); this.game.connection.sendMessage(message); }; Communication.prototype.requestChat = function(chat) { if (chat.length > 0) { var message = new ClientMessage(Communication.OUTGOING_REQUEST_CHAT); message.appendString(chat); this.game.connection.sendMessage(message); } }; Communication.prototype.requestLookAt = function(userId) { var message = new ClientMessage(Communication.OUTGOING_REQUEST_LOOK_AT); message.appendInt(userId); this.game.connection.sendMessage(message); }; Communication.prototype.requestWave = function() { var message = new ClientMessage(Communication.OUTGOING_REQUEST_WAVE); this.game.connection.sendMessage(message); }; Communication.prototype.requestInteractFurni = function(itemId) { var message = new ClientMessage(Communication.OUTGOING_REQUEST_ITEM_INTERACT); message.appendInt(itemId); this.game.connection.sendMessage(message); }; Communication.prototype.handleMessage = function(data) { var request = new ServerMessage(data); switch (request.id) { case Communication.INCOMING_LOGIN_OK: this.handleLoggedIn(request); break; case Communication.INCOMING_MAP_DATA: this.handleMap(request); break; case Communication.INCOMING_PLAYERS_DATA: this.handlePlayers(request); break; case Communication.INCOMING_PLAYER_STATUS: this.handleStatus(request); break; case Communication.INCOMING_PLAYER_REMOVE: this.handleRemovePlayer(request); break; case Communication.INCOMING_CHAT: this.handleChat(request); break; case Communication.INCOMING_PLAYER_WAVE: this.handleWave(request); break; case Communication.INCOMING_ROOM_ITEM_DATA: this.handleRoomItems(request); break; case Communication.INCOMING_ITEM_REMOVE: this.handleRemoveFurni(request); break; case Communication.INCOMING_ITEM_STATE: this.handleFurniState(request); break; case Communication.INCOMING_WALL_ITEM_DATA: this.handleWallItems(request); } }; Communication.prototype.handleLoggedIn = function(request) { this.game.onLoggedIn(); }; Communication.prototype.handleMap = function(request) { updateStatus("Received map"); var cols = request.popInt(); var rows = request.popInt(); var doorX = request.popInt(); var doorY = request.popInt(); var heightmap = []; for (var i = 0; i < cols; i++) { heightmap.push([]); for (var j = 0; j < rows; j++) { heightmap[i].push(request.popInt()); } } this.game.setMap(cols, rows, doorX, doorY, heightmap); }; Communication.prototype.handlePlayers = function(request) { var count = request.popInt(); //updateStatus("Received (" + count + ") players"); for (var i = 0; i < count; i++) { var id = request.popInt(); var x = request.popInt(); var y = request.popInt(); var z = request.popFloat(); var rot = request.popInt(); var name = request.popString(); var look = request.popString(); if (this.game.currentRoom != null) { this.game.currentRoom.setPlayer(id, x, y, z, rot, name, look); } } }; Communication.prototype.handleRoomItems = function(request) { var count = request.popInt(); //updateStatus("Received (" + count + ") room items"); for (var i = 0; i < count; i++) { var id = request.popInt(); var x = request.popInt(); var y = request.popInt(); var z = request.popFloat(); var rot = request.popInt(); var baseId = request.popInt(); var state = request.popInt(); if (this.game.currentRoom != null) { this.game.currentRoom.setRoomItem(id, x, y, z, rot, baseId, state); } } }; Communication.prototype.handleWallItems = function(request) { var count = request.popInt(); //updateStatus("Received (" + count + ") wall items"); for (var i = 0; i < count; i++) { var id = request.popInt(); var x = request.popInt(); var y = request.popInt(); var rot = request.popInt(); var baseId = request.popInt(); var state = request.popInt(); if (this.game.currentRoom != null) { this.game.currentRoom.setWallItem(id, x, y, rot, baseId, state); } } }; Communication.prototype.handleFurniState = function(request) { var itemId = request.popInt(); var state = request.popInt(); if (this.game.currentRoom != null) { this.game.currentRoom.setFurniState(itemId, state); } }; Communication.prototype.handleStatus = function(request) { var count = request.popInt(); //updateStatus("Received (" + count + ") statusses"); for (var i = 0; i < count; i++) { var userId = request.popInt(); var x = request.popInt(); var y = request.popInt(); var z = request.popFloat(); var rot = request.popInt(); var statussesCount = request.popInt(); var statusses = {}; for (var j = 0; j < statussesCount; j++) { var key = request.popString(); var value = request.popString(); statusses[key] = value; } this.game.currentRoom.updateUserStatus(userId, x, y, z, rot, statusses); } /*var userId = request.popInt(); var x = request.popInt(); var y = request.popInt(); var rot = request.popInt(); if (this.game.currentRoom != null) { this.game.currentRoom.movePlayer(userId, x, y, rot); }*/ }; Communication.prototype.handleRemovePlayer = function(request) { var userId = request.popInt(); if (this.game.currentRoom != null) { this.game.currentRoom.removePlayer(userId); } }; Communication.prototype.handleRemoveFurni = function(request) { var furniId = request.popInt(); if (this.game.currentRoom != null) { this.game.currentRoom.removeFurni(furniId); } }; Communication.prototype.handleChat = function(request) { var userId = request.popInt(); var text = request.popString(); if (this.game.currentRoom != null) { this.game.currentRoom.addChat(userId, text); } }; Communication.prototype.handleWave = function(request) { var userId = request.popInt(); if (this.game.currentRoom != null) { this.game.currentRoom.addWave(userId); } };
class Model_Services_Data_ApiData{ constructor() { this.a = 1; } getData(bsCommon = {}) { return { a: 8, b: 2 } } } module.exports = Model_Services_Data_ApiData;
// @flow import type { Theme } from '../types'; const theme: Theme = { treeStyle: { padding: 0, }, bodyStyle: { padding: '0 5px', }, bodyTextStyle: { padding: 0, wordWrap: 'break-word', }, checkboxStyle: { width: 30, height: 30, }, checkboxIconStyle: { fontSize: 20, fill: 'black', }, checkboxIconCheckedStyle: { fill: '#1A70BB', }, expanderStyle: { minWidth: '20px', width: '20px', display: 'inline-block', textAlign: 'center', marginRight: 0, fill: 'black', }, listItemStyle: { margin: '2px 0', padding: '0 8px', }, paginatorStyle: { paddingTop: 0, paddingBottom: 0, }, paginatorTextStyle: { textAlign: 'center', color: '#1A70BB', }, loadingStyle: { paddingTop: 0, paddingBottom: 0, }, loadingTextStyle: { textAlign: 'center', color: '#1A70BB', }, listStyle: { paddingTop: 0, paddingBottom: 0, }, bodyClassName: null, bodyTextClassName: null, checkboxClassName: null, expanderClassName: null, listClassName: null, listItemClassName: null, loadingClassName: null, loadingTextClassName: null, paginatorClassName: null, paginatorTextClassName: null, }; export default theme;
import { computed } from '@ember/object'; import BaseTooltipElement from 'ember-bootstrap/components/base/bs-tooltip/element'; export default class TooltipElement extends BaseTooltipElement { @computed('fade', 'actualPlacement', 'showHelp') get popperClassNames() { let classes = ['tooltip', `bs-tooltip-${this.get('actualPlacement')}`]; if (this.get('fade')) { classes.push('fade'); } if (this.get('showHelp')) { classes.push('show'); } return classes; } }
import React from 'react'; import ArrowBackIosIcon from '@material-ui/icons/ArrowBackIos'; import './styles/breadcrumbs.scss'; export const Breadcrumbs = props => { return ( <div className='breadcrumbs-wrapper'> <div className='breadcrumbs container-margin-left'> <ArrowBackIosIcon style={{ fontSize: 14 }}/> <span> {'back'} </span> </div> </div> ) }
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Created with IntelliJ IDEA. * User: Natalia.Ukhorskaya * Date: 3/30/12 * Time: 3:37 PM */ var LoginView = (function () { function LoginView(loginModel) { var model = loginModel; var isLoggedIn = false; var confirmDialog = new ConfirmDialog(); var instance = { setUserName:function (name) { if (name != "[\"null\"]") setUserName(eval(name)[0]); }, isLoggedIn:function () { return isLoggedIn; }, logout:function () { isLoggedIn = false; $("#login").css("display", "block"); $("#userName").html(""); $("#userName").css("display", "none"); } }; $("a > img[src*='twitter']").click(function () { login("twitter"); }); $("a > img[src*='facebook']").click(function () { login("facebook"); }); $("a > img[src*='google']").click(function () { login("google"); }); $("#logout").click(function (e) { model.logout(); }); model.getUserName(); function login(param) { confirmDialog.open(function (param) { return function () { model.login(param); }; }(param)); } function setUserName(userName) { if (userName != "") { $("#login").css("display", "none"); $("#userName").css("display", "block"); isLoggedIn = true; userName = decodeURI(userName); userName = replaceAll(userName, "\\+", " "); $("#userName").html("<div id='userNameTitle'><span>Welcome, " + userName + "</span><img src='/static/images/toogleShortcutsOpen.png' id='userNameImg'/></div>"); document.getElementById("userNameTitle").onclick = function (e) { userNameClick(e); }; } } var isLogoutShown = false; function userNameClick(e) { if (!isLogoutShown) { $("#headerlinks").bind("mouseleave", function () { var timeout = setTimeout(function () { close(); }, 100); $("#logout").bind("mouseover", function () { clearTimeout(timeout); $("#logout").bind("mouseleave", function () { timeout = setTimeout(function () { close(); }, 500); }); }); }); isLogoutShown = true; var div = document.createElement("div"); div.id = "logout"; div.innerHTML = "Logout"; div.style.position = "absolute"; var element = document.getElementById("userNameTitle"); if (element == null) { return; } var left = element.offsetLeft; var top = element.offsetTop; for (var parent = element.offsetParent; parent; parent = parent.offsetParent) { left += parent.offsetLeft - parent.scrollLeft; top += parent.offsetTop - parent.scrollTop } div.style.left = left + 240 - 42 + "px"; div.style.top = top + 27 - 3 + "px"; div.onclick = function () { close(); model.logout(); }; document.body.appendChild(div); } else { close(); } function close() { isLogoutShown = false; var el = document.getElementById("logout"); if (el != null) { el.parentNode.removeChild(document.getElementById("logout")); } } } return instance; } return LoginView; })();
import React, {Component} from 'react'; import {connect} from 'react-redux'; import {Route, Link, BrowserRouter as Router, HashRouter} from 'react-router-dom'; import Header from "./Header"; import axios from 'axios'; import { setCompany } from '../actions/orderActions'; import {getUserInfo, setAdmin} from '../actions/userActions'; import store from "../store"; @connect ((store) => { return { companyList: store.user.CompanyList, order: store.order, token: store.user.Token, user: store.user } }) export default class PickCompany extends Component { constructor(props) { super(props); this.state = { companyList: props.companyList, selectedCompany: "", alert: false }; } componentWillMount() { this.props.dispatch(getUserInfo()); } componentWillReceiveProps(props) { this.setState({companyList: props.companyList}); } setCompany(e) { let selectedCompanyObj = this.state.companyList.filter(x=>x.No === e.currentTarget.value)[0] !== undefined ? this.state.companyList.filter(x=>x.No === e.currentTarget.value)[0]: {}; let selectedCompany = this.state.companyList.filter(x=>x.No === e.currentTarget.value)[0] !== undefined ? this.state.companyList.filter(x=>x.No === e.currentTarget.value)[0].No : ""; // console.log(selectedCompany , this.props.user.CompanyNo, selectedCompany === this.props.user.CompanyNo) if (selectedCompany === this.props.user.CompanyNo) { this.props.dispatch(setAdmin(true)); } else { this.props.dispatch(setAdmin(false)); } this.props.dispatch(setCompany(selectedCompanyObj)); this.setState({selectedCompany}); this.setState({alert: false}); } goToAddMoreMembers() { if (Object.keys(this.state.selectedCompany).length > 0) { this.props.history.push("/register-others"); } else { this.setState({alert: true}); } } render() { let alertClass = this.state.alert === true ? "alert alert-danger" : "alert alert-danger d-none"; return ( <React.Fragment> <Header /> <div className="container"> <div className="row"> <article className="col-12"> <div className="row"> <div className="col-4"> <img className="img-fluid" src="/images/registration-emea-2019.png" alt="" /> </div> <div className="col-8 d-flex align-items-center flex-wrap"> <div> <h2 className="h2 font-weight-light text-primary">Welcome to Directions EMEA registration process.</h2> <p className="">In order to continue please select a Company.</p> <p className={alertClass}>Please select a company to continue</p> <select onChange={(e)=>this.setCompany(e)} className="form-control rounded-0 mb-3" value={this.state.selectedCompany}> <option value="">Please select a company</option> {this.state.companyList.map((o,i)=> {return( <option key={i} value={o.No}>{o.Name}</option>)})} </select> <button type="button" onClick={() => this.goToAddMoreMembers()} className="btn btn-primary px-5">Next</button> </div> </div> </div> </article> </div> </div> </React.Fragment> ) } }
import { preProcessCountryData } from "../utils"; export default (state, action) => { switch (action.type) { case "SET_INDIA_VALUE": { return preProcessCountryData(action.value); } default: return action.value; } };
/** * @param {number[]} heights * @return {number} */ var largestRectangleArea = function(heights) { let result = resolve(heights, [], 0); return result; }; function calculate(selected) { if (selected.length == 0) return 0; let min = Math.min(selected); return min * selected.length; } function resolve(heights, selected, prevArea) { console.log(selected); let area = calculate(selected); if (prevArea > area) { return prevArea; } let max = 0; for (let i = selected.length; i < heights.length; i++) { let buffer = []; for (let j = 0; j <= i; j++) { buffer.push(heights[j]); } let result = resolve(heights, buffer, area); if (result > max) { max = result; } } return max; } console.log(largestRectangleArea([2, 1, 5, 6, 2, 3]));
import * as React from 'react'; import { StyleSheet, Text, View, SafeAreaView, KeyboardAvoidingView } from 'react-native'; import theme from '../src/theme' import Header from '../components/header0' import EmailInput from '../components/enterEmailContainer' export default function HomeScreen() { return ( <SafeAreaView style={styles.container}> <KeyboardAvoidingView behaviour='position'> <Header /> <EmailInput /> </KeyboardAvoidingView> </SafeAreaView> ); } HomeScreen.navigationOptions = { header: null }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: theme.palette.primary.light, } });
function happyHolidays() { return 'Happy holidays!'; } function happyHolidaysTo(you) { return 'Happy holidays,'+ ' you'+'!'; } function happyHolidayTo(holiday, name) { holiday = 'Independence Day'; name = 'you'; return 'Happy '+holiday +', '+ name+'!'; } function holidayCountdown(holiday, days) { holiday = 'Mother\'s Day'; days = 20; return 'It\'s '+days+' days until '+holiday+'!'; }
import {createStore} from 'redux'; const reduser = (state = 0, action ) => { switch (action.type) { case 'INK': return state + 1; case 'DEC': return state - 1; case 'RND': return state + action.value; default: return state; } } const ink = () =>({type:'INK' });//функия action creator(созадёт действие) let store = createStore(reduser);//создаёт стор с редьюсером console.log(store.getState());//достаёт стейт из стора document.getElementById('ink').addEventListener('click', () => { store.dispatch(ink()/*использование action crateror */);//вызывает нужный редьюсер в сторе }); document.getElementById('dec').addEventListener('click', () => { store.dispatch({type:'DEC'}); }); document.getElementById('rnd').addEventListener('click', () => { const value = Math.floor(Math.random() * 10); store.dispatch({type:'RND', value});//напрямую зависимлсть в редьюсер запихивать нельзя - она должна быть чистой. поэтому передаём значение }); const update = () =>{ document.getElementById('counter').textContent = store.getState(); } store.subscribe(update);//вызывает колюэк при каждом обрпщении к стору
/* * @lc app=leetcode.cn id=557 lang=javascript * * [557] 反转字符串中的单词 III */ // @lc code=start /** * @param {string} s * @return {string} */ var reverseOneWord = function(s) { let sArr = s.split(""); let left = 0, right = sArr.length - 1; while (left < right) { const temp = sArr[left]; sArr[left] = sArr[right]; sArr[right] = temp; left++; right--; } return sArr.join(""); } var reverseWords = function(s) { let sArr = s.split(" "); let result = []; for (let i = 0; i < sArr.length; i++) { let temp = sArr[i]; let word = reverseOneWord(temp); result.push(word); } return result.join(" ") }; // @lc code=end
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2014 SAP AG or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ jQuery.sap.declare("sap.ui.commons.CalloutRenderer"); jQuery.sap.require("sap.ui.commons.CalloutBaseRenderer"); jQuery.sap.require("sap.ui.core.Renderer"); /** * @class Callout renderer. * @static */ sap.ui.commons.CalloutRenderer = sap.ui.core.Renderer.extend(sap.ui.commons.CalloutBaseRenderer); /** * Renders the HTML for content. * * @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer * @param {sap.ui.core.Control} oCallout an object representation of the Callout that should be rendered */ sap.ui.commons.CalloutRenderer.renderContent = function(oRenderManager, oCallout){ var rm = oRenderManager; var content = oCallout.getContent(); // content for (var i = 0; i < content.length; i++) { rm.renderControl(content[i]); } }; /** * Add the root CSS class to the Callout to redefine/extend CalloutBase * * @param {sap.ui.core.RenderManager} * oRenderManager the RenderManager that can be used for writing to * the Render-Output-Buffer * @param {sap.ui.core.Control} * oControl an object representation of the control that should be * rendered */ sap.ui.commons.CalloutRenderer.addRootClasses = function(oRenderManager, oControl) { oRenderManager.addClass("sapUiClt"); }; /** * Add the content CSS class to the Callout to redefine/extend CalloutBase * * @param {sap.ui.core.RenderManager} * oRenderManager the RenderManager that can be used for writing to * the Render-Output-Buffer * @param {sap.ui.core.Control} * oControl an object representation of the control that should be * rendered */ sap.ui.commons.CalloutRenderer.addContentClasses = function(oRenderManager, oControl) { oRenderManager.addClass("sapUiCltCont"); }; /** * Add the arrow/tip CSS class to the Callout to redefine/extend CalloutBase * * @param {sap.ui.core.RenderManager} * oRenderManager the RenderManager that can be used for writing to * the Render-Output-Buffer * @param {sap.ui.core.Control} * oControl an object representation of the control that should be * rendered */ sap.ui.commons.CalloutRenderer.addArrowClasses = function(oRenderManager, oControl) { oRenderManager.addClass("sapUiCltArr"); };
Days = new Mongo.Collection('days'); if (Meteor.isClient) { Session.setDefault('rating', 0); Template.body.helpers({ rating: function () { return Session.get('rating'); }, checked: function (n) { return n === Session.get('rating') ? 'checked' : ''; }, anyChecked: function () { return Session.get('rating') !== 0 ? 'class="active"' : ''; }, days: function () { return Days.find({}, { sort: { date: -1 } }); }, averageRating: function () { return (this.points / this.ratingCount).toFixed(2); } }); Template.body.events({ 'submit #rating': function (e) { e.preventDefault(); document.getElementById('submit').disabled = true; document.getElementById('rating').className += ' disabled'; [].slice.call(e.target.getElementsByTagName('input')) .forEach(function (input, i) { input.disabled = true; if (input.checked) { var rating = parseInt(input.value, 10); Meteor.call('addRating', rating); [].slice.call(e.target.getElementsByTagName('label')) .forEach(function (label, j) { if (j <= i) { setTimeout(function () { label.className = 'spin'; }, j * 50); } }) } }); }, 'change #rating input[type="radio"]': function () { document.getElementById('rating').className = 'active'; document.getElementById('submit').disabled = false; } }) } Meteor.methods({ addRating: function (rating) { if (rating > 0 && rating <= 5) { var d = new Date(); var today = [d.getUTCFullYear(), zeropad(d.getUTCMonth() + 1, 2), zeropad(d.getUTCDate(), 2)].join('-'); Days.upsert( { date: today }, { $inc: { points: rating, ratingCount: 1 } } ); } } }); function zeropad(str, width) { str = str + ''; return str.length >= width ? str : new Array(width - str.length + 1).join('0') + str; }
import React from 'react'; import { shallow } from 'enzyme'; import SideMenu from './SideMenu'; it('should match the snapshot with all data passed in correctly', () => { const mockProps = { changeCity: jest.fn(), searchHistory: ['Denver', 'Phoenix'], fetchWeatherData: jest.fn(), toggleActiveState: jest.fn() } const menu = shallow(<SideMenu { ...mockProps } />); expect(menu).toMatchSnapshot(); });
var assert = require('assert'), bigml = require('../index'); try { describe('Manage whizzml library objects', function () { var libraryId, library = new bigml.Library(), sourceCode = '(define (mu x) (+ x 1))'; describe('#create(sourceCode, args, callback)', function () { it('should create a library from a excerpt of code', function (done) { library.create(sourceCode, undefined, function (error, data) { assert.equal(data.code, bigml.constants.HTTP_CREATED); libraryId = data.resource; done(); }); }); }); describe('#get(library, finished, query, callback)', function () { it('should retrieve a finished library', function (done) { library.get(libraryId, true, function (error, data) { if (data.object.status.code === bigml.constants.FINISHED) { assert.ok(true); done(); } }); }); }); describe('#update(library, args, callback)', function () { it('should update properties in the library', function (done) { var newName = 'my new name'; library.update(libraryId, {name: newName}, function (error, data) { assert.equal(data.code, bigml.constants.HTTP_ACCEPTED); library.get(libraryId, true, function (errorcb, datacb) { if (datacb.object.status.code === bigml.constants.FINISHED && datacb.object.name === newName) { assert.ok(true); done(); } }); }); }); }); describe('#delete(library, args, callback)', function () { it('should delete the remote library', function (done) { library.delete(libraryId, function (error, data) { assert.equal(error, null); done(); }); }); }); }); } catch(ex) {console.log(ex, ex.stack.split("\n"));}
// Chiedere all’utente il cognome // inserirlo in un array con altri cognomi: ‘Bianchi’, ‘Rossi’, ‘Duzioni’, ‘Balsano’, ‘Verdi’ // stampa la lista ordinata alfabeticamente // scrivi anche la posizione “umana” della lista in cui il nuovo utente si trova // Consigli del giorno: // 1. consultiamo la documentazione W3Schools o MDN per trovare i metodi javascript che possono esserci utili; // 2. anche perchè appunto parte dell’ex sarà cercare qualcosa.PS:: OCIO!!!! :octagonal_sign: // solo su questo EX usiamo while e non for (poi dal prox in poi farete come volete ) // INPUT BOTTONE var bottoneInvia = document.getElementById("invia"); // EVENTO BOTTONE bottoneInvia.addEventListener("click", function() { // ARRAY COGNOMI var cognomi = ["Bianchi", "Rossi", "Duzioni", "Blasano", "Verdi"]; // VAR RICHIESTA COGNOME var richiestaInput = document.getElementById("input"); // PUSH PER L'INPUT cognomi.push(richiestaInput.value); // ORDINE ALFABETICO cognomi.sort(); // OUTPUT var lista = ""; var i = 0; while (i < cognomi.length) { lista = lista + "<li>" + cognomi[i] + "</li>"; i++; } // VARIABILE LISTA document.getElementById("lista").innerHTML = lista; } );
import React, { useState, useEffect} from "react"; import Axios from "./Axios"; const App = () => { const [movie, setMovie] = useState([]); useEffect(() => { const getMovie = async () => { const { data } = await Axios.get("/films/1/"); setMovie(data) } getMovie() }, []); return ( <div> <h1> Title: {movie.title}</h1> <h2> Director: {movie.director}</h2> </div> ) } export default App;
var milestones = [ { "url": "https://api.github.com/repos/biorender/biorender/milestones/1", "html_url": "https://github.com/biorender/biorender/milestones/Mitochondrion%20Scene", "labels_url": "https://api.github.com/repos/biorender/biorender/milestones/1/labels", "id": 1563953, "number": 1, "title": "Mitochondrion Scene", "description": "", "creator": { "login": "thejmazz", "id": 1270998, "avatar_url": "https://avatars.githubusercontent.com/u/1270998?v=3", "gravatar_id": "", "url": "https://api.github.com/users/thejmazz", "html_url": "https://github.com/thejmazz", "followers_url": "https://api.github.com/users/thejmazz/followers", "following_url": "https://api.github.com/users/thejmazz/following{/other_user}", "gists_url": "https://api.github.com/users/thejmazz/gists{/gist_id}", "starred_url": "https://api.github.com/users/thejmazz/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/thejmazz/subscriptions", "organizations_url": "https://api.github.com/users/thejmazz/orgs", "repos_url": "https://api.github.com/users/thejmazz/repos", "events_url": "https://api.github.com/users/thejmazz/events{/privacy}", "received_events_url": "https://api.github.com/users/thejmazz/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 0, "state": "open", "created_at": "2016-02-04T18:14:57Z", "updated_at": "2016-02-09T05:32:44Z", "due_on": "2016-02-22T05:00:00Z", "closed_at": null }, { "url": "https://api.github.com/repos/biorender/biorender/milestones/4", "html_url": "https://github.com/biorender/biorender/milestones/Graphics/Modellng%20Backbone", "labels_url": "https://api.github.com/repos/biorender/biorender/milestones/4/labels", "id": 1571945, "number": 4, "title": "Graphics/Modellng Backbone", "description": "", "creator": { "login": "thejmazz", "id": 1270998, "avatar_url": "https://avatars.githubusercontent.com/u/1270998?v=3", "gravatar_id": "", "url": "https://api.github.com/users/thejmazz", "html_url": "https://github.com/thejmazz", "followers_url": "https://api.github.com/users/thejmazz/followers", "following_url": "https://api.github.com/users/thejmazz/following{/other_user}", "gists_url": "https://api.github.com/users/thejmazz/gists{/gist_id}", "starred_url": "https://api.github.com/users/thejmazz/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/thejmazz/subscriptions", "organizations_url": "https://api.github.com/users/thejmazz/orgs", "repos_url": "https://api.github.com/users/thejmazz/repos", "events_url": "https://api.github.com/users/thejmazz/events{/privacy}", "received_events_url": "https://api.github.com/users/thejmazz/received_events", "type": "User", "site_admin": false }, "open_issues": 7, "closed_issues": 0, "state": "open", "created_at": "2016-02-09T04:40:30Z", "updated_at": "2016-02-09T05:39:19Z", "due_on": "2016-03-15T04:00:00Z", "closed_at": null }, { "url": "https://api.github.com/repos/biorender/biorender/milestones/6", "html_url": "https://github.com/biorender/biorender/milestones/Basic%20Cell%20Scene", "labels_url": "https://api.github.com/repos/biorender/biorender/milestones/6/labels", "id": 1571948, "number": 6, "title": "Basic Cell Scene", "description": "", "creator": { "login": "thejmazz", "id": 1270998, "avatar_url": "https://avatars.githubusercontent.com/u/1270998?v=3", "gravatar_id": "", "url": "https://api.github.com/users/thejmazz", "html_url": "https://github.com/thejmazz", "followers_url": "https://api.github.com/users/thejmazz/followers", "following_url": "https://api.github.com/users/thejmazz/following{/other_user}", "gists_url": "https://api.github.com/users/thejmazz/gists{/gist_id}", "starred_url": "https://api.github.com/users/thejmazz/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/thejmazz/subscriptions", "organizations_url": "https://api.github.com/users/thejmazz/orgs", "repos_url": "https://api.github.com/users/thejmazz/repos", "events_url": "https://api.github.com/users/thejmazz/events{/privacy}", "received_events_url": "https://api.github.com/users/thejmazz/received_events", "type": "User", "site_admin": false }, "open_issues": 8, "closed_issues": 0, "state": "open", "created_at": "2016-02-09T04:41:41Z", "updated_at": "2016-02-09T05:40:23Z", "due_on": "2016-04-15T04:00:00Z", "closed_at": null }, { "url": "https://api.github.com/repos/biorender/biorender/milestones/2", "html_url": "https://github.com/biorender/biorender/milestones/Final", "labels_url": "https://api.github.com/repos/biorender/biorender/milestones/2/labels", "id": 1571930, "number": 2, "title": "Final", "description": "", "creator": { "login": "thejmazz", "id": 1270998, "avatar_url": "https://avatars.githubusercontent.com/u/1270998?v=3", "gravatar_id": "", "url": "https://api.github.com/users/thejmazz", "html_url": "https://github.com/thejmazz", "followers_url": "https://api.github.com/users/thejmazz/followers", "following_url": "https://api.github.com/users/thejmazz/following{/other_user}", "gists_url": "https://api.github.com/users/thejmazz/gists{/gist_id}", "starred_url": "https://api.github.com/users/thejmazz/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/thejmazz/subscriptions", "organizations_url": "https://api.github.com/users/thejmazz/orgs", "repos_url": "https://api.github.com/users/thejmazz/repos", "events_url": "https://api.github.com/users/thejmazz/events{/privacy}", "received_events_url": "https://api.github.com/users/thejmazz/received_events", "type": "User", "site_admin": false }, "open_issues": 2, "closed_issues": 0, "state": "open", "created_at": "2016-02-09T04:23:36Z", "updated_at": "2016-02-09T05:41:18Z", "due_on": "2016-04-29T04:00:00Z", "closed_at": null } ]; var status = "refreshing";
"use strict"; var createMailer = require("../lib/mailer").createMailer; module.exports["Remove BCC"] = function(test){ var mailer = createMailer(), input = "test: tere\r\n"+ "bcC: abc@tr.ee,\r\n"+ " cde@rrr.ee,\r\n"+ " sss@sss.ee\r\n"+ "subject:test\r\n"+ "\r\n"+ "hello!", expected = "test: tere\r\n"+ "subject:test\r\n"+ "\r\n"+ "hello!"; test.equal(mailer.removeBCC(input), expected); test.done(); } module.exports["Get envelope"] = function(test){ var mailer = createMailer(), input = { from: "andris@tr.ee", to: "kusti <kusti@ee.ee>, andris@tr.ee", bcc: ["juha@tr.ee, composer: andris@kreata.ee, juss: andris <andris@tr.ee>", "mesta@kesta.ee"] }, expected = { from: "andris@tr.ee", to: ["kusti@ee.ee", "andris@tr.ee", "juha@tr.ee", "andris@kreata.ee", "mesta@kesta.ee"] } test.deepEqual(mailer.getEnvelope(input), expected); test.done(); }
/* global fetch */ 'use strict' export const SET_FEATURED_GAMES = 'SET_FEATURED_GAMES' export const ADD_FEATURED_GAME = 'ADD_FEATURED_GAME' export const REMOVE_FEATURED_GAME = 'REMOVE_FEATURED_GAME' export const UPDATE_FEATURED_GAME = 'UPDATE_FEATURED_GAME' export const CREATE_BET = 'CREATE_BETCREATE_BET' // Regular actions export function setFeaturedGames (featuredGames) { return { type: SET_FEATURED_GAMES, featuredGames } } export function addFeaturedGame (featuredGame) { return { type: ADD_FEATURED_GAME, featuredGame } } export function removeFeaturedGame (gameId) { return { type: REMOVE_FEATURED_GAME, gameId } } export function updateFeaturedGame (game) { return { type: UPDATE_FEATURED_GAME, game } } export function createBet (gameId, teamId, amount) { return { type: CREATE_BET, gameId, teamId, amount } } // Thunk actions export function fetchFeaturedGames () { return (dispatch, state) => { fetch('/api/featured-games') .then((res) => { return res.json() }) .then((data) => { dispatch(setFeaturedGames(data)) }) .catch((err) => { console.log(err) }) } }
const accountService = require('../services/AccountsServices') const accountTokenService = require('../services/AccountsTokenService') const httpStatus = require('../constants/http-status-codes.json') const apiResponse = require('../helpers/apiResponse') const bcrypt = require('bcrypt'); const redis = require('../utility/redis'); // Login. exports.login = async function (req, res) { try { var user = await accountService.findByUsername(req.body.name); if(user) { let passwordValid = await bcrypt.compare(req.body.password, user.password); if (passwordValid) { var token = await accountTokenService.createToken(user); let response = { "user": user } response.user.token = token.token; // And store the user in Redis under key 2212 redis().sadd(['user'+response.user.id, response.user.token], function(err){ console.log(err) }); return apiResponse.responseFormat(res, true, "Login", {'user': response.user}, "", httpStatus.SUCCESS) } else { console.log('error') return apiResponse.responseFormat(res, false, "Password do not match", "", "Invalid credentials", httpStatus.UNAUTHORIZED) } } else { return apiResponse.responseFormat(res, false, "User not found", "", "User not found", httpStatus.NOT_FOUND) } } catch (e) { console.log(e) return apiResponse.responseFormat(res, false, "Users not found", "", { "errors": JSON.parse(e.message) }, httpStatus.INTERNAL_SERVER_ERROR) } }; // Login. exports.logout = async function (req, res) { try { if(req.headers.authorization) { let token = req.headers.authorization.split(" ")[1]; let tokenUser = await accountTokenService.getUserbyToken(token); if(tokenUser) { redis().exists('user'+tokenUser.user_id, function(err, reply) { if (reply === 1) { redis().srem('user'+tokenUser.user_id, token) } else { console.log('doesn\'t exist'); } }) await accountTokenService.updateToken(token); return apiResponse.responseFormat(res, true, "Logout Success", "", "", httpStatus.SUCCESS) } else { return apiResponse.responseFormat(res, false, "Invalid Token", "", "Invalid Token", httpStatus.NOT_FOUND) } } else { return apiResponse.responseFormat(res, false, "Token not found", "", "Token not found", httpStatus.NOT_FOUND) } } catch (e) { console.log(e) return apiResponse.responseFormat(res, false, "Users not found", "", { "errors": JSON.parse(e.message) }, httpStatus.INTERNAL_SERVER_ERROR) } };
// Static Snapshots (function() { var counter = 0; function process(win, topinfo, top_page, top_frame) { for (var i = 0; i < win.frames.length; i++) { var url = process(win.frames[i], topinfo, false, top_frame); win.frames[i].frameElement.setAttribute("data-src-target", url); } return addSnapshot(win, topinfo, top_page, top_frame); } function addSnapshot(win, topinfo, top_page, top_frame) { if (win.WB_wombat_location && win.WB_wombat_location.href) { url = win.WB_wombat_location.href; //url = url.replace(/^(https?:\/\/)/, '$1snapshot:') } else if (win.document.all.length <= 3) { url = "about:blank"; return url; } else { url = "http://embed.snapshot/" + counter; counter++; } var contents = new XMLSerializer().serializeToString(win.document); var params = {prefix: topinfo.prefix, url: url, top_url: topinfo.url, top_ts: topinfo.timestamp, title: win.document.title, } var data = {params: params, wb_type: "snapshot", top_page, top_page, contents: contents} top_frame.postMessage(data, "*"); return url; } function doSnapshot(event) { if (!event.data || event.source != window.__WB_top_frame) { return; } var message = event.data; if (message.wb_type == "snapshot-req") { process(window, window.wbinfo, true, window.__WB_top_frame); } } window.addEventListener("message", doSnapshot); }()); // Password Check (function() { var pass_form_targets = {}; function exclude_password_targets() { var passFields = document.querySelectorAll("input[type=password]"); for (var i = 0; i < passFields.length; i++) { var input = passFields[i]; if (input && input.form && input.form.action) { var form_action = input.form.action; if (window._wb_wombat) { form_action = window._wb_wombat.extract_orig(form_action); } if (!form_action) { return; } // Skip password check if checked within last 5 mins if (pass_form_targets[form_action] && ((Date.now() / 1000) - pass_form_targets[form_action]) < 300) { return; } var req = new XMLHttpRequest(); req._no_rewrite = true; req.addEventListener("load", function() { pass_form_targets[form_action] = Date.now() / 1000; }); var url = "/_skipreq?url=" + encodeURIComponent(form_action); req.open("GET", url); req.send(); } } } function startCheck() { if (!window.wbinfo.is_live) { return; } exclude_password_targets(); setInterval(exclude_password_targets, 4900); } window.addEventListener("DOMContentLoaded", startCheck); })(); // Autoscroll (function() { var sid = undefined; var scroll_timeout = 2000; var doneCallback = undefined; var lastScrolled = undefined; function scroll() { if (window.scrollY + window.innerHeight < Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)) { window.scrollBy(0, 200); lastScrolled = Date.now(); } else if (!lastScrolled || (Date.now() - lastScrolled) > scroll_timeout) { stop(); }; } function start(done, timeout) { doneCallback = done; lastScrolled = Date.now(); if (timeout) { scroll_timeout = timeout; } sid = setInterval(scroll, 100); } function stop(skipCallback) { if (sid == undefined) { return; } clearInterval(sid); sid = undefined; if (doneCallback && !skipCallback) { doneCallback(); } } function isDone() { return sid == undefined; } function setDoneCallback(donecb) { doneCallback = donecb; } function receiveEvent() { if (!event.data || event.source != window.__WB_top_frame) { return; } var message = event.data; if (!message.wb_type) { return; } function sendDone() { window.__WB_top_frame.postMessage({wb_type: "autoscroll", on: false}, "*"); } if (message.wb_type == "autoscroll") { if (message.start) { start(sendDone, message.timeout); } else { stop(message.skipCallback); } } } window.addEventListener("message", receiveEvent); return {"start": start, "stop": stop, "isDone": isDone, "setDoneCallback": setDoneCallback}; })();
import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import DetailsScreen from '../../screens/DetailsScreen'; import HomeScreen from '../../screens/HomeScreen'; const HomeStack = createStackNavigator(); function HomeStackScreen() { return ( <HomeStack.Navigator> <HomeStack.Screen name="Home" component={HomeScreen} /> <HomeStack.Screen name="Details" component={DetailsScreen} /> </HomeStack.Navigator> ); } export default HomeStackScreen;
export const GET_VEHICLE_SHIFTS = '/rovr-app/services/admin/dayShiftGroup?deliveryStartPointId='; export const GET_VEHICLES = '/rovr-app/services/admin/vehicle/deliveryStartPointExternalId/'; export const GET_DEPOT_DETAILS = '/rovr-app/services/admin/deliverystartpoint/'; export const GET_VEHICLE_SHIFT_DATA = '/rovr-app/services/admin/problem?deliveryStartPointId='; export const POST_VEHICLE_SHIFT = '/rovr-app/services/admin/dayShiftGroup/' ; export const DAY_SHIFT_GROUP = '/rovr-app/services/admin/dayShiftGroup/'; export const AD_HOC = 'rovr-app/services/admin/plannedvehicleshifts/dsp/'; // ANALYTICS export const START_DATE = '/rovr-app/services/csvdata/solutionMetric/download?startDate/'; export const RESERVATION_BOOK = '/rovr-app/services/customer/slot/reservation/book/'; export const SLOT_VIEW = '/rovr-app/services/customer/slot/view'; // CUSTOME CONTROL export const COST_GROUP = '/rovr-app/services/admin/costGroup/' // DEPOTDETAILPAGE export const HOLIDAY_RULE = '/rovr-app/services/admin/holidayRule/' export const HOLIDAY_CALENDAR = '/rovr-app/services/admin/holidayCalender/' // DEPOTPAGE export const DELIVERY_STARTPOINT_ID ='/rovr-app/services/admin/problem/groupByVehicle?deliveryStartPointId='; // DEPOTSTAT export const STORE_ID = '/rovr-app/services/admin/solutionop/solutionkpi?storeId='; // HOLIDAY export const DELIVERY_STARTPOINT = '/rovr-app/services/admin/deliverystartpoint/'; // HSC export const VAN_COUNT_DSP_ID = '/rovr-app/services/admin/hscvehicleshiftrules/retrieveVanCount?dspId='; export const SHIFT_TYPE = '/rovr-app/services/admin/shifttype/'; export const VEHICLE_TYPE = '/rovr-app/services/admin/vehicletype/'; export const DSP_DATE_UI_ID = '/rovr-app/services/admin/hscvehicleshiftrules/retrieveByDspDateUI?dspId='; export const SHIFT_RULE = '/rovr-app/services/admin/hscvehicleshiftrules/'; // SHFT export const SHIFT_EVENT = '/rovr-app/services/admin/shiftEvent/'; // STORE GROOUP export const SHIFT_GROUP = '/rovr-app/services/admin/shiftGroup/'; export const SHIFT_EVENT_RULE = '/rovr-app/services/admin/shiftEventRule/'; // HUB WAVE export const HUB_WAVE_GET_BY_DSP = '/rovr-app/services/admin/hubDepOverRide/dspId/'; export const HUB_WAVE = '/rovr-app/services/admin/hubDepOverRide/';
import React from 'react' import App, { Container } from 'next/app' import BaseLayout from '../components/layout/BaseLayout' import Loading from '../components/Loading' import ToastPopup from '../components/ToastPopup' // import '../styles/main.scss' import '../styles/reset.css' import '../styles/index.css' import Footer from '../components/shared/Footer' import { MenuContextProvider } from '../context/menuContext' import { WindowContextProvider } from '../context/windowContext' import { ToastProvider } from '../context/toastContext' import { clientAuth, serverAuth } from '../helpers/auth' // import '../styles/common.css' import Cookies from 'js-cookie' import { UserProvider } from '../context/userContext' // import 'react-toastify/dist/ReactToastify.css' class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {} let isLoaded = false // 모든 페이지를 이동 할 떄 경유 // 여기서 권한 체크를 // 서버쪽이랑 클라이언트 쪽을 별개로 처리 // process.browser로 클라이언트인지 서버쪽인지 확인 let user = process.browser ? clientAuth() : serverAuth(ctx.req) if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) } return { pageProps, isLoaded, user } } componentDidMount() { setTimeout(() => { this.setState({ show: false }) }, 3000) } _ renderWindowIfLoaded = () => { const { Component, pageProps, isLoaded, user } = this.props return isLoaded ? ( <Loading /> ) : ( <BaseLayout> <UserProvider> <ToastProvider> <WindowContextProvider> <MenuContextProvider> <Component {...pageProps} user={user} /> <Footer /> <ToastPopup /> </MenuContextProvider> </WindowContextProvider> </ToastProvider> </UserProvider> </BaseLayout> ) } render() { const { Component, pageProps, isLoaded } = this.props return <Container>{this.renderWindowIfLoaded()}</Container> } } export default MyApp
import React from 'react'; import { Text, View } from 'react-native'; import ButtonAccount from '../components/button'; import styles from './styles'; import { useTranslation } from 'react-i18next'; export default function SupportScreen(props) { const { t } = useTranslation(); const { navigate } = props.navigation; return ( <View> <ButtonAccount title={t('support.frequently_asked_questions')} onPress={() => navigate('askedquestions')} /> <ButtonAccount title={t('support.buying_guide')} onPress={() => navigate('askedquestions')} /> <ButtonAccount title={t('support.forms')} onPress={() => navigate('askedquestions')} /> <ButtonAccount title={t('support.online_sales_policy')} onPress={() => navigate('askedquestions')} /> <ButtonAccount title={t('support.anhdevs_online')} onPress={() => navigate('askedquestions')} /> <ButtonAccount title={t('support.contact')} onPress={() => navigate('askedquestions')} /> <ButtonAccount title={t('support.terms_of_use')} onPress={() => navigate('askedquestions')} /> <ButtonAccount title={t('support.chat_online')} onPress={() => navigate('askedquestions')} /> <View style={styles.box_version}> <View style={styles.version}> <Text style={styles.txt}>{t('support.version')}</Text> <Text style={styles.txt}>{'1.0.0'}</Text> </View> </View> </View> ); }
const chai = require('chai'); const should = chai.should(); const expect = chai.expect; const chaiHttp = require('chai-http'); const app = require('../../express_server.js'); const indexController = require('../../controllers/indexController'); const index = require('../../routes/index'); const db = require('../../server/urlDB'); const users = require('../../server/userDB'); describe('/---Index Integration test with session active---/', () => { it('should return the home page with a cookie', () => { indexController.testVar = 'hi'; return chai.request(app) .get('/') .then((response) => { const string = response.text; const matchReg = string.match(/<p>([\s\S]*)?<\/p>/i)||[]; const out = matchReg[1] || ''; expect(out).to.be.length(6); expect(out).to.be.a('string'); response.should.have.status(200); response.should.be.html; delete indexController.testVar; }) .catch((error) => { throw error; }); }); }); describe('---Index Integration test with no session', () => { it('should return the home page with no cookie', () => { return chai.request(app) .get('/') .then((response) => { const string = response.text; const matchReg = string.match(/<p>([\s\S]*)?<\/p>/i)||[]; const out = matchReg[1] || ''; expect(out).to.not.be.length(6); response.should.have.status(200); response.should.be.html; }) .catch((error) => { throw error; }); }); });
randKey = function(len){ if(typeof(len) != 'number'){ len = 5; } len = Math.max(0, len); return Math.random().toString().substring(5, 5 + len); }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsFolderShared = { name: 'folder_shared', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-5 3c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm4 8h-8v-1c0-1.33 2.67-2 4-2s4 .67 4 2v1z"/></svg>` };
module.exports = (sequelize, type) => sequelize.define('Reservation', { date: type.STRING, });
export const CATEGORIES = [ { id: 1, name: 'Buy Sport Shoes', desc: 'Get latest PS4/XBOX/PC Games at the lowest prices and more', img: 'assests/images/shoes/responsive/hypervenomWallpaper0.jpg', type: 'sport' }, { id: 2, name: 'Buy Sneakers', desc: 'Get updated with the latest gaming events around the world', img: 'assests/images/shoes/responsive/shoes0.jpg', type: 'casual' }, { id: 3, name: 'Buy Boots Shoes', desc: 'Buy or Sell new or used controllers anywhere around India', img: 'assests/images/shoes/boots.jpg', type: 'boots' }, { id: 4, name: 'Buy Formal Shoes', desc: 'Get latest accessories for your consoles and up your gaming experience', img: 'assests/images/shoes/formals.jpg', type: 'formals' } ]
"use strict"; var request = require('request'); var baseUrl = require('../../common').baseUrl; exports.create = function (callback) { request.post({ url: baseUrl + '/customers', form: {url: 'uuchat.com', email:'test@gmail.com'} }, function (err, res) { callback(res); }); }; exports.delete = function (cid, callback) { request.delete({ url: baseUrl + '/customers/' + cid }, function (err, res) { callback(); }); };
class Buttons{ constructor(x, y, w, h, msg, r, g, b){ this.loc = createVector(x, y); this.w = w; this.h = h; this.r = r; this.g = g; this.b = b; this.message = msg; } run(){ this.render(); } render(){ fill(this.r, this.g, this.b); rect(this.loc.x, this.loc.y, this.w, this.h, this.message, this.clr) } }
// 1. Use q-oi/http to send GET request to port 7000 // a. will return a string that represents a user ID // 2. Send a GET request to port 7001/${user-id} // 3. console.log the resulting object let QHTTP = require('q-io/http'); let options = { url: 'http://localhost:7000', method: 'GET', } let user_id; QHTTP.request(options) .then(data => { data.body.read(second) .then(data => { second(data.toString()); }) .catch(onRejected) }) .then(console.log) .catch(onRejected); function second(id) { return new Promise((resolve, reject) => { let options = { url: 'http://localhost:7001', method: 'GET', pathInfo: id } QHTTP.request(options) .then(console.log(options)) .then(data => { resolve(data); }) .catch(reject(onRejected)); }) } function onRejected(e) { console.log(e.message) }
import React from "react"; import { Image, View } from "react-native"; import { styles } from "./styles"; import { TouchableHighlight } from "react-native-gesture-handler"; export default function BottomNavigation({ navigation }) { return ( <View style={styles.bottomNavigationContainer}> <TouchableHighlight onPress={() => navigation.navigate("Home")}> <Image style={styles.bn1} source={require("./home.png")} /> </TouchableHighlight> <TouchableHighlight onPress={() => navigation.navigate("Start")}> <Image style={styles.bn2} source={require("./schedule.png")} /> </TouchableHighlight> <TouchableHighlight> <Image style={styles.bn3} source={require("./information.png")} /> </TouchableHighlight> <TouchableHighlight onPress={() => navigation.navigate("Start")}> <Image style={styles.bn4} source={require("./user.png")} /> </TouchableHighlight> </View> ); }
import { combineReducers } from 'redux'; import paramsReducer from './params'; import dataReducer from './data'; import plotReducer from './plot'; import hyperReducer from "./hyper"; import stepReducer from "./step"; const appReducer = combineReducers({ params: paramsReducer, data: dataReducer, plot: plotReducer, hyper: hyperReducer, step: stepReducer }); export default appReducer
/*global ODSA */ // Written by Jun Yang and Cliff Shaffer // Elements of the queue are stored in the first n positions of the array $(document).ready(function() { "use strict"; var av_name = "aqueueFirstCON"; // 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 = new JSAV(av_name); // Relative offsets var leftMargin = 300; var topMargin = 0; // Create the graphics for front and rear boxes var arrFront = av.ds.array([""], {indexed: false, left: 200, top: topMargin}); av.label("front", {left: 163, top: topMargin + 4}); var arrRear = av.ds.array([""], {indexed: false, left: 200, top: topMargin + 35}); av.label("rear", {left: 168, top: topMargin + 39}); av.ds.array([4], {indexed: false, left: 200, top: topMargin + 70}); av.label("listSize", {left: 147, top: topMargin + 74}); var arr = av.ds.array([12, 45, 5, 81, "", "", "", ""], {indexed: true, top: topMargin, left: leftMargin}); arr.addClass([4, 5, 6, 7], "unused"); // Slide 1 av.umsg(interpret("sc1")); av.displayInit(); // Slide 2 av.umsg(interpret("sc2")); arrFront.value(0, 3); arrFront.addClass([0], "special"); arr.addClass([3], "special"); arrRear.value(0, 0); arrRear.addClass([0], "processing"); arr.addClass([0], "processing"); av.step(); // Slide 3 av.umsg(interpret("sc3")); av.step(); // Slide 4 av.umsg(interpret("sc4")); arrFront.value(0, 0); arr.removeClass([3], "special"); arr.addClass([3], "processing"); arrRear.value(0, 3); arr.removeClass([0], "processing"); arr.addClass([0], "special"); av.step(); // Slide 5 av.umsg(interpret("sc5")); av.recorded(); });
'use strict'; var _ = require('lodash'); var __ = require('hamjest'); var express = require('express'); var LIBNAME = require('./library-name.js'); var Library = require('fastcall').Library; var path = require('path'); describe('CTAPI status', () => { var CT_init; var library; var params; var server; var statusCode; beforeEach(() => { var location = path.join(__dirname, '../target/debug/', LIBNAME); library = new Library(location).asyncFunction({ CT_init: ['int8', ['uint16', 'uint16']]}); CT_init = library.interface.CT_init; var app = express(); app.post('/k2/ctapi/ct_init/:ctn/:pn', (request, response) => { response.send(statusCode); }); server = app.listen(8080); }); afterEach(() => { library.release(); library = null; server.close(); }); _.forEach([0, -1, -8, -10, -11, -127, -128], value => { it(`should return ${value} when the servers response contains ${value}`, done => { statusCode = value.toString(); CT_init(1, 1).then(response => { __.assertThat(response, __.is(value)); done(); }); }); }); it('should return -128 when the servers response is not a valid CTAPI status code', done => { statusCode = '1'; CT_init(1, 1).then(response => { __.assertThat(response, __.is(-128)); done(); }); }); });
var countdownDate = new Date("May 30, 2021 00:00:00").getTime(); var countdownFunc = window.setInterval(function ( ){ var now = new Date().getTime(); var distance = countdownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / (1000)); window.document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; if (distance < 0) { window.clearInterval(countdownFunc); window.document.getElementById("demo").innerHTML = "EXPIRED"; } },1000); //countdownFunc
// z7RPLbJykv68026AD6lRTzuLiLERSaOX - API key for giphy usage // create buttons that display at top of screen // each button has a different search parameter // clicking on buttons pulls up, up to 10 images // clicking on an image will switch it to an animated gif // each image will display rating either below or above itself // include a search in column next to the display images/gifs // when search is processed button is added to top amongst all other buttons let gifTopic = []; let topButtons = $('#topic-buttons'); let giphyDisplay = $('#giphy-display'); let giphySearch = $('#giphy-search'); let submit = $('#submit'); let searchTerm; let gifStill; $('#topic-buttons').text('Input a topic to try the gif maker!') // Button Generator submit.on('click', function () { event.preventDefault(); topButtons.empty(); if ($('#new-giphy-search').val() === '') { return; } else { searchTerm = $('#new-giphy-search').val().trim(); gifTopic.push(searchTerm) for (x = 0; x < gifTopic.length; x++) { $('#new-giphy-search').val(""); let button = $('<button>'); button.addClass('p-3 m-2 bd-highlight align-content-start flex-wrap btn btn-outline-light') button.attr('id', 'giphy-find') button.attr('data-gif', gifTopic[x]) button.on('click', giphyHunter) button.text(gifTopic[x]) topButtons.append(button) } } }); // Giphy Search using the buttons on click function handed them function giphyHunter() { let search = $(this).attr('data-gif'); console.log(search); let queryURL = "https://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=z7RPLbJykv68026AD6lRTzuLiLERSaOX&limit=10"; $.ajax({ url: queryURL, method: "GET" }).then(function (response) { console.log(response) var results = response.data; $("#giphy-display").empty(); for (var i = 0; i < results.length; i++) { var gifDiv = $("<div>"); var rating = results[i].rating; var p = $("<p>").text("Rating: " + rating); gifStill = $("<img>"); gifStill.attr("src", results[i].images.fixed_height_still.url); gifStill.attr('data-still', results[i].images.fixed_height_still.url) gifStill.attr('data-animate', results[i].images.original.url); gifStill.attr('data-state', 'still'); gifStill.addClass('rounded') gifStill.on('click', gifPlay) gifDiv.prepend(p); gifDiv.prepend(gifStill); $("#giphy-display").prepend(gifDiv); } }) } function gifPlay() { let gifAnimate = $(this).attr('data-animate') let gifPause = $(this).attr('data-still') console.log(this) let state = $(this).attr("data-state") if (state === 'still') { $(this).attr("src", gifAnimate); $(this).attr("data-state", 'animate') } else { $(this).attr("src", gifPause); $(this).attr("data-state", 'still') } }
/** * * @authors Your Name (you@example.org) * @date 2018-07-28 14:56:52 * @version $Id$ */ /*认证? 好像是做登录这一块的流程的*/ import React from 'react'; import { BrowserRouter as Router, Route, NavLink, Redirect, withRouter } from 'react-router-dom'; const RouterPage3 = () => { return ( <Router> <div> <AuthButton/> <ul> <li> <NavLink to="/public">Public</NavLink> </li> <li> <NavLink to="/protected">Protected</NavLink> </li> </ul> <Route path="/public" component = {Public}></Route> <Route path="/login" component={Login}></Route> <PrivateRoute path="/protected" component={Protected} /> </div> </Router> ) } /*withRouter 用来监听路由更新*/ const AuthButton = withRouter(({history}) => { return ( fakeAuth.isAuthenticated ? ( <p>Welcome! <button onClick = { ()=>{ console.log(history); fakeAuth.signout(()=>{ history.push('/') }) } }>Sign out</button></p> ):( <p>You are not logged in</p> ) ) }) /*PrivateRoute是一个自定义组件 props传入组件 和{...rest}其它参数*/ const PrivateRoute = ({component:Component,...rest}) =>{ return ( /*返回一个路由,render() 实现对应的组件*/ <Route {...rest} render={(props)=>{return ( fakeAuth.isAuthenticated ? ( <Component {...props}/> ):( <Redirect to = {{ pathname:'/login', state:{from:props.location}/*state数据,跳转login前的地址location*/ }}/> ) )}}/> ) } class Login extends React.Component { constructor(props){ super(props); this.state = { redirectToReferrer:false } } login = ()=>{ const _t = this; fakeAuth.authenticate( ()=> { _t.setState({redirectToReferrer:true}) } ) } render(){ console.log(this.props.location) const _t = this; const { from } = this.props.location.state || { from: {pathname:'/'}}; const {redirectToReferrer} = this.state; if(redirectToReferrer){ return <Redirect to={from}/> } return ( <div> <p>You must log in to view the page at {from.pathname}</p> <button onClick = {_t.login}>Log in</button> </div> ) } } const fakeAuth = { isAuthenticated:false, authenticate(cb){ this.isAuthenticated = true; setTimeout(cb,100); }, signout(cb){ this.isAuthenticated = false; setTimeout(cb,100); } } const Protected = ()=>{ return (<h3>Protected</h3>) } const Public = ()=>{ return (<div>Public</div>) } export default RouterPage3;
import React, { Component } from "react"; // what is the difference between props and state? // prop includes data that we feed to the component // state includes data that is local or private to that component so that other components can't access that state // props are read only export default class Counter extends Component { // state obj comprises any data the Component might need // this state code is executed once, when the component is created // delete state during conversion to CONTROLLED PROPERTY // state = { // value: this.props.counter.value // }; // handleIncrement = () => { // // this.props.value = 0; NOPE! The prop is read only - this is where we use our setState because the property has a state, as does the component // this.setState({ // value: this.state.value + 1 // }); // }; // these are the properties we set on our components, excluding key // {this.props.children} can be used to access children for a component // console.log("props", this.props); render() { return ( <div> <span className={this.getBadgeClasses()}>{this.formatCount()}</span> <button onClick={() => this.props.onIncrement(this.props.counter)} className="btn btn-secondary btn-sm" > Increment </button> <button onClick={() => this.props.onDelete(this.props.counter.id)} className="btn btn-danger btn-sm m-2" > Delete </button> </div> ); } formatCount() { const { value: count } = this.props.counter; return count === 0 ? "Zero" : count; } getBadgeClasses() { let classes = "badge m-2 badge-"; return (classes += this.props.counter.value === 0 ? "warning" : "primary"); } // export default Counter; }
export reactDefault from './react.default'; export reactFunction from './react.function';
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _builtins = require('./builtins.json'); var _builtins2 = _interopRequireDefault(_builtins); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { tokenPostfix: '.mac', defaultToken: '', keywords: ['if', 'then', 'else', 'elseif', 'for', 'thru', 'do', 'while', 'until', 'step', 'in', 'and', 'or', 'not'], constants: ['true', 'false'], operators: ['=', '::', ':', '::=', ':=', '!!', '!', '^', '.', '*', '/', '+', '-', '>=', '<=', '>', '<', '%', '$'], builtins: _builtins2.default, escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, symbols: /[\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%|#]+/, identifiers: /\b[a-zA-Z][a-zA-Z0-9_]*/, brackets: [{ open: '{', close: '}', token: 'delimiter.curly' }, { open: '[', close: ']', token: 'delimiter.bracket' }, { open: '(', close: ')', token: 'delimiter.parenthesis' }], tokenizer: { root: [ // Variables [/\b([A-Za-z]+[A-Za-z0-9_]*)(?=:)/, 'variable'], [/\b([A-Za-z]+[A-Za-z0-9_]*)(?=\[.*\]:)/, 'variable'], // Identifiers [/@identifiers/, { cases: { "@builtins": "support.function.builtin", '@keywords': 'keyword', '@constants': 'keyword', '@default': 'identifier' } }], // Whitespace + comments { include: '@whitespace' }, // Strings [/"([^"\\]|\\.)*$/, 'invalid'], // non-teminated double quote [/"/, { token: 'string.delim', bracket: '@open', next: '@string.$0' }], // Numbers { include: '@numbers' }, // Brackets & delimiters [/[{}()\[\]]/, '@brackets'], [/[,;$]/, 'delimiter'], // Symbols & operators [/@symbols/, { cases: { '@operators': 'operator', '@default': '' } }]], whitespace: [[/[ \t\r\n]+/, 'white'], [/\/\*/, 'comment', '@comment'], [/\/\/.*$/, 'comment']], comment: [[/[^\/*]+/, 'comment'], [/\/\*/, 'comment', '@push'], ['\\*/', 'comment', '@pop'], [/[\/*]/, 'comment']], string: [[/[^\\"]+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/"/, 'string', '@pop']], numbers: [ // Integer [/-?\d+(?:(b|e)-?\d)?/, 'number'], // Float including bfloat and exponents [/-?\d*\.+\d+(?:(b|e)-?\d)?/, 'number']] } };
var mapContainer = document.getElementById('map'), // 지도를 표시할 div mapOption = { center: new kakao.maps.LatLng(37.520601,126.84039), // 지도의 중심좌표 level: 5 // 지도의 확대 레벨 }; var map = new kakao.maps.Map(mapContainer, mapOption); // 지도를 생성합니다 // 일반 지도와 스카이뷰로 지도 타입을 전환할 수 있는 지도타입 컨트롤을 생성합니다 var mapTypeControl = new kakao.maps.MapTypeControl(); // 지도에 컨트롤을 추가해야 지도위에 표시됩니다 // kakao.maps.ControlPosition은 컨트롤이 표시될 위치를 정의하는데 TOPRIGHT는 오른쪽 위를 의미합니다 map.addControl(mapTypeControl, kakao.maps.ControlPosition.TOPRIGHT); // 지도 확대 축소를 제어할 수 있는 줌 컨트롤을 생성합니다 var zoomControl = new kakao.maps.ZoomControl(); map.addControl(zoomControl, kakao.maps.ControlPosition.RIGHT);
var header = require('../header.js'); /* ============================================ ; Title: Program Header ; Author: Professor Krasso ; Date: 19 January 2018 ; Modified By: Heather Peterson ; Description: Assignment 6.4 - Nested Object Literals ;=========================================== /* /* Expected output: FirstName LastName Assignment 6.4 Today's Date Ticket <id> was created on <dateCreated> and assigned to employee <firstName lastName> (<jobTitle>). */ // start program var ticket = { // ticket properties id: 01, name: "Timmy Simmons", dateCreated: "1/19/2018", priority: "High", personId: "1313", person: { // person properties id: 01, firstName: "Timmy", lastName: "Simmons", jobTitle: "(Manager)." } }; console.log("Ticket " + ticket["id"] + " was created on " + ticket["dateCreated"] + " and assigned to employee " + ticket.person["firstName"] + " " + ticket.person["lastName"] + " " + ticket.person["jobTitle"]); //outputs the nested object literals // end program //Ouput: //Heather Peterson //Assignment 6.4 //Date: 01-19-2018 //Ticket 1 was created on 1/19/2018 and assigned to employee Timmy Simmons (Manager).
const bcrypt = require('bcryptjs') const jwt = require('jsonwebtoken') const {APP_SECRET, getUserId} = require('../utils') async function signup(parent, args, context, info) { const password = await bcrypt.hash(args.password, 10) const user = await context.prisma.createUser({...args, password}) const token = jwt.sign({userId: user.id}, APP_SECRET) return { token, user } } async function login(parent, args, context, info) { const user = await context.prisma.user({email: args.email}) if(!user){ throw new Error('No such user found') } const valid = bcrypt.compare(args.password, user.password) if(!valid){ throw new Error('Password Invalid') } const token = jwt.sign({userId: user.id}, APP_SECRET) return { token, user } } function post(parent, {url, description}, context, info) { const userId = getUserId(context) return context.prisma.createLink({ url, description, postedBy: {connect: {id: userId}} }) } async function vote(parent, {linkId}, context, info){ const userId = getUserId(context) const voteExists = await context.prisma.$exists.vote({ user: {id: userId}, link: {id: linkId} }) if(voteExists){ throw new Error(`Already voted for link: ${linkId}`) } return context.prisma.createVote({ link: {connect: {id: linkId}}, user: {connect: {id: userId}} }) } module.exports = { post, vote, signup, login, }
((app => { class FryService { constructor() { this.frysQ = fryQuotes; } getRandomFryQuote() { const randomFryIndex = Math.floor(Math.random() * this.frysQ.length); return this.frysQ[randomFryIndex]; } generateFryQuote(delay, callback) { callback(this.getRandomFryQuote()); setInterval(() => callback(this.getRandomFryQuote()), delay); } } app.FryService = FryService; var fryQuotes = [{ "source": "Fry", "line": "I wish! It\"s a nickel." }, { "source": "Fry", "line": "Tell her she looks thin." }, { "source": "Fry", "line": "Negative, bossy meat creature!" }, { "source": "Fry", "line": "Yeah. Give a little credit to our public schools." }, { "source": "Fry", "line": "I found what I need. And it\"s not friends, it\"s things." }, { "source": "Fry", "line": "Leela, are you alright? You got wanged on the head." }, { "source": "Fry", "line": "That could be \"my\" beautiful soul sitting naked on a couch. If I could just learn to play this stupid thing." }, { "source": "Fry", "line": "But existing is basically all I do!" }, { "source": "Fry", "line": "You\"re going back for the Countess, aren\"t you?" }, { "source": "Fry", "line": "Wow! A superpowers drug you can just rub onto your skin? You\"d think it would be something you\"d have to freebase." }, { "source": "Fry", "line": "I found what I need. And it\"s not friends, it\"s things." } ]; }))(window.app || (window.app = {}));
$(function() { // Search function if ( $( '.search-field' ).length ) $('.search-field').focus().simpleJekyllSearch(); // To top function $().UItoTop({ easingType: 'easeOutQuart' }); // Link active class on menu var perm = $('#pagepermalink').attr('href'); var listItems = $("header nav a"); listItems.each( function (index,e) { var url = $(e).attr('href'); var text = $(e).text(); if ( url == perm ) { $(e).addClass('active'); $(e).html( text ); } }); // Get md5 for Post (image filename) if ($('body').hasClass('post')){ var string = $('section > header > h1').html() + $('section > header h3').html(); var hash = md5(string); console.log(string,hash); } // Image zoom on Posts // $('body.post article > figure > img').click(function(e){ // // var ele = $(e.target); // // ele.toggleClass('mega'); // $('#zoom').attr("open", ""); // }); // $('#zoom').click(function(e){ // $(e.delegateTarget).removeAttr('open'); // }) // MODAL // Get the modal var modal = document.getElementById("myModal"); var modal_window = document.querySelector(".modal-content"); // Get the button that opens the modal var btn = document.getElementById("myBtn"); // Get the <span> element that closes the modal // var span = document.getElementsByClassName("close")[0]; // When the user clicks the button, open the modal if (btn){ btn.onclick = function(e) { e.preventDefault(); modal.style.display = "block"; } } // When the user clicks on <span> (x), close the modal // span.onclick = function() { // modal.style.display = "none"; // } // When the user clicks anywhere outside of the modal, close it if (modal_window) { window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } modal_window.onclick = function(event) { modal.style.display = "none"; } } });
'use strict'; angular .module('questionnaire1description') .component('questionnaire1description', { templateUrl: 'pages/questionnaire1description/questionnaire1description.template.html' });
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, { Fragment, Component } from "react"; import { SafeAreaView, StyleSheet, ScrollView, FlatList, View, Text, Image, StatusBar } from "react-native"; import { Button, Card, Icon, ListItem } from "react-native-elements"; import { connect } from "react-redux"; import { getPlaylistList } from "../redux/actions/playerActions"; class ViewPlaylistsScreen extends Component { static navigationOptions = { header: null }; render() { keyExtractor = (item, index) => { return index.toString(); }; renderItem = ({ item, index }) => { let subtitle = ""; if (item.hasOwnProperty("tracks")) { item.tracks.forEach( (track, index) => (subtitle += track.title + (index < item.tracks.length - 1 ? ", " : "")) ); } return ( <ListItem title={item.title} subtitle={<Text numberOfLines={1}>{subtitle}</Text>} leftAvatar={{ source: require("../images/ariana-grande.jpg") }} onPress={() => this.props.navigation.navigate("PlaylistDetails", { playlist: item }) } /> ); }; return ( <Fragment> <Button title="reload playlists" type="clear" onPress={() => this.props.getPlaylistList()} /> <FlatList keyExtractor={keyExtractor} data={this.props.playlists} renderItem={renderItem} /> </Fragment> ); } } //Map the redux state to your props. const mapStateToProps = state => ({ playlists: state.player.playlists, playlistsLoading: state.player.playlistsLoading, errorMessage: state.player.errorMessage }); //Map your action creators to your props. const mapDispatchToProps = dispatch => ({ getPlaylistList: () => dispatch(getPlaylistList()) }); export default connect( mapStateToProps, mapDispatchToProps )(ViewPlaylistsScreen);
import React from "react"; import "./loading.scss"; const Loader = () => { return ( <div className="loader"> <span className="loader-inner-1"></span> <span className="loader-inner-2"></span> <span className="loader-inner-3"></span> </div> ); }; export default Loader;
import Ember from 'ember'; import config from './config/environment'; const Router = Ember.Router.extend({ location: config.locationType, rootURL: config.rootURL }); Router.map(function() { this.route('about'); this.route('contacts', function() { this.route('new'); this.route('show', { path: '/:id' }); this.route('edit', { path: '/:id/edit' }); }); this.route('members-area'); this.route('donnees-personnelles'); this.route('demos'); this.route('live'); this.route('mind'); this.route('getAttitude'); this.route('getAttitudeResults', {path: '/getAttitudeResults/:text'}); this.route('getTweetsSent'); this.route('getSent'); this.route('getWordCount'); this.route('getWordCountResults', {path: '/getWordCountResults/:url'}); this.route('watsonConcept'); this.route('getwatsonConceptResults', {path: '/getwatsonConceptResults/:url'}); this.route('getTweets'); this.route('getTweetsResult', {path: '/getTweetsResult/:keyword'}); this.route('getTweetsSentResult', {path: '/getTweetsSentResult/:clavier'}); this.route('getSentResults', {path: '/getSentResults/:sent'}); this.route('word-count-po-f.js'); this.route('getwatson-concept-results'); this.route('scrapyresults', {path: '/scrapyresults/:scrapy'}); this.route('kontact'); this.route('home'); this.route('about-founders'); this.route('jobs'); this.route('google'); this.route('francais'); this.route('anglais'); this.route('signup'); this.route('webinars'); this.route('advertisefromthesky'); this.route('ip-gps'); this.route('ipgps'); this.route('getip-gps-results', {path: '/getip-gps-results/:url'}); }); export default Router;
require('./app.js'); require('./site/escalas/escalas.js'); //require('./site/escalas/jquery.timesheet.js'); alert('hey');
const mongoose = require("mongoose"); const mongoosePaginate = require('mongoose-paginate-v2'); let productModel = new mongoose.Schema({ product_name:{ type:String, required:true }, category_id: { type:mongoose.Schema.Types.ObjectId, ref:'category' }, status:{ type:Number, default:1 }, added_date:{ type: Date, default: Date.now } }); productModel.plugin(mongoosePaginate); module.exports = mongoose.model('product',productModel);
// // ClearBox Language File (JavaScript) // var CB_NavTextPrv='anterior', // text of previous image CB_NavTextNxt='próximo', // text of next image CB_NavTextFull='tela cheia', // text of original size (only at pictures) CB_NavTextOpen='abrir em nova aba', // text of open in a new browser window CB_NavTextDL='download', // text of download picture or any other content CB_NavTextClose='fechar', // text of close CB CB_NavTextStart='iniciar slideshow', // text of start slideshow CB_NavTextStop='parar slideshow', // text of stop slideshow CB_NavTextRotR='girar para a direita', // text of rotation right CB_NavTextRotL='girar para a esquerda', // text of rotation left CB_NavTextReady='pronto' // text of clearbox ready ;
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Das Verändern, Kopieren, Benutzen des Codes ist nur mit ausdrücklicher // Genehmigung gestattet. // // ================================================================================ function MneIframeEditorXml(editor, param) { editor.xml_save = function(iv, parent) { var i,j; var tag; var str; var endtag; var v = iv; for ( i=0; i<parent.childNodes.length; i++ ) { tag = parent.childNodes[i]; endtag = ""; switch(tag.tagName) { case "SPAN": str = "<text"; if ( tag.className.indexOf("mne_bold") >= 0 ) str += ' weight="bold"'; if ( tag.className.indexOf("mne_italic") >=0 ) str += ' style="italic"'; if ( tag.className.indexOf("mne_font") >= 0 ) str = str + ' size="' + tag.className.match(/mne_font[^ ]*/).toString().substr(8) + '"'; else str += ' size="n"'; str += ">"; var t = this.getRawTextContent(tag); t = t.replace(/>/g, "&gt;"); t = t.replace(/</g, "&lt;"); v = v + str + t + "</text>"; break; case "DIV": str = "<part"; if ( tag.className.indexOf("mne_alignc") >= 0 ) str += ' align="center"'; if ( tag.className.indexOf("mne_alignr") >= 0 ) str += ' align="right"'; if ( tag.className.indexOf("mne_alignl") >= 0 ) str += ' align="left"'; str += ">"; v = v + str; endtag = "</part>"; break; case "UL": v = v + "<itemize>"; endtag = "</itemize>"; break; case "OL": v = v + "<enumerate>"; endtag = "</enumerate>"; break; case "LI": v = v + "<item>"; endtag = "</item>"; break; case "TABLE": str = "<table"; if ( tag.className.indexOf("mne_borderno") >= 0 ) str += ' border="0"'; else str += ' border="1"'; if ( tag.className.indexOf("mne_padding") >= 0 ) str += ' padding="1"'; else str += ' padding="0"'; if ( tag.className.indexOf("mne_alignc") >= 0 ) str += ' align="center"'; if ( tag.className.indexOf("mne_alignr") >= 0 ) str += ' align="right"'; if ( tag.className.indexOf("mne_alignl") >= 0 ) str += ' align="left"'; str += ">"; v = v + str; endtag = "</table>"; break; case "TR": v = v + "<tr>"; endtag = "</tr>"; break; case "TD": { var w; str = "<td"; w = tag.style.width; if ( typeof w == 'undefined' || parseInt(w) == 0 || parseInt(w).toString() == "NaN") { var j; for ( j=0; j<tag.childNodes.length; j++) { if ( tag.childNodes[j].tagName == 'UL' || tag.childNodes[j].tagName == "OL") w = tag.offsetWidth; } } if ( typeof w != 'undefined' && parseInt(w) != 0 && parseInt(w).toString() != "NaN" ) str += ' relwidth="' + parseInt(parseFloat(w) / MneMisc.prototype.posGetWidth(this.editarea) * 100 ) + '"'; if ( tag.className.indexOf("mne_padding") >= 0 ) str += ' padding="1"'; else str += ' padding="0"'; if ( tag.className.indexOf("mne_valignt") >= 0 ) str += ' valign="top"'; if ( tag.className.indexOf("mne_valignm") >= 0 ) str += ' valign="middle"'; if ( tag.className.indexOf("mne_valignb") >= 0 ) str += ' valign="bottom"'; str += ">"; v = v + str; endtag = "</td>"; break; } } if ( tag.tagName != "SPAN" ) v = this.xml_save(v, tag) + endtag; } return v; }; editor.output = param.output; editor.save = function(nochange) { if (this.output == null ) return; if ( this.clearNode(null) != true ) this.output.value = this.xml_save("", this.editarea); else this.output.value = ''; if ( nochange != true ) this.buttons.setModify(false); }; }
import React, { Component } from 'react'; import { Container,ListGroup, ListGroupItem , Button } from 'reactstrap'; import {CSSTransition , TransitionGroup} from 'react-transition-group' //import uuid from 'uuid';//uudi for ganerating randome ids import { connect } from 'react-redux'//allows us to get state from redux into react component import { getItems , deleteItem } from '../actions/itemActions' //the function //run it here $* it will dispatch to the reducerfile and return the atates egg.. and bring it to the component import PropTypes from 'prop-types'////**the action u bring from redux its will be stored as prop */ ////$* life cycle method called run at certine points when the component mount"api req or an action"" class ShoppingList extends Component { componentDidMount(){ this.props.getItems(); } onDeleteClick= (id) => { this.props.deleteItem(id) } //{items} used the {} used to destructring to pull it out of what we put in it render() { const { items } = this.props.item return( <Container> <ListGroup> <TransitionGroup className="shopping-list"> { items.map(({_id ,name }) => ( <CSSTransition key={_id} timeout={500} classNames ="fade"> <ListGroupItem> <Button className ="remove-btn" color="danger" size="sm" onClick={this.onDeleteClick.bind(this, _id)}> &times; </Button> {name} </ListGroupItem> </CSSTransition> ))} </TransitionGroup> </ListGroup> </Container> ) } } ShoppingList.propTypes={ getItems: PropTypes.func.isRequired, item: PropTypes.object.isRequired } const mapStateToProps = (state) =>( {item: state.item }) // mapStateToProps allows to take item state and map it into component property //the item in the reducer file export default connect (mapStateToProps ,{getItems , deleteItem } ) (ShoppingList)//getItems fron above , //render comment //item represennt the whole state object , items is the array inside the state reducerfile *//
const up = ({ current, boardBox, width }) => { if (current < 0 || current - Number(width) < 0) { return { uData: boardBox, uUpdated: false }; } else { let uData = boardBox.map((e, i) => { if (e.props.active === true) { return { ...e, props: { ...e.props, active: false, selected: false } }; } else if (i === current - Number(width)) { return { ...e, props: { ...e.props, active: true, selected: false } }; } else { return e; } }); return { uData, uUpdated: true }; } }; export default up;
export default { state: { aeorusUI_form_isShow: false, aeorusUI_form_isShowIn: false, aeorusUI_form_input: '', aeorusUI_form_items: [] }, mutations: { aeorusUI_form_show(state, params) { state.aeorusUI_form_isShow = true; state.aeorusUI_form_isShowIn = true; state.aeorusUI_form_input = params.input; state.aeorusUI_form_items = params.items; }, aeorusUI_form_hide(state) { state.aeorusUI_form_isShow = false; }, aeorusUI_form_showOut(state) { state.aeorusUI_form_isShowIn = false; }, aeorusUI_form_confirm(state, params) {}, aeorusUI_form_cancel(state) {} }, actions: { aeorusUI_form_show(ctx, params) { ctx.commit('aeorusUI_form_show', params); }, aeorusUI_form_hide(ctx) { ctx.commit('aeorusUI_form_hide'); }, aeorusUI_form_showOut(ctx) { ctx.commit('aeorusUI_form_showOut'); }, aeorusUI_form_confirm(ctx, params) { ctx.commit('aeorusUI_form_confirm', params); }, aeorusUI_form_cancel(ctx) { ctx.commit('aeorusUI_form_cancel'); } } }
import React, { useState, useEffect, useRef } from 'react'; import { Button, Row, Col, Form, Input, notification, Select } from "antd"; import { updateBebGasApi } from "../../Api/gaseosa"; import { UserOutlined, NumberOutlined, AlignLeftOutlined, DollarOutlined } from '@ant-design/icons'; export default function EditBebGasForm(props) { const { bebGas, setIsVisibleModal, setReloadBebGas } = props; const [BebGasData, setBebGasData] = useState({ nombre: bebGas.nombre, cantidad: bebGas.cantidad, precio: bebGas.precio, restaurante: bebGas.restaurante, descripcion: bebGas.descripcion }) const updateBebGas = e => { e.preventDefault(); let BebGasUpdate = BebGasData; if (!BebGasUpdate.nombre || !BebGasUpdate.cantidad || !BebGasUpdate.precio || !BebGasUpdate.restaurante || !BebGasUpdate.descripcion) { openNotification('bottomRight', "Por favor rellene todos los espacios", "error") return; } updateBebGasApi(BebGasUpdate, bebGas._id).then(result => { openNotification('bottomRight', result.message, "success") setIsVisibleModal(false) setReloadBebGas(true); }); } const openNotification = (placement, message, type) => { notification[type]({ message: message, placement, }); }; return ( <div> <EditForm BebGasData={BebGasData} setBebGasData={setBebGasData} updateBebGas={updateBebGas} /> </div> ) } function EditForm(props) { const { BebGasData, setBebGasData, updateBebGas } = props; const { Option } = Select return ( <Form className="form-edit"> <Row gutter={24}> <Col span={12}> <Form.Item> <Input prefix={<UserOutlined />} placeholder="Nombre" onChange={e => setBebGasData({ ...BebGasData, nombre: e.target.value })} /> </Form.Item> </Col> <Col span={12}> <Form.Item> <Input prefix={<NumberOutlined />} placeholder="Cantidad" onChange={e => setBebGasData({ ...BebGasData, cantidad: e.target.value })} /> </Form.Item> </Col> </Row> <Row gutter={24}> <Col span={12}> <Form.Item> <Input prefix={<DollarOutlined />} placeholder="Precio" onChange={e => setBebGasData({ ...BebGasData, precio: e.target.value })} /> </Form.Item> </Col> <Col span={12}> <Form.Item> <Select placeholder="Seleccione un Restaurante" onChange={e => setBebGasData({ ...BebGasData, restaurante: e })} > <Option value="Piccola Stella">Piccola Stella</Option> <Option value="Turin Anivo">Turin Anivo</Option> <Option value="Notte Di Fuoco">Notte Di Fuoco</Option> </Select> </Form.Item> </Col> </Row> <Row gutter={24}> <Col span={12}> <Form.Item> <Input prefix={<AlignLeftOutlined />} placeholder="Descripción" onChange={e => setBebGasData({ ...BebGasData, descripcion: e.target.value })} /> </Form.Item> </Col> </Row> <Form.Item> <Button type="primary" htmlType="submit" className="btn-submit" onClick={updateBebGas}> Actualizar Bebida Gaseosa </Button> </Form.Item> </Form> ) }
import { v4 as uuidv4 } from 'uuid'; export class Product { constructor(product = {}) { this.product = product; this.products = []; } }
/*! * SAP UI development toolkit for HTML5 (SAPUI5) * * (c) Copyright 2009-2014 SAP SE. All rights reserved */ /* ---------------------------------------------------------------------------------- * Hint: This is a derived (generated) file. Changes should be done in the underlying * source files only (*.control, *.js) or they will be lost after the next generation. * ---------------------------------------------------------------------------------- */ // Provides control sap.viz.ui5.core.BaseStructuredType. jQuery.sap.declare("sap.viz.ui5.core.BaseStructuredType"); jQuery.sap.require("sap.viz.library"); jQuery.sap.require("sap.ui.core.Element"); /** * Constructor for a new ui5/core/BaseStructuredType. * * Accepts an object literal <code>mSettings</code> that defines initial * property values, aggregated and associated objects as well as event handlers. * * If the name of a setting is ambiguous (e.g. a property has the same name as an event), * then the framework assumes property, aggregation, association, event in that order. * To override this automatic resolution, one of the prefixes "aggregation:", "association:" * or "event:" can be added to the name of the setting (such a prefixed name must be * enclosed in single or double quotes). * * The supported settings are: * <ul> * <li>Properties * <ul></ul> * </li> * <li>Aggregations * <ul></ul> * </li> * <li>Associations * <ul></ul> * </li> * <li>Events * <ul></ul> * </li> * </ul> * * * In addition, all settings applicable to the base type {@link sap.ui.core.Element#constructor sap.ui.core.Element} * can be used as well. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * Abstract base class for all elements that represent VIZ modules or complex property types * @extends sap.ui.core.Element * @version 1.26.6 * * @constructor * @public * @since 1.7.2 * @experimental Since version 1.7.2. * Charting API is not finished yet and might change completely * @name sap.viz.ui5.core.BaseStructuredType * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ sap.ui.core.Element.extend("sap.viz.ui5.core.BaseStructuredType", { metadata : { "abstract" : true, library : "sap.viz" }}); /** * Creates a new subclass of class sap.viz.ui5.core.BaseStructuredType with name <code>sClassName</code> * and enriches it with the information contained in <code>oClassInfo</code>. * * <code>oClassInfo</code> might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}. * * @param {string} sClassName name of the class to be created * @param {object} [oClassInfo] object literal with informations about the class * @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata. * @return {function} the created class / constructor function * @public * @static * @name sap.viz.ui5.core.BaseStructuredType.extend * @function */ // Start of sap/viz/ui5/core/BaseStructuredType.js sap.viz.ui5.core.BaseStructuredType.prototype._getOrCreate = function(sName) { var o = this.getAggregation(sName); if ( !o ) { var oAggregation = this.getMetadata().getAggregations()[sName]; jQuery.sap.require(oAggregation.type); var FNClass = jQuery.sap.getObject(oAggregation.type); o = new FNClass(); this.setAggregation(sName, o); } return o; }; sap.viz.ui5.core.BaseStructuredType.prototype._getOptions = function(bIncludeDefaults) { var oMetadata = this.getMetadata(), mOptions = {}, mProps,mDefaults,mAggrs,n,oValue; // HACK: convert UI5 wrapper names back to VIZ names function tovizKey(n) { n = (n === 'toolTip' ? 'tooltip' : n); return n; } function tovizValue(n){ var result = n; switch(n){ case 'triangleUp' : result = 'triangle-up'; break; case 'triangleDown' : result = 'triangle-down'; break; case 'triangleLeft' : result = 'triangle-left'; break; case 'triangleRight' : result = 'triangle-right'; break; } return result; } // enforce enrichment of metadata oMetadata.getJSONKeys(); // collect non-default values for all VIZ properties with a simple type var mProps = oMetadata.getAllProperties(); var mDefaults = oMetadata.getPropertyDefaults(); for(n in mProps) { // assumption: a property is a VIZ property if and only if it has been introduced by this class // This check needs to be enhanced as soon as inheritance is reflected in the wrappers if ( mProps[n]._oParent === oMetadata ) { oValue = this.getProperty(n); // use values only for non-default values if(oValue instanceof Array){ if(bIncludeDefaults || !mDefaults[n] || oValue.toString() !== mDefaults[n].toString()){ mOptions[tovizKey(n)] = tovizValue(oValue); } }else{ if ( bIncludeDefaults || oValue !== mDefaults[n] ) { mOptions[tovizKey(n)] = tovizValue(oValue); } } } } // collect non-null values for all VIZ properties with a complex type var mAggrs = oMetadata.getAllAggregations(); for(n in mAggrs) { // assumption: an aggregation is a VIZ aggregation if and only if it has been introduced by this class // This check needs to be enhanced as soon as inheritance is reflected in the wrappers if ( mAggrs[n]._oParent == oMetadata ) { oValue = this.getAggregation(n, null); if ( oValue !== null ) { // transitively retrieve options mOptions[tovizKey(n)] = oValue._getOptions(bIncludeDefaults); } } } return mOptions; }; /** * Helper method to convert a given object into an object of the type expected by the given aggregation. * Used to mediate between old and new Interaction APIs. * * Although this is a static method, <code>this</code> must be the object that will aggregate the given * object. <code>this</code> will be used to determine the metadata of the aggregation * * @return {object} the converted object or - if not applicable - the given object */ sap.viz.ui5.core.BaseStructuredType._convertAggregatedObject = function(sAggregationName, oObject, bMultiple) { if ( oObject != null ) { // get aggregation information var oAggregation = this.getMetadata().getAllAggregations()[sAggregationName]; // get class name of the given object var sClassName = oObject.getMetadata && oObject.getMetadata().getName(); if ( oAggregation && sClassName !== oAggregation.type ) { // TODO inheritance? // ensure that the class for the type is loaded jQuery.sap.require(oAggregation.type); // create a new instance of the desired class with the options of the current one var fnClass = jQuery.sap.getObject(oAggregation.type); oObject = new fnClass(oObject._getOptions(true)); // also include default values as they might differ between types jQuery.sap.log.warning("[Deprecated] Type of aggregation '" + this.getMetadata().getName() + "." + sAggregationName + " has been changed from '" + sClassName + "' to '" + oAggregation.type + "'."); } } return oObject; }; sap.viz.ui5.core.BaseStructuredType.prototype.validateProperty = function(sPropertyName, oValue) { if ( /^(lineSize|size)$/.test(sPropertyName) ) { var oProperty = this.getMetadata().getAllProperties()[sPropertyName]; if ( oProperty && oProperty.type === "int" && typeof oValue !== "number" ) { oValue = oValue ? parseInt(oValue, 10) : null; } } return sap.ui.core.Element.prototype.validateProperty.call(this, sPropertyName, oValue); }; sap.viz.ui5.core.BaseStructuredType.prototype.validateAggregation = function(sAggregationName, oObject, bMultiple) { if ( sAggregationName === "selectability" ) { // can convert types in the following two cases // - if a behaviors.Interaction receives a controller.Interaction_selectability (e.g. chart.GetInteraction().setSelectability(...) in old code) // - if a controller.Interaction receives a behaviors.Interaction_selectability oObject = sap.viz.ui5.core.BaseStructuredType._convertAggregatedObject.call(this, sAggregationName, oObject, bMultiple); } return sap.ui.core.Element.prototype.validateAggregation.call(this, sAggregationName, oObject, bMultiple); };
// components/areaList/index.js import {address} from '../../address.js' const app=getApp() Component({ /** * 组件的属性列表 */ properties: { fullIndex:{ type:Array, value:[0,0,3] }, isAll:{ type:Boolean, value:false }, address:{ type:Object, value:{} } }, /** * 组件的初始数据 */ externalClasses: ['picker-class'], data: { area: address, failProvince:{}, failCity:{}, failCounty:{}, fullAreaPicker:[], columnItem:{ id: 0, name: "全部" } }, //在组件实例进入页面节点树时执行 attached(){ //初始化,省市县 let tpladdress=this.data.area let parray = [] let carray = [] let tarray = [] if ( this.data.isAll ){ parray.push(this.data.columnItem ) carray.push(this.data.columnItem ) tarray.push(this.data.columnItem ) } for (let key in tpladdress) { let province = { id: key, name: address[key].name, child: address[key].child } parray.push(province) } let provinceIndex = this.data.fullIndex[0] || 0 let cityIndex = this.data.fullIndex[1] || 0 let countyIndex=this.data.fullIndex[2] || 0 this.setData({ province: parray, failProvince: parray[provinceIndex] }) if (parray[provinceIndex].child) { for (let key in parray[provinceIndex].child) { let item = parray[provinceIndex].child[key] let city = { id: key, name: item.name, child: item.child } carray.push(city) } } this.setData({ city: carray, failCity: carray[cityIndex] }) if (carray[cityIndex].child) { for (let key in carray[cityIndex].child) { let item = carray[cityIndex].child[key] let city = { id: key, name: item, child: item.child } tarray.push(city) } } this.setData({ county: tarray, failCounty: tarray[countyIndex] }) let pro={ id: this.data.province[provinceIndex].id, name: this.data.province[provinceIndex].name } let pcity={ id:this.data.city[cityIndex].id, name: this.data.city[cityIndex].name } let pcounty={ id: this.data.county[countyIndex].id, name:this.data.county[countyIndex].name } this.setData({ fullAreaPicker: [this.data.province, this.data.city, this.data.county], address:{ province: pro, city: pcity, county: pcounty, fullName: this.data.province[provinceIndex].name + ',' + this.data.city[cityIndex].name + ',' + this.data.county[countyIndex].name } }) this.triggerEvent('changeAddress', this.data.address) }, /** * 组件的方法列表 */ methods: { changeFullArea(e) { let index = e.detail.value let fullAddress = this.data.fullAreaPicker let province = { id: fullAddress[0][index[0]].id, name: fullAddress[0][index[0]].name } let city = { id: fullAddress[1][index[1]].id, name: fullAddress[1][index[1]].name } let county = { id: fullAddress[2][index[2]].id, name: fullAddress[2][index[2]].name } let address = { province: province, city: city, county: county, fullName: province.name + ',' + city.name + ',' + county.name } this.setData({ address: address }) this.triggerEvent('changeAddress', this.data.address) }, changeColum(e){ let model=e.detail let column = model.column let value=model.value switch (column) { case 0:{ this.changeProvince(value) break } case 1: { this.changeCity(value) break } } }, changeProvince(val){ let province= this.data.province[val] let cityList=[] let countyList=[] if (this.data.isAll ){ cityList.push(this.data.columnItem) countyList.push(this.data.columnItem) } if( province.child ){ for (let key in province.child ){ let item = province.child[key] let citys={ id:key, name: item.name, child: item.child } cityList.push( citys ) } this.setData({ 'fullAreaPicker[1]': cityList }) let countys=cityList[0].child if (countys ){ for (let key in countys ){ let item = countys[key] let county={ id:key, name: item } countyList.push(county) } this.setData({ 'fullAreaPicker[2]': countyList }) } this.setData({ fullIndex: [val, 0, 0] }) } }, changeCity(val){ let tplCity = this.data.fullAreaPicker[1] let city=tplCity[val] let countyList=[] if (this.data.isAll) { countyList.push(this.data.columnItem) } if( city.child) { for(let key in city.child){ let item = city.child[key] let county={ id:key, name:item } countyList.push( county ) } this.setData({ 'fullAreaPicker[2]': countyList }) let indexValue = this.data.fullIndex indexValue[1] = val indexValue[2] = 0 this.setData({ fullIndex: indexValue }) } } }, setAddressIndex(val){ } })
import React, { Component } from 'react'; export default class About extends Component { render() { return ( <div> <div className="slds-box slds-theme_default"> <div className="slds-grid slds-gutters"> <div className="slds-box slds-col" style={{ backgroundColor: 'white' }} > <span>1</span> </div> <div className="slds-box slds-col" style={{ backgroundColor: 'white' }} > <span>2</span> </div> </div> </div> </div> ); } }
/** * Copyright (c) Benjamin Ansbach - all rights reserved. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const P_NAME = Symbol('name'); const P_PUBKEY = Symbol('public_key'); const P_ENC_PRIVATE_KEY = Symbol('encrypted_private_key'); /** * Represents a key entry. */ class Key { /** * Constructor. * * @param {String} name * @param {PublicKey} publicKey * @param {BC} encryptedPrivateKey */ constructor(name, publicKey, encryptedPrivateKey) { this[P_NAME] = name; this[P_PUBKEY] = publicKey; this[P_ENC_PRIVATE_KEY] = encryptedPrivateKey; } /** * Gets the name of the key. * * @return {String} */ get name() { return this[P_NAME]; } /** * Gets the associated public key. * * @return {PublicKey} */ get publicKey() { return this[P_PUBKEY]; } /** * Gets the encrypted private key. * * @return {BC} */ get encryptedPrivateKey() { return this[P_ENC_PRIVATE_KEY]; } } module.exports = Key;
// Hugs file for Creating, Reading, Updating, and Deleting Hugs var firebase = require("../firebase/admin"); var firebase2 = require("../firebase/config"); const admin = require("firebase-admin"); require("firebase/firestore"); require("firebase/storage"); global.XMLHttpRequest = require("xhr2"); // Import const Users = require("./Users"); const Friends = require("./Friends"); // Firestore const db = firebase.firestore(); const users = db.collection("users"); const hugs = db.collection("hugs"); // Storage const storageRef = firebase2.storage().ref(); const storage = firebase2.storage(); function convertDate(date) { const dateStr = date.toString(); const dateArr = dateStr.split(" "); let hours = date.getHours(); let minutes = date.getMinutes(); let ampm = hours >= 12 ? "pm" : "am"; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? "0" + minutes : minutes; let strTime = hours + ":" + minutes + ampm; return `${dateArr[0]} ${dateArr[1]} ${dateArr[2]} ${dateArr[3]} ${strTime}`; } const HugsAPI = { // HELPER FUNCTIONS uploadBase64ArrayToHugs: async function (base64Array, imageName) { let downloadURLArrays = []; // Edge check if (base64Array.length == 0) { return downloadURLArrays; } // Traverse through base64 strings // console.log(base64Array.length); for (let i = 0; i < base64Array.length; i++) { let baseString = base64Array[i]; // Get only the data of the base64 baseString = baseString.substr(baseString.indexOf(",") + 1); // Path to image is: hug_images/[topLevelHug.id]/Timestamp in milliseconds[i] // Where "i" is the ith string in the base64Array let path = `${imageName}-${i}.jpg`; // console.log(path); const hugImageRef = storageRef.child(path); //convert base64 to buffer / blob const blob = Buffer.from(baseString, "base64"); // MIME Metadata let metadata = { contentType: "image/jpeg", }; // Upload to firestore await hugImageRef.put(blob, metadata).then((snapshot) => { console.log("Success!"); }); // Add to array downloadURLArrays.push(await hugImageRef.getDownloadURL()); } console.log(downloadURLArrays); return downloadURLArrays; }, // The user that calls this function is the sender // TODO: More error handling and monitor upload progress? createHug: async function (currentUser, friendId, message, base64) { // Set current user var currUser = users.doc(currentUser); // Save a reference to the top level hug with an autoID (I think) var topLevelHug = hugs.doc(); //possible problems if we make a doc every time // Set the date of the hug (also used to ID image) let dateInMillis = Date.now(); let dateInSeconds = Math.floor(dateInMillis / 1000); var dateTime = new admin.firestore.Timestamp(dateInSeconds, 0); // Create a unique image ID var imageName = `hug_images/${topLevelHug.id}/${dateInMillis}`; var imageDownloadURLSArray = await this.uploadBase64ArrayToHugs( base64, imageName ); // Set the topLevelHug's data await topLevelHug.set({ completed: false, date_time: dateTime, receiver_description: "", sender_description: message, images: imageDownloadURLSArray, receiver_ref: users.doc(friendId), sender_ref: currUser, }); // MAKE SURE THIS HAPPENS AFTER WE MAKE THE TOP LEVEL HUG // Add hug to user await currUser .collection("user_hugs") .doc(topLevelHug.id) .set({ completed: false, date_time: dateTime, friend_ref: users.doc(friendId), hug_ref: topLevelHug, // Use the ref to the top level hug ^^ pinned: false, }) .then(function (docRef) { console.log( "Document written with ID: " + currUser.collection("user_hugs").doc(topLevelHug.id).id ); }) .catch(function (error) { console.error("Error adding document: ", error); }); // add hug to friend await users .doc(friendId) .collection("user_hugs") .doc(topLevelHug.id) .set({ completed: false, date_time: dateTime, //dateTime is an actual DateTime object (timestamp?) friend_ref: users.doc(currentUser), hug_ref: topLevelHug, //Use the ref to the top level hug ^^ pinned: false, }) .then(() => { console.log( "Document written with ID: " + users.doc(friendId).collection("user_hugs").doc(topLevelHug.id).id ); }) .catch(function (error) { console.error("Error adding document: ", error); }); return { out: topLevelHug.id }; }, // hugId is the global hug. dropHug: async function (currentUser, hugId) { // Set current user var currUser = users.doc(currentUser); // Set ref for top level hug const topLevelHugRef = hugs.doc(hugId); const topLevelHug = await topLevelHugRef.get(); const topLevelHugData = topLevelHug.data(); const friendId = topLevelHugData.sender_ref.id; // delete currentUser and friend user_hug reference await currUser.collection("user_hugs").doc(hugId).delete(); await users.doc(friendId).collection("user_hugs").doc(hugId).delete(); // Remove hug images from storage // TODO: Loop through each element in the images array of hugId for (let i = 0; i < topLevelHugData.images.length; i++) { // Every time we get another HTTPS URL from images, we need to make an httpsReference // Create a reference from a HTTPS URL const httpsReference = await storage.refFromURL( topLevelHugData.images[i] ); await httpsReference.delete(); } // Delete the global hug document await topLevelHugRef.delete(); return { out: true }; }, deleteAllImagesInArray: function (imagesArray) { var storage = firebase.storage(); // Loop through each element in the images array of hugId imagesArray.forEach(function (image) { // Every time we get another HTTPS URL from images, we need to make an httpsReference // Create a reference from a HTTPS URL var httpsReference = storage.refFromURL(image); httpsReference .delete() .then(function () { // File deleted successfully }) .catch(function (error) { // Uh-oh, an error occurred! }); }); }, deleteImage: async function (imageHttps) { // Create a root reference in firebase storage var httpsReference = storage.refFromURL(imageHttps); httpsReference .delete() .then(function () { // File deleted successfully }) .catch(function (error) { // Uh-oh, an error occurred! }); }, deleteImageFromPath: function (pathString) { storageRef .child(pathString) .delete() .then(function () { // File deleted successfully }) .catch(function (error) { // Uh-oh, an error occurred! }); }, }; const UpdateHugAPI = { /** * Helper Function for Respond to Hug * @param {string} hugId */ updateUserHugCount: function (hugId) { db.collection("hugs") .doc(hugId) .get() .then(async function (doc) { if (doc.exists) { // Increment receiver and sender hug count let receiverId = doc.data().receiver_ref.id; let senderId = doc.data().sender_ref.id; console.log(receiverId, senderId); Users.HugCountAPI.increaseHugCount(receiverId); Users.HugCountAPI.increaseHugCount(senderId); // Update each user's user_hug to completed : true users.doc(receiverId).update({ completed: true, }); users.doc(senderId).update({ completed: true, }); } else { console.log("Hugs 300 No such document!"); } }) .catch(function (error) { console.log("Error getting document:", error); }); }, /** * Allow the user to respond to hug * @param {string} currentUser * @param {string} hugId * @param {string} message * @param {[string]} base64 */ respondToHug: async function (currentUser, hugId, message, base64) { try { let currUserRef = users.doc(currentUser); // Set the date of the hug (also used to ID image) let dateInMillis = Date.now(); // Create a unique image ID let imageRef = `hug_images/${hugId}/${dateInMillis}`; // Set a var to an array of the downloadURLs let imageDownloadURLSArray = await HugsAPI.uploadBase64ArrayToHugs( base64, imageRef ); const hugQuery = await hugs.doc(hugId).get(); const hugData = hugQuery.data(); // Update the top level hug to include more pictures and the receiver's message await hugs.doc(hugId).update({ completed: true, receiver_description: message, images: [...hugData.images, ...imageDownloadURLSArray], }); await currUserRef .collection("user_hugs") .doc(hugId) .update({ completed: true, date_time: hugData.date_time, }) .then(function (docRef) { console.log( "Document updated with ID: " + currUserRef.collection("user_hugs").doc(hugId).id ); }) .catch(function (error) { console.error("Error adding document: ", error); }); await users .doc(hugData.sender_ref.id) .collection("user_hugs") .doc(hugId) .update({ completed: true, date_time: hugData.date_time, }) .then(function (docRef) { console.log( "Document updated with ID: " + users .doc(hugData.sender_ref.id) .collection("user_hugs") .doc(hugId).id ); }) .catch(function (error) { console.error("Error adding document: ", error); }); // Update User Hug Counts this.updateUserHugCount(hugId); // Update both users' hug dates Friends.FriendsAPI.updateFriendHugDate( currentUser, hugData.sender_ref.id, hugData.date_time ); return { out: true }; } catch (err) { console.log("Hugs 315 Error occurred responding to hug", err); } }, }; const ViewHugAPI = { getHugById: async function (hugId) { var fullHugInfo = {}; // Set the hugData const hugQuery = await hugs.doc(hugId).get(); const hugData = hugQuery.data(); if (hugData == undefined) { return { out: "Hug does not exist" }; } // Set the receiver profile var receiverProfile = await Users.UsersAPI.getUserProfile( hugData.receiver_ref.id ); // Set the sender user profile var senderProfile = await Users.UsersAPI.getUserProfile( hugData.sender_ref.id ); // console.log(hugData); if (Object.keys(hugData).length != 0) { const oldDateTime = hugData.date_time.toDate(); const newDateTime = convertDate(oldDateTime); fullHugInfo.date_time = newDateTime; fullHugInfo.images = hugData.images; // RECEIVER fullHugInfo.receiver_description = hugData.receiver_description; fullHugInfo.receiver_name = receiverProfile.name; fullHugInfo.receiver_username = receiverProfile.username; fullHugInfo.receiver_profile_picture = receiverProfile.profile_pic; fullHugInfo.receiver_id = hugData.receiver_ref.id; // SENDER fullHugInfo.sender_description = hugData.sender_description; fullHugInfo.sender_name = senderProfile.name; fullHugInfo.sender_username = senderProfile.username; fullHugInfo.sender_profile_picture = senderProfile.profile_pic; fullHugInfo.sender_id = hugData.sender_ref.id; } else { console.log("Hugs 347 No such document!"); } return fullHugInfo; }, // Gets all hugs from the currently logged in user getUserHugs: async function (currentUser) { // Unpaginated var results = []; const userHugsQuery = await users .doc(currentUser) .collection("user_hugs") .orderBy("date_time", "desc") .where("completed", "==", true) .get(); // Go through each user_hug that is completed for (const doc of userHugsQuery.docs) { let currHugId = doc.data().hug_ref.id; let currHug = await hugs.doc(currHugId).get(); let currHugData = currHug.data(); var loadIn = {}; // Set the name of the person currentUser hugged if (users.doc(currentUser).id == currHugData.receiver_ref.id) { let friend = await Users.UsersAPI.getUserProfile( currHugData.sender_ref.id ); loadIn.friend_name = friend.name; loadIn.friend_username = friend.username; loadIn.friend_profile_pic = friend.profile_pic; } else if (users.doc(currentUser).id == currHugData.sender_ref.id) { let friend = await Users.UsersAPI.getUserProfile( currHugData.receiver_ref.id ); loadIn.friend_name = friend.name; loadIn.friend_username = friend.username; loadIn.friend_profile_pic = friend.profile_pic; } // Set the message to be the SENDER'S message ALWAYS loadIn.message = currHugData.sender_description; // Set the image to be the first image added loadIn.image = currHugData.images[0]; // Set the hugId loadIn.hug_id = currHugId; // Set if the hug is pinned or not loadIn.pinned = doc.data().pinned; // add the JSON the results array results = [...results, loadIn]; } var feed = { userHugs: results }; return feed; }, getSharedHugs: async function (currentUser, targetUser) { var results = []; const hugsQuery = await hugs .orderBy("date_time", "desc") .where("completed", "==", true) .get(); // Go through each user_hug that is completed for (const doc of hugsQuery.docs) { let currHugData = doc.data(); var loadIn = {}; senderId = currHugData.sender_ref.id; receiverId = currHugData.receiver_ref.id; // adds any hug with both users to the results array if ( (senderId === currentUser && receiverId === targetUser) || (senderId === targetUser && receiverId === currentUser) ) { // Set the name of the person currentUser hugged if (users.doc(currentUser).id == currHugData.receiver_ref.id) { let friend = await Users.UsersAPI.getUserProfile( currHugData.sender_ref.id ); loadIn.friend_name = friend.name; loadIn.friend_username = friend.username; loadIn.friend_profile_pic = friend.profile_pic; } else if (users.doc(currentUser).id == currHugData.sender_ref.id) { let friend = await Users.UsersAPI.getUserProfile( currHugData.receiver_ref.id ); loadIn.friend_name = friend.name; loadIn.friend_username = friend.username; loadIn.friend_profile_pic = friend.profile_pic; } // Set the message to be the SENDER'S message ALWAYS loadIn.message = currHugData.sender_description; // Set the image to be the first image added loadIn.image = currHugData.images[0]; // Set the hugId loadIn.hug_id = doc.id; // add the JSON the results array results = [...results, loadIn]; } } console.log(results); return { sharedHugs: results }; }, }; // Export the module module.exports = { HugsAPI, UpdateHugAPI, ViewHugAPI };
import React from 'react'; const Work = () => { return ( <section className="section full-horizontal full-vertical" id="work"> <div className="even"> <div className="section__content"> <h2 className="section__content--heading"> Experience </h2> <div className="row"> <div className="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2"> <ul className="timeline timeline-centered"> <li className="timeline-item"> <div className="timeline-info"> <span>May 2018 - August 2018</span> </div> <div className="timeline-marker"></div> <div className="timeline-content"> <h3 className="timeline-title">HackerYou, Inc</h3> <p>Masterclass Fullstack Bootcamp (MERN)</p> </div> </li> <li className="timeline-item"> <div className="timeline-info"> <span>April 2017 - Feburary 2018</span> </div> <div className="timeline-marker"></div> <div className="timeline-content"> <h3 className="timeline-title">SunLife Financial</h3> <p>Junior Web Developer</p> </div> </li> <li className="timeline-item"> <div className="timeline-info"> <span>June 2016 - September 2016</span> </div> <div className="timeline-marker"></div> <div className="timeline-content"> <h3 className="timeline-title">PitchUpp</h3> <p>Contracted: Junior Ruby on Rails Developer</p> </div> </li> <li className="timeline-item"> <div className="timeline-info"> <span>April 2014 - April 2017</span> </div> <div className="timeline-marker"></div> <div className="timeline-content"> <h3 className="timeline-title">SunLife Financial</h3> <p>Application Developer Support</p> </div> </li> <li className="timeline-item"> <div className="timeline-info"> <span>June 2013</span> </div> <div className="timeline-marker"></div> <div className="timeline-content"> <h3 className="timeline-title">University of Toronto</h3> <p>Graduation from University</p> </div> </li> <li className="timeline-item"> <div className="timeline-info"> <span>May 2010 - March 2011</span> </div> <div className="timeline-marker"></div> <div className="timeline-content"> <h3 className="timeline-title">University of Toronto</h3> <p>Web Developer (Intern)</p> </div> </li> </ul> </div> </div> </div> </div> </section> ); } export default Work;