In my object in ApexChart I have 2 values that I want to change dynamically. This works well:
min: 1675123200000,
max: 1675206000000,
My code to change (just console log test for now) is this:
min: {
myfunc(min) {
min = 1675123200000;
console.log('MIN', min);
return min;
}
},
I believe is nothing wrong with my code but I wonder if I missing something. (I am of the view that my question is not a duplicate of this question).
There is no error and no console.log result. Looks like the value is just missing and the entire script is ignoring it.
Could be because my code is wrong or perhaps the script (ApexChart) do not accept the function there?
Related
Please be gentle as I have extreme learning difficulties when it comes to maths but I want to try and pass this test on a practice website. The numbers are supplied into the function when it's called but otherwise I've been testing with console.log.
This function should take a number as an argument and return the square of that number. The code I've got below isn't passing all the needs of the test and comes back with the following errors:
Errors:
squareNum's output was 2, but it should be 4
squareNum's output was 9, but it should be 81
squareNum's output was 97, but it should be 9409
Code I have so far:
function squareNum(num){
Math.sqrt
return num;
}
Can you please show much working code along with an explanation of why it's working so I can learn from it.
From your question, it seems that you need to calculate the square of the number, and not its square root.
The following function should do the trick!
function squareNum(num)
{
return num*num;
}
Math.sqrt is a function to find the square root of a number. All you need to do is this:
function squareNum(num) {
return num * num;
}
DESCRIPTION
I am trying to create an inline blot for text highlighting. I know this feature is already present in quill. But in my implementation I would like to assign a different value to the html element depending on the type of highlighting that was assigned. Here's what I got:
let Inline = Quill.import('blots/inline');
class TextHighlight extends Inline {
static create(value) {
let node = super.create();
if(!value || value < 1) return node;
if(value == 5){
node.style.color = 'rgb(225, 225, 225)';
}
else {
node.style.borderRadius = '2px';
node.style.padding = '2px';
if(value == 1){ node.style.background = 'rgb(254, 255, 171)'; }
if(value == 2){ node.style.background = 'rgb(255, 171, 171)'; }
if(value == 3){ node.style.background = 'rgb(171, 207, 255)'; }
if(value == 4){ node.style.background = 'rgb(178, 255, 171)'; }
}
node.setAttribute('data-value' , value);
return node;
}
formats() {
console.log('#formats()');
let result = this.domNode.getAttribute('data-value');
return result ? result : 0;
}
}
TextHighlight.blotName = 'texthighlight';
TextHighlight.tagName = 'span';
My remove/add function:
function highlightSelectedText(value) {
if (value < 0 || value > 5) return false;
var range = quill.getSelection();
if (range && range.length > 0) {
if (value > 0) {
quill.formatText(
range.index,
range.length,
'texthighlight',
value,
true);
}
else {
quill.formatText(range.index, range.length, 'texthighlight', false, false);
}
}
}
And finally the creation of the Quill instance:
var toolbarOptions = {
container: '#toolbar-container',
handlers: {
'texthighlight': function (value) {
highlightSelectedText(value);
}
}
};
var quill = new Quill('#editor', {
theme: 'bubble',
modules: {
toolbar: toolbarOptions
}
});
The problems
Highlighted text snippets have the following Delta:
...
{
"attributes": {
"0": "3"
},
"insert": "highlighted text"
},
...
"texthighlight" should appear instead of 0, like:
...
{
"attributes": {
"texthighlight": "3"
},
"insert": "highlighted text"
},
...
If I apply formatting more than once, it starts accumulating, putting markup inside markup. For example:
<span class="texthighlight"><span class="texthighlight"><span class="texthighlight"><span class="texthighlight"></span></span></span></span>
The expected behavior is that only one highlight is present.
I cannot remove the formatting.
CONCLUSION
There is no doubt that I lack knowledge about how to properly implement this. I was able to create simpler blots in other situations, but now I'm really getting confused about overriding certain blot methods. For example, the following list shows which methods I mean, and what I understand about each:
static formats(node): Returns formats represented by domNode. Called on selection events when index is within formatted range.
formats(): Returns formats represented by this Blot. It is used for Delta generation. Called on selection events when index is within formatted range.
format(format , value): Applies formatting to this blot.
In the highlight implementation demonstrated, only formats() and create(value) are being called. I know there is an example of how each of these methods is implemented, but I am not getting the desired behavior. I think it's because I don't know how to exactly implement them. Could someone answer me what they really do, when they are called, and how they should behave (be implemented)?
Can somebody help me, please? :(
EDIT (Dec 18, 2019)
So... After hours of research, I was finally able to make the editor a little more correct. In this whole story I ended up creating a blot that is capable of formatting text with different styles depending on the value passed to formatting. You can even remove formatting by providing or omitting a value.
I was finally able to get an answer for item 2 and, as I thought, found it within the toolbar module. Regarding the formats methods and their differences, I think I could better understand it. I still don't understand why formats are called so often. I think I'll find the answer looking at quill core, but... The quill source code is very large as it involves multiple files.
I am putting here a more updated version of the code shown earlier. It is all commented, favoring anyone who wants to learn more about how to:
Define custom blots/formats,
Define blots that accept values, and behave in different ways
depending on the configured value.
Define custom toolbar buttons that respond and reflect the state of the
editor content.
I hope that this will enable people to better understand how this tool can be used, and to create greater interest and contribution with it.
Full Example on GitHub
ORIGINAL ANSWER
It seems that I somehow managed to get the desired result. I am putting an answer here, but I do not consider it correct yet, as it is not complete. The desired result is obtained, but I'm still unable to understood how or why things work. Understanding the process becomes something fundamental, especially if and when the code needs to be changed in the future. Below you can check the code of the whole project. To test, just run it.
My remaining questions are:
What are the differences between formats and static formats(domNode)? If you
observe code execution, they are called a few times, and static formats(domNode) are called twice. Is this normal? I do not know, that's why I am asking.
Within function highlightSelectedText(hl), why does hl appear with
a false value? How does this happen?
When formatting is applied, the create is used. When
it is removed, format(format, value) is called. There are snippets of code (inside format) that are never reached. Shouldn't applying
and removing formats be a format-only job? Why do I have to change
the DOM element in two different locations?
I think I can find the answer to number 2 by looking at the toolbar module source code. But I'm not quite sure. If I can figure it all out, I'll be back here to edit this answer, okay? I know others may also have the same questions.
I am drawing a chart, which gets dollar values (from 0 to millions), and I am trying to show nice ticks. I already used d3.nice to get 5 ticks that all have nice values, it's very cool. But since there's such a large variance, I am struggling to display my dollar values correctly.
I wish to do:
0-999: shows itself
1,000 - 999,999: shows 1k-999k (it's ok if 999,500 shows 1M, but not ok to show 1.00k by using d3.format('.3s'), or having 467k go to 400k by using d3.format('.1s'))
1,000,000 - 999,999,999: shows 1M-999M (also ok if it rolls over when rounding)
Prior to d3 version 4, this was easy. You could do:
.ticks((d) => {
var prefix = d3.formatPrefix(d);
return prefix(d).toFixed()+''+prefix.symbol;
})
But now, I am reading the d3 v4 docs after this fails on me, and it says:
The d3.formatPrefix method has been changed. Rather than returning an SI-prefix string, it returns an SI-prefix format function for a given specifier and reference value. For example, to format thousands:
var f = d3.formatPrefix(",.0", 1e3);
f(1e3); // "1k"
f(1e4); // "10k"
f(1e5); // "100k"
f(1e6); // "1,000k"
This seems impossible to accomplish now, then, because I want to vary the amount of significant digits, but I see no obvious way to accomplish that. Am I missing something simple?
If I understand your desired output correctly, you can use the number itself to define the value of d3.formatPrefix.
Look at this demo:
[1, 999, 1000, 999000, 1000000].forEach(function(d) {
var prefix = d3.formatPrefix(".0", d)
console.log(d + ": " + prefix(d))
})
<script src="https://d3js.org/d3.v4.min.js"></script>
PS: Using this approach, 999500 will give you 1000k, not 1M.
Okay well I suppose this was easy enough, but a little hacky. Here's the formatter function I used to make this behaviour:
(val) => {
let prefix = d3.formatPrefix('.3s', val);
let str = prefix(val);
if (val === 0) {
return '0';
}
return parseInt(str.slice(0, str.length - 2))+''+str.slice(str.length - 1);
}
I would be happy to use something better so if you have a cleaner answer, post and I'll accept.
I ran into a problem with an object which I'm trying to modify. The object has a certain amount of keys in the format key_yyyy-mm-dd. When certain inputfields lose focus, I trigger a function to modify the object. This function is as follows:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
});
}
.no_hotel are the textboxes that trigger the function, and they also provide a value which I want to put in my object.
Now, say I put 3 in my first text box, a console.log will return the following object:
Object
key_2011-08-21: 3
key_2011-08-22: 0
key_2011-08-23: 0
key_2011-08-24: 0
key_2011-08-25: 0
However, the next time I put something in the textbox (or another textbox that should trigger the function), it DOES trigger, however the object returned remains the same. So instead of changing the first number to, say, 5, it will just return 3 again.
I have no idea why. My code seems pretty straightforward, and a console.log of day and $(this).val() returns the right values. It's just my object that doesnt get updated.
Does anyone have any idea? Thanks a lot!
EDIT:
hotelBooking is initialized right after $(document).ready():
var hotelBooking = {};
The method that calls updateHotelBooking is the following:
$(".roomrequest").blur(function()
{
updateHotelBooking();
});
EDIT2: JSFiddle: http://jsfiddle.net/pBYeD/2/
it has to do with something with the console rather than your code, if you change the logging code to this, you will see that you have the correct values:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
**logObject(hotelBooking);**
});
}
function logObject(hotelBooking){
for(var i in hotelBooking){
console.log(i+": "+hotelBooking[i]);
}
console.log("------");
}
Are you sure the problem does not come from the debugger output?
As far as i can see in my chrome output, if i let the fiddle as is, the object doesn't appear to change in the console (just the number on the left takes a +3). However if I add something like console.log(hotelBooking["key_" + day]); just before or after, it's shown as changing.
I'm trying to create my own JS Password Strength Meter.
It was working before but i didn't like how it worked so I tried using
{score +=10;}
Instead of just:
score++
This is my code:
http://jsfiddle.net/RSq4L/
Best Regards,
Shawn,
Hope someone can help
Multiple issues:
Your passwordStrength() function was not defined in the global scope in the jsFiddle so it wasn't getting called. This is probably an artifact of how you set up the jsFiddle, perhaps not an issue in your real code.
The method of getting the appropriate ratingMsg will not work because you don't have array values for every possible score so many scores will generate an "undefined" ratingMsg.
Your CSS classes are also sparse so there are many score values that they will not match for either and no appropriate CSS class/style will be in effect. If you want a specific class for each rating value, then perhaps you should put the classname in the ratings array so it can be fetched from there along with the ratingsMsg.
For the first issue, in your jsFiddle, you also have to make sure the password processing function is defined in the global scope. The way your jsFiddle is set up, it is not (it's in the onload handler). You can fix this in the jsFiddle by just setting the first drop-down in the upper left to "no wrap (head)".
For the second issue, you are using:
ratingMsg[score]
but, your array is a sparse array not guaranteed to have an entry for most possible scores. You simply can't do it that way because many elements you access will have undefined values which won't give you a meaningful message. For example, if score was 15, you would be accessing ratingMsg[15], but there is no value in that space in the array so you won't get a meaningful rating message.
The solution is to find a different way to select the right message. The simplest way would just be an if/else if/else if statement that would check which range the score is in and set the appropriate msg. There are more elegant table driven ways, but all will involve searching through a data structure to find which two values the current score is between and using that msg.
If you look at this jsFiddle http://jsfiddle.net/jfriend00/dA7XC/, you'll see that your code is getting called, but it only hits values in the array sometimes.
And, here's a rewritten algorithm that finds the appropriate msg no matter what the score show in this fiddle: http://jsfiddle.net/jfriend00/jYcBT/.
It uses a data structure like this:
var ratingMsg = [
0, "Unclassified",
10, "Weak",
20, "Fair",
50, "Better",
60, "Medium",
70, "Good",
90, "Strong"
];
and a for loop like this to get the appropraite ratingMsg:
for (var i = ratingMsg.length - 2 ; i >= 0; i-=2) {
if (score >= ratingMsg[i]) {
msg = ratingMsg[i+1];
break;
}
}
Here you go: http://jsfiddle.net/RSq4L/11/
The first problem is that in your fiddle you have the onLoad option set, so your passwordStrength function is not actually being declared in the global scope. It is being declared inside of the onLoad block that jsFiddle wraps your code with. This causes the page to error out when the keypress handler tries to invoke the function.
You can fix this problem in several different ways:
By explicitly declaring the function as global as per my example above.
By choosing one of jsFiddle's "no wrap" options instead of onLoad.
By dynamically binding your event-handler instead of setting it through the element's onkeydown attribute in the markup.
The second problem is how you are keying your score messages. You have:
var ratingMsg = new Array(0);
ratingMsg[0] = "Unclassified";
ratingMsg[10] = "Weak";
ratingMsg[30] = "Fair";
ratingMsg[50] = "Better";
ratingMsg[60] = "Medium";
ratingMsg[70] = "Good";
ratingMsg[90] = "Strong";
...and you lookup the message by doing ratingMsg[score]. This will only work if the score exactly matches one of your indices. And based upon your math this will not always be the case.
I would suggest doing something like:
ratingMsg = {};
ratingMsg[0] = "Unclassified";
ratingMsg[10] = "Weak";
ratingMsg[30] = "Fair";
ratingMsg[50] = "Better";
ratingMsg[60] = "Medium";
ratingMsg[70] = "Good";
ratingMsg[90] = "Strong";
function closestRating(score) {
var bestKey = 0;
var bestMatch = 100;
for (var key in ratingMsg) {
if (key <= score && score - key < bestMatch) {
bestMatch = score - key;
bestKey = key;
}
}
return ratingMsg[bestKey];
}
On an unrelated note, are you sure you want to be using onkeydown? I think onkeyup would work better.
Your fiddler script had several errors. Here's the corrected one: new script.
You were missing a semicolon here: document.getElementById("passwordDescription").innerHTML = "" + ratingMsg[score] + ""
You forgot to escape '^' on your regular expression
I just wrote this for it:
Jquery Plugin for password strength forcing