WebCL doesn't fill global table - javascript

I started using Nokia WebCL implementation for Mozilla Firefox.
I'm testing my application on Firefox version 32.0 (which is version for which Nokia binding was implemented).
This is my code (for simplicity and to show you what my issue is I've simplified the kernel code to minimum):
Kernel code:
<script id="julia_set" type="text/x-opencl">
__kernel void julia_set(__global int* pix)
{
pix[0]=5;
}
</script>
My Javascript code:
function loadKernel(id){
var kernelElement = document.getElementById(id);
var kernelSource = kernelElement.text;
if (kernelElement.src != "") {
var mHttpReq = new XMLHttpRequest();
mHttpReq.open("GET", kernelElement.src, false);
mHttpReq.send(null);
kernelSource = mHttpReq.responseText;
}
return kernelSource;
}
var platforms = webcl.getPlatforms();
var width = 2;
var height = 2;
var ctx = webcl.createContext(platforms[2],WebCL.DEVICE_TYPE_GPU);
var length = 4*width*height;
var bufSize = 4*length;
var bufferC = ctx.createBuffer (WebCL.MEM_WRITE_ONLY, bufSize);
var kernelSrc = loadKernel("julia_set");
var program = ctx.createProgram(kernelSrc);
var device = ctx.getInfo(WebCL.CONTEXT_DEVICES)[0];
try {
program.build ([device], "");
} catch(e) {
alert ("Failed to build WebCL program. Error "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_STATUS)
+ ": "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_LOG));
throw e;
}
var kernel = program.createKernel ("julia_set");
kernel.setArg (0, bufferC);
var cmdQueue = ctx.createCommandQueue (device);
var local = [16,16];
var global = [32,32];
cmdQueue.enqueueNDRangeKernel(kernel, 2, null,global, local);
var outBuffer = new Uint32Array(length);
cmdQueue.enqueueReadBuffer (bufferC, false, 0, bufSize, outBuffer);
cmdQueue.finish ();
console.log(outBuffer);
It's the most simple OpenCL application I could imagine. I expect my outBuffer to be filled with 0's and first element to be 5, but all the elements are 0. Whatever I try to do in kernel, my array seems untouched.
The device I'm using is NVidia GeForce GT 750M.
What can be possibly wrong in my code?

if(get_global_id(0)==0 && get_global_id(1)==0)
pix[0]=5;
should fix the issue, without race condition.

Related

Google Script appendRow() fails

Everytime I try appendRow() I just get [Ljava.lang.Object;#4ed3710 in my spreadsheet.
function my() { //does not work
var ssMASTER = SpreadsheetApp.openById('1e4-----vQX');
var shMASTER = ssMASTER.getSheetByName('master_request');
var valuesMASTER = shMASTER.getDataRange().getValues();
var valuesPermaWrt = new Array();
valuesPermaWrt.push(["WhatEverItem"]);
Logger.log("writing:" + valuesPermaWrt); //Log: WhatEverItem
ssMASTER.appendRow([valuesPermaWrt]); //fails
}
I followed the solution from elias91:
var orderString = timeStamp + "," + ordNum + "," + clc + "," + orderRng.toString();
var orderValues = orderString.split(",");
from the Google Sheets: How to appendRow with 2d getValues array?
to create my failed version like here:
function blablaArray() { //does not work
var ssMASTER = SpreadsheetApp.openById('1e61------IuFV');
var shMASTER = ssMASTER.getSheetByName('master_request');
var valuesMASTER = shMASTER.getDataRange().getValues();
Logger.log("writing:" + valuesMASTER[0]);
//Log: [Timestamp, currently, scheduled in, Pin number]
var preappendMe = valuesMASTER[0].toString();
var appendMe = new Array();
var appendMe = preappendMe.split(",");
ssMASTER.appendRow([appendMe]); //fails
}
I know appendRow() is described here https://developers.google.com/apps-script/reference/spreadsheet/sheet#activate. But copy-pasting variables 10 times seems like a hack rather a programmatic solution, so I want it to be done through Array and not like here through each String variable.
function blablaSS() { //works fine
var ssMASTER = SpreadsheetApp.openById('1e61-----xAU');
var shMASTER = ssMASTER.getSheetByName('master_request');
var singularvalue = "ede";
ssMASTER.appendRow(["a man", singularvalue, "panama"]);
}
Try calling JSON.stringify() on your data before appending to the Google Sheet.
var valuesPermaWrt = new Array();
valuesPermaWrt.push(JSON.stringify(["WhatEverItem"]));
ssMASTER.appendRow(valuesPermaWrt);

Is it possible to post process HTML5 video elements audio output with Web Audio Api?

I have an html5 video element and I need to apply different processing realtime on the video's output audio. On desktop I made it work with the WebAudio API. The Api is seemingly present on iOS also. I am able to inspect the created objects, but it doesn't modify the video's output signal.
Here's my example code:
$(function () {
window.AudioContext = window.AudioContext||window.webkitAudioContext;
var audioContext = new AudioContext();
var bufferSize = 1024;
var selectedChannel = 0;
var effect = (function() {
var node = audioContext.createScriptProcessor(bufferSize, 2, 2);
node.addEventListener('audioprocess', function(e) {
var input = e.inputBuffer.getChannelData(selectedChannel);
var outputL = e.outputBuffer.getChannelData(0);
var outputR = e.outputBuffer.getChannelData(1);
for (var i = 0; i < bufferSize; i++) {
outputL[i] = selectedChannel==0? input[i] : 0.0;
outputR[i] = selectedChannel==1? input[i] : 0.0;
}
});
return node;
})();
var streamAttached = false;
function attachStream(video) {
if (streamAttached) {
return;
}
var source = audioContext.createMediaElementSource(video);
source.connect(effect);
effect.connect(audioContext.destination);
streamAttached = true;
}
function iOS_video_touch_start() {
var video = $('#vid')[0];
video.play();
attachStream(video);
}
var needtouch = false;
$('#vid').on('play', function () {
attachStream(this);
}).on('loadedmetadata', function () {
this.play();
this.volume=1.0;
if (this && this.paused) {
if (needtouch == false) {
needtouch = true;
this.addEventListener("touchstart", iOS_video_touch_start, true);
}
}
});
window.panToRight = function(){
selectedChannel = 1;
};
window.panToLeft = function(){
selectedChannel = 0;
};
});
You can also check it on CP:
http://codepen.io/anon/pen/pgeJQG
With the buttons you are able to toggle between the left and the right channels. On desktop browsers (Chrome, Firefox, Safari tested) it works fine.
I have also tried the older createJavaScriptNode() instead of createScriptProcessor(). I have also tried it with an alternative effect chain, which was looking like this:
var audioContext = new (window.AudioContext||window.webkitAudioContext)();
audioContext.createGain = audioContext.createGain||audioContext.createGainNode;
var gainL = audioContext.createGain();
var gainR = audioContext.createGain();
gainL.gain.value = 1;
gainR.gain.value = 1;
var merger = audioContext.createChannelMerger(2);
var splitter = audioContext.createChannelSplitter(2);
//Connect to source
source = audioContext.createMediaElementSource(video);
//Connect the source to the splitter
source.connect(splitter, 0, 0);
//Connect splitter' outputs to each Gain Nodes
splitter.connect(gainL, 0);
splitter.connect(gainR, 1);
//Connect Left and Right Nodes to the Merger Node inputs
//Assuming stereo as initial status
gainL.connect(merger, 0, 0);
gainL.connect(merger, 0, 1);
//Connect Merger output to context destination
merger.connect(audioContext.destination, 0, 0);
As you probably noticed this code was using the built in nodes only. But no luck.
So my questions are: Is this even possible on mobile? If it is, than what am I missing? If it is not, than any possible workaround? Thanks
With Chrome on Android, MediaElementSource is not currently routed to WebAudio. This is a known issue and is planned to be fixed eventually.

getElementsByTagName().length doesn't work in Firefox / Internet Explorer

This is related to another question (Chart is rendered in Chrome, but not in FF and IE), however, I am of the opinion that it is a valid question in itself and this will hopefully help describing the problem more in-depth.
I realized this behavior when I opened my webpage with Firefox by chance and noticed that my amChart graph wasn't working anymore, which I traced back to these lines in the code:
xmlData = xmlHttp.responseXML;
var x=xmlData.getElementsByTagName("row");
xmlRowCount = x.length;
Apparently the Firefox & Internet Explorer engines execute "xmlData.getElementsByTagName" differently from Google Chrome (where it works fine), which in turn leads to wrong return values and therefore an utter breaking of all following code.
The question is why FF and IE do this and how to prevent them from doing it and return the proper result just like Chrome.
I appreciate any suggestions and hope that some of you can help me and might know the reason for this strange behavior.
best regards,
daZza
Edit: To make the browser test complete, I also downloaded and tested Opera. It works fine there, which makes this whole thing even stranger. What is the difference between IE/FF vs. Chrome/Opera?
EDIT2: This finding looks promising... I tried adding a second console.log message that prints out the same thing, but uses the "non namespace name" of the XML tag, in this case z:row instead of row (row is the namespace name, z:row is the hard tag in the xml file).
What I discovered is, that Firefox/IE return 417 with this new console.log on the non-namespace name. Chrome/Opera return 0. And the same is true vice-versa, so Chrome returns 417 using the namespace, while FF/IE return 0.
This leads me to believe, tha FF/IE have a broken XML DOM that cannot utilize/use/detect/... namespaces in XML files.
I guess the only fix in that case is to use a XML without a namespace so it works on all browsers?
Here's a short example of the XML file (taken from a Sharepoint API):
<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
<s:ElementType name='row' content='eltOnly' rs:CommandTimeout='30'>
<s:AttributeType name='blub' rs:name='blah' rs:number='1'>
<s:datatype dt:type='string' dt:maxLength='512' />
</s:AttributeType>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row blub="blahblah" />
</rs:data>
</xml>
PS: Here's are some code snippets that might be relevant to the issue:
JS section at the bottom of the HTML header (this is where the error occurs):
var xmlRowCount;
var arrArt = new Array();
var arrPriority = new Array();
var arrTermin = new Array();
var arrResult = new Array();
var arrCalcPrio = new Array();
var avgCalcPrio = new Array();
var terminCounter = 0;
var avgCounter = 0;
// button_bereichand button_unterbereich are the values from two dropdown boxes. --> Shouldn't have relevance for the problem at hand. The xmlFile parameter is an well formed and validated XML file within the same domain.
function loadXML(xmlFile, button_bereich, button_unterbereich)
{
var xmlHttp = null;
var xmlData;
var sum = 0;
var bereich = button_bereich;
var unterbereich = button_unterbereich;
var spUnterbereich = "";
console.log("Bereich: " + bereich);
console.log("Unterbereich: " + unterbereich);
arrArt.length = 0;
arrPriority.length = 0;
arrCalcPrio.length = 0;
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Mircosoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
var txt="";
xmlData = xmlHttp.responseXML;
var x=xmlData.getElementsByTagName("row");
xmlRowCount = x.length;
// Chrome: 417 | Firefox: 0 | Internet Explorer: 0
console.log("Rowcount: " + xmlRowCount);
for (i=0;i<xmlRowCount;i++)
{
// do something with each row
}
for (j=0;j<xmlRowCount-1;)
{
// do something
}
}
}
}
xmlHttp.send();
}
return xmlData;
}
// bereichElement and bereichText are the values from two dropdown boxes. --> Shouldn't have relevance for the problem at hand
function getGraph()
{
chartData.length = 0;
validateData();
var bereichElement = document.getElementById("bereich");
var bereichText = bereichElement.options[bereichElement.selectedIndex].text;
var unterbereichElement = document.getElementById("unterbereich");
var unterbereichText = unterbereichElement.options[unterbereichElement.selectedIndex].text;
var xmlDoc=loadXML("sp_xml.xml", bereichText, unterbereichText);
}
JS in HTML Body( Body has body onload="getGraph();"> parameter):
// Actual chart creation (amCharts lib)
var chart;
var chartData = [];
var chartCursor;
AmCharts.ready(function() {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "amcharts/images/";
chart.dataProvider = chartData;
chart.categoryField = "date";
chart.dataDateFormat = "YYYY-MM-DD";
chart.baseHref = true;
// listen for "dataUpdated" event (fired when chart is rendered) and call zoomChart method when it happens
chart.addListener("dataUpdated", zoomChart);
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true;
categoryAxis.minPeriod = "DD";
categoryAxis.dashLength = 1;
categoryAxis.gridAlpha = 0.15;
categoryAxis.minorGridEnabled = true;
categoryAxis.axisColor = "#DADADA";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisAlpha = 0.2;
valueAxis.dashLength = 1;
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.title = "red line";
graph.valueField = "visits";
graph.bullet = "round";
graph.bulletBorderColor = "#FFFFFF";
graph.bulletBorderThickness = 2;
graph.bulletBorderAlpha = 1;
graph.lineThickness = 2;
graph.lineColor = "#0db503";
graph.negativeLineColor = "#b5030d";
graph.balloonText = "[[category]]<br><b><span style='font-size:14px;'>value: [[value]]</span></b>";
graph.hideBulletsCount = 50;
chart.addGraph(graph);
// CURSOR
chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorPosition = "mouse";
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chartScrollbar.graph = graph;
chartScrollbar.scrollbarHeight = 40;
chartScrollbar.color = "#FFFFFF";
chartScrollbar.autoGridCount = true;
chart.addChartScrollbar(chartScrollbar);
// WRITE
chart.write("charts_container");
});
// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
chart.zoomToIndexes(chartData.length - 40, chartData.length - 1);
}
// changes cursor mode from pan to select
function setPanSelect() {
if (document.getElementById("rb1").checked) {
chartCursor.pan = false;
chartCursor.zoomable = true;
} else {
chartCursor.pan = true;
}
chart.validateNow();
}
function validateData()
{
chart.validateData();
console.log("Data validated");
}
Your issue is that getElementsByTagName as specified in http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-A6C9094 specified matching on the "tagname", not the local name, and the tag name includes the prefix (see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-104682815 where it explicitly says the tagName is the qualified name).
That's the behavior Firefox and IE implement.
WebKit never implemented that spec correctly, matching only on localName instead, as far as I can tell.
You can work around that by using getElementsByTagNameNS, which lets you explicitly match on localname only in all modern browsers. You can either pass in your actual namespace, or just "*" if you don't care about the namespace part.

Detect lock screen or running screensaver with Firefox/OS X

I'm creating an extension for Firefox (SDK Add-on) in which I'll need to detect screensaver and lock-screen events so that I can set a user's availability status in a web-app.
I've managed to do this already for Windows and now need to port to OS X. For the Windows version, I was using calls to native API to find out if screen was locked, etc. Is there a similar way of getting OS information from a Firefox extension on OS X? I've tried Googling this and haven't found a solid answer - any help appreciated!
On OSX you can query a locked screen/screensaver using CGSessionCopyCurrentDictionary and looking for the presence and value of the "CGSSessionScreenIsLocked" key.
This is platform API, so one will have to use js-ctypes again and write a bunch of code to get that working.
I did get it working: The following code is a working example you can run in a privileged Scratchpad. To get a privileged one, open a pad for e.g. about:newtab.
Components.utils.import("resource://gre/modules/ctypes.jsm");
var CoreFoundation = new (function() {
this.CFNumberRef = ctypes.voidptr_t;
this.CFStringRef = ctypes.voidptr_t;
this.CFDictionaryRef = ctypes.voidptr_t;
var lib = ctypes.open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");
this.CFRelease = lib.declare(
"CFRelease",
ctypes.default_abi,
ctypes.void_t,
ctypes.voidptr_t);
var CFStringCreateWithCharacters = lib.declare(
"CFStringCreateWithCharacters",
ctypes.default_abi,
this.CFStringRef,
ctypes.voidptr_t,
ctypes.jschar.ptr,
ctypes.int32_t);
this.CFStringCreateWithCharacters = function(str) {
var rv = CFStringCreateWithCharacters(null, str, str.length);
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, this.CFRelease);
};
var CFDictionaryGetValue = lib.declare(
"CFDictionaryGetValue",
ctypes.default_abi,
this.CFNumberRef,
this.CFDictionaryRef,
this.CFStringRef);
this.CFDictionaryGetInt = function(dict, str) {
var rv = CFDictionaryGetValue(dict, this.CFStringCreateWithCharacters(str));
if (!rv || rv.isNull()) {
return null;
};
return this.CFNumberGetValue(rv);
};
var CFNumberGetValue = lib.declare(
"CFNumberGetValue",
ctypes.default_abi,
ctypes.bool,
this.CFNumberRef,
ctypes.int32_t,
ctypes.int32_t.ptr);
this.CFNumberGetValue = function(num) {
var rv = new ctypes.int32_t();
CFNumberGetValue(num, 3, rv.address());
console.log("CFNumberGetValue", rv, rv.value);
return rv.value;
};
this.close = function() {
lib.close();
};
})();
var ApplicationServices = new (function() {
var lib = ctypes.open("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices");
var CGSessionCopyCurrentDictionary = lib.declare(
"CGSessionCopyCurrentDictionary",
ctypes.default_abi,
CoreFoundation.CFDictionaryRef);
this.CGSessionCopyCurrentDictionary = function() {
var rv = CGSessionCopyCurrentDictionary();
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, CoreFoundation.CFRelease);
};
this.close = function() {
lib.close();
};
})();
setInterval(function() {
var dict = ApplicationServices.CGSessionCopyCurrentDictionary();
if (dict) {
var locked = CoreFoundation.CFDictionaryGetInt(dict, "CGSSessionScreenIsLocked");
console.log("rv", locked);
if (locked) {
// do something;
}
}
}, 500);

Can't display this simple .hide() code in Internet explorer

I have been trying this piece of code on a page and it is working fine in Chrome as well as Firefox.
But not in Internet Explorer, only the alert function within the if condition will show up.
$('#element-14').change(
function(){
$('.late').hide();
$('.normal').hide();
var tempDate= new Date();
var dateViolatetmp = $('#element-14').val();
var dateViolatearr = dateViolatetmp.split('/');
var dateViolate= new Date(dateViolatearr[2],(parseInt(dateViolatearr[0],10)-1).toString(),dateViolatearr[1]);
var one_day=1000*60*60*24;
var tempDate_unixtime =tempDate.getTime() ;
var dateViolate_unixtime =dateViolate.getTime();
var dayDifference = Math.round((tempDate_unixtime/one_day)) - Math.round((dateViolate_unixtime/one_day));
if(dayDifference<=30){
$('.normal').show();
alert("ok1");
}
else{
$('.late').show();
alert("ok2");
}
});
Do you see all the values as expected in the console with this code? The reason I wrote if(console) conditions is because I'm not sure if it even exists in IE (otherwise would not surprise me a bit(!) and I don't have it installed).
$('#element-14').change(function() {
if (console) console.log('#element-14 changed.');
$('.late, .normal').hide();
var arr = $('#element-14').val().split('/');
if (console) {
console.log('val:',$('#element-14').val());
console.log('arr:',arr);
}
var dateV = new Date(parseInt(arr[2]), parseInt(arr[0])-1, arr[1]);
if (console) console.log('dateV:',dateV);
var one_day = 1000*60*60*24;
var now = new Date();
if (console) console.log('now:',now);
var dayDiff = Math.round((now.getTime()-dateV.getTime()) / one_day);
if (console) console.log('dayDiff:',dayDiff);
$(dayDiff <= 30 ? '.normal' : '.late').show();
});

Categories