Thursday, July 29, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to get the array values from different arrays into a single using PHP?

Posted: 29 Jul 2021 08:49 AM PDT

I have an array-like:

Array  (      [0] => 4      [1] => 1861  )  Array  (      [0] => 4      [1] => 1938  )  Array  (      [0] => 4      [1] => 1452  )  Array  (      [0] => 4      [1] => 1938  )  Array  (      [0] => 21  )  

This is a single array contain this array of elements. I need the result like :

$arr = array(4,1861,1938,1452,21);  

That means I need the only array unique values from these arrays. For this, I am using array_walk_recursive(), array_merge() etc. But I didn't get my results.

Extract frame from MP4 without FFMPEG

Posted: 29 Jul 2021 08:49 AM PDT

I'm running a php site on shared hosting, so FFMPEG isn't available. What other options do I have for extracting the first frame as a JPG when a user uploads a video file.

Is there any way to use composition to alter the CSS of an web-component with a shadow dom?

Posted: 29 Jul 2021 08:49 AM PDT

my team lead has decided to use LitElement to create framework-agnostic web components, which makes sense, as we're creating a company-wide UI library that would be ideal to be used with Vue2, Vue3, React, Preact, and others.

However, I'm extremely worried about styling. Right now with our current (Vue 2) based UI library, if one of our teams needs to override the internal styling of an element for whatever reason (usually edge cases), one of the things they can do is use CSS Composition in order to do exactly that. Something like:

// in components/my-element.js  class MyElement extends LitElement {    render(){      return html`        <div class="stackui-my-element">          <p class="paragraph">A paragraph</p>        </div>      `;    }  }  customElements.define('my-element', MyElement);    // in app/businessthing.js  import React from 'react';  import {css} from 'styled-components'  const customCSS = css`    .this-thing {      & .stackui-my-element .paragraph {        border: 2px dotted pink;      }    }  `  export default (props) => <div class="this-thing"><my-element /></div>  

As far as I can tell, the above code won't work ("My Paragraph" would not be surrounded with pink polka dots) because MyElement has its own shadow dom, and you can't reach in it from without to change the styles of the element.

Is there some sort of exception to the rule, or can you reach inside the shadow dom somehow? Other than losing CSS encapsulation, what are the other effects of disabling the shadow dom?

Problem in removing localhost name for deploying Next.js

Posted: 29 Jul 2021 08:49 AM PDT

So, I am working on an important next.Js project. And I am stuck while trying to change some api's. For example,

import axios from "axios";    export const fetchCategories = async (id = false) => {    try {      if (id === false) {        let response = await axios({          method: "get",          url: `http://localhost:3000/api/category/create`,          json: true,        });        return response;      }   

This function is a component that makes an axios request to the next.js own server localhost, is there a way to change this url to get the actual dinamic route instead of a hardcoded one like this? I know there's a way I'm just struggling with this problem.

Batch file that searches cmdline output for keyword and displays the previous line(x5)

Posted: 29 Jul 2021 08:49 AM PDT

I have a batch file that runs a command in the command line and searches the output for a keyword. It then outputs the line previous to the line with the keyword.

For example: Search for KEYWORD

PREVIOUS LINE

KEYWORD

result: PREVIOUS LINE

The code is as follows

set Output="pnputil -e"  FOR /F "eol=. tokens=*" %%a IN ( '%Output%' ) DO (      set line=%%a      set ourline=!line:KEYWORD=!      if not !line!==!ourline! (          SET Output=!prev_line!      )      SET prev_line=%%a  )  echo Installed OEM file found as: !Output!  

I want to replicate this but the line I want is 5 lines previous to the keyword. The output I want is followed by 4 lines of random info with only one constant keyword 5 lines after it that I can search.

Laravel eloquent relation ship empty using select

Posted: 29 Jul 2021 08:49 AM PDT

here my code :

            $users = Classroom::with(['students.classrooms',                  'students' => function ($query) use ($search, $validated, $user) {                      $query->select('name', 'firstname', 'email', 'nickname', 'locale', 'timezone', 'classroom_user.created_at', 'avatar', 'lastConnection', 'level', 'level_ja', 'classroom_user.classroom_id', 'classroom_user.user_id');                                                                           },              ])                  ->whereIn('id', $classroom_ids)                  ->get()                  ->pluck('students')                  ->flatten();                $users = $users->paginate(10);  

Using the select method on "students" relation make "classrooms" empty in the result, but if i don't use the select method, classrooms is not empty.

My question : How to add students.classrooms relation in the select method in "students" relation ?

Thanks !

python fstring results in error with line breaks on CDSW/linux

Posted: 29 Jul 2021 08:49 AM PDT

I have a strange issue. This works:

a = 3   f"""a= {a}""" # works  

But this does not on the Cloudera Data Science Workbench (a unix system):

f"""a=  {a}"""  # error    Engine, line 1  "    ^  SyntaxError: EOL while scanning string literal  

On Windows I cannot recreate the problem and it did not use to be a problem on CDSW either. Has anyone had a similar problem or could point me towards what might cause such a problem?

Convert lstart to mysql timestamp

Posted: 29 Jul 2021 08:49 AM PDT

I have a bash script that gets the time a process started with ps lstart. So something like Thu Jul 29 14:48:08 2021.

I would like to insert it into a mysql column of type timestamp. I have tried to convert the lstart value like

timestamp=`date -d "${lstart}" +"%s"`  

but when trying to insert in the table the script complains that

incorrect datetime value: '1627570088' for column  

I can change the type from timestamp to another if it is the correct way.

The idea of this column is to use it to remove all rows with a start date older than a given datetime.

Express .use() callback gets called multiple times when using express.static()

Posted: 29 Jul 2021 08:49 AM PDT

I'm trying to authenticate user and once authenticated I want to create a new user in my own database with the data provided by authentication server.

The problem I am facing is that this createNewAccount() gets called 3 times. I don't exactly know why but once I removed the express.static('app/web') call this no longer happens. Still I need that call to serve static content, can someone tell me what I am doing wrong?

expressApp.use('/console',requiresAuth(),express.static('app/web'), (req,res)=>{      createNewAccount(req.oidc.user.email);  

});

How can I add hyperlink to table head column entries in react using material ui table?

Posted: 29 Jul 2021 08:49 AM PDT

// this is my header

const tableHeadCells = [      {id:"Customer_ID",label:"CustomerId"},      {id:"Type", label: "Type"},      {id:"First_Name", label: "First Name"},      {id:"Last_Name", label: "Last Name"},      {id:"Company_Name", label: "Company Name"},      {id:"Person Mobile", label: "Person Mobile"},      {id:"Person Email", label: "Person Email"},      {id:"Status",label: "Status"},      {id: "Date", label: "Date"}  ]  

// this is the table data

function createData(CustomerId,Type, First_Name,Last_Name, Company_Name, Person_Mobile,                       Person_Email,Status,Date) {    return {            CustomerId,Type, First_Name,Last_Name, Company_Name, Person_Mobile,             Person_Email,Status,Date};    }  

}

const tableBodyRowsData = [      createData(1,'COMPANY','Gaurav', 'Kumar', 'Complere Infosystem',923456789 ,                "Gaurav@gmail.com","ACTIVE","11/12/2019"),    createData(2,'COMPANY','Shyam', 'Lal', 'Complere Infosystem',913456789 ,                "Shyam@gmail.com","ACTIVE","11/12/2019"),    createData(3,'COMPANY','Ram', 'Lal', 'Complere Infosystem',933456789 ,                "ram@gmail.com","ACTIVE","11/12/2019"),    createData(4,'COMPANY','Sahil', 'Kumar' , 'Complere Infosystem',943456789 ,                "Sahil@gmail.com","ACTIVE","11/12/2019"),  

];

// this is the piece of code that I am using to display the head cells and data in table

<TableContainer>      <Table className={classes.table}>        <TableHead>          <TableRow>            {headCells.map( (item) => (              <TableCell                key={item.id}>                  {item.label}              </TableCell>            ))}          </TableRow>        </TableHead>        <TableBody>          {handleRecordsPaging().map( (item) => (            <TableRow               key={item.CustomerId}            >            {Object.values(item).map( (value) => (                <TableCell key={value}>{value}</TableCell>             ))}            </TableRow>          ))}        </TableBody>      </Table>    </TableContainer>  

// I want to know that how can I make the first column (Customer_ID) of the table clickable?, If I click on it, then it should go to the other page?

Firefox Ctrl-F with selected text to prime search bar

Posted: 29 Jul 2021 08:49 AM PDT

Does anyone remember when you could select text on the current browser page in Firefox or Chrome, and when you pressed Ctrl-F to open the search bar, the browser put the selected text in the search bar for you?

Is there an option or setting that will enable that. I haven't been able to do that in some time and I really miss that convenience.

How to use Sphinx autofunction for file outside module

Posted: 29 Jul 2021 08:49 AM PDT

I have a package written, call it MAUDIE. Also in the folder containing the MAUDIE modules, I have a docs folder containing the sphinx documentation, and a tutorial folder. In the tutorial folder, I have a file use_Maudie.py, it's a script to run a basic use case at the command line, with a function use_maudie().

I want to include the docustring from use_maudie() in my documentation, and tried the following:

.. currentmodule:: MAUDIE.tutorial.use_Maudie  .. autofunction:: use_maudie  

This (probably obviously) didn't work, as there is no module MAUDIE.tutorial. Is there a way to include the formatted version of the use_maudie() Docustring and still leave use_Maudie.py in the tutorial folder?

AEM spa Navigation

Posted: 29 Jul 2021 08:49 AM PDT

I am using AEM 6.5.9 to follow the REact SPA tutorial. I am working on the navigation section. I completed the section but noticed every time I click on the menu the page refresh and call a new document, doing some debug, noticed that the CMP-navigation class is not being proxied to the rest of the router components, also the prop isRouted is missing hence, the component is rendering a normal link. I was wondering if I am missing any steps to actually make the Navigation component works.

Find below some screenshots of the issue:

  1. cmp-navigation class not getting passed to child component enter image description here
  2. isRouted prop notes getting passsed enter image description here

Tengo el mismo problema

Posted: 29 Jul 2021 08:50 AM PDT

la respuesta que encontré fue que, estan en mantenimiento y todo volverá a funcionar el 3 de agosto del 2021

Google My Buisiness "code": 403, "message": "Google My Business API has not been used in project xxx

How to code a condition statement in Python for opening websites

Posted: 29 Jul 2021 08:49 AM PDT

I want to get the code to open a webpage if the page is not on the default browser. If the page is open on the default browser it will not open the Chrome page. For example if I have a tab open for YouTube, the code will not open a new tab for YouTube. If the browser does not have a tab for YouTube, then the code create a new tab for YouTube.

import time  import hashlib  import webbrowser    #product = input("Enter the name of the product you want to buy: ")  webpage = input("Enter the link to the webpage: ")    #get the webpage of the link  webbrowser.get('windows-default').open(webpage)  print("web page opened")  

Check typing for hybrid types

Posted: 29 Jul 2021 08:50 AM PDT

Is there a function similar to isinstance that can identify if some data is of hybrid types, for example (suppose such a function is named isinstance2):

data = [1, 2, 3]  data2 = ('a', 'b', 'c')    isinstance2(data, list[int])  # True  isinstance2(data2, list[int]) # False  isinstance2(data2, set[str])  # True  

The use case is a class that checks types during instantiation:

class foo():       def __init__(self, data):         if isinstance2(data, list[str]):             # do stuff         else:             raise TypeError  

IBM Cloud for Db2-oc instance throws: "Service Broker returned error status code 500" while creating a new credential

Posted: 29 Jul 2021 08:49 AM PDT

Service Broker returned error status code 500

The plan is Lite, i've tried all free regions and they have the same problem.

IN-MEMORY WEB API Library, Angular front-end & back-end

Posted: 29 Jul 2021 08:49 AM PDT

I am creating a front / back end project. Currently I am only developing the front-end part. I want to use as library this one in-memory web api until the back-end is finished. But how do I delete this library from my project after I will have back-end part finished? And can I create a specific folder in the project to install this library to have it easy to uninstall from my project later.

Please help me!

How can I set up the y value of a matplotlib grid of 2x2 to a shared constant?

Posted: 29 Jul 2021 08:50 AM PDT

I am currently working on a project that will plot the data collected from a accelerometer. In order to get a good insight of what we will do I need to plot the data as a grid which I have done with matplotlib:

fig, axs = plt.subplots(2, 2)  axs[0, 0].plot(x, y)  axs[0, 0].set_title("Non Faulty Acc X Data")  axs[0, 1].plot(x2, y2, 'tab:orange')  axs[0, 1].set_title('Non Faulty Acc X Data')  axs[1, 0].plot(x3, y3, 'tab:green')  axs[1, 0].set_title('Faulty Acc X Data')  axs[1, 1].plot(x4, y4, 'tab:red')  axs[1, 1].set_title('Faulty Acc X Data')  

With this code I get the following output. Image of the output of the code

As you can see, the y-value (time) is not the same between both graphs.
I have tried this code:

plt.ylim([0, 1])  

I have both tried it as seperate after each .set_title and .plot methods. And I have tried using it in the for loop as well:

for ax in axs.flat:      plt.ylim([0, 1])      ax.set(ylabel='Time')  

After that nothing changes.
I basically need the second graphs y-values to be able to match the y-values of the first one to get an accurate output.

Cannot get If statements on RaycastHit2D to execute except for the top-most one

Posted: 29 Jul 2021 08:50 AM PDT

In my Unity 2D game, I have set up 3 different 2D Raycasts on the same GameObject for score-detection purposes with the help of boolean and if statements. The object in question today is a torus that is scrolling from right to left, which the player (the balloon) has to go through or avoid using up and down motion. The player gets more points when going through the torus as opposed to going around it.

The issue: hit2 and hit3 do not return anything. hit1 returns hit correctly when the player is detected inside the torus. Interestingly, if I put hit2 before hit1, it would return correctly. But now hit1 and hit3 would not return anything. The same is true for hit3 when it is placed in front.

This is the "hit1" part for example:

if(!Rayhit1)      {           if(hit1.collider.name == "GameObject")           {                RayHit1 = true;                score.value += 30;           }      }  if(!hit1)      {           RayHit1 = false;      }  

Snapshot of the game

Here are snippets of my code that concern the process of detecting score:

private bool RayHit1 = false;  private bool RayHit2 = false;  private bool RayHit3 = false;    void Update()  {       int layer = 9;       int layerMask = 1;       RaycastHit2D hit1 = Physics2D.Raycast(a,b,c,d); //letters to shorten my Raycast arguments       RaycastHit2D hit2 = Physics2D.Raycast(a,b,c,d); //the arguments aren't the same       RaycastHit2D hit3 = Physics2D.Raycast(a,b,c,d); //shortened them to make the code pasted here neat    if(!Rayhit1)  {       if(hit1.collider.name == "GameObject")       {            RayHit1 = true; //boolean to true for just 1 frame so that the score does not add more than once            score.value += 30;       }  }  if(!hit1)  {       RayHit1 = false; //reset boolean to false when Raycast returns nothing  }    if(!Rayhit2)  {       if(hit2.collider.name == "GameObject")       {            RayHit2 = true;            score.value += 10;       }  }  if(!hit2)  {       RayHit2 = false;  }    if(!Rayhit3)  {       if(hit3.collider.name == "GameObject")       {            RayHit3 = true;            score.value += 10;       }  }  if(!hit3)  {       RayHit3 = false;  }     }  

How to update specific state in array of objects?

Posted: 29 Jul 2021 08:49 AM PDT

I'm trying to write quite simple toDoList with React, but stuck with state update. Any help will be appreciated

I have a state array of objects

const [toDoList, setToDoList] = useState([]);      [        {        categoryName: "Free time"        color: "red"        id: "30728c8-13a0-01c1-6385-5307f873d3f7"        tasks: []      }   ]  

I need to add objects to toDoList.tasks. Objects like this:

{    task: "Watch TV",    id: "30728c8-13a0-01c1-6385-5307f873d3f7",    isDone: false,  }  

How can I update tasks state in toDoList.object?

JavaFX - Batch not inserting data properly (Jumped/Skipped)

Posted: 29 Jul 2021 08:50 AM PDT

I have 20723 data in ObservableList. When data's inserted into database(SQL Server) from the ObservableList. The first 5483 data jump or skipped, but will inserted later. So the value is still 20723. I have try to sort the array but it's not the problem and right now i'm stuck. How to fix this?

The code:

List to store data, using observable list to display it in table. The data is stored in table properly.

ObservableList<Membermlm> membermlm = FXCollections.observableArrayList();  

Insert data into observable array list

Objects[] rowObjects;  int id;   while ((rowObjects = reader.nextRecord()) != null) {                  id++;                  membermlm.add(new Membermlm(id,                          String.valueOf(rowObjects[0]), String.valueOf(rowObjects[1]),                          String.valueOf(rowObjects[2]), String.valueOf(rowObjects[3]),                          String.valueOf(rowObjects[4]), String.valueOf(rowObjects[5]),                          String.valueOf(rowObjects[6])  

Insert into database from observable array list

 sql = "INSERT INTO biodata (id, kode, nama, alamat, kota)" + "VALUES (?, ?, ?, ?, ?) ";          try (                  PreparedStatement statement = con.prepareStatement(sql);          ) {              con.setAutoCommit(false);              int counter = 0;              int i =0;  for (Membermlm m : membermlm) {                  statement.setInt(1, m.getId());                  statement.setString(2, m.getKode());                  statement.setString(3, m.getNama());                  statement.setString(4, m.getAlamat());                  statement.setString(5, m.getKota());                  statement.addBatch();                  counter++;                  if (counter % 1000 == 0 || counter == membermlm.size()) {                      statement.executeBatch(); // Execute every 1000 items.                      statement.clearParameters();                      statement.clearBatch();                  }              }    

For example (from first row) : | ID | Name | |---------------------|------------------| | 99 | John | | 197 | Andrew | | 302 | Martin | | 393 | Jone | | 495 | Maria | | 604 | Andro |

Then starting from the id 5484 : | ID | Name | |---------------------|------------------| | 5484 | John | | 5485 | Andrew | | 5486 | Martin | | 5487 | Jone | | 5488 | Maria |

Command docker build --pull --rm -f "src\Dockerfile" -t ang:1.0 "src"" terminated with exit code: 1

Posted: 29 Jul 2021 08:49 AM PDT

Docker Terminal

Executing task: docker build --pull --rm -f "src\Dockerfile" -t ang251120:1.0 "src" <

Sending build context to Docker daemon 2.248MB

Step 1/7 : FROM node:latest as builder

latest: Pulling from library/node

Digest: sha256:8229a1f3580d32fa18b2304fa23df6e9e3d53fdb958fd8ffe812ca7a0a26bb69

Status: Image is up to date for node:latest

---> 8f1b7f0dfc2f

Step 2/7 : RUN mkdir -p /app

---> Using cache

---> 849a2534b55b

Step 3/7 : WORKDIR /app

---> Using cache

---> 260692585d71

Step 4/7 : COPY . .

---> 1c906f814f03

Step 5/7 : RUN npm install

---> Running in 2e4b09b03b8f

npm ERR! code ENOENT

npm ERR! syscall open

npm ERR! path /app/package.json

npm ERR! errno -2

npm ERR! enoent ENOENT: no such file or directory, open '/app/package.json'

npm ERR! enoent This is related to npm not being able to find a file.

npm ERR! enoent

npm ERR! A complete log of this run can be found in:

npm ERR! /root/.npm/_logs/2021-07-29T15_27_34_838Z-debug.log

The command '/bin/sh -c npm install' returned a non-zero code: 254

The terminal process "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command docker build --pull --rm -f "src\Dockerfile" -t ang251120:1.0 "src"" terminated with exit code: 1.

Terminal will be reused by tasks, press any key to close it.

Dockerfile

FROM node:latest as builder

RUN mkdir -p /app

WORKDIR /app

COPY . .

RUN npm install

RUN npm run build --prod

CMD [ "npm", "start" ]

/////////////////////////////////////////////////////////////////

package.json

{

"name": "angular8-springboot-client",

"version": "0.0.0",

"scripts": {

"ng": "ng",    "start": "ng serve",    "build": "ng build",    "test": "ng test",    "lint": "ng lint",    "e2e": "ng e2e",    "postinstall": "ngcc"  

},

"private": true,

"dependencies": {

"@angular/animations": "^10.1.6",    "@angular/cdk": "^10.2.7",    "@angular/common": "~10.1.6",    "@angular/compiler": "~10.1.6",    "@angular/core": "^10.1.6",    "@angular/forms": "~10.1.6",    "@angular/localize": "^10.1.6",    "@angular/material": "^10.2.7",    "@angular/platform-browser": "~10.1.6",    "@angular/platform-browser-dynamic": "~10.1.6",    "@angular/router": "~10.1.6",    "@fortawesome/fontawesome-free": "^5.15.3",    "@ng-bootstrap/ng-bootstrap": "^7.0.0",    "@types/chart.js": "^2.9.32",    "angular-bootstrap-md": "^11.0.0",    "animate.css": "^4.1.1",    "bootstrap": "^4.5.3",    "chart.js": "^2.9.4",    "hammerjs": "^2.0.8",    "igniteui-cli": "^8.0.0",    "jquery": "^3.5.1",    "ngx-bootstrap": "^6.1.0",    "ngx-bootstrap-icons": "^1.0.0",    "rxjs": "~6.6.3",    "save": "^2.4.0",    "tslib": "^2.0.0",    "zone.js": "~0.10.2"  

},

"devDependencies": {

"@angular-devkit/build-angular": "~0.1001.7",    "@angular/cli": "^10.1.7",    "@angular/compiler-cli": "~10.1.6",    "@angular/language-service": "~10.1.6",    "@babel/core": "^7.12.1",    "@types/jasmine": "~3.3.8",    "@types/jasminewd2": "~2.0.3",    "@types/node": "^12.11.1",    "codelyzer": "^5.1.2",    "jasmine-core": "~3.5.0",    "jasmine-spec-reporter": "~5.0.0",    "karma": "~5.0.0",    "karma-chrome-launcher": "~3.1.0",    "karma-coverage-istanbul-reporter": "~3.0.2",    "karma-jasmine": "~4.0.0",    "karma-jasmine-html-reporter": "^1.5.0",    "protractor": "~7.0.0",    "ts-node": "~7.0.0",    "tslint": "~6.1.0",    "typescript": "~4.0.3"  

}

}

split string by space and '-' SQL server

Posted: 29 Jul 2021 08:49 AM PDT

I have the following column value:

test-00 - test-01 - test-02  

I need to get the string between ' -' and ' -'

test-01  

Is it possible in sql server? I've tried with : STRING_SPLIT(column,' -') but it works only for '-' not for ' -'

sh Break CSV files by value of column name matched while retaining header

Posted: 29 Jul 2021 08:49 AM PDT

I have a directory with many CSV files from table exports

tblA.csv

A,B,C  1,1,1  1,2,2  2,2,2  3,3,3  

tblB.csv

C,D,A  1,1,1  1,2,2  2,2,2  3,3,3  

In order to break the files I found this script

   awk -F, '        NR== 1 { hdr = $0;next}        {out = "File" $1 ".csv"}        printed[$1]++<1 {print hdr >out}        {print $0 > out}    ' tblA.csv   

that creates 3 files

A,B,C  1,1,1  1,2,2  
A,B,C  2,2,2  
A,B,C  3,3,3  

Now for tblB.csv I still need to break the file by column A but that column is the 3rd not the 1st

I can't figure out a way to pass the argument A have the it loop the header to find a column name that matches the argument I passed and then break the file using that column value. Or if that column name does not exist just skip the file.

How to make Chrome 92 display alert(), prompt() and confirm() from iframe opened on different subdomain

Posted: 29 Jul 2021 08:49 AM PDT

I have this situation:

A page from http://desktop.ourdomain.local contains an iframe with src="http://legacy-application.ourdomain.local"

http://legacy-application.ourdomain.local, makes extensive use of alerts and prompts, which worked fine until google released chrome 92, which states that this is no more an option (see https://www.chromestatus.com/feature/5148698084376576)

Tried many things among those explained here

And many trials about CORS, and many combinations of iframe sandboxing (allow-same-origin allow-scripts allow-modal ...)

Did anybody run into the same problem, and solved ?

How to get available space on a network drive in c++?

Posted: 29 Jul 2021 08:49 AM PDT

I tried using std::filesystem::space(dir) but with no luck -> it cannot determine available disk space, sets it to uintmax.

auto info = std::filesystem::space("K:\\Dir");  if(info.available == static_cast<uintmax_t>(-1))  {       std::cout << "Error occurred!\n";  }  

K:\Dir does indeed exist. And this snippet prints Error occurred for my drive mounted on K:.

StateNotifierProvider not updating state

Posted: 29 Jul 2021 08:49 AM PDT

I am trying to use Riverpod state management. I have two TextFormField and I want to set the value of a Text by taking the sum of the values entered in each of the fields using a StateNotifierProvider.

In the following code, CashCounterData is a data model to be used by the StateNotifier, CashCounter. The notifier has two methods, setCount and setCash that are called in the onChanged method of each TextFormField.

final cashProvider = StateNotifierProvider<CashCounter, CashCounterData>((ref) => CashCounter());    class CashCounter extends StateNotifier<CashCounterData> {    CashCounter() : super(_initialData);      static const _initialData = CashCounterData(0, 0);      void setCount(int value){      state = CashCounterData(value, state.cash);    }      void setCash(value){      state = CashCounterData(state.count, value);    }      int get count => state.count;    int get cash => state.cash;  }    class CashCounterData {    final int count;    final int cash;      const CashCounterData(this.count, this.cash);  }  

Next, I implemented the UI and am trying to tie in the StateNotifierProvider defined above. However, when I enter values into each TextFormField, the Text widget is always displaying 0.

class CalculatableTextFormField extends HookWidget {    @override    Widget build(BuildContext context) {      final cashCounterProvider = useProvider(cashProvider.notifier);      final TextEditingController _count = TextEditingController();      final TextEditingController _cash = TextEditingController();      return Scaffold(        body: Form(          child: Column(            mainAxisAlignment: MainAxisAlignment.center,            children: [              Text(                  '${cashCounterProvider.count + cashCounterProvider.cash}'              ),              TextFormField(                controller: _count,                keyboardType: TextInputType.number,                onChanged: (value)=>cashCounterProvider.setCount(int.parse(value)),              ),              TextFormField(                controller: _cash,                keyboardType: TextInputType.number,                onChanged: (value)=>cashCounterProvider.setCash(int.parse(value)),              )            ],          ),        ),      );    }  }  

What am I missing to get my desired behavior?

Big projects that require very good performance really don't use polymorphism?

Posted: 29 Jul 2021 08:49 AM PDT

For quite some time I have been interested in perfomance in C ++.

A lot of things keep coming up, whether in conferences or in books:

Do not use a virtual function, have the data in the cache, the branches etc.

There are many benchmarks with examples of video games to show the differences in performance. The thing is, the examples are always very simple.

How does that really work in code that is more than 20 lines? in AAA video games, finance etc.

If I have 100 types of objects that have different update, different behavior and other joys, it's easy to set up via polymorphism or function pointers.

Now, by following the advice given to make a powerful code, the above options are not possible. We will therefore prefer to have 100 arrays that we will update separately. We will have good access to the cache, the functions will probably be inline etc. in short, the performance will in principle be better.

So, I have 100 arrays and 100 differents functions that i will have to call at each frame. The tables dynamically change depending on what happens, new players appear, a monster dies etc. Some array will have 0 elements active, others 10... I would call functions that will have no work (array without active element) but I have no choice, I have to have a flag or look if elements are active or not in my array.

I end up with something like this:

obj1update ();  obje2update ();  ....    obj1behavior ();  obj2behavior ();  ....    obj1render ();  obj2render ();  .....    objectxy ();  ....  

Of course, there will undoubtedly be a function which manages all the update calls on the objects, one for the behavior etc but to simplify it gives as above.

To stay in the video game, if the x action of a player causes the arrival of y monsters, there are several types of monsters which have different functions. We will therefore put the monsters in our tables and this time the functions dealing with these monsters will have work.

We can use the ECS pattern or a derivative but they will potentially have very different behaviors (an ia that directs them or other), different components and therefore different functions will be needed to process them. They will be called hard in the code since we don't have polymorphism or function pointers and we will have to check at each frame if they have something to process or not.

Is it really done that way? suppose i have 500 types? 1000 ?

Edit:

Lots of comments so I'll get back to you here.

As Federico said, I want to know if these recommendations are good for books but less so in practice.

Several resources that I have looked at:

https://www.agner.org/optimize/#testp Great suite of several books

www.youtube.com/watch?v=WDIkqP4JbkE&t Scott Meyers talk on memory

https://people.freebsd.org/~lstewart/articles/cpumemory.pdf On memory

www.youtube.com/watch?v=rX0ItVEVjHc&t Data-oriented programming

https://www.dataorienteddesign.com/dodbook/ data oriented design book

There are also other resources but it already gives you an idea on what I'm basing

How to Auto Sliding Images with collectionView

Posted: 29 Jul 2021 08:49 AM PDT

I want to create a slideshow with UICollectionView. Now I've created a collection view and also a custom cell. I am showing all the images, but not auto scrolling. So I want, when the view controller is loaded, all the cell of collection view should scroll automatically, even when sliding button pressed. But I searched all the documents but haven't found. So please give any idea or give me any tutorial link also.

No comments:

Post a Comment