Javascript – how the bar chart labels are displayed based on values

I use CanvasJS.charts with Javascript and PHP, here is PHP code:

$sql = "select count(*) from test1 where MONTH(`call_date`)=MONTH(CURRENT_DATE()) and Year(call_date) = YEAR(CURDATE()) ";  
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
$sql1 = "select count(*) from test2 where MONTH(`call_date`)=MONTH(CURRENT_DATE()) and Year(call_date) = YEAR(CURDATE())";  

$result1 = mysqli_query($link,$sql1);
$row1 = mysqli_fetch_array($result1);
$row11 = $row(0)+$row1(0);

$sql = "select count(*) from test3 where MONTH(`call_date`)=MONTH(CURRENT_DATE()) and Year(call_date) = YEAR(CURDATE()) ";  
$result = mysqli_query($link,$sql);
$row12 = mysqli_fetch_array($result);
$sql1 = "select count(*) from test4 where MONTH(`call_date`)=MONTH(CURRENT_DATE()) and Year(call_date) = YEAR(CURDATE())";  

$result1 = mysqli_query($link,$sql1);
$row13 = mysqli_fetch_array($result1);
$row112 = $row12(0)+$row13(0);

$dataPoints1 = array(
                array("label"=>"Total Calls Answered", "y"=>$row11),
                array("label"=>"Total Incoming Calls", "y"=>$row112),//type tq

            );

This is javascript code:

window.onload = function() {
var chart = new CanvasJS.Chart("barChartContainer", {
    animationEnabled: true,
    exportEnabled: true,
    theme: "light1", // "light1", "light2", "dark1", "dark2"
    //title:{
        //text: "Simple Column Chart with Index Labels"
    //},
    axisX: {

        //prefix: "$",
        suffix:  "", //hr
        interval: 1
    },
    data: ({
        //type: "bar",
        type: "column", //change type to bar, line, area, pie, etc
        //indexLabel: "{y}", //Shows y value on all Data Points
        indexLabel: "{y}",
        yValueFormatString: "#,##0",
        indexLabelFontColor: '#121111', //"#5A5757",
        indexLabelPlacement: "outside",   
        dataPoints: 
    })
});
setColor(chart);
chart.render();
function setColor(chart){
                for(var i = 0; i < chart.options.data.length; i++) {
                dataSeries = chart.options.data(i);
                for(var j = 0; j < dataSeries.dataPoints.length; j++){
                    if(dataSeries.dataPoints(j).y < 51){
                    dataSeries.dataPoints(j).color = '#6eba01';
                    } if(dataSeries.dataPoints(j).y >= 51){
                    dataSeries.dataPoints(j).color = '#1a2b6d';
                } if(dataSeries.dataPoints(j).y >= 101) {
                    dataSeries.dataPoints(j).color = 'orange';
                }
                }
            }
}
}

Here in each bar I show the values ​​like 20,30,50... These values ​​result from two queries like tables calle test1 and Table 2.
Here is my requirement on how to display the values ​​individually hover on the bar.

Example: A bar contains 20 values, of which 20 values ​​10 come from the table test1 and 10 from the table test2 test1:10 test2:10 We are floating on this particular bar.

Please help me with this.

Thanks a lot
Sandeep

php – Show user message does not exist or is not registered with Javascript or Ajax

Good morning, good morning, how can I display a message that says USER IS NOT REGISTERED? If the person enters the user incorrectly?

I just want to use Javascript or its Ajax effect.

This is the form:

   
INICIO DE SESIÓN
mail_outline
lock

I want to show a message this way
Enter the image description here

Javascript – I have a problem with form of credit calculations

I am trying to do the following calculation:

The user enters his salary.
The system calculates a 30% credit on your salary.
The system grants you 30% of your salary plus 33% interest.

Example: If I have a salary of $ 1000, the system grants me $ 300 credit and I have to pay a total of $ 399 because $ 99 is interest, which is 33%.

Take an example of code but I don't know how to customize it and it just shows me the interests on the form. I also commented on the click element as there is no need to click, but neither does it show me the results and I don't know how to fix it.

Thank you

let importeSueldo = document.getElementById("importeSueldo")
let inporteOtorgado = document.getElementById("inporteOtorgado")
let importeDevolucion = document.getElementById("importeDevolucion")
    
inporteOtorgado.forEach((elemento) => {
 // elemento.addEventListener("click", () => {
    if (importeSueldo.value == "") {
    	console.log("Falta el valor de tu inversión")
    } else {
      let calculoUno = importeSueldo.value * elemento.value / 100
	  let calculoFinal = Number(importeSueldo.value) + Number(calculoUno)
	  importeDevolucion.value = calculoFinal
    }
  //})
})
Mi sueldo:

Te otorgamos (30%):

A devolver en un pago (33%):

Javascript – Pass form information without backend through query parameters

I created a contact form on a site I do in ReactJS. This site is just a frontend and I don't want to spend any time building the backend. I was wondering if you can send the form to my email. It may just be the query parameters that appear in the URL when I send a SEND.

Insert picture description here

Javascript – Dynamic Stamp does not work in Reader DC

I used Acrobat PRO to create a dynamic stamp, but when used in standard, the designed operations that require a number of fields are not performed.
The script:

this.getField("Invoice").value = app.response("Cantidad");
this.getField("Name").value = app.response("Name");
this.getField("Corporation").value = app.response("Corporation");
this.getField("Date").value = util.printd("mm/dd/yyyy", new Date());

It works perfectly in PRO and asks for it, but not in Stadard.

Array – heap selection sorting in Javascript

I designed and implemented this fancy sorting algorithm that combines natural runs in the input array with a heap data structure:

function ArrayRangeException(message) {
    this.message = message;
    this.getMessage = function() { return this.message; }
}

function RangeCheck(arrayLength, fromIndex, toIndex) {
    if (fromIndex < 0) {
        throw new ArrayRangeException("'fromIndex' is negative: " + fromIndex);
    }

    if (toIndex > arrayLength) {
        throw new ArrayRangeException(
                "'toIndex' is too large: " + toIndex + ", array length: " + 
                arrayLength);
    }

    if (fromIndex > toIndex) {
        throw new ArrayRangeException(
            "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
    }
}   

function RunHeap(array, cmp) {
    this.cmp = cmp;
    this.array = array;
    const auxArrayLength = (array.length >>> 1) + 1;
    this.fromIndexArray = Array(auxArrayLength);
    this.toIndexArray = Array(auxArrayLength);
    this.size = 0;

    this.pushRun = function(fromIndex, toIndex) {
        const nodeIndex = this.size++;
        this.fromIndexArray(nodeIndex) = fromIndex;
        this.toIndexArray(nodeIndex) = toIndex;
    },

    this.popElement = function() {
        const returnValue = this.array(this.fromIndexArray(0));
        this.fromIndexArray(0)++;

        if (this.fromIndexArray(0) === this.toIndexArray(0)) {
            const last1 = this.fromIndexArray(--this.size);
            this.fromIndexArray(0) = last1;

            const last2 = this.toIndexArray(this.size);
            this.toIndexArray(0) = last2;
        }

        this.siftDown(0);
        return returnValue;
    },

    this.swap = function(array, index1, index2) {
        const tmp = array(index1);
        array(index1) = array(index2);
        array(index2) = tmp;
    },

    this.isLessThan = function(runIndex1, runIndex2) {
        const element1 = this.array(this.fromIndexArray(runIndex1));
        const element2 = this.array(this.fromIndexArray(runIndex2));
        const cmp = this.cmp(element1, element2);

        if (cmp != 0) {
            return cmp < 0;
        }

        return this.fromIndexArray(runIndex1) < this.fromIndexArray(runIndex2);
    },

    this.siftDown = function(index) {
        let nodeIndex = index;
        let leftChildIndex = (index << 1) + 1
        let rightChildIndex = leftChildIndex + 1;
        let minIndex = index;

        while (true) {
            if (leftChildIndex < this.size 
            && this.isLessThan(leftChildIndex, nodeIndex)) {
                minIndex = leftChildIndex;
            }

            if (rightChildIndex < this.size 
            && this.isLessThan(rightChildIndex, minIndex)) {
                minIndex = rightChildIndex;
            }

            if (minIndex === nodeIndex) {
                return;
            }

            this.swap(this.fromIndexArray, minIndex, nodeIndex);
            this.swap(this.toIndexArray, minIndex, nodeIndex);

            nodeIndex = minIndex;
            leftChildIndex = (nodeIndex << 1) + 1;
            rightChildIndex = leftChildIndex + 1;
        }
    },

    this.buildHeap = function() {
        for (i = Math.floor(this.size / 2); i >= 0; --i) {
            this.siftDown(i);
        }
    },

    this.extendRun = function(length) {
        this.toIndexArray(this.size - 1) += length;
    },

    this.appendRun = function(fromIndex, toIndex) {
        this.fromIndexArray(this.size) = fromIndex;
        this.toIndexArray(this.size) = toIndex;
        this.size++;
    }
}

function reverseRun(array, fromIndex, toIndex) {
    for (i1 = fromIndex, i2 = toIndex; i1 < i2; i1++, i2--) {
        const savedArrayComponent = array(i1);
        array(i1) = array(i2);
        array(i2) = savedArrayComponent;
    }
}

function createRunHeap(array, cmp) {
    let runHeap = new RunHeap(array, cmp);
    let left = 0;
    let right = 1;
    let last = array.length - 1;
    let previousWasDescending = false;

    while (left < last) {
        head = left;
        right = left + 1;

        if (cmp(array(left), array(right)) <= 0) {
            while (left < last && cmp(array(left), array(right)) <= 0) {
                ++left;
                ++right;
            }

            if (previousWasDescending) {
                if (cmp(array(head - 1), array(head)) <= 0) {
                    runHeap.extendRun(right - head);
                } else {
                    runHeap.appendRun(head, right);
                }
            } else {
                runHeap.appendRun(head, right);
            }

            previousWasDescending = false;
        } else { // Scan a descending run:
            while (left < last && cmp(array(left), array(right)) > 0) {
                ++left;
                ++right;
            }

            reverseRun(array, head, left);

            if (previousWasDescending) {
                if (cmp(array(head - 1), array(head)) <= 0) {
                    runHeap.extendRun(right - head);
                } else {
                    runHeap.appendRun(head, right);
                }
            } else {
                runHeap.appendRun(head, right);
            }

            previousWasDescending = true;
        }

        ++left;
        ++right;
    }

    if (left === last) {
        if (cmp(array(last - 1), array(last)) <= 0) {
            runHeap.extendRun(1);
        } else {
            runHeap.appendRun(last, last + 1);
        }
    }

    return runHeap;
}

Array.prototype.heapSelectionSort = 
function(cmp, fromIndex, toIndex) {
    if (!cmp) {
        cmp = (a, b) => a - b;
    }

    if (!fromIndex) {
        fromIndex = 0;
    }

    if (!toIndex) {
        toIndex = this.length;
    }

    RangeCheck(this.length, fromIndex, toIndex);

    if (toIndex - fromIndex < 2) {
        return this;
    }

    const aux = this.slice(fromIndex, toIndex);
    const runHeap = createRunHeap(aux, cmp);
    runHeap.buildHeap();

    let index = fromIndex;

    while (index < toIndex) {
        this(index) = runHeap.popElement();
        index++;
    }

    return this;
};

(You can find the entire demo list here: https://gist.github.com/coderodde/47ae57983954c89ab7bef21b3fa7b232)

Critical inquiry

Since I am not a professional Javascript developer, I would like to equate my code above with the idiomatic JS code.

Design pattern for Javascript modules – Software Engineering Stack Exchange

Partly for use in my own projects and partly for fun when I'm stuck at home, I try to create another "block" based editor.

So far I've used simple objects, starting with a global one window.myeditor Object, then different sub-objects to handle different things. For example I have window.myeditor.toolbar abstract functions for creating toolbars in each block. I also used it Object.create to expand my base window.myeditor.block Object to create different block types (paragraph / heading / etc.) and then create instances of these objects for each element on the page.

However, it gets a bit messy. I cannot use global variables in the objects because they are not instantiated again Object.create and so all my objects see exactly the same variables, not a big problem, but not ideal. I also create functions like _focus() in my main block object, which does some standard tasks and then calls focus() from the inside, a function that should be replaced by subordinate objects so that they can expand this functionality. I also find myself duplicating code (e.g. code to make it bold / italic) that I could probably centralize if I had a clearer way of "modularizing" logic.

Looking at how other projects work, the current favorite seems to be building on classes, most likely via modules, although I'm struggling to familiarize myself with a basic implementation, and I think I'm just screwing up the basic architecture.

For example, I currently have something in the following direction:

Editor Class / module with a global instance for the main editor (not that this is required, but I would ideally design it so that it does not depend on having a global instance for anything, so that multiple editor instances would actually be possible without being mutually exclusive bring to ). This instance contains an instance of BlockRegistry The various block types and a reference to their class are stored here. The editor also has a number of BlockContainer Instances that control a block section on the page. There is a basis Block Class for handling a single block of content to be expanded by plugin block types.

The BlockContainer Class must list all HTML sub-elements and create one SomeBlockTypeThatExtendsBlock Instance for them, with the right handler, but to do this, they need to access them BlockRegistry Instance to see if it's a supported block type and the right class.

I can imagine that I get this problem with different class instances that regularly need access to functions of other instances, but I'm not sure which method is right here, except to constantly access the global instance within modules and pass references everywhere. or just put a code in one place that may have to point to something else.

I think I just miss something obvious and I screw up the basic design.

Javascript – Angular Folder Directory Approach

I know that the correct folder structure for an Angular application should look like this:

/app
    /core module
        /components
        /services
    /feature module
        /components
        /services
        /models
    /shared
        /components
        /constants
        /directives
        /interceptors
        /interfaces
        /models
        /pipes
        /sass
        /services

But I have a welcome page and a number of sub-modules associated with a main module. Does it make sense to nest these modules in the parent module?

/app
    /core module
        /components
        /services
    /main plan configuration module
        /sub module one (plan configuration step one)
            /components
            /services
            /models
        /sub module two (plan configuration step two)
            /components
            /services
            /models
    /shared
        /components
        ...

Or should I not nest them and leave the folder structure as follows:

/app
    /core module
        /components
        /services
    /main plan configuration module
        /components
        /models
        /services
    /sub module one (plan configuration step one)
        /components
        /services
        /models
    /sub module two (plan configuration step two)
        /components
        /services
        /models
    /shared
        /components
        ...

I know this is probably a very personal decision for most people, but I'm not the only one working on this code base, and I want to put together something that other developers can use easily enough.

tic tac toe – simple tic-tac-toe game in Javascript (NO A.I.)

After trying to implement "algorithms" for a tic-tac-toe game for a few hours, I came up with something I'm not really proud of.

Here is the code:

const TicTacToe = (function(){

    const grids = document.querySelectorAll(".box");
    const winning_combinations = (
        (0, 1, 2),
        (3, 4, 5),
        (6, 7, 8),
        (0, 3, 6),
        (1, 4, 7),
        (2, 5, 8),
        (0, 4, 8),
        (2, 4, 6)
    );

    let turn = 'X';
    let marks = 0;
    let currPos = void 0;

    for(let i = 0, len = grids.length; i < len; ++i)
        grids(i).addEventListener("click", () => mark( (currPos=i) )  );

    function mark(pos){
        if(grids(currPos).textContent != '')
            return alert("grid taken!");

        grids(currPos).textContent = turn;

        if(!foundWinner())
            turn = (turn === 'X') ? 'O' : 'X';
        else
            win();

    }   

    function foundWinner(){

        for(let currSet = 0, len = winning_combinations.length; currSet < len; ++currSet){

            winning_combinations(currSet).forEach(pos => {
                if(grids(pos).textContent == turn){
                    marks++;
                }               
            });

            if(marks == 3){
                return true;
            }
            else{
                marks = 0;
            }
        }

        return false;

    }

    function win(){
        return alert(turn + " won!");
    }

    return{
        reset: function(){
            // todo
        }
    }

}) ();

The problem is that I'm pretty sure this has code O(n log n) Time complexity, and I would at least like to do it O(n). I tried to make possible combinations based on the grid the player pressed on – unlike all winning combinations – but to no avail.

If I can improve this code in any way or make it more efficient, please let me know!

Javascript – (Js) Schedule Conflict Detection Algorithm Logic & Length

Getting check boxes is a bit verbose. Instead, use a single selector to get all of them instead of having to select each one individually.

const daysOfWeek = {};
for (const input of document.querySelectorAll('.form-group > input(type="checkbox")') {
  daysOfWeek(input.id) = input;
}

Instead of examining each variable to see if it is enabled, loop through this object to see if values ​​have been checked.

Think to avoid the hell of indentation returnearly if an error occurs instead of a very big one else block if there is no error.

Your savedSchedules is an object that is never reassigned:

var savedSchedules = {};

So it will always be true – that if (savedSchedules && Check is superfluous as it will always be true.

It is also not necessary to check how many keys the object has beforehand – just go through them all regardless. If there are none, no conflicts are detected. So the Object.keys(savedSchedules).length >= 1 can be removed.

Object.entriesThe callback accepts an entry array parameter of the key and value. Since you already have the value as a variable, you do not have to select it again by going through them (key)::

Object.entries(savedSchedules).forEach(function((key, value)) {
  schedule_ = savedSchedules(key);

simplified to

Object.entries(savedSchedules).forEach(function((key, schedule_)) {

But since you have the schedule name (the key) you can also remove and use it Object.values instead:

Object.values(savedSchedules).forEach(function(schedule_) {

But you're trying to find out if there are any any Conflicts, it would be better to short-circuit if a problem is found. Consider using a for Loop instead. If a problem is found, notify the user and return.

The underscores after the variable names are confusing – they do not match a convention I know. It looks like you should distinguish the object of a single schedule from the day and the object value for the day. I think it would be appropriate to explicitly note this in the variable names, e.g. schedule, day, and dayObj.

Also since you are using Object.entriesYour environment supports ES6 – you should always use it in ES6 const Never declare variables, if possible var (and let only if you need to reassign).

The startTime The variable name (which comes from the input) is somewhat unclear once you are deep in the review phase and compare with it value_.StartTime Variable names. You might call the input variable inputStartTime (and the same for endTime) to reduce possible confusion?

The conflict checker is a decent section of code that is likely to deserve to be in its own role. This way, you can get a decent overview of the entire click process from the click listener without having to scroll through large amounts of code to get a general idea.

Assign to onclick should usually be avoided. It can work when it's done once, but if each other Code follows the same bad practices and always tries to do the same. Your previous listener will be overwritten. It is best to always use it addEventListener instead.

Completely:

const daysOfWeek = {};
for (const input of document.querySelectorAll('.form-group > input(type="checkbox")')) {
    daysOfWeek(input.id) = input;
}
const getConflicts = () => {
    for (const schedule of Object.values(savedSchedules)) {
        // Loop through the schedule (key_ = 'Name', 'Sunday', ...)
        for (const (day, dayObj) of Object.entries(schedule)) {
            // Only check if weekday has a time value and weekdays that are selected
            if (day === 'Name' || !dayObj || !daysOfWeek(day).checked) {
                continue;
            }
            // if there is conflict, return it
            const conflict = checkForConflict(dayObj.StartTime, dayObj.EndTime, inputStartTime, inputEndTime);
            if (conflict) {
                console.log('Conflict Detected');
                const conflictData = (day, `Start: ${dayObj.StartTime}/${inputStartTime}`, `End: ${dayObj.EndTime}/${inputEndTime}`);
                return `There is a scheduling conflict ${conflictData}:  - Cannot proceed...`;
            }
        }
    }
};
saveButton.addEventListener('click', () => {
    // Check that fields are filled
    if (!scheduleName || !inputStartTime || !inputEndTime || Object.values(daysOfWeek).every(input => !input.checked)) {
        warningMsg.textContent = 'All required fields must contain data';
        return;
    }
    // Check for Schedule Conflicts
    const conflictsMessage = getConflicts();
    if (conflictsMessage) {
        // Handle Conflict Resolution -> Overwrite Schedule, etc
        // Probably CALL A FUNCTION HERE, don't write it all inside this click listener
        return;
    }
    // Save the Schedule

    // ...
});

The generation of schedule Object doesn't appear, but it would be great if you didn't have to if (day === 'Name' check – Instead of combining the schedule name with the day key, you should put the days in a completely separate property, e.g.

{
  scheduleName: 'schedule-1',
  days: {
    Sunday: ...
    Monday: ...