How can I calculate ichimoku indicator parts via javascript?

I have a Stock market monitoring platform that uses javascript.
I have two question of which the first may be a little irrelevant to this topic and I apologise for that:

  1. Can I use codes for other languages as a shortcut to bend the rules and enable them in this platform according to browser abilities?
  2. How can I calculate Ichimoku indicator parts in javascript?

I have a code that can save you time but it’s not fully done:

const inputs = { tenkan: -9, kijun: -26, senkou: -52, chikou: -26 };

main['ichimoku_' + pair] = generateIchimoku(pair, false);
main['chikou_' + pair] = generateIchimoku(pair, true);

const generateIchimoku = (pair, isChikou) => {

    const high = isChikou ? main.high[pair].slice(0, inputs.chikou) : main.high[pair];
    const low = isChikou ? main.low[pair].slice(0, inputs.chikou) : main.low[pair];

    const getHi = val => Math.max(...high.slice(val));
    const getLo = val => Math.min(...low.slice(val));

    const tenkan = (getHi(inputs.tenkan) + getLo(inputs.tenkan)) / 2;
    const kijun = (getHi(inputs.kijun) + getLo(inputs.kijun)) / 2;

    const spliceTo = isChikou ? main.high[pair].length + inputs.chikou * 2 : main.high[pair].length + inputs.chikou;
    const tenkanOld = (Math.max(...high.slice(spliceTo + inputs.tenkan, spliceTo)) + Math.min(...low.slice(spliceTo + inputs.tenkan, spliceTo))) / 2;
    const kijunOld = (Math.max(...high.slice(spliceTo + inputs.kijun, spliceTo)) + Math.min(...low.slice(spliceTo + inputs.kijun, spliceTo))) / 2;
    const senkouA = (tenkanOld + kijunOld) / 2;
    const senkouB = (Math.max(...high.slice(spliceTo + inputs.senkou, spliceTo)) + Math.min(...low.slice(spliceTo + inputs.senkou, spliceTo))) / 2;
    
    return { tenkan, kijun, senkouA, senkouB };
};

consts “main” and “pair” are not defined.

Axios API POST request returning a 307 redirect error even after being tested in Postman

I recently moved my ReactJS app away from using the fetch() method for API calls and instead implemented Axios. The URL’s for my API calls were all working before and were able to correctly communicate with my MongoDB database, and most of them still do when made through Axios.

My registration URL however keeps returning a 307 internal redirect response and not posting to my database.

The registration request should return a JSON object that either contains a JWT token or “NA” depending on whether or not the user already exists in the database. When tested through Postman this POST request returns correctly in both cases.

However when making an indentical call through my ReactJS frontend a blank response with no data is sent back along with the aforementioned 307 internal redirect code.

The URL I am currently using for users to register is
http://localhost:3000/register/username/password/ID_number/mobile_number/email/accountnum/college/degree/date/location

The response and URL in Google Chrome dev tools

From testing I know that both the URL itself and my backend controller method to handle the registration are working correctly as they both work in isolation. The issue only arises when I try send the same request from my frontend.

Any ideas as to what could be causing this would be greatly appreciated. I can provide any additional info if need be.

Using chrome.runtime.sendMessage to chrome extension in FlutterFlow

I’ve developed chrome extension and the website is ready; website is built in flutter flow.
The issue is that now I am trying to send message to my chrome extension using “externally connectable”, now I am trying to send message from the custom action button in flutter flow but it is unable to read the “sendMessage”, how to fix this and send message to my chrome extension?

What I have done


import 'dart:convert';
import 'dart:js' as js;

Future<void> newCustomAction() async {
  Map<String, dynamic> message = {'greeting': 'Hello'};
  String jsonString = jsonEncode(message);

  print('Message sent to extension');

  js.context.callMethod(
      'sendMessage', ['iedkcaeeboijleablfnnjjeihpgejjha', jsonString]);
}

JS Apexcharts: How to Get Index of Clicked Bar

i have a probleme to get the correct index of clicked bar in Apexchar.
my chart is filled by series contians [100,100,66.66,….,0,0], when i click to bar with value **0 **i get index of serie -1 and that is not correct
help me please .

see attached image to understand

TypeError : Customer.update() is not a function

When I am executing other funcitons like find, add in database then they are running perfectly fine , but when I am updating the database entry then I am getting this error , I am using mongodb atlas, can someone help me how to solve this error. This is the github link of the code : Github URL This is the error which I am getting

I searched on internet but didn’t find any solution which fixes my problem, so that’s why I am asking a new question, a similar kind of question already being asked but that didn’t work in my case

Change sticky logo color based on bright of the background

I have a web design where the website logo can be white or black. The header is sticky but haven’t semi-transparent background.

So the rest of the website goes under the sticky logo. Some zones are so clear and others are so dark. There is some way to know if the logo should be white or black in every scroll?

I seen ways to get the bright of images, but really I need the average bright of a small part of the rendered viewport, that might be a part of image, text, plain background color or a mix…

Thanks in advance.

Add Angular Custom element into Vue project

I create a custom Angular element and after concat I created a single Js file Which I am using in Vue or any simple Html project it is showing me an error

ERROR Error: NG0403
at e._moduleDoBootstrap

Here are the links from where I take the reference

https://itnext.io/building-micro-frontend-applications-with-angular-elements-34483da08bcb

Micro Frontend in Angular using Angular Elements

Use Angular Custom Element in Vue.js

at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

i want to send a token back to the user to reset his password but i am getting this error

Error: there was an error sending the email, try again later
at exports.forgotPassword (C:UsersAbdurehmanDesktopnode coursenode practiceFinalYearProjectcontrollersauthController.js:167:7)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

I searched everywhere but could not find the solution to my problem,i haven’t implemented the resetting functionality yet because first i want the sending token to work hope ya’ll understand

This is the authController.js file

here is my code :

exports.forgotPassword = async (req, res, next) => {


  const user = await User.findOne({ email: req.body.email });
  if (!user) {
    return next(new AppError('no user with this email', 404));
  }


  const resetToken = user.createPasswordResetToken();

  await user.save({ validateBeforeSave: false });

 
  const resetURL = `${req.protocol}://${req.get(
    'host'
  )}/api/v1/users/resetPassword/${resetToken}`;

  const message = `forgot your password ? submit a PATCH request with your new password to : ${resetURL}.n If you didn't forget your password , please ignore this email`;
  try {
    await sendEmail({
      email: user.email,
      subject: 'your password reset token (valid for 10 minutes)',
      message,
    });
    res.status(200).json({

      status: 'success',
      message: 'Token sent to email',
    });
  } catch (err) {
    user.passwordResetToken = undefined;
    user.passwordResetExpires = undefined;
    await user.save({ validateBeforeSave: false });
    return next(
      new AppError('there was an error sending the email , try again later'),
      500
    );
  }
};

Convert PDF file to base64

I make an request in Node.js to odoo and receive an string response like:

%PDF-1.4

1 0 obj
<<
/Type /Pages
/Count 0
/Kids [ ]
>>
endobj
2 0 obj
<<
/Producer (Odoo)
/Creator (Odoo)
>>
endobj
3 0 obj
<<
/Type /EmbeddedFile
/Params <<
/CheckSum (01088e581e88074028ca5b18a7ea79b1)
/ModDate (D72202306090837425300470047)
/Size /6195
>>
/Subtype /text#2Fxml
/Length 6195
>>
stream
<?xml version='1.0' encoding='UTF-8'?>....." how can i make this downloadable in the webbrowser

Its an PDF file. I want this to return as an Base64 so i can download it in the frontend.

I have tried:

let buffer = Buffer.from(file);
let arraybuffer = Uint8Array.from(buffer).buffer;
return 'data:application/pdf;base64,' + Buffer.from(arraybuffer).toString("base64");

And in the frontend:

 let a = document.createElement("a")
 a.href = result.data.getInvoicePdf
 a.download = this.invoice.name
 a.click()

I can download it, but the PDF file is empty. What am i doing wrong here?

vue-treeselect get selected values

I have the following code to populate a vue-treeselect from a json file. I need to save the options that the user has selected in localStorage, and get them selected again when the page is reloaded.

var tree = new Vue({
    el: "#app",
    data: {
        value: null,
        clearOnSelect: true,
        closeOnSelect: true,
        flat: true,
        sortValueBy: 'ORDER_SELECTED',
        options: [],
    },
    methods: {
        normalizer: function (node) {
            return {
                id: node.id,
                label: node.label,
                children: node.children,
            };
        },
    },
    mounted() {
        let vm = this;


        $.getJSON("/categories.json", function (json) {
            vm.options = json;
        });
    },
});

Converting huge JSON object to Blob by stringifying “directly into” an ArrayBuffer/Blob to avoid maximum string length error

I have some code like this in my application:

let blob = new Blob([JSON.stringify(json)], {type: "application/json"});

However, it sometimes fails because in Chrome the maximum string length is ~500MB, and json can sometimes be larger than this.

I’m looking for a way to go straight from my json variable (i.e. a POJO) to a Blob, probably via some sort of streaming stringification that saves to an ArrayBuffer as it goes.

Important:

  • Solution must work in the browser.
  • If an npm package is proposed in an answer, it must not be one that expects the json to simply be an array, since that case is very easy to handle. It must instead expect an arbitrarily nested JSON object where e.g. 90% of the data could be in foo.bar.whatever rather than spread evenly over the top-level keys.
  • I am not looking for a solution that expects a stream as an input, and results in a stream of string chunks as the output, like json-stream-stringify or streaming-json-stringify, for example. Instead, I’d like to input an already-in-memory POJO, and get a Blob out which contains the stringified JSON.

Related:

Update calendar when inserting new event

I have the following js to load the events in the calendar:

function show_events(events, month, day) {
    
  $(".events-container").empty();
  $(".events-container").show(250);
  console.log(event_data["events"]);

  if(events.length===0) {
    var event_card = $("<div class='event-card'></div>");
    var event_name = $("<div class='event-name'>Não há refeições marcadas para "+day+"  "+month+".</div>");
    $(event_card).css({ "border-left": "10px solid #FF1744" });
    $(event_card).append(event_name);
    $(".events-container").append(event_card);
  }
  else {
  
    for(var i=0; i<events.length; i++) {
        var event_card = $("<div class='event-card'></div>");
        var event_name = $("<div class='event-name'>"+events[i]["occasion"]+"</div>");
        var event_count = $("<div class='event-count'> Confirmada</div>");
        if(events[i]["cancelled"]===true) {
            $(event_card).css({
                "border-left": "10px solid #FF1744"
            });
            event_count = $("<div class='event-cancelled'>Cancelled</div>");
        }
        $(event_card).append(event_name).append(event_count);
        $(".events-container").append(event_card);
    }
  }

}  

function check_events(day, month, year) {
  var events = [];
  for(var i=0; i<event_data["events"].length; i++) {
      var event = event_data["events"][i];
      if(event["day"]===day &&
          event["month"]===month &&
          event["year"]===year) {
              events.push(event);
          }
  }
  return events;
  
}  

var event_data = {
  "events": []
};

$(document).ready(function () {

  $.getJSON('consrefeicoes.php', function (datta) {

    for (var i = 0; i < datta.length; i++) {

      PequenoAlm = datta[i].PequenoAlm;
      Alm = datta[i].Alm;
      Lan = datta[i].Lan;
      jant = datta[i].jant;
      Ceia = datta[i].Ceia;
      Valencia = datta[i].Valencia;
      Ano = datta[i].Ano;
      Colaborador = datta[i].Colaborador;
      mes = datta[i].mes;
      dia = datta[i].dia;
      Data = datta[i].Data;

      var testees = [];
      var testees = [PequenoAlm, Alm, Lan, jant, Ceia];

      var testees1 = testees.filter(Boolean).join(', ');
  
      event_data.events.push({
        "occasion": testees1,
        "year": Number(Ano),
        "month": Number(mes),
        "day": Number(dia)
      })
  
     };

     init_calendar(new Date())

   });
  });

With this code I load the events inserted in the database in the calendar. Now, when I insert a new event, I want to update the calendar with the new event inserted.

For that I’m doing it this way, inside the ajax success:

success: function(data){ 
  $.getJSON('consrefeicoes.php', function (datta) {

    for (var i = 0; i < datta.length; i++) {
      
       PequenoAlm = datta[i].PequenoAlm;
       Alm = datta[i].Alm;
       Lan = datta[i].Lan;
       jant = datta[i].jant;
       Ceia = datta[i].Ceia;
       Valencia = datta[i].Valencia;
       Ano = datta[i].Ano;
       Colaborador = datta[i].Colaborador;
       mes = datta[i].mes;
       dia = datta[i].dia;
      
       var testees = [];
       var testees = [PequenoAlm, Alm, Lan, jant, Ceia];
        
       var testees1 = testees.filter(Boolean).join(',');
            
        event_data.events.push({
          "occasion": testees1,
          "invited_count": Valencia,
          "year": Number(Ano),
          "month": Number(mes),
          "day": Number(dia)
         })
            
        };
      
        init_calendar(new Date())
      
     });
 }

In this way it updates the new events inserted in the database in the calendar, but it has a problem.

The problem is that it duplicates events that already exist in the calendar.

I need that before loading the events in the calendar again, that I remove all the events loaded in the calendar and reload all the existing events in the calendar.

MUI breakpoints inside Stickybits breaks Stickybits

I encountered the problem with applying MUI breakpoints. I’m trying to be able to set a dynamic offset for the sticky header using MUI breakpoints. No syntax errors, just stop working as expected.

I’m using this package called stickybits, it’s basically the same thing as the css poosition sticky except it has some handy features that will allow me to apply some classes when the header is pinned. Anywho, I’m new to MUI and react in general, but for the most part I have a solid understanding what I’m doing. So for the header I still I have to apply an offset, but the offset is based off the screen size.

So this is easily done normally with the MUI breakpoints. Well, appearently for some reason it breaks the sticky package because when I apply the MUI breakpoints inside of the stickyBitStickyOffset, the offset works fine but then it breaks the rest of the options. Like I have an option set for a specific class for when the header is stuck, and it works fine if I use just a regular Integer value, but when I use an object so I can insert the different break points it stops applying the ‘stuck’ class. I’m confused as to why, I get zero syntax errors so I’m just left wondering what’s going wrong.

Here is the package: https://www.npmjs.com/package/stickybits

And here is the code that’ll work just fine:


   const sticky = stickybits(stickyHeader.current, {
      stickyBitStickyOffset: 98,
      useStickyClasses: true,
      stickyClass: "stuck",
    });

This however will break it.

    const sticky = stickybits(stickyHeader.current, {
      //stickyBitStickyOffset: 98,
      stickyBitStickyOffset: {
        [theme.breakpoints.only("desktop")]: 98,
        [theme.breakpoints.up("desktop")]: 168,
      },
      useStickyClasses: true,
      stickyClass: "stuck",
    });

Any help with this would be greatly appreciated.

Thanks,
Jon

How do I replace a string in json with the file name?

I have multiple json files with the exact same string and I want to replace them with their respective file name. What do I do?

Here’s an example for what I want to do, in the file name hello.json
there’s a string
"url/hello.png"
I want to do the same with another file for example cat.json and replace the string
"url/hello.png"
with the file name like this
"url/cat.png"