Making neat variable lists from multiple arrays to use as ‘clean’ arguments in a later function (javascript)

okay I’m pretty noob but have been enjoying the recursive-ness of js

I’m [hopefully] making expandable info boxes that operate independently.

Instead of making 5 different animation/onClick() behaviours for each one, I figure I’ll name all the elements to a specification i made up (because sadly i’m in wix/velo and I need to refer to them as $(‘#element’), etc) and then generate an object that contains the strings to plug in as arguments.
After some mind blowing moments, I was successful (yes I’m dumb).
here is my final output that gives me each category and their array with the strings

heres the code if the image didn’t load:

let parts = ["Win')", "List')", "Text')", "ArL')", "ArR')"];
let cats = ["$w('fam", "$w('mwl", "$w('aes", "$w('hrm"];

function merger(c, p) {
   let result = [];
   let i;
   for (i = 0; i != p.length; i++) result[i] = c + p[i];
   return result;
}

const final = {
   fam: merger(cats[0], parts),
   mwl: merger(cats[1], parts),
   aes: merger(cats[2], parts),
   hrm: merger(cats[3], parts)
};
//object made with category: [string1, string2,...] for each
console.log (final);

I know {final} could be improved but that brings me to my actual question(s).

My animation/onClick() function (not pictured, happens after); if it was to run independently for each category, it needs the strings in the array of each category, which thankfully I managed to generate.

However I’d rather not refer to them literally from the array like categoryStr[0] because then I’d still kinda have to copy/paste the function [i] times for each category, no?

So how can I turn all the strings in each array of this object I’ve made into objects themselves, so that way the functions I do later only need to refer to a single object like ‘for each {category}Str.Text” instead of for famStr[i], for hrmStr[i], etc.

Like later I’d hope to make a for loop or something that executes my future “interactiveFunction(category)” for all my categories using each of their variable lists in a tidy way, but hitting that goal is just beyond me, I figure I can do that if the variable list is clean and I just reference a neat object like ‘category.param’ instead of ‘category[2]’. idk data types and valid references haven’t quite settled for me yet. I figure a first post would usually be embarrassing but hey I’m drunk, head-scratching, and an outside perspective from StackOverflow peeps would really help me rn along with all the docs i’ve been reading. Maybe it’s time to hire a tutor…

Uv map not loading correctly in three.js

My uv map is loading like it’s one side of a block:
enter image description here

Here is my code:

    const grass = new THREE.TextureLoader().load( 'https://raw.githubusercontent.com/Isaiah08-D/namelater/main/textures/blocks/grass.png' );
    
    
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({map:grass});
    ...

  var noise = new noisejs.Noise(Math.random());



    for (let x=0; x < 201; x += 10) {
      for (let z=0; z<201; z+=10) {
        //const chunk = getChunk(x, z)
        const cube = new THREE.Mesh(geometry, material)
        cube.position.x = x
        cube.position.z = z
        cube.position.y = noise.perlin2(x/100, z/100) * 100;
        cube.scale.set(10,10,10);
        blocklist.push(cube);
        scene.add( cube );
      }
    };

And you can find the uv map here.
What is wrong? Thanks in advance!

R script calling in PHP for online statistical analysis of the HTML input data

After the varibles as $alldata; I wrote this for call an R script called rCommands

        echo "<p>Saving the received json into file dataReceived/input_".$timeStamp.".json</p>"; 
        file_put_contents("dataReceived/input_".$timeStamp.".json", json_encode($allData)); 
        echo "<p>Calling R code to compute min, mean, and max values</p>";
        exec("Rscript rCommands.txt ".$timeStamp);
        echo "<p>Parsing the result dataReceived/output_".$timeStamp.".json of the R code</p>";
        $result = json_decode(file_get_contents("dataReceived/output_".$timeStamp.".json"), true);
        echo "<p>Result: ".print_r($result, true)."</p>";```

Here the R code in which I want to obtain a data.frame, and then use for the statistical analysis
library("RJSONIO")
args = commandArgs(trailingOnly=TRUE)
if (length(args) != 1) {
  stop("Exactly one argument must be supplied (timestamp).n", call.=FALSE)
}
allData<- fromJSON(paste("dataReceived/input_", args[1], ".json", sep = ""))
data= as.data.frame(allData)
x <- toJSON(data)
fileConn<-file(paste("dataReceived/output_", args[1], ".json", sep = ""))
writeLines(x, fileConn)
close(fileConn) ```

Material table datasource storing data in filteredData property instead of data property

In my angular project, I have a table on a page that contains a list of bank accounts with their balance and other data etc (ref pic below).
Bank list table

My aim is to make table entries clickable so that every time someone clicks a row in the table, another component that contains bank transactions in a material table, Bank Ledger, opens in a dialog and shows record of the corresponding bank account, row of which has been clicked in the Bank Balance table.

To do that, I send account number to a function in service which pushes it to an observable subject. And the bank ledger component is subscribed to the aforementioned observable. Refer below code:

Component on which Bank Balance table is:

  constructor(private Fin:Finservice) {}

  acnum:number;

  viewBankLedger(): void {
    const dialogRef = this.dialog.open( BankledgerComponent , { width: '40vw', height: '80vh', disableClose: true, panelClass: "foo" } ); 
  }

  openLedger(row) {
    this.acnum = row.bank_acnum;
    this.Fin.getBankACNum(this.acnum);
    this.viewBankLedger();
  }

Fin Service:

  private _subject = new Subject<any>();
  changebank = this._subject.asObservable();

  getBankACNum(acnum: number){
    this._subject.next(acnum);
  }

Bank Ledger component:

export class BankledgerComponent implements OnInit {

  constructor(private Fin: Finservice, private LS: LedgerService) {}

  ngOnInit() {
    this.Fin.changebank.subscribe( result => {
      this.acnum = result;
      const bankACNum = {
        acnum: this.acnum,
      };
      this.getLedger(bankACNum);  
    })
  }
  
  BankLedgerDataSource = new MatTableDataSource<BankLedger>();
  bankLedger: BankLedger[];
  acnum:number;
  ledgerColumns: string[] = ['serial', 'bl_date', 'bl_part', 'bl_debit', 'bl_credit', 'bl_balance'];

  getLedger(bankACNum:ACNum){
    this.LS.showBankLedger(bankACNum).subscribe((results:BankLedger[])=>{
      this.bankLedger = results;
      this.BankLedgerDataSource.data = this.bankLedger;
      console.log(this.BankLedgerDataSource);
    })
  }

}

Bank Ledger template:

<div mat-dialog-content style="background-color: white; border-radius: 5px; padding: 1%;">

        <table style="width: 100%;" mat-table [dataSource]="BankLedgerDataSource" class="mat-elevation-z8">
            
        <ng-container matColumnDef="serial">
            <th mat-header-cell *matHeaderCellDef> S.No. </th>
            <td mat-cell *matCellDef="let element; let i = index;"> {{i+1}} </td>
        </ng-container>
                
        <ng-container matColumnDef="bl_date">
            <th mat-header-cell *matHeaderCellDef> Date </th>
            <td mat-cell *matCellDef="let element">{{element.bl_date | date:'dd/MM/yyyy'}} </td>
        </ng-container>
                
        <ng-container matColumnDef="bl_part">
            <th mat-header-cell *matHeaderCellDef> Particulars </th>
            <td mat-cell *matCellDef="let element"> {{element.bl_part}} </td>
        </ng-container>

        <ng-container matColumnDef="bl_debit">
            <th mat-header-cell *matHeaderCellDef> Debit Amount</th>
            <td mat-cell *matCellDef="let element"> {{element.bl_debit  | INRCurrency}} </td>
        </ng-container>

        <ng-container matColumnDef="bl_credit">
            <th mat-header-cell *matHeaderCellDef> Credit Amount</th>
            <td mat-cell *matCellDef="let element"> {{element.bl_credit  | INRCurrency}} </td>
        </ng-container>
            
        <ng-container matColumnDef="bl_balance">
            <th mat-header-cell *matHeaderCellDef> Balance </th>
            <td mat-cell *matCellDef="let element"> {{element.bl_balance  | CreditDebit}} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="ledgerColumns"></tr>
        <tr class="tablerow" mat-row *matRowDef="let row; columns: ledgerColumns;"> </tr>

    </table>
La la la
</div>

<div mat-dialog-actions style="margin-top: 2%; border-top: 1px solid black;">
    <button type="button" class="btn btn-outline-dark" [mat-dialog-close]="true">Close</button>
</div>

As you can see above, have subscribed to the subject, created a json package and sent it to a method that retrieves corresponding data from the api using another service, called Ledger Service.

export class LedgerService {

  constructor(private httpClient: HttpClient) { }
  
showBankLedger(acnum: ACNum): Observable<BankLedger[]> {
    return this.httpClient.post<any>(`${this.PHP_API_SERVER}/apiroute.php`, acnum);
  }

While everything should work fine, I am facing multiple problems God kows why. Here are the problem I am facing:

  1. After the component that contains Bank Balance table loads for the first time; the first time I click any row, the dialog pops up but data does not seem to go through because there are no logs in the console.

  2. After I close the dialog, second click onward, data does seem to go to the Bank Ledger Component, but the table does not show any data. Also, data gets stored din the filteredData property of MatDataSource.

Console log of bankLedger property

Console log of BankLedgerDataSource

  1. The results after are same 3rd click onward, but with an exception; after the 3rd click, console logs data 2 times instead of 1. In the 4th click, data is logged 3 times. And it continues so on and so forth.

Console log of corresponding clicks

Please help. I am stumped.

How to override javascript function “_title_changed” in webclient odoo

My goal is to change the Page title using the company name. I am trying to change the function but still there’s no effect. Any idea on how to achieve this?

var session = require('web.session');
var AbstractWebClient = require('web.AbstractWebClient');

AbstractWebClient.include({
    _title_changed: function () {
        this._super();
        var company_name = session.user_companies.current_company[1];
        document.title = company_name;
        console.log('_title_changed function');
    },
});

Fluent UI style not working in passed commands with buttons to CommandBar

i am using Fluent UI in my project. I dont know how to change hoover style in CommandBar.

I initializing my buttons with this simple code in javascript:

// inside `buttons` array
key: 'newfolder',
text: 'New Folder',
iconProps: { 
    iconName: 'NewFolder',
        styles: {
           root: { 
              color: 'orange' 
           }, 
           rootHovered: { 
              color: 'red' 
           }
    } 
},
onClick: ...

Then i am passing this buttons to CommandBar:

<CommandBar
    items={buttons}
        styles={{
            root: {
                paddingLeft: '5px'
            },
    }}
/>

and i can override default color to asked one.
enter image description here

My question is, how to set mouse hover color over button in CommandBar component? enter image description here

As you can see, it is still blue even if i passed red as rootHovered color

Boolean flickering from true to false

I’m trying to switch the position of an element between fixed and absolute based on how close the element is to the other. So I have a button which is fixed from the top to the bottom till it’s bottom value + 25px is less or equal to footers y value so that it stops to the top. My problem is that the button stops in the right place so the switch from fixed to absolute goes well but while the relative position of the button to the footer are negative the boolean which toggles the classes of the button flickers between true and false so that it goes from absolute to fixed back and forth very quickly.

This is my code that is tracking the position & switching the boolean:

Is there a logic issue or what? I cannot figure this out:(

var button = document.querySelector('.bottomCtaFixed')
            var footer = document.querySelector('.footer')
            window.addEventListener('scroll', (e) => {

                var buttonRect = button.getBoundingClientRect()
                var buttonBottom = buttonRect.bottom + 25

                var footerRect = footer.getBoundingClientRect()
                var footerTop = footerRect.y

                var relativePos = footerTop - buttonBottom
                console.log('button', buttonRect)
                console.log('footer', footerRect)
                console.log('buttonBottom', buttonBottom)
                console.log('relativePos', relativePos)

                if(relativePos <= 0) {
                    this.isStill = true
                    if(footerTop >= buttonBottom) {
                        this.isStill = false
                    } else {
                        this.isStill = true
                    }
                } else {
                    this.isStill = false
                }
                console.log(this.isStill)
            })

And here’s the classes:

.bottomCtaFixed {
        position: fixed;
        bottom: 25px;
        left: 25px;
        margin-top: 25px;
        width: calc(100% - 50px);
        z-index: 101;
        @media screen and (max-width: 290px) {
            display: none
        }
        @media screen and (min-width: $bp-xs) {
            display: none
        }
    }
    .bottomCtaStill {
        position: absolute; 
        top: calc(-9vh - 25px);
        left: 25px;
        width: calc(100% - 50px);
        z-index: 101;
        @media screen and (max-width: 290px) {
            display: none
        }
        @media screen and (min-width: $bp-xs) {
            display: none
        }
    }

Understand the following exercise of js loops and strings in array

I’m trying to make sense of the following javascript exercise but can’t seem to make sense of it, all I know for now is that I can access each string with “acrostic[i]” where the i would be the number in the array but don’t know where to go from there.

const acrostic = [
  "Give me your patience, sister, while I frame",
  "Exact in capitals your golden name;",,
  "Or sue the fair Apollo and he will",
  "Rouse from his heavy slumber and instill",
  "Great love in me for thee and Poesy.",
  "Imagine not that greatest mastery",
  "And kingdom over all the Realms of verse,",
  "Nears more to heaven in aught, than when we nurse",
  "And surety give to love and Brotherhood.",
  " ",
  "Anthropophagi in Othello's mood;",
  "Ulysses storm'd and his enchanted belt",
  "Glow with the Muse, but they are never felt",
  "Unbosom'd so and so eternal made,",
  "Such tender incense in their laurel shade",
  "To all the regent sisters of the Nine",
  "As this poor offering to you, sister mine.",
  " ",
  "Kind sister! aye, this third name says you are;",
  "Enchanted has it been the Lord knows where;",
  "And may it taste to you like good old wine,",
  "Take you to real happiness and give",
  "Sons, daughters and a home like honied hive."
];

/* Declare a variable that will return the final string */
let georgianaAugustaKeats = "acrostic[i][0]";

for (let i = 0; i < acrostic.length; i += 1) {
  /* add each first character of each string to the array
   to the georgianaAugustaKeats variable*/
 
}
console.log(georgianaAugustaKeats);

How to create 500 error with the help of PHP

How to create error with PHP like 500 (Internal server error), 502 (bad gateway) and 521 (Web server is down)

I am not asking how to prevent or custom error page. I want to create issues/error to my server.

What code with PHP or Javascript i can do to bring my website/webserver down.?

Note : I am not attempting hacking to someone. I want to down my own web server temporary for testing and personal work.

Issue related to Js/React arrays

I’m creating an array indexes in which i’m appending values(this will later be used in a map function).

let indexes = [];
export default function SortTiles() {

    let num = info.num_tiles;
    for (let i = 10; i < num+10; i++) {
        indexes = [...indexes, i];
    }
    console.log(indexes);
    console.log("UWU")

    return(
        <div id={"sort-tiles"}>
            {/*{indexes.map(makeTiles)}*/}
        </div>
    )
}

But when i’m trying to console.log my array this is the output i’m getting:
The output image
The output is being printed twice and the numbers in the array is also duplicated.

An error while changing text with javascript

I’m using google recaptcha with my django project. But it is not English. So I want to change its writing with javascript.

html

{% extends 'base.html' %}
{% block content %}
<div class="form-body">
    <div class="row">
        <div class="form-holder">
            <div class="form-content">
                <div class="form-items">
                    <h1>Registration</h1>
                    <br><br>
                    <form class="requires-validation" method="POST" novalidate>

                      {% csrf_token %}
                      {{form.as_p}}
                        <div class="form-button">
                            <button id="submit" type="submit" class="btn btn-primary">Register</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
  document.querySelector('recaptcha-anchor-label').innerHTML = "I'm not a robot";

</script>

{% endblock %}

After I did that it won’t apply the html in browser. Below the error message:

Cannot set properties of null (setting ‘innerHTML’)

Axios POSTing data records to Dynamo, but unable to Axios GET request to find – Javascript/Typescript

I have the following code for POSTing a record via axios to my DB, and then I would like to search for said record by its ID match as well as list all the latest records.

I have confirmed, via checking Dynamo, that the record gets added to the DB but cannot get it to appear when I look for it via the GET /search.

It makes me wonder if I’m somehow making a mistake.

I know that my database has 6000+ records of this same type, so I could just be getting unlucky (as I have not yet included pagination in my queries)… but I’ve tested this about 50 times with 0 retrieval success via the query vs running the same POST and GET via Postman and having about a 50% success rate.

test('post result then search for presence', async () => {
    const trafficAnalyticMessage = buildTrafficAnalyticMessage();

    const result = await axios.post(messagesUrl, trafficAnalyticMessage, {
      headers: {
        'x-api-key': 'redacted',
      },
    });

    const message = result.data as dataMessageApi.Message;
    logger.log(`Message ${util.inspect(message)}`);
    // logger.log(`Result ${util.inspect(result)}`);

    const results = await axios.get(searchUrl, {
      headers: {
        'x-api-key': 'redacted',
      },
      params: {
        type: 'analytic',
        subtype: 'traffic_volumes',
        startTime: 1,
      },
    });

    logger.log(
      'Attempting to search for message with id: ' + JSON.stringify(message.id),
    );

    const messages = results.data as dataMessageApi.Message[];
    const found = messages.find((m) => m.id === message.id);

    logger.log('Message returned from search: ' + JSON.stringify(found));
    // expect(found).toBeDefined();

    let date: string;
    // log length, first and last msg id
    logger.log(`Length of search response:  ${messages.length}`);
    // 1
    logger.log('First ID:  ' + JSON.stringify(messages[0].id));
    date = new Date(messages[0].timestamp!).toUTCString();
    logger.log(`First timestamp: ${date}`);
    // 2
    logger.log('Second ID:  ' + JSON.stringify(messages[1].id));
    date = new Date(messages[1].timestamp!).toUTCString();
    logger.log(`Second timestamp: ${date}`);
    // 3
    logger.log('Third ID:  ' + JSON.stringify(messages[2].id));
    date = new Date(messages[2].timestamp!).toUTCString();
    logger.log(`Third timestamp: ${date}`);
    // 4
    logger.log('Fourth ID:  ' + JSON.stringify(messages[3].id));
    date = new Date(messages[3].timestamp!).toUTCString();
    logger.log(`Fourth timestamp: ${date}`);
    // Fifth from last
    logger.log(
      'Fifth from last ID:  ' +
        JSON.stringify(messages[messages.length - 5].id),
    );
    date = new Date(messages[messages.length - 5].timestamp!).toUTCString();
    logger.log(`Fifth to last timestamp: ${date}`);
    logger.log(
      'Fourth from last ID:  ' +
        JSON.stringify(messages[messages.length - 4].id),
    );
    date = new Date(messages[messages.length - 4].timestamp!).toUTCString();
    logger.log(`Fourth from last timestamp: ${date}`);
    logger.log(
      'Third from last ID:  ' +
        JSON.stringify(messages[messages.length - 3].id),
    );
    date = new Date(messages[messages.length - 3].timestamp!).toUTCString();
    logger.log(`Third from last timestamp: ${date}`);
    logger.log(
      'Second to last ID:  ' + JSON.stringify(messages[messages.length - 2].id),
    );
    date = new Date(messages[messages.length - 2].timestamp!).toUTCString();
    logger.log(`Second to last timestamp: ${date}`);
    logger.log('Last ID:  ' + JSON.stringify(messages[messages.length - 1].id));
    date = new Date(messages[messages.length - 1].timestamp!).toUTCString();
    logger.log(`Last timestamp: ${date}`);

    expect(result).toBeDefined();
    expect(result.status).toBe(201);
  });

This is the output I am getting:

enter image description here

Any help would be greatly appreciated.

**Also, please can you advise me how to add the GET as a .then result of the POST? Or a promise or some kind of 2-part resolution? I have had great trouble figuring out how that works. I’m new to this kind of work.

Thanks so much!!**

what happend re-define setInterval to variable in useEffect hook?

I want to know what happened if I define setInterval function repeatedly to same variable in react hook useEffect.

I checked variable have new setInterval id value every defining.
But I wonder is there instance remained in memory about previous setInterval timer, even if new setInterval defined at same variable??

 useEffect(() => {
    const timer = setInterval(
      () => {
        if (count < elementLength - 1) {
          boolean.current = false;
          setCount(prev => prev + 1);
        } else {
          boolean.current = true;
          setCount(0);
        }
      },
      boolean.current ? 50 : 2500
    );

    return () => {
      clearInterval(timer);
    };
  }, [count]);

The best way to refresh paginated data on the client side?

I have a REST API that implements server-side pagination returning the following data:

{
  items: [
    {
      id: 1,
      name: 1
    },
    {
      id: 2,
      name: 2
    }
  ],
  nextToken: <some-hash-key> // cursor-based
}

How should the client application refresh the list if the resource gets updated (client isn’t aware of the update, so this is a pull model)? I have some ideas:

  1. fetch all resources at a regular interval (like every 10 seconds)
  2. maintain a session ID that rotates every N minutes. When a new session is created, fetch all resources

Both approaches are fundamentally the same idea. The first approach is more costly but allows more real-time updates. The second approach is based on session ID which I think is more idiomatic, but no real-time updates. Is there any other approach?