with the code below I have to clean up a sharepoint people picker using typescript, the code runs without errors but it doesn't clean up the people picker, what am I doing wrong?
React Code:
var tendinesportello = this.Fields.Lok_SportelloCompetente.find("select");
var sportelloValIniziale = tendinesportello.val();
try {
var operatoreincaricato = this.Fields.User_OperatoreIncaricato.find(
"input.sp-peoplepicker-editorInput"
).get(0);
console.log(operatoreincaricato);
console.log("Operatore incaricato: " + operatoreincaricato);
} catch (err) {
console.log("Errroe recupero valore: " + err.toString());
}
MakeReadOnlyUserFields([this.Fields.User_OperatoreIncaricato]);
//Seleziono il people picker
let peoplePicker: SPClientPeoplePicker =
SPClientPeoplePicker.PickerObjectFromSubElement(operatoreincaricato);
tendinesportello.on("change", function () {
if (sportelloValIniziale != tendinesportello.val()) {
console.log("Il valore è change");
//Eseguo la pulizia del picker
cleanPeoplePicker(peoplePicker);
}
});
export function cleanPeoplePicker(peoplePicker: SPClientPeoplePicker) {
try {
var selectedUsers = peoplePicker.GetAllUserInfo();
var resovledListElmId = peoplePicker.ResolvedListElementId;
$("#" + resovledListElmId)
.children()
.each(function (index, element) {
console.log("Sono in DeleteProcessedUser elemento: " + index);
peoplePicker.DeleteProcessedUser(element[index]);
});
} catch (err) {
console.log("Errore pulizia picker: " + err);
}
}
Related
I have drift's async script code in the index.html file of the react app.
<script>
"use strict";
!function () {
var t = window.driftt = window.drift = window.driftt || [];
if (!t.init) {
if (t.invoked) return void (window.console && console.error && console.error("Drift snippet included twice."));
t.invoked = !0, t.methods = ["identify", "config", "track", "reset", "debug", "show", "ping", "page", "hide", "off", "on"],
t.factory = function (e) {
return function () {
var n = Array.prototype.slice.call(arguments);
return n.unshift(e), t.push(n), t;
};
}, t.methods.forEach(function (e) {
t[e] = t.factory(e);
}), t.load = function (t) {
var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement("script");
o.type = "text/javascript", o.async = !0, o.crossorigin = "anonymous", o.src = "https://js.driftt.com/include/" + n + "/" + t + ".js";
var i = document.getElementsByTagName("script")[0];
i.parentNode.insertBefore(o, i);
};
}
}();
drift.SNIPPET_VERSION = '0.3.1';
drift.load('----api----');
drift.on('ready', api => {
api.widget.hide();
})
</script>
The issue is, it is getting popped up in every page of the app whereas I want it only when I click a button(onClick)
The function to trigger onClick :
openDriftChat = () =>{
const { setDriftState } = this.props;
if (window.drift.api) {
//this needs to happen only once but currently happening on every page load
if (!this.props.driftInit) {
if (localStorage.token) {
var tokenBase64 = localStorage.token.split(".")[1];
var tokenBase64_1 = tokenBase64.replace("-", "+").replace("_", "/");
var token = JSON.parse(window.atob(tokenBase64_1));
window.drift.identify(token.email, {
email: token.email,
nickname: token.name
});
setDriftState(true);
}
}
window.drift.api.openChat();
}
}
I basically want it pop up only when I call the function.
Hello I had the same issue:
To hide the welcome message use the following css code
iframe#drift-widget.drift-widget-welcome-expanded-online {
display: none !important;
}
iframe#drift-widget.drift-widget-welcome-expanded-away {
display: none !important;
}
The welcome message will only be shown when your drift button. Some extra info:
To hide the drift button icon use the following js code
drift.on('ready', function (api) {
api.widget.hide()
drift.on('message', function (e) {
if (!e.data.sidebarOpen) {
api.widget.show()
}
})
drift.on('sidebarClose', function (e) {
if (e.data.widgetVisible) {
api.widget.hide()
}
})
})
To call for the sidebar from a specific button use the following
Javascript
(function () {
var DRIFT_CHAT_SELECTOR = '.drift-open-chat'
function ready(fn) {
if (document.readyState != 'loading') {
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function () {
if (document.readyState != 'loading')
fn();
});
}
}
function forEachElement(selector, fn) {
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++)
fn(elements[i], i);
}
function openSidebar(driftApi, event) {
event.preventDefault();
driftApi.sidebar.open();
return false;
}
ready(function () {
drift.on('ready', function (api) {
var handleClick = openSidebar.bind(this, api)
forEachElement(DRIFT_CHAT_SELECTOR, function (el) {
el.addEventListener('click', handleClick);
});
});
});
})();
HTML
<a class="drift-open-chat">Open Chat</a>
I hope this helps someone out there.
PS: The above javascript code must be included after you have initialized your drift widget.
You need to disable that through the application: turn off the Playbooks.
Here is the link to do so: https://app.drift.com/playbooks
Hope it helps.
I am trying to insert the sensor data into a SQL Server database. I have tried all the possible way to insert the incoming data into database, but I failed. I am new to Nodejs and I really have no idea why these errors are occurred during executing process. It would be great if anyone could help me.
Thank you in advance.
The error I get is:
TypeError: Cannot read property 'writeHead' of undefined.
function addData (req, resp, reqBody, data)
{
try {
if (!reqBody) throw new Error("Input not valid");
data = JSON.parse(reqBody);
//reqBody = JSON.parse(data);
if (data) {//add more validations if necessary
var sql = "INSERT INTO arduinoData (Machine, StartTime, EndTime, LengthTime) VALUES ";
sql += util.format("(%s, '%s', %s, %s) ", data.Machine, data.StartTime, data.EndTime, data.LengthTime);
db.executeSql(sql, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
httpMsgs.send200(req, resp);
}
});
}
else {
throw new Error("Input not valid");
}
}
catch (ex) {
httpMsgs.show500(req, resp, ex);
}
};
function sendBackupData()
{
var jsonTable = { "table": [] };
fs.readFile("backup.json", "utf8", function (err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
if (jsonTable.table.length == 0) {
return;
}
for (var index = 0; index < jsonTable.table.length; index++) {
var options = {
url: serverURL,
method: "POST",
form: jsonTable.table.shift()
};
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent backup message!");
} else {
console.log('Error: ' + error);
console.log("CANT'T SEND BACK");
console.log(options.form);
jsonTable.table.push(options.form);
}
});
}
var outputJSON = JSON.stringify(jsonTable);
console.log(outputJSON);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
console.log("Sent backup data!");
});
});
}
function getTime()
{
var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
// Unix Time
var unixTime = Math.floor(date / 1000);
// Check if it is day or night
var isDay;
if (date.getHours() >= 8 & date.getHours() < 16)
{
isDay = true;
}
else
{
isDay = false;
}
return [year + '-' + month + '-' + day, hour + ':' + minute + ':' + second, unixTime, isDay];
}
/*
--- Main Code ---
*/
function vibrationStart()
{
/*
Should get:
- Start time and date the vibration started
- Whether it was day or night
Will send the message, if there is network connection, once complete.
Will store message into a JSON file if there is no network connection.
*/
var jsonTable = { "table": [] };
var startTime = getTime();
console.log(startTime[0] + " " + startTime[1]);
var startData = {
machine: machineName,
start_time: startTime[0] + " " + startTime[1],
day_night: startTime[3],
active: "true"
};
const options = {
url: serverURL,
method: "POST",
form: startData
};
var reqBody = [{
Machine : "",
StartTime : ""
}];
reqBody.push({"Machine" : startData.machine,"StartTime" : startData.start_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent starting message!");
sendBackupData();
addData();
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(startData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
return startTime[2];
}
function vibrationStop(startTimeUnix)
{
var jsonTable = { "table": [] };
var endTime = getTime();
console.log(endTime[0] + " " + endTime[1]);
var endTimeUnix = endTime[2];
var lengthTime = endTimeUnix - startTimeUnix;
console.log("Length time: " + lengthTime);
var endData = {
machine: machineName,
end_time: endTime[0] + " " + endTime[1],
length_time: lengthTime,
active: "false"
};
const options = {
url: serverURL,
method: "POST",
form: endData
};
var reqBody = [{
EndTime : "",
LengthTime :"",
}];
reqBody.push({"EndTime" : endData.end_time,"LengthTime" : endData.length_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent end message!");
sendBackupData();
addData()
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(endData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
}
http.createServer(function (req, resp) {
app.get('/', addData);
}).listen(settings.webPort, function () {
console.log("Started listening at: " + settings.webPort);
});
I'm new using rails 5.1 with webpacker gem and came a across this issue while trying to configure my environment to use bpmn-js library.
I installed the bpmn-js package with yarn but i still needed to add some required files from bpmn-js examples project to work properly in project/app/javascript/packs/application.js. The problem is that application.js uses fs module to create a new diagram as shown below:
project/app/javascript/packs/application.js
import 'bpmn-js'
import 'diagram-js'
import 'bpmn-moddle'
import 'bootstrap/dist/css/bootstrap'
import 'bootstrap/dist/css/bootstrap-theme'
import 'bpmn-js/assets/bpmn-font/css/bpmn'
import 'bpmn-js/assets/bpmn-font/css/bpmn-embedded'
//import 'diagram-js/assets/diagram-js'
//import ModelerIndex from 'bpmn_stuff/modeler_index.js';
console.log('Hello World from webpacker')
'use strict';
var $ = require('jquery');
var BpmnModeler = require('bpmn-js/lib/Modeler');
var container = $('#js-drop-zone');
var canvas = $('#js-canvas');
var modeler = new BpmnModeler({ container: canvas });
var newDiagramXML = fs.readFileSync(__dirname + '/../resources/newDiagram.bpmn', 'utf-8');
function createNewDiagram() {
openDiagram(newDiagramXML);
}
function openDiagram(xml) {
modeler.importXML(xml, function(err) {
if (err) {
container
.removeClass('with-diagram')
.addClass('with-error');
container.find('.error pre').text(err.message);
console.error(err);
} else {
container
.removeClass('with-error')
.addClass('with-diagram');
}
});
}
function saveSVG(done) {
modeler.saveSVG(done);
}
function saveDiagram(done) {
modeler.saveXML({ format: true }, function(err, xml) {
done(err, xml);
});
}
function registerFileDrop(container, callback) {
function handleFileSelect(e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) {
var xml = e.target.result;
callback(xml);
};
reader.readAsText(file);
}
function handleDragOver(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
container.get(0).addEventListener('dragover', handleDragOver, false);
container.get(0).addEventListener('drop', handleFileSelect, false);
}
////// file drag / drop ///////////////////////
// check file api availability
if (!window.FileList || !window.FileReader) {
window.alert(
'Looks like you use an older browser that does not support drag and drop. ' +
'Try using Chrome, Firefox or the Internet Explorer > 10.');
} else {
registerFileDrop(container, openDiagram);
}
// bootstrap diagram functions
//$(document).on('ready', function() {
$('#js-create-diagram').click(function(e) {
e.stopPropagation();
e.preventDefault();
createNewDiagram();
});
var downloadLink = $('#js-download-diagram');
var downloadSvgLink = $('#js-download-svg');
$('.buttons a').click(function(e) {
if (!$(this).is('.active')) {
e.preventDefault();
e.stopPropagation();
}
});
function setEncoded(link, name, data) {
var encodedData = encodeURIComponent(data);
if (data) {
link.addClass('active').attr({
'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
'download': name
});
} else {
link.removeClass('active');
}
}
var _ = require('lodash');
var exportArtifacts = _.debounce(function() {
saveSVG(function(err, svg) {
setEncoded(downloadSvgLink, 'diagram.svg', err ? null : svg);
});
saveDiagram(function(err, xml) {
setEncoded(downloadLink, 'diagram.bpmn', err ? null : xml);
});
}, 500);
modeler.on('commandStack.changed', exportArtifacts);
//});
You cant use 'fs' library in a Not node environment.
This line is the problem:
var newDiagramXML = fs.readFileSync(__dirname + '/../resources/newDiagram.bpmn', 'utf-8');
You cant use 'fs' library in a Not node environment. I had to Replace it's use with another approach. After looking at some examples i could just change this line to open directly the diagram XML.
Change the line:
var newDiagramXML = fs.readFileSync(__dirname + '/../resources/newDiagram.bpmn', 'utf-8');
For this:
var newDiagramXML = '<?xml version="1.0" encoding="UTF-8"?>\n'+
'<bpmn:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" targetNamespace="http://bpmn.io/schema/bpmn" id="Definitions_1">\n'+
' <bpmn:process id="Process_1" isExecutable="false">\n'+
' <bpmn:startEvent id="StartEvent_1"/>\n'+
' </bpmn:process>\n' +
' <bpmndi:BPMNDiagram id="BPMNDiagram_1">\n' +
' <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">\n' +
' <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1">\n' +
' <dc:Bounds height="36.0" width="36.0" x="173.0" y="102.0"/>\n' +
' </bpmndi:BPMNShape>\n' +
' </bpmndi:BPMNPlane>\n' +
' </bpmndi:BPMNDiagram>' +
'</bpmn:definitions>';
I've this code that work in genymotion enviroment. I need to record audio, so this is my code:
controllers.js
.controller('PlaylistsCtrl', function($scope, $cordovaMedia, $ionicPlatform) {
function __log(e, data) {
log.innerHTML += "\n" + e + " " + (data || '');
}
var recorder = null;
$scope.onSuccess = function() {
console.log('Media success');
}
$scope.onError = function(e) {
console.log('Media error', e);
}
$scope.onStatus = function(type) {
console.log('Media status', type);
}
$scope.startRecording = function () {
if (recorder == null) {
console.log('init recorder');
recorder = new Media('record.mp3', $scope.onSuccess, $scope.onError, $scope.onStatus);
}
recorder.startRecord();
recordBtn.disabled = true;
stopBtn.disabled = false;
__log('startRecording');
}
$scope.stopRecording = function() {
recorder.stopRecord();
__log('stopRecording');
}
$scope.playRecording = function() {
recorder.play();
__log('playRecording');
__log( JSON.stringify(recorder) )
console.log( JSON.stringify(recorder) );
}
record.html
<button id='recordBtn' ng-click='startRecording()'>record</button>
<button id='stopBtn' ng-click='stopRecording()'>stop</button>
<button id='playBtn' ng-click='playRecording()'>play</button>
<h2>Log</h2>
<pre id="log"></pre>
My problem is when i run my app in ionic viewer, and i click to #recordBtn, , nothing happens, startRecording() not work. Thank you !
I am beginner on Ionic Framework, and I find a problem that I dont be able find solution. Well, it's is a extract for my code:
I have this code in view.html
<ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="nota in notas" >
<h1>{{nota.titulo}}</h1>
<h2>{{nota.texto}}</h2>
</ion-item>
This is my controler:
.controller('ChatsCtrl', function($scope, Chats, $cordovaSQLite) {
$scope.notas= Chats.getNotas();
})
And in services.js the function getNotas() is something like this:
.factory('Chats', function( $cordovaSQLite) {
return {
getNotas: function() {
...
}
}
}
Well, when I enter on the app screen that show the info from DB, it work well, but I don't understand why the last record don't show., But nevertheless, when I recharge the page F5 (in the browser) the record appear. I understand that the controller is called when the view is called to render, but, if I set a new note in other view, why when I try see this last record in other view this dont show?
I think that this problem should be a foolish, but I don't understand why this happens.
The app it's a simple project that set and get notes from SQLite database, I thought that it would be easier.
Thanks you so much.
//Controlador DasControl
.controller('DashCtrl', function($scope, $cordovaSQLite) {
$scope.insert = function(titulo, texto) {
if (window.cordova) {
db = $cordovaSQLite.openDB({ name: "my.db" }); //device
}else{
db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
}
var query = "INSERT INTO people (title, text) VALUES (?,?)";
$cordovaSQLite.execute(db, query, [titulo, texto]).then(function(res) {
console.log("INSERT ID -> " + res.insertId);
}, function (err) {
console.error(err);
});
}
})
//Controlador para la vista de notas
.controller('ChatsCtrl', function($scope, Chats, $cordovaSQLite) {
$scope.notas= Chats.getNotas();
})
When I call the function insert the work fine, but when I call the second controler only work when I reload the page.
.factory('Chats', function( $cordovaSQLite) {
return {
getNotas: function() {
console.log("peticion notas");
//Consulta en la base de datos
if (window.cordova) {
db = $cordovaSQLite.openDB({ name: "my.db" }); //device
}else{
db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
}
//Creamos un vector donde vamos a introducir las notas.
var notas = [];
var salida = null;
var query = "SELECT * FROM people";
var res = $cordovaSQLite.execute(db, query).then(function(res) {
var len = res.rows.length;
if(len>0) {
for (var i = 0; i < len; i++) {
notas.push({
titulo: res.rows.item(i).title,
texto: res.rows.item(i).text
});
console.log("SELECTED -> " + res.rows.item(i).title + " " + res.rows.item(i).text);
}
}
if(res.rows.length > 0) {
console.log("SELECTED -> " + res.rows.item(0).title + " " + res.rows.item(0).text);
} else {
console.log("No results found");
}
}, function (err) {
console.error(err);
});
return notas;
}
To update the $scope.notas, every time you add new note, you can use events.
So, when, I new note is added, send event, in, the add note controller :
$rootScope.$broadCast('notaAdded', newNotaObject);
And, then, listen & add new node in the ChatsCtrl :
$rootScope.$on('notaAdded', function(event, newNota){
$scope.notas.push(newNota);
})