Function running after data loading still gives an error because data is not loaded

I am getting Binance coin data from Binance npm package. But when I try to run filter or map function it gives the error: TypeError: Cannot read properties of undefined (reading 'filter')

The code:

const client = Binance();

  const [dataLoading, setDataLoaded] = useState(true);
  const [tradesData, setTradesData] = useState();
  const [length, setLength] = useState();

  const tradesDataSet = async () => {
    setTradesData(await client.trades({ symbol: "BTCUSDT" }));

    setDataLoaded(false);
  };

  useEffect(() => {
    tradesDataSet();
  }, []);
  console.log(
    tradesData.filter((trade) => trade.price * trade.qty > 3000).length
  );

How do I troubleshoot?

Add download Button for React Table

I’m trying to add a download button that downloads a dynamic react table on click as a csv File but I’m not sure how to do it..

import React, {Component} from "react";
import DynamicTable from '@atlaskit/dynamic-table';
import styled from 'styled-components';


const Wrapper = styled.div`
min-width: 600px;
th{font-size:13px}
th{font-size:14px} `;


render() {
const { error, isLoaded, shareFilterRows } = this.state;
if (error) {
  return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
  return <div>Loading Shared Filters...</div>;
} else {
  return (<Wrapper>
    <div>
    <DynamicTable
      head={shareFilterHead}
      rows={shareFilterRows}
      rowsPerPage={10}
      defaultPage={1}
      loadingSpinnerSize="large"
      isLoading={false}
      isFixedSize
      defaultSortKey="filterID"
      defaultSortOrder="ASC"
      onSort={() => console.log('onSort')}
      onSetPage={() => console.log('onSetPage')}
      
      />
  </div>
  </Wrapper>
  );
  }
}

}

This is how my table gets displayed img. I would appreciate any hint or help to make that button work. Thank you guys.

Accelerometer data when Android phone screen is off, in a progressive-web-app with service worker

I know that a standard website probably cannot access accelerometer data when the Android phone screen is off. It seems to be the same for a native Android app as explained in How to get sensor data in service when screen is turned off? (I don’t know if this answer is still up-to-date).

But is it possible in the context of a PWA?

Can a progressive-web-app, with a registered service worker, access to the accelerometer data when the screen is off?

Getting a SyntaxError only on my computer

I’m having trouble connecting to an API when I run node server.js on terminal.

My friend is running the same code as me but he is able connect.

Here is the SyntaxError:

SyntaxError: Invalid or unexpected token
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:139:18)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:236:14)
at async link (node:internal/modules/esm/module_job:67:21)

Appartently the error is in the last line of code:

const OMIE_APP_KEY = ""
const OMIE_APP_SECRET = ""

const api = axios.create({
    baseURL: "https://app.omie.com.br/api/v1/produtos/requisicaocompra/",
  }); 
  

const app = express()
const server = http.createServer(app)
const sockets = new Server(server)
let data = schema.data


mongoose.connect('mongodb://localhost/aluno_teste') //conexão com o banco de dados

mongoose.connection
    .once('open', () => console.log('Conexao com MongoDB (banco de dados) foi estabelecida com sucesso'))
    .on('error', (error) => {
        console.warn('Falha ao se conectar com o banco de dados. Motivo: ', error)
    })

app.use(express.static('public2'))//torna pública a pasta 'public2' para quem tiver acesso ao "port" exposto pelo server

sockets.on('connection', async (socket) => {

    socket.on('IncluirProduto', async (obj) => {
        //let a = await data.findOne({})
        if(0 == 1){
            async function incluirPedido() {
                try {
                  const response = await api.post('/', {call:"IncluirProduto",app_key:OMIE_APP_KEY,app_secret:OMIE_APP_SECRET,param:[{

For more information, here is the Code

Thanks in advance!

Ionic React Overmind Can’t perform a React state update on an unmounted component

I use Overmind with ionic react:

Tab1:

const { count } = useAppState()
const { increaseCount } = useActions()

return
<IonPage>
  <IonContent>
    <IonRouterLink routerLink='/tab1/page1'>1. Go to another page</IonRouterLink> // Go to page 1
    <IonText><p>{count}</p></IonText>
    <IonButton onClick={() => increaseCount()}>4. Increase again</IonButton>
  </IonContent>
</IonPage>

Page2:

const { count } = useAppState()
const { increaseCount } = useActions()

return
<IonPage>
  <IonContent>
    <IonBackButton defaultHref="/" /> // Go back to tab 1
    <IonText><p>{count}</p></IonText>
    <IonButton onClick={() => increaseCount()}>4. Increase again</IonButton>
  </IonContent>
</IonPage>

When I do this:

  1. Go to the other page
  2. Increase the count (modify state)
  3. Go back to main page
  4. Increase the count (modify state)
    ==> Go to console and there is the error
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

I created this minimum reproduction code: https://github.com/dopeshot/ionic-overmind-cant-perform-state-update

I also created an short video of the issue: https://www.youtube.com/watch?v=5w6r1_lxoS8

How can I fix this issue?

How to draw a image instead of a color in canvas for Agar.io

I am currently making a clone of Agar.io based upon this
I am stuck on getting skins to appear instead of the solid random color. With the current code, when you select a skin, making config.skin true, it freezes and I am not able to move, but can still chat. And I still have no image drawn.

config.skin is a base64 encoded image string

graph is the canvas’s 2d context

    if (config.skin) {
      graph.strokeStyle = "hsl(" + userCurrent.hue + ", 100%, 45%)";
      graph.fillStyle = "hsl(" + userCurrent.hue + ", 100%, 50%)";
      graph.lineWidth = playerConfig.border;
      var skin = new Image();//userCurrent.x - 2 * userCurrent.size, userCurrent.y - 2 * userCurrent.size);
      skin.src = config.skin;
      skin.onload = () => { // jshint ignore:line
        graph.beginPath();
        graph.arc(userCurrent.h / 2, userCurrent.w / 2, userCurrent.radius, 0, Math.PI * 2, false);
        graph.clip();
        graph.drawImage(skin, userCurrent.x - 2 * userCurrent.size, userCurrent.y - 2 * userCurrent.size); //, 4 * userCurrent.size, 4 * userCurrent.size);
      };
    } else {
      graph.strokeStyle = "hsl(" + userCurrent.hue + ", 100%, 45%)";
      graph.fillStyle = "hsl(" + userCurrent.hue + ", 100%, 50%)";
      graph.lineWidth = playerConfig.border;
    }

full code at github

Error while loadind data to react-native-pure-chart

Actually i’m would load data dynamically to react-native-pure-chart.

I have an API that give the data for each time where there was some measures and the response look’s like the following:

Array [
  230,
  230,
  230,
  50,
  250,
]
Array [
  "14",
  "13",
  "09",
  "09",
  "09",
]



const [itemsY, setItemsY] = useState([]);
  const [itemsX, setItemsX] = useState([]);

  useEffect(() => {
     fetchData1();

  }, [1])
const fetchData1 = () => {
      DataService.getEnergyDataList()
      .then(response => {
          setItemsY([...itemsY,...response.data.map(res => res.Voltage)]);
          setItemsX([...itemsX, ...response.data.map(res => res.Time.substr(11, 2))]);
      })
      .catch(e => {
          console.log(e);
      });
   
  };
  let sampleData = [
     {x: itemsX, y: itemsY},
]

     <PureChart 
     data={sampleData} 
     type='line' width={'100%'}
    height={300}
    customValueRenderer={(index, point) => {
      if (index % 2 === 0) return null
      return (
        <Text style={{textAlign: 'center'}}>{point.y}</Text>
      )
    }}/>

Error: Exception in HostFunction: Malformed calls from JS: field sizes are different.

[[3,3,3,3,3],[2,2,2,2,2],[[357,”RCTView”,21,{“position”:”absolute”,”height”:”100%”,”width”:”100%”}],[367,”RCTView”,21,{“borderTopColor”:-2039584,”borderTopWidth”:1,”width”:”100%”}]],2038]

Verifiable Random Function implementation in Javascript [closed]

I’m trying to implement the VRF in JavaScript as described in this paper https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-06.pdf .
I use ed25519 from the elliptic.js library and the bn.js library for big integer
The ‘ecvrf_prove’ and ‘ecvrf_prove_to_hash’ function already work, but the ‘ecvrf_verify’ function can’t verify the proof.
My first idea was to look at the calculation of U and V in steps 5 and 6. But i didn’t find any error or maybe i didn’t understand the whole thing.
Here is some code, maybe can someone can help me fix this or tell me what i’m doing wrong.
Thanks

// 5.3. ECVRF Verifying
/**
 * ECVRF_verify(Y, pi_string, alpha_string)
 * @param {*} y public key, an EC point
 * @param {*} pi_string  VRF proof, octet string of length ptLen+n+qLen
 * @param {*} alpha_string VRF input, octet string
 * @return ("VALID", beta_string), where beta_string is the VRF hash output, octet string
        of length hLen (64) bytes; or ("INVALID", []) upon failure
 */
function ecvrf_verify(y, pi_string, alpha_string) {
    // 1. D = ECVRF_decode_proof(pi_string)
    // 2. If D is "INVALID", output "INVALID" and stop
    const d = _ecvrf_decode_proof(pi_string)
    if (d == 'INVALID') {
        return 'INVALID'
    }

    // 3. (Gamma, c, s) = D
    const gamma = d[0]
    const c = d[1]
    const s = d[2]

    // 4. H = ECVRF_hash_to_curve(suite_string, y, alpha_string)
    const y_point = _string_to_point(y)
    if (y_point == 'INVALID') {
        return 'INVALID'
    }

    const h = _ecvrf_hash_to_try_and_increment(SUITE_STRING, y_point, alpha_string)
    if (h == 'INVALID') {
        return 'INVALID'
    }

    // 5. U = s*B - c*y
    const s_b = BASE.mul(s)
    let c_y = y_point.mul(c)
    // Negate c_y
    c_y = c_y.neg()
    const u = s_b.add(c_y)

    // 6. V = s*H - c*Gamma
    const s_h = h.mul(s)
    let c_g = gamma.mul(s)
    // Negate c_g
    c_g = c_g.neg()
    const v = s_h.add(c_g)

    // 7. c’ = ECVRF_hash_points(H, Gamma, U, V)
    const cp = _ecvrf_hash_points(h, gamma, u, v)

    // 8. If c and c’ are equal, output ("VALID", ECVRF_proof_to_hash(pi_string)); else output "INVALID"
    if (c.eq(cp)) {
        return {
            status: 'VALID',
            pi_string: ecvrf_proof_to_hash(pi_string)
        }
    }
    else{
        return 'INVALID'
    }
}
// section 5.4.3. ECVRF Hash Points
/**
 * ECVRF_hash_points(P1, P2, ..., PM)
 * @param {*} p1 an EC points in G
 * @param {*} p2 an EC points in G
 * @param {*} p3 an EC points in G
 * @param {*} p4 an EC points in G
 * @retrun c hash value, integer between 0 and 2^(8n)-1
 */
function _ecvrf_hash_points(p1, p2, p3, p4) {
    // 1. two_string = 0x02 = int_to_string(2, 1), a single octet with value 2
    const two_string = Buffer.alloc(1, 2)

    // 2. Initialize str = suite_string || two_string
    let string = Buffer.concat([SUITE_STRING, two_string])

    // 3.for PJ in [P1, P2, ... PM]:
    //       str = str || point_to_string(PJ)
    string = Buffer.concat([string, _point_to_string(p1), _point_to_string(p2), _point_to_string(p3), _point_to_string(p4)])

    // 4. c_string = Hash(str)
    const c_string = _hash(string)

    // 5. truncated_c_string = c_string[0]...c_string[n-1]
    const truncated_c_string = c_string.slice(0, 16)

    // 6. c = string_to_int(truncated_c_string)
   const c = _string_to_int(truncated_c_string)

    // 7. Output c
    return c
}

Specify condition in script in laravel

enter image description here

I have pasted the complete code of script:

 <script>
     var SITEURL = "{{ url('/') }}";
      var today = moment();
      $('#calendar').fullCalendar({
                     defaultView: 'week',
      
                      visibleRange: {
                      start: moment('<? echo $dateFrom;?>T00:00:00'),
                      end: moment('<? echo $dateTo;?>T24:00:00')
                    } ,
                    header: {
                        
                        left: '',
                        center: 'title',
                        right: ''
                      },
                    
                    editable: true,
                    eventLimit: true, // allow "more" link when too many events
                    schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
                       views: {
                        week: {
                           
                             type: 'timeline',
                            slotLabelInterval: { hours: 24},
                            slotDuration: { hours: 24},
                        }
                    },                
                    resourceLabelText: 'Time Slot',
                  
                    resources: [
                        
                        { id: '1', title: '08:00 - 08:30' , eventColor: 'green'},
                        { id: '2', title: '08:30 - 09:00', eventColor: 'green' },
                        { id: '3', title: '09:00 - 09:30', eventColor: 'green'  },
                        { id: '4', title: '09:30 - 10:00', eventColor: 'green'},
                        { id: '5', title: '10:30 - 11:00', eventColor: 'green' },
                        { id: '6', title: '11:30 - 12:00', eventColor: 'green'},
                        { id: '7', title: '12:30 - 13:00', eventColor: 'green' },
                        { id: '8', title: '13:30 - 14:00', eventColor: 'green'},
                        { id: '9', title: '14:30 - 15:00', eventColor: 'green' },
                        { id: '10', title: '15:30 - 16:00', eventColor: 'green'},
                        { id: '11', title: '16:30 - 17:00', eventColor: 'green' },
                        { id: '12', title: '17:30 - 18:00', eventColor: 'green'},
                        { id: '13', title: '18:30 - 19:00', eventColor: 'green' },
                        
                        ],
      
                    events: [
                      <?php
         
           foreach ($data as $sl => $valuegm){
             
  
         ?>
                      { id: '<?php echo $valuegm->id; ?>', 
                      resourceId: '<?php echo $valuegm->timeslot_id; ?>',
                      start: '<?php echo $valuegm->date; ?>',
                      end: '<?php echo $valuegm->date;?>', title: '',
                      description: '<?php if(!$valuegm->doctor_id==null)
                      {echo "<b>".$valuegm->get_doctor->name."</b><br/>".$valuegm->get_doctor->get_specialty->name."<br/>
                      Mobile:".$valuegm->get_doctor->mobile."<br/>
                      Address:".$valuegm->get_doctor->address."<br/>";?><? if(!$valuegm->get_doctor->email==null)
                      { echo "Email:".$valuegm->get_doctor->email."<br/>";}?>
                      <? echo "City:".$valuegm->get_doctor->get_city->description."<br/>";?>
                      <? if(!$valuegm->get_doctor->area_id==null){ echo "Area:".$valuegm->get_doctor->get_area->name."<br/>";}?>
                      <?}else{echo "<b>".$valuegm->get_pharmacy->name."</b><br/>Mobile:".$valuegm->get_pharmacy->mobile."<br/>
                      Address:".$valuegm->get_pharmacy->address."<br/>";?>
                      <? if(!$valuegm->get_pharmacy->email==null){ echo "Email:".$valuegm->get_pharmacy->email."<br/>";}?>
                      <? echo "City:".$valuegm->get_pharmacy->get_city->description."<br/>";?>
                      <? if(!$valuegm->get_pharmacy->area_id==null){ echo "Area:".$valuegm->get_pharmacy->get_area->name."<br/>";}?><?}?>
                      
                    
                    
                    
                      
                      <?php $f = $valuegm->rating; if ($f == 1) { echo "Rating: Positive"; } elseif ($f == 2) { echo "Rating: Netural"; }elseif ($f == 3) { echo "Rating: Negative"; }?>
                      
                      
                    
                    
                    
                      
                      <?php echo "<p>".$valuegm->feedback."</p>";?><br/>',url: SITEURL + '/search/<?php echo $valuegm->id;?>/<?php echo $dateFrom;?>/<?php echo $dateTo;?>'},
                      <?php }?>],
                      
                                          
        eventRender: function(event, element) { 
            element.find('.fc-title').append("<br/>" + event.description ); 
            
        } 
      
                });
   </script>
  

Actually i am working with this part : if the doctor review is positive then background color should be green ,if the doctor review is negative then background color should be red. but now we have specifyed as green. Actually i am working with how to specify the background color based on the feedback of the customer in this below code.

resources: [

                    { id: '1', title: '08:00 - 08:30' , eventColor: 'green'},
                    { id: '2', title: '08:30 - 09:00', eventColor: 'green' },
                    { id: '3', title: '09:00 - 09:30', eventColor: 'green'  },
                    { id: '4', title: '09:30 - 10:00', eventColor: 'green'},
                    { id: '5', title: '10:30 - 11:00', eventColor: 'green' },
                    { id: '6', title: '11:30 - 12:00', eventColor: 'green'},
                    { id: '7', title: '12:30 - 13:00', eventColor: 'green' },
                    { id: '8', title: '13:30 - 14:00', eventColor: 'green'},
                    { id: '9', title: '14:30 - 15:00', eventColor: 'green' },
                    { id: '10', title: '15:30 - 16:00', eventColor: 'green'},
                    { id: '11', title: '16:30 - 17:00', eventColor: 'green' },
                    { id: '12', title: '17:30 - 18:00', eventColor: 'green'},
                    { id: '13', title: '18:30 - 19:00', eventColor: 'green' },

                    ],

i have specifyed the particular line for fetching review(please refer the complete code for
better understanding). please try figure out this:

              <?php $f = $valuegm->rating; if ($f == 1) { echo "Rating: Positive"; } elseif ($f == 2) { echo "Rating: Netural"; }elseif ($f == 3) { echo "Rating: Negative"; }?>

Iterating over a styled component in REACT produces warning “Over 200 classes were generated for component”

I’m new to React and am trying to animate some elements from an array using the ReShake.js library. Here’s my code:

import { ShakeHorizontal } from 'reshake'
const state = {
    invalidWordSubmitted: true,
}
const isInvalidWordSubmitted = () => {
  return state.invalidWordSubmitted ? '.invalidWordSubmitted' : ''

}

// here is the bit that I think is causing the problem:

           <div id="gameBoard" className="gameBoard">         
        {board.map((row, rowNumber) =>
          row.map((letter, colNumber) => (
            <span
              key={colNumber}
              className={`${getCellStyles(
                rowNumber,
                colNumber,
                letter
              )} letterTile`}
            >
              <ShakeHorizontal trigger={`${isInvalidWordSubmitted()}`}>
              {letter}
              </ShakeHorizontal>
            </span>
          ))
        )}
      </div>

It works ok, but there is serious lag in the browser, and the console shows me the following warning: react_devtools_backend.js:4045 Over 200 classes were generated for component styled.div with the id of "sc-bdvvtL"

Should I be adding unique ids to each of the iterated <ShakeHorizontal> components?
I couldn’t find anything in the docs: https://github.com/elrumordelaluz/reshake/tree/master/src

Add MapBox map in a html video tag

I have a MapBox map object

<div class="#" id="map">
var map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/hybrid/style.json?key=mykey'

});

I would like to add this map on a html video tag like this beautiful example https://www.matsim.org/gallery/paris.
I tried this without success

<video src="">
   <div class="#" id="map"></div>
</video>

Could you please help me if there exist a solution?

React hooks cause unintentional re-render

thanks for reading. I’m working with a React/Leaflet map and noticing the map container / elements re-render any time I show or close a modal. I’ve created a sandbox to demonstrate the problem but this occurs in other places throughout my app if additional examples would help.

https://codesandbox.io/s/elegant-rain-01f9l?file=/src/App.js

From reading alternative SO posts, such as this very similar one, I recognize this is likely caused by my hooks (ex. handleShow/setShow) which force the entire component to re-render. The unintended behavior is noticed as follows:

If you drag the map so that the current location is out of view and open a modal, we force the re-load of and . This is evident because the map re-pans to the current location, and a new ‘search icon’ appears in the top right on the map.

Steps to replicate:

*If you notice an issue in sandbox related to react-bootstrap/Modal, just update the dependency to latest (refresh icon) – this is a weird sandbox issue but unrelated to my question.

  1. Drag map so that current location is out of view
  2. Click menu icon (top right) > Add Location
  3. When modal appears, notice map re-centers to current location and another search icon appears.

I can’t download the pdf file with FileStreamResult when I call it from ajax

I am trying to call my FileStream Result function from an ajax, the question is that it is calling the method and it does everything inside, I checked this with a breakpoint, but at the end it is not downloading the pdf I want. Before it was downloading and it was calling it from
like this: “using (Html.BeginForm("EmisionAllLabel", "WareHouseReceipt", FormMethod.Post))“. But now I need to do it from an ajax but it doesn’t work for me. Maybe it’s because I’m missing something but I don’t have much experience with ajax regarding this and I can’t identify the problem. I appreciate your comments.
Attached are the codes used:

    $('#btnValidarEmision').on("click", function () {

        let emisionguia = $('#guiaAerea').val();
        $.ajax({
            url: "/WareHouseReceipt/" + "EmisionEtiqueta",
            type: "POST",
            data: { "guiaAerea": emisionguia },
            success: function (saved) {

            },
            error: function () {
                console.log("Error");
            }
        });
    });

FileStreamResult

public FileStreamResult EmisionEtiqueta(string guiaAerea)
{

    IList<ICriterion> criterionlist = new List<ICriterion>();
    criterionlist.Add(Expression.Eq("Econtainer", true));
    criterionlist.Add(Expression.Eq("StatusId", 1));
    criterionlist.Add(Expression.Eq("Emision", false));
    IList<VwWareHouseReceipt> etiquetas = vwWarehouseReceiptDao.findByCriteria(criterionlist);


    //mem buffer
    MemoryStream ms = new MemoryStream();



    //the document
    Document document = new Document(new Rectangle(float.Parse("289.50"), 370, 0, 0));

    BaseFont bf2 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

    BaseFont helveticanormal = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, true);
    BaseFont helveticanegrita = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, true);

    //create the fonts
    BaseFont timesNormal = BaseFont.CreateFont(BaseFont.TIMES_ROMAN,
                                               BaseFont.CP1252,
                                               BaseFont.NOT_EMBEDDED);

    Font fontSmall = new Font(timesNormal, 7, Font.NORMAL);

    Font fontNormal = new Font(timesNormal, 9, Font.NORMAL);

    Font fontH1 = new Font(timesNormal, 16, Font.NORMAL);

    //the writer
    PdfWriter writer = PdfWriter.GetInstance(document, ms);//fs);

    // step 3: we open the document
    document.Open();

    for (int i = 0; i < etiquetas.Count; i++) { 
    

    }
    document.Close();

    //close the document
    // document.PageSize = PageSize.HALFLETTER;
    //document.PageSize = PageSize.

    //prepare output stream
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=EtiquetasEmisionEcont" + guiaAerea + ".pdf");
    Response.Buffer = true;
    Response.Clear();
    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.End();

    return new FileStreamResult(Response.OutputStream, "application/pdf");

Note: I deleted the “for” so that there would not be too much text.

Pass by reference – what is the better way to reassign the value of the property?

let spaceShip = {
   homePlanet : 'earth',
   color: 'black
}



//first way to reassign the value of the property
let reassign = obj => {
  obj.homePlanet = 'mars';
};
 
reassign(spaceShip);

//second way to reassign the value of the property
spaceship.homePlanet = 'mars'

What is the difference?? and What is the better way to do it??
Is both way changes the value permanantly??