问:
Tracking Elements on ctx, ctx placed on boxgeometry threejs
I've applied ctx to all the side of BoxGeometry .furthermore, I'm using raycaster to get the data present on ctx so that onclick it gives x,y co-ordinates of ctx and index of that partcular side to understand which side the ctx is present.

this is my code

```<code>document.addEventListener ("mousedown",( event ) => {
var vector = new THREE.Vector3();
   pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
vector.unproject( camera );
raycaster.setFromCamera( pointer, camera);
var intersects = raycaster.intersectObject( this.cube );

if (intersects.length > 0) {
  index = Math.floor(intersects[0].faceIndex / 2);
  if (index == 0) {
    let templabelarray = []
    for (let i = 0; i < this.labels.length; i++) {
      if (this.labels[i].typename == 'Left' ) {
        templabelarray.push(this.labels[i]);
      }
      this.state.totalLabels.push(templabelarray);

      let rect =  this.ctxArr[0].getBoundingClientRect()
      this.x = e.clientX - rect.left
      this.y = e.clientY - rect.top
      let i = 0, r;
</code>```

this.labels will give me the array for ctx present on the particular side and further i"m pssing it into state variable

Using this I'm able to get the index but, unable to fetch x,y co-ordinates for ctx.
any help would be greatly appreciated

Body:
I've applied ctx to all the side of BoxGeometry .furthermore, I'm using raycaster to get the data present on ctx so that onclick it gives x,y co-ordinates of ctx and index of that partcular side to understand which side the ctx is present.

this is my code

document.addEventListener ("mousedown",( event ) => {
var vector = new THREE.Vector3();
   pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
vector.unproject( camera );
raycaster.setFromCamera( pointer, camera);
var intersects = raycaster.intersectObject( this.cube );

if (intersects.length > 0) {
  index = Math.floor(intersects[0].faceIndex / 2);
  if (index == 0) {
    let templabelarray = []
    for (let i = 0; i < this.labels.length; i++) {
      if (this.labels[i].typename == 'Left' ) {
        templabelarray.push(this.labels[i]);
      }
      this.state.totalLabels.push(templabelarray);

      let rect =  this.ctxArr[0].getBoundingClientRect()
      this.x = e.clientX - rect.left
      this.y = e.clientY - rect.top
      let i = 0, r;

this.labels will give me the array for ctx present on the particular side and further i"m pssing it into state variable

Using this I'm able to get the index but, unable to fetch x,y co-ordinates for ctx.
any help would be greatly appreciated


来源: stackexchange

问:
Is it possible to extract class/interface functions with ts-json-schema-generator?
I am working on a Builder for a typescript sdk library and I am trying to extract all the sdk classes with their respective functions into a json that the Builder can use.

I am trying to accomplish this:

```<code>class Form {
 propA: string
 propB: string

 funcA(value: boolean, text: string) {
 ...
 }
}
</code>```

to

```<code>{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Form": {
      "type": "object",
      "properties": {
        "propA": {
          "type": "string"
        },
        "propB": {
          "type": "string"
        },
        "NamedParameters<typeof funcA>": {
          "type": "object",
          "properties": {
            "value": {
              "type": "boolean"
            },
            "text": {
              "type": "string"
            }
          },
          "required": [
            "value",
            "text"
          ],
          "additionalProperties": false
        }
      },
      "additionalProperties": false
    }
  }
}
</code>```

But there seems to be no way to accomplish this. Does anyone know an alternative or a solution?

ContentLicense: CC BY-SA 4.0

Body:
I am working on a Builder for a typescript sdk library and I am trying to extract all the sdk classes with their respective functions into a json that the Builder can use.

I am trying to accomplish this:

class Form {
 propA: string
 propB: string

 funcA(value: boolean, text: string) {
 ...
 }
}

to

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Form": {
      "type": "object",
      "properties": {
        "propA": {
          "type": "string"
        },
        "propB": {
          "type": "string"
        },
        "NamedParameters<typeof funcA>": {
          "type": "object",
          "properties": {
            "value": {
              "type": "boolean"
            },
            "text": {
              "type": "string"
            }
          },
          "required": [
            "value",
            "text"
          ],
          "additionalProperties": false
        }
      },
      "additionalProperties": false
    }
  }
}

But there seems to be no way to accomplish this. Does anyone know an alternative or a solution?


问:
Swift laggy zooom in/out PDFView in .singlePage mode
Why is using PDFView in .singlePage mode when I try to zoom in and zoom out is lagging?

I don't have any kinds of strange settings, just create a project from scratch to replicate this.

```<code>func displayPDF() {
    pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))

    if let pdf = Bundle.main.url(forResource: "sample_pdf", withExtension: "pdf", subdirectory: nil, localization: nil)  {

        let doc = PDFDocument(url: pdf)
        pdfView.document = doc
    }
    pdfView.displayMode = .singlePage
    view.addSubview(pdfView)
}
</code>```

This is an example of what is going on:

https://streamable.com/eyxiw2

Body:
Why is using PDFView in .singlePage mode when I try to zoom in and zoom out is lagging?

I don't have any kinds of strange settings, just create a project from scratch to replicate this.

func displayPDF() {
    pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))

    if let pdf = Bundle.main.url(forResource: "sample_pdf", withExtension: "pdf", subdirectory: nil, localization: nil)  {

        let doc = PDFDocument(url: pdf)
        pdfView.document = doc
    }
    pdfView.displayMode = .singlePage
    view.addSubview(pdfView)
}

This is an example of what is going on:

https://streamable.com/eyxiw2


问:
Add image to images array using concat
I used "append" to add image to images array but recently I got this Massage
The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. I tried but unfortunately did not succeed.

images = []
labels = []

for directory_path in glob.glob("images/*"):
    label = directory_path.split("\\")[-1]     # Assign last folder name of the directory as labels
    print(label)
    for img_path in glob.glob(os.path.join(directory_path, "*.jpg")):       # Execute for every .jpg  images
        print(img_path)
        img = cv2.imread(img_path, 0)       # Reading color images
        img = cv2.resize(img, (SIZE, SIZE)) # Resize images
        plt.imshow(img, cmap='gray')        # Show image in grayscale
        images.append(img) # Add image to images array
        labels.append(label)                # Add label to labels array
```
<p>Alternative  <code>pd.concat(img,images)</code>  Add image to images array</p>
<p>I had this error :</p>
<pre class="lang-py prettyprint-override"><code>TypeError: cannot concatenate object of type '<class 'numpy.ndarray'>'; only Series and DataFrame objs are valid
</code>```

Title: Add image to images array using concat

Body:
I used "append" to add image to images array but recently I got this Massage
The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. I tried but unfortunately did not succeed.

images = []
labels = []

for directory_path in glob.glob("images/*"):
    label = directory_path.split("\\")[-1]     # Assign last folder name of the directory as labels
    print(label)
    for img_path in glob.glob(os.path.join(directory_path, "*.jpg")):       # Execute for every .jpg  images
        print(img_path)
        img = cv2.imread(img_path, 0)       # Reading color images
        img = cv2.resize(img, (SIZE, SIZE)) # Resize images
        plt.imshow(img, cmap='gray')        # Show image in grayscale
        images.append(img) # Add image to images array
        labels.append(label)                # Add label to labels array

Alternative  pd.concat(img,images)  Add image to images array

I had this error :

TypeError: cannot concatenate object of type '<class 'numpy.ndarray'>'; only Series and DataFrame objs are valid


问:
Converting multi page pdf to jpeg results in a single page
Have written this python script to convert multi page pdfs to jpeg.

```<code>import requests, io
from pdf2image import convert_from_bytes

url = 'http://www.asx.com.au/asxpdf/20171108/pdf/43p1l61zf2yct8.pdf'
response = requests.get(url)
pages = convert_from_bytes(response.content)

in_mem_file = io.BytesIO()
for page in pages:
    page.save(in_mem_file, format="jpeg")
in_mem_file.seek(0)

f = open('./test3.jpeg', 'wb')
f.write(in_mem_file.read())
f.close()
in_mem_file.close()
</code>```

But this gives the first page itself. Why am i not getting the second page in the output file.

Body:
Have written this python script to convert multi page pdfs to jpeg.

import requests, io
from pdf2image import convert_from_bytes

url = 'http://www.asx.com.au/asxpdf/20171108/pdf/43p1l61zf2yct8.pdf'
response = requests.get(url)
pages = convert_from_bytes(response.content)

in_mem_file = io.BytesIO()
for page in pages:
    page.save(in_mem_file, format="jpeg")
in_mem_file.seek(0)

f = open('./test3.jpeg', 'wb')
f.write(in_mem_file.read())
f.close()
in_mem_file.close()

But this gives the first page itself. Why am i not getting the second page in the output file.


问:
Divide Gstreamer source in several branches
I need to read rtsp and after that to divide to several branches.
Smth like tee plugin does, but tee copy the frame.
I need that 1 frame to go to one branch of pipeline and another one to go to another branch  the third frame to the first branch and so on... Is it possible to do in Gstreamer?</p>


问:
How to manage too much rows in mysql (Growing 100k - 300k + per day)
I use MySQL as my primary database for my tracking software.

Tracking is standalone module in my app and I track users and user_events .

In users table I save each unique user which visits website and in user_events table I save events of that users. (one to many relation)

I have implemented that tracker in dozen of sites with medium to large traffic and going to add more sites, but problem is that users and user_events table is growing too much rate (currently I have ~9M users and ~15M rows in user_events table) So, my queries is slowing down time by time.

How can I organize tables, that I can save as much rows as I can and not to destroy query performance? Can anyone suggest anything?

Should I use alternative sql databases for such apps? or event nosql databases?


问:
Problem with Flutter Drift DAO when calling method to fetch data, problem is the context i use for calling method from dao to fetch data
Error: Could not find the correct Provider above this AddUser Widget
This happens because you used a BuildContext that does not include the provider

```<code>- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

</code>```

The provider you are trying to read is in a different route.

```<code>  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

</code>```

You used a BuildContext that is an ancestor of the provider you are trying to read.

```<code>  Make sure that AddUser is under your MultiProvider/Provider<UserTableDao>.
  This usually happens when you are creating a provider and trying to read it immediately.

</code>```

This one is my debug console result

`

```<code>  @override
  Widget build(
    BuildContext context,
  ) {
    return Scaffold(
      appBar: AppBar(
        flexibleSpace: const Image(
          image: AssetImage('assets/images/slow-motion.gif'),
          fit: BoxFit.cover,
        ),
        title: const Text('Χρηστες'),
        actions: [
          IconButton(
              onPressed: () {
                addUserDetails(context);
              },
              icon: const Icon(
                Icons.save,
              ))
        ],
      ),
</code>```

`

```<code>void addUserDetails(BuildContext newcontext) {
    final userEntity = UserTableCompanion(
      id: drift.Value(widget.counter),
      userName: drift.Value(usernameController.text),
      password: drift.Value(passwrodContoller.text),
      email: drift.Value(emailControler.text),
      name: drift.Value(nameController.text),
    );
    // Provider.of<AppDb>(context, listen: false).insertUsers(userEntity);
    final dao = Provider.of<UserTableDao>(newcontext, listen: false);
    dao.insertUsers(userEntity);
</code>```

this is my method and where i call it

I already have the dao functions, i get the data to insert it
I know what my problem is but i find it difficult to solve it
It has something to do with the context i use and where i get it from

Body:
Error: Could not find the correct Provider above this AddUser Widget
This happens because you used a BuildContext that does not include the provider

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

You used a BuildContext that is an ancestor of the provider you are trying to read.

  Make sure that AddUser is under your MultiProvider/Provider<UserTableDao>.
  This usually happens when you are creating a provider and trying to read it immediately.

This one is my debug console result

`

  @override
  Widget build(
    BuildContext context,
  ) {
    return Scaffold(
      appBar: AppBar(
        flexibleSpace: const Image(
          image: AssetImage('assets/images/slow-motion.gif'),
          fit: BoxFit.cover,
        ),
        title: const Text('Χρηστες'),
        actions: [
          IconButton(
              onPressed: () {
                addUserDetails(context);
              },
              icon: const Icon(
                Icons.save,
              ))
        ],
      ),

`

void addUserDetails(BuildContext newcontext) {
    final userEntity = UserTableCompanion(
      id: drift.Value(widget.counter),
      userName: drift.Value(usernameController.text),
      password: drift.Value(passwrodContoller.text),
      email: drift.Value(emailControler.text),
      name: drift.Value(nameController.text),
    );
    // Provider.of<AppDb>(context, listen: false).insertUsers(userEntity);
    final dao = Provider.of<UserTableDao>(newcontext, listen: false);
    dao.insertUsers(userEntity);

this is my method and where i call it

I already have the dao functions, i get the data to insert it
I know what my problem is but i find it difficult to solve it
It has something to do with the context i use and where i get it from


问:
Constraint Exception
I had a weird issue while accessing the REST API of my application.
While checking in log , the error message is visible two times in the span of 60 days.

javax.validation.ConstraintDeclarationException: HV000152: Two methods
defined in parallel types must not declare parameter constraints, if
they are overridden by the same method, but methods
AppConfig#setApiVersion(String) and
AppConfig$$EnhancerBySpringCGLIB$$1fccb006#setApiVersion(String) both
define parameter constraints.

Note: There are frequent calls for the same API which worked most of the time. No recent deployments during the issue occurrence.
I am using Spring Boot version 2.6.9 and docker image of adoptopenjdk/openjdk15:jre-15.0.1_9-alpine.

Any help will be appreciated.

Title: Constraint Exception


问:
Number of users drops during load test in Locust
I have a simple Locust load test that I run with 1000 users and 100 spawn rate. When I get to the web UI I see that the amount of users grows up to 1000 stays like this for few seconds (up to 20) and then drops to 500+ and sometime 400+. The interesting thing is that when I edit the value from web UI to bring it back up to 1000 it drops again but to 900 - 950 range. Did anyone have such problem and possibly a solution?</p>


问:
File Format to Write out map data
I want to write out the hashmap in java, having Key:String and Value:List<UserInfo>.
The UserInfo object has (id, name, category, type) vaues.

Can someone suggest the file format to writeout the map data, which is easy to read.
I wrote in csv file, but have to write key for each object of list, that doesn't look good.

I'm beginner in file reading and writing in java.

Title: File Format to Write out map data


问:
Convert Grouped-By rows into single column separated by comma
I have a question that might be similar to other "pivot" type questions but it is a very different. I am not looking at flattening, transposing or pivoting, but converting a ranking into a row.

Imagine I have 3 calculus classes, each class has 10 students, with their exam scores.

and I want to rank students but display the ranked student ID in a row by class

How would I do this in Pandas/Python?

I could (in fact, have successful done a row-wise function to do that, but performance is very poor when you have thousands of rows)

Cheers, and many thanks in advance
Nelson


问:
Why am I getting "OLE DB or ODBC Error" when importing data from Azure SQL into Power BI Deskop, using parameters for db details?
I need to connect Power BI to an Azure SQL database.  If I enter the server name and database directly into the "SQL Server database" dialog, it connects, prompts me for credentials, allows me to select tables, and subsequently imports data just fine. screenshot of database details dialog

However, if I enter the server and database name as parameters (screenshot of adding database details as parameters), and use the exact same server and db names as the "current value" of the parameters, I get the same table selection options, and can see data previews, as before, but when Power BI tries to import the data, I get the following error:

"Failed to save modifications to the server. Error returned: 'OLE DB or ODBC error: [Expression.Error] The import serverName matches no exports. Did you miss a module reference?" for every table I try to import.  serverName there is the name I gave to the server parameter.

error dialog

Can anyone help?


问:
Connecting to Teradata using SQLAlchemy results in errors
I'm trying to connect to Teradata with SQLAlchemy and then save the results as pandas.DataFrame.

```<code>engine = create_engine(f"teradata://{UID}:{PWD}@host/?dsn={DSN}")
query = """SELECT TOP 10 * from db_5.mobile_sa"""
with engine.connect() as connect:
    df = pd.read_sql(query,connect)
</code>```

This results in an error:

```<code>sqlalchemy.exc.DatabaseError: (teradata.api.DatabaseError) (11470, '[HYC00] [Cloudera][ODBC] (11470) Transactions are not supported.') (Background on this error at: https://sqlalche.me/e/14/4xp6)
</code>```

I've found that I should try to set autocommit to true, so I tried solutions from SQLAlchemy documentation and added isolation_level="AUTOCOMMIT" to create_engine() , but this time I got

```<code>TypeError: Invalid argument(s) 'isolation_level' sent to create_engine(), using configuration TeradataDialect/SingletonThreadPool/Engine.  Please check that the keyword arguments are appropriate for this combination of components.
</code>```

I also tried to add &autocommit=true to connection url, but that didn't seem to have an effect.
How do I go around it?

Body:
I'm trying to connect to Teradata with SQLAlchemy and then save the results as pandas.DataFrame.

engine = create_engine(f"teradata://{UID}:{PWD}@host/?dsn={DSN}")
query = """SELECT TOP 10 * from db_5.mobile_sa"""
with engine.connect() as connect:
    df = pd.read_sql(query,connect)

This results in an error:

sqlalchemy.exc.DatabaseError: (teradata.api.DatabaseError) (11470, '[HYC00] [Cloudera][ODBC] (11470) Transactions are not supported.') (Background on this error at: https://sqlalche.me/e/14/4xp6)

I've found that I should try to set autocommit to true, so I tried solutions from SQLAlchemy documentation and added isolation_level="AUTOCOMMIT" to create_engine() , but this time I got

TypeError: Invalid argument(s) 'isolation_level' sent to create_engine(), using configuration TeradataDialect/SingletonThreadPool/Engine.  Please check that the keyword arguments are appropriate for this combination of components.

I also tried to add &autocommit=true to connection url, but that didn't seem to have an effect.
How do I go around it?


问:
How to send embed generated qr-code in ejs using mailgun in node js?
This the code of sending an email using mailgun:

```<code>const qrcodeEmail = async (email, subject,text,qrcode,user,data) => {
  try {
    const requiredPath = path.join(__dirname, "../views/emailTemplates/qrcodeEmail.ejs");

    const emailData = await ejs.renderFile(requiredPath,{user:user,data:data,qrcode:qrcode});
     var mailData = {
        from: 'moilasurprise7@gmail.com',
        to: 'moilasurprise7@gmail.com',
        subject:subject,
        html:emailData,
      };

      mailgun.messages().send(mailData, function (error, body) {
        if(error){
            console.log(error);
        }
        console.log("email sent successfully");
      });
} catch (error) {
    console.log(error.message);
}
};
</code>```

The email is sent,the user and order details are showing but the qr-code is not displaying down here is the ejs email template.

Note: the qr-code is generated in this manner.

```<code> await QRCode.toDataURL(text);
</code>```

This is the ejs template where the qrcode is rendered:

```<code><table style="width:100%;max-width:620px;margin:0 auto;background-color:#ffffff;">
                    <tbody>
                        <tr>
                            <td style="padding: 30px 30px 20px">
                                <p style="margin-bottom: 10px;">Hi <%= user.name %>  <%=user.lastName%>       ,</p>
                                <p style="margin-bottom: 10px;">Here is your ticket order</p>
                                <p style="margin-bottom: 10px;">eventName : <%= data.eventName %> </p>
                                <p style="margin-bottom: 10px;">EventVenue : <%= data.eventVenue %> </p>
                                <p style="margin-bottom: 10px;">eventDuration : <%= data.eventDuration %> </p>
                                <p style="margin-bottom: 10px;">eventRegion : <%= data.eventRegion %> </p>
                                <p style="margin-bottom: 10px;">Ticket Type : <%= data.category %> </p>
                                <p style="margin-bottom: 10px;">Ticket price : $<%= data.price %> </p>
                                <p style="margin-bottom: 10px;">eventDate:  <%=     data.eventDate.getDate()%>/<%= data.eventDate.getMonth() + 1%>/<%= data.eventDate.getFullYear()%> </p>
                                 <a href="#"><img src="<%=qrcode%>" alt="qr-code"></a>
                            </td>
                        </tr>
                    </tbody>
                </table>
</code>```

Body:
This the code of sending an email using mailgun:

const qrcodeEmail = async (email, subject,text,qrcode,user,data) => {
  try {
    const requiredPath = path.join(__dirname, "../views/emailTemplates/qrcodeEmail.ejs");

    const emailData = await ejs.renderFile(requiredPath,{user:user,data:data,qrcode:qrcode});
     var mailData = {
        from: 'moilasurprise7@gmail.com',
        to: 'moilasurprise7@gmail.com',
        subject:subject,
        html:emailData,
      };

      mailgun.messages().send(mailData, function (error, body) {
        if(error){
            console.log(error);
        }
        console.log("email sent successfully");
      });
} catch (error) {
    console.log(error.message);
}
};

The email is sent,the user and order details are showing but the qr-code is not displaying down here is the ejs email template.

Note: the qr-code is generated in this manner.

 await QRCode.toDataURL(text);

This is the ejs template where the qrcode is rendered:

Hi <%= user.name %>  <%=user.lastName%>       ,

Here is your ticket order

eventName : <%= data.eventName %>

EventVenue : <%= data.eventVenue %>

eventDuration : <%= data.eventDuration %>

eventRegion : <%= data.eventRegion %>

Ticket Type : <%= data.category %>

Ticket price : $<%= data.price %>

eventDate:  <%=     data.eventDate.getDate()%>/<%= data.eventDate.getMonth() + 1%>/<%= data.eventDate.getFullYear()%>

                                 <img src="<%=qrcode%>" alt="qr-code">


问:
Find Median Using MySQL, Hacker Rank Challenge
A median is defined as a number separating the higher half of a data set from the lower half. Query the median of the Northern Latitudes (LAT_N) from STATION and round your answer to  decimal places.
(where LAT_N is the northern latitude and LONG_W is the western longitude.)
Input STATION table:
enter image description here

Median is the middle number of sorted numbers. So I found the total records using COUNT function. The count was 499. So the median is (499+1)/2 = 250.

After getting the middle number as 250 I used this query:

SELECT ROUND(LAT_N,4) FROM (
SELECT LAT_N, DENSE_RANK() OVER (ORDER BY LAT_N) dens_rank

FROM STATION) AS E
WHERE E.dens_rank = 250

(Anyway Hacker Rank approved it!). But I want to pass that 250 dynamically.

Something Like:
SELECT ROUND(LAT_N,4) FROM (
SELECT LAT_N, DENSE_RANK() OVER (ORDER BY LAT_N) dens_rank

FROM STATION) AS E
WHERE E.dens_rank = COUNT((E.LAT_N+1)/2)

Error Message:
ERROR 1111 (HY000) at line 1: Invalid use of group function


问:
How to config bitnami/nginx as L4 reverse proxy?
I'm using eks, aws-rds, binami/nginx (not bitnami/nginx-ingress-controller) with AWS NLB, my aws-rds is private access only, eks server can access it. one ec2 in another aws account want to access the private rds throuth nginx server (NLB).

ec2(vpc2) -> nginx (eks/vpc1) -> rds(vpc1)

How should i configure the bitnami/nginx Chart values.yaml? I have other solutions, but this question want to discuss bitnami/nginx solution.


问:
MATLAB error handling of SIMULINK (sim) due to external component
My problem is that I am running a sweep study with some parameters. I change them in MATLAB and then run a simulation in MATLAB with the sim command. The simulation in SIMULINK contains an external software component from COMSOL with an FEM behind it. In some cases where the configuration is unfavorable (rapid changes in the feedback loop of the controlled system), the FEM tool is not able to converge in finite time, resulting in an error after a few simulation seconds/minutes/hours. The simulation command is inside a try-catch section to avoid that the program is stopped and the next study step starts to process the acquired data.

The problem is that in case the simulation has a convergence problem, the data generated up to this error is not sent to the workspace, but would be valid, and so I cannot find out from the data what was the reason for the convergence problem.

As additional information, I have been using the ToWorkspace block to send the data to my workspace where I do my post processing, and that works fine when the simulation is complete.

If any of you have any ideas on how to solve this problem, maybe you can help me.
Thank you in advance.


问:
How to avoid "Look rotation viewing vector is zero" properly?
I am getting the "Look rotation viewing vector is zero" error but I can't avoid it.

I would expect to check the input vector against Vector3.zero (== or Equals) but it doesn't work.

Can you point me towards the right direction?

I checked this an tried all possibilities :

if (forward.Equals(Vector3.zero))
    return defaultRotation;

if (forward == Vector3.zero)
    return defaultRotation;

if (forward.sqrMagnitude < 0.001)
    return defaultRotation;

//still throws <look rotation zero> error.
return Quaternion.LookRotation(forward);
```


问:
100% CPU usage within visual studio but only 10% in release
I created a piece of code that needs to receive data through an API request by running a lot of tasks in parallel.

```<code>
            for (decimal i = StartNum.Value; i <= EndNum.Value; i++)
            {
                foreach (String zip in zips)
                {
                    TList.Add(Task.Run(() => GetDataFor(zip, i)));
                }
                while (TList.Count > 0)
                {
                    Task result = Task.WhenAny(TList).Result;
                    TList.Remove(result);
                    ProgressBar.Value++;
                }
            }
</code>```

This code causes a couple thousands of tasks to be created and waits for them all to finish to then again make a new tasklist until EndNum.Value is reached.

While debugging the code seems to use 100% of the CPU, shown in task manager and the VS diagnostics.
However when I build the app and run the exe file outside VS cpu utilisation reaches only 10%. Does this mean there is still a 10 times performance increase to be reached? If so how can I execute my funtion more efficiently so I can reach full utilisation?
Note that the actual performance of the app is identical in both cases

I tried using the Parallel.ForEach way but performance seems to be slower this way.

Body:
I created a piece of code that needs to receive data through an API request by running a lot of tasks in parallel.

            for (decimal i = StartNum.Value; i <= EndNum.Value; i++)
            {
                foreach (String zip in zips)
                {
                    TList.Add(Task.Run(() => GetDataFor(zip, i)));
                }
                while (TList.Count > 0)
                {
                    Task result = Task.WhenAny(TList).Result;
                    TList.Remove(result);
                    ProgressBar.Value++;
                }
            }

This code causes a couple thousands of tasks to be created and waits for them all to finish to then again make a new tasklist until EndNum.Value is reached.

While debugging the code seems to use 100% of the CPU, shown in task manager and the VS diagnostics.
However when I build the app and run the exe file outside VS cpu utilisation reaches only 10%. Does this mean there is still a 10 times performance increase to be reached? If so how can I execute my funtion more efficiently so I can reach full utilisation?
Note that the actual performance of the app is identical in both cases

I tried using the Parallel.ForEach way but performance seems to be slower this way.


问:
how to open files from android download manager's notification in react native android?
I am trying to open pdf files which gets downloaded through the android download manager in react native .
I have used rn-fetch-blob for this and I think am unable to set the path in the download manager...
here is code for it ...
tried opening files from the notifications but was not able to do so  , every time i clicked on the "file downloaded successfully notification" got an toast error saying "Can't open file".

const downloadFile = fileUrl => {
  let date = new Date();
  let FILE_URL = fileUrl;
  let file_ext = getFileExtention(FILE_URL);
  file_ext = '.' + file_ext[0];
  const {config, fs} = RNFetchBlob;
  let RootDir = fs.dirs.DownloadDir;
  let options = {
    fileCache: true,
    addAndroidDownloads: {
      path:
        RootDir +
        '/file_' +
        Math.floor(date.getTime() + date.getSeconds() / 2) +
        file_ext,
      description: 'downloading file...',
      notification: true,
      useDownloadManager: true,
    },
  };
  config(options)
    .fetch('GET', FILE_URL)
    .then(res => {
      console.log('res -> ', JSON.stringify(res));
    });
};```


问:
main.js in react app is not working properly
I am new to programming and trying to convert a html templete into a react app and i have copy the assets folder and paste it into the public folder of react app and all the link and scripts from the index.html of templete into index.html of the react app but when i am trying to convert the html code into react component  then the main.js file functions of vendor folder not working in the component and the function of vendor folder's are showing not defined in main.js of react app.

I am expecting not to change the js code of main.js and it should work as normally as working in the html templete.


问:
How to download an image from a website and save it to the Blob via Azure Functions?
This code saves the image with a size of 0 bytes. Why doesn't it save the whole image?

Here is an example of how to directly save an image to blob storage.

```<code>[FunctionName("ImportFunc")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "import/{category}")] HttpRequest req,
        [Blob("images/{category}.jpeg", FileAccess.Write)]
        Stream image,
        string category,
        ILogger log)
    {
        try
        {
            // URL of the image to download
            string imageUrl = "https://www.w3schools.com/html/img_girl.jpg";

            // Create a new HttpClient instance
            HttpClient httpClient = new HttpClient();

            // Download the image as a stream
            image = await httpClient.GetStreamAsync(imageUrl);

            return new OkResult();
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Something went wrong");
            return new OkResult();
        }
    }
</code>```

Body:
This code saves the image with a size of 0 bytes. Why doesn't it save the whole image?

Here is an example of how to directly save an image to blob storage.

[FunctionName("ImportFunc")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "import/{category}")] HttpRequest req,
        [Blob("images/{category}.jpeg", FileAccess.Write)]
        Stream image,
        string category,
        ILogger log)
    {
        try
        {
            // URL of the image to download
            string imageUrl = "https://www.w3schools.com/html/img_girl.jpg";

            // Create a new HttpClient instance
            HttpClient httpClient = new HttpClient();

            // Download the image as a stream
            image = await httpClient.GetStreamAsync(imageUrl);

            return new OkResult();
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Something went wrong");
            return new OkResult();
        }
    }


问:
How to Add EventBridge Schedules with Nodejs, which target SQS Send Message
I wanted to add EventBridge Schedules, which target SQS sendMessage, using nodejs but not able to find any good documentation.

I am trying to insert EventBridge Schedules, with nodejs


问:
Embed a powerapp url in iframe
getting 400 bad request

I'm trying to embed a Microsoft Dynamics 365-powerapp url in my angular6 application inside an iframe. I'm getting bad request.

Title: Embed a powerapp url in iframe


问:
Typescript not identifying property in mixin
I am learning Adonis Js v5 Framework. I trying to make mixin for User Model as documented here: click

Below I have attached code and Image of error that I am getting

I just want to know Am I doing it in right way or is there any other workaround for this

This is mixin HasProfilePhoto.ts

```<code>
import { BaseModel} from "@ioc:Adonis/Lucid/Orm";
import { NormalizeConstructor } from '@ioc:Adonis/Core/Helpers'

const HasProfilePhoto = <T extends NormalizeConstructor<typeof BaseModel>>(superclass:T)=>{

    return class extends superclass{

        public async updateProfilePhoto(photo:any):Promise<void>{
            await photo.moveToDisk('./');
            //@ts-ignore
            this.profilePhotoPath = photo.fileName;
            await this.save();

        }

        public defaultProfilePhotoUrl():string
        {
            //@ts-ignore
            let name = this.name.split(' ').map(segment=>{
                return segment.substring(0,1);
            }).join(' ').trim();

            return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&color=7F9CF5&background=EBF4FF`;
        }
    }
}

export default HasProfilePhoto;

</code>```

This is UserModel File

```<code>import { DateTime } from 'luxon'
import Hash from '@ioc:Adonis/Core/Hash'
import { column, beforeSave, BaseModel, computed, afterFind } from '@ioc:Adonis/Lucid/Orm'
import { compose } from '@ioc:Adonis/Core/Helpers';
import HasProfilePhoto from 'App/Mixins/HasProfilePhoto';
import HasApiTokens from 'App/Mixins/HasApiTokens';
import Drive from '@ioc:Adonis/Core/Drive'
import Env from '@ioc:Adonis/Core/Env';

export default class User extends compose(BaseModel,HasApiTokens,HasProfilePhoto) {

    @column({ isPrimary: true })
    public id: number

    @column()
    public name: string

    @column()
    public email: string

    @column({ serializeAs: null })
    public password: string

    @column()
    public rememberMeToken: string | null

    @column()
    public profilePhotoPath: string | null

    @computed({serializeAs:'profile_photo_url'})
    public profilePhotoUrl: string;

    @column.dateTime()
    public emailVerifiedAt:DateTime|null

    @column.dateTime({ autoCreate: true })
    public createdAt: DateTime

    @column.dateTime({ autoCreate: true, autoUpdate: true })
    public updatedAt: DateTime

    @beforeSave()
    public static async hashPassword (user: User) {
        if (user.$dirty.password) {
        user.password = await Hash.make(user.password)
        }
    }

    @afterFind()
    public static async addPofilePhotoUrl(user:User){

        if(user.profilePhotoPath){
            let url = await Drive.getUrl(user.profilePhotoPath);
            url = Env.get('APP_URL')+url
            //this.$addColumn('profile_photo_url',{});
            user.profilePhotoUrl = url;
            return;
        }
        user.profilePhotoUrl = user.defaultProfilePhotoUrl();
    }

}

</code>```

IMAGE

Body:
I am learning Adonis Js v5 Framework. I trying to make mixin for User Model as documented here: click

Below I have attached code and Image of error that I am getting

I just want to know Am I doing it in right way or is there any other workaround for this

This is mixin HasProfilePhoto.ts

import { BaseModel} from "@ioc:Adonis/Lucid/Orm";
import { NormalizeConstructor } from '@ioc:Adonis/Core/Helpers'

const HasProfilePhoto = <T extends NormalizeConstructor<typeof BaseModel>>(superclass:T)=>{

    return class extends superclass{

        public async updateProfilePhoto(photo:any):Promise<void>{
            await photo.moveToDisk('./');
            //@ts-ignore
            this.profilePhotoPath = photo.fileName;
            await this.save();

        }

        public defaultProfilePhotoUrl():string
        {
            //@ts-ignore
            let name = this.name.split(' ').map(segment=>{
                return segment.substring(0,1);
            }).join(' ').trim();

            return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&color=7F9CF5&background=EBF4FF`;
        }
    }
}

export default HasProfilePhoto;

This is UserModel File

import { DateTime } from 'luxon'
import Hash from '@ioc:Adonis/Core/Hash'
import { column, beforeSave, BaseModel, computed, afterFind } from '@ioc:Adonis/Lucid/Orm'
import { compose } from '@ioc:Adonis/Core/Helpers';
import HasProfilePhoto from 'App/Mixins/HasProfilePhoto';
import HasApiTokens from 'App/Mixins/HasApiTokens';
import Drive from '@ioc:Adonis/Core/Drive'
import Env from '@ioc:Adonis/Core/Env';

export default class User extends compose(BaseModel,HasApiTokens,HasProfilePhoto) {

    @column({ isPrimary: true })
    public id: number

    @column()
    public name: string

    @column()
    public email: string

    @column({ serializeAs: null })
    public password: string

    @column()
    public rememberMeToken: string | null

    @column()
    public profilePhotoPath: string | null

    @computed({serializeAs:'profile_photo_url'})
    public profilePhotoUrl: string;

    @column.dateTime()
    public emailVerifiedAt:DateTime|null

    @column.dateTime({ autoCreate: true })
    public createdAt: DateTime

    @column.dateTime({ autoCreate: true, autoUpdate: true })
    public updatedAt: DateTime

    @beforeSave()
    public static async hashPassword (user: User) {
        if (user.$dirty.password) {
        user.password = await Hash.make(user.password)
        }
    }

    @afterFind()
    public static async addPofilePhotoUrl(user:User){

        if(user.profilePhotoPath){
            let url = await Drive.getUrl(user.profilePhotoPath);
            url = Env.get('APP_URL')+url
            //this.$addColumn('profile_photo_url',{});
            user.profilePhotoUrl = url;
            return;
        }
        user.profilePhotoUrl = user.defaultProfilePhotoUrl();
    }

}

IMAGE


问:
How to speed asyncio up?
I know this has been asked many times, but none of the solutions worked for my code (or I am too stupid to implent them correctly), but I have a problem with an asynchronous request in Python. I am trying to process around 40 000 pdfs and it is quite slow. My code is as follows:

```<code>async def post_file(data, token, mime_type, filename, summarize=False):
    global logs
    xml_post = prepare_file_for_post(data, token, mime_type, filename)
    headers = {'Content-Type': 'application/xml'}
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=200),headers=headers) as session:
        start_time = datetime.now()
        async with session.post(url, data=xml_post) as response:
            end_time = datetime.now()
            logging.info("Done processing|" + filename + "|in|" + str((end_time - start_time).total_seconds()))
            resp = await response.content.read()
            if summarize:
                return read_recognized_text_from_response(resp)
            else:
                return read_entire_response(resp)

def write_summarized_result_to_file(barcode_1, barcode_2, recognized_text, file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        if barcode_1 != None:
            f.write("Barcode 1: " + str(barcode_1.text) + "\n")
        else:
            f.write("Barcode 1: None\n")
        if barcode_2 != None:
            f.write("Barcode 2: " + str(barcode_2.text) + "\n")
        else:
            f.write("Barcode 2: None\n")
        f.write("------------------------------------" + "\n\n")
        for item in recognized_text:
            f.write("%s\n" % item)

def write_entire_result_to_file(result, file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(result)

async def analyze_file(input_folder, filename, token, semaphore):
    await semaphore.acquire()
    data, mime_type = read_file(input_folder + '/' + filename)
    if entire_output:
        result = await post_file(data, token, mime_type, filename)
        write_entire_result_to_file(result, output_folder + today + '_' + str(filename) + '.xml')
    else:
        barcode_1, barcode_2, recognized_text = await post_file(data, token, mime_type, filename, True)
        write_summarized_result_to_file(barcode_1, barcode_2, recognized_text, output_folder + today + '_' + str(filename) + '.txt')
    semaphore.release()

async def main(input_folder, token):
    ocr_task = []
    semaphore = asyncio.Semaphore(value=4)
    for filename in os.listdir(input_folder):
         if filename.endswith('pdf') or filename.endswith('jpg') or filename.endswith('png') or filename.endswith('jpeg') or filename.endswith('tif') or filename.endswith('tiff'):
            ocr_task = asyncio.create_task(analyze_file(input_folder, filename, token, semaphore))
    try:
        await asyncio.wait([ocr_task])
    except Exception as e:
        logging.error("An error occured|" + e)
</code>```

And the way I start the process:

```<code>token = authorize()
start_time_total = datetime.now()
await main(input_folder, token)
end_time_total = datetime.now()
logging.info("Done processing|all Files|in|" + str((end_time_total - start_time_total).total_seconds()))
</code>```

If somebody could point out to my mistake, that would be awesome, because I kind of tried everything I found.

Title: How to speed asyncio up?

Body:
I know this has been asked many times, but none of the solutions worked for my code (or I am too stupid to implent them correctly), but I have a problem with an asynchronous request in Python. I am trying to process around 40 000 pdfs and it is quite slow. My code is as follows:

async def post_file(data, token, mime_type, filename, summarize=False):
    global logs
    xml_post = prepare_file_for_post(data, token, mime_type, filename)
    headers = {'Content-Type': 'application/xml'}
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=200),headers=headers) as session:
        start_time = datetime.now()
        async with session.post(url, data=xml_post) as response:
            end_time = datetime.now()
            logging.info("Done processing|" + filename + "|in|" + str((end_time - start_time).total_seconds()))
            resp = await response.content.read()
            if summarize:
                return read_recognized_text_from_response(resp)
            else:
                return read_entire_response(resp)

def write_summarized_result_to_file(barcode_1, barcode_2, recognized_text, file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        if barcode_1 != None:
            f.write("Barcode 1: " + str(barcode_1.text) + "\n")
        else:
            f.write("Barcode 1: None\n")
        if barcode_2 != None:
            f.write("Barcode 2: " + str(barcode_2.text) + "\n")
        else:
            f.write("Barcode 2: None\n")
        f.write("------------------------------------" + "\n\n")
        for item in recognized_text:
            f.write("%s\n" % item)

def write_entire_result_to_file(result, file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(result)

async def analyze_file(input_folder, filename, token, semaphore):
    await semaphore.acquire()
    data, mime_type = read_file(input_folder + '/' + filename)
    if entire_output:
        result = await post_file(data, token, mime_type, filename)
        write_entire_result_to_file(result, output_folder + today + '_' + str(filename) + '.xml')
    else:
        barcode_1, barcode_2, recognized_text = await post_file(data, token, mime_type, filename, True)
        write_summarized_result_to_file(barcode_1, barcode_2, recognized_text, output_folder + today + '_' + str(filename) + '.txt')
    semaphore.release()

async def main(input_folder, token):
    ocr_task = []
    semaphore = asyncio.Semaphore(value=4)
    for filename in os.listdir(input_folder):
         if filename.endswith('pdf') or filename.endswith('jpg') or filename.endswith('png') or filename.endswith('jpeg') or filename.endswith('tif') or filename.endswith('tiff'):
            ocr_task = asyncio.create_task(analyze_file(input_folder, filename, token, semaphore))
    try:
        await asyncio.wait([ocr_task])
    except Exception as e:
        logging.error("An error occured|" + e)

And the way I start the process:

token = authorize()
start_time_total = datetime.now()
await main(input_folder, token)
end_time_total = datetime.now()
logging.info("Done processing|all Files|in|" + str((end_time_total - start_time_total).total_seconds()))

If somebody could point out to my mistake, that would be awesome, because I kind of tried everything I found.


问:
Newest Python on Red Hat 7.9?
How to install almost newest Python (currently 3.11) on the Red Hat® Enterprise (GNU/)Linux® server 7.9? Or at least not older than two years (actually 3.8)? In a Corporate behind Firewall with Regulatory and Policies…

Based on the Product Life Cycle of Red Hat® Software Collections for Red Hat® Enterprise Linux® 7 there should be Python 3.8 available. But the Red Hat® Developers Software Collections page says, there is only Python 3.6 available. The Introduction page of Red Hat Software Collections says, there is only Python 3.5 available. How to make (payed) Enterprise Red Hat® consistent, please? How to make Red Hat® reduce their tech.&arch. debts?

Dtto for Rad Hat® 8, please?

Title: Newest Python on Red Hat 7.9?


问:
Proper JSON construction to add different languages
I need to change this Query to be able to handle the different languages.
I'm already on my way but I want to be able to write out languages also.

```<code>with data (code, bez) as (
  values
    ('01', 'Test 1'),
    ('02', 'Test 2'),
    ('03', 'Test 3'),
    ('04', 'Test 4')
), languages (lang) as (
  values ('de'), ('fr'), ('it'), ('en')
)
select jsonb_build_object('cus_test', jsonb_object_agg('1'||code, l))
from (
  select code,
         jsonb_object_agg('bezeichnung_'||lang, bez) ||
             jsonb_build_object('code', '1'||code) ||
             jsonb_build_object('cus_immopaccode', code) ||
             jsonb_build_object('cus_immopac_mandant_cd', 1) as l
  from data
    cross join languages
  group by data.code
) x
;
</code>```

At the moment the output is like this:

```<code>{
  "cus_test": {
    "101": {
      "code": "101",
      "bezeichnung_de": "Test 1",
      "bezeichnung_en": "Test 1",
      "bezeichnung_fr": "Test 1",
      "bezeichnung_it": "Test 1",
      "cus_immopaccode": "01",
      "cus_immopac_mandant_cd": 1
    },
    "102": {
      "code": "102",
      "bezeichnung_de": "Test 2",
      "bezeichnung_en": "Test 2",
      "bezeichnung_fr": "Test 2",
      "bezeichnung_it": "Test 2",
      "cus_immopaccode": "02",
      "cus_immopac_mandant_cd": 1
    },
    "103": {
      "code": "103",
      "bezeichnung_de": "Test 3",
      "bezeichnung_en": "Test 3",
      "bezeichnung_fr": "Test 3",
      "bezeichnung_it": "Test 3",
      "cus_immopaccode": "03",
      "cus_immopac_mandant_cd": 1
    },
    "104": {
      "code": "104",
      "bezeichnung_de": "Test 4",
      "bezeichnung_en": "Test 4",
      "bezeichnung_fr": "Test 4",
      "bezeichnung_it": "Test 4",
      "cus_immopaccode": "04",
      "cus_immopac_mandant_cd": 1
    }
  }
}
</code>```

Now I want to add the language translations to it like this:

```<code>with data (code, bez_de, bez_fr, bez_it, bez_en) as (
  values
    ('01','Pruefung 1', 'Test 1','la proova 1','Test 1'),
    ('02', 'Pruefung 1', 'Test 1','la proova 1','Test 1'),
    ('03', 'Pruefung 1', 'Test 1','la proova 1','Test 1'),
    ('04', 'Pruefung 1', 'Test 1','la proova 1','Test 1'))
</code>```

But I don't how to implement it correctly.

Body:
I need to change this Query to be able to handle the different languages.
I'm already on my way but I want to be able to write out languages also.

with data (code, bez) as (
  values
    ('01', 'Test 1'),
    ('02', 'Test 2'),
    ('03', 'Test 3'),
    ('04', 'Test 4')
), languages (lang) as (
  values ('de'), ('fr'), ('it'), ('en')
)
select jsonb_build_object('cus_test', jsonb_object_agg('1'||code, l))
from (
  select code,
         jsonb_object_agg('bezeichnung_'||lang, bez) ||
             jsonb_build_object('code', '1'||code) ||
             jsonb_build_object('cus_immopaccode', code) ||
             jsonb_build_object('cus_immopac_mandant_cd', 1) as l
  from data
    cross join languages
  group by data.code
) x
;

At the moment the output is like this:

{
  "cus_test": {
    "101": {
      "code": "101",
      "bezeichnung_de": "Test 1",
      "bezeichnung_en": "Test 1",
      "bezeichnung_fr": "Test 1",
      "bezeichnung_it": "Test 1",
      "cus_immopaccode": "01",
      "cus_immopac_mandant_cd": 1
    },
    "102": {
      "code": "102",
      "bezeichnung_de": "Test 2",
      "bezeichnung_en": "Test 2",
      "bezeichnung_fr": "Test 2",
      "bezeichnung_it": "Test 2",
      "cus_immopaccode": "02",
      "cus_immopac_mandant_cd": 1
    },
    "103": {
      "code": "103",
      "bezeichnung_de": "Test 3",
      "bezeichnung_en": "Test 3",
      "bezeichnung_fr": "Test 3",
      "bezeichnung_it": "Test 3",
      "cus_immopaccode": "03",
      "cus_immopac_mandant_cd": 1
    },
    "104": {
      "code": "104",
      "bezeichnung_de": "Test 4",
      "bezeichnung_en": "Test 4",
      "bezeichnung_fr": "Test 4",
      "bezeichnung_it": "Test 4",
      "cus_immopaccode": "04",
      "cus_immopac_mandant_cd": 1
    }
  }
}

Now I want to add the language translations to it like this:

with data (code, bez_de, bez_fr, bez_it, bez_en) as (
  values
    ('01','Pruefung 1', 'Test 1','la proova 1','Test 1'),
    ('02', 'Pruefung 1', 'Test 1','la proova 1','Test 1'),
    ('03', 'Pruefung 1', 'Test 1','la proova 1','Test 1'),
    ('04', 'Pruefung 1', 'Test 1','la proova 1','Test 1'))

But I don't how to implement it correctly.


问:
How can I get full info on update page
I have an ASP.NET Core MVC project without Entity Framework.

When I click on the "update" button, I want to update page and make it does not become empty.

This is my view:

```<code><div class="form-group">
        <form asp-action="OdemeTurGuncelle">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                ID
                <input asp-for="odemetur_id" class="form-control" />
                <span asp-validation-for="odemetur_id" class="text-danger"></span>
            </div>
            <div class="form-group">
                Ödeme Türü
                <input asp-for="odemetur_adi" class="form-control" />
                <span asp-validation-for="odemetur_adi" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
</div>
</code>```

And my controller :

```<code>[HttpGet]
public IActionResult OdemeTurGuncelle()
{
    return View();
}

[HttpPost]
public IActionResult OdemeTurGuncelle(OdemeTur odemeTur)
{
    string constr = Genel.conString;

    using (NpgsqlConnection con = new NpgsqlConnection(constr))
    {
        string query = "UPDATE odemeturleri SET odemetur_adi=@odemetur_adi WHERE odemetur_id=@odemetur_id";

        using (NpgsqlCommand cmd = new NpgsqlCommand(query))
        {
            cmd.Connection = con;
            con.Open();

            cmd.Parameters.AddWithValue("@odemetur_id", odemeTur.odemetur_id);
            cmd.Parameters.AddWithValue("@odemetur_adi", odemeTur.odemetur_adi);

            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    // return View(ders);
    return RedirectToAction("Index");
}
</code>```

I can do it with Entity Framework, but I want to do it without EF

Title: How can I get full info on update page

Body:
I have an ASP.NET Core MVC project without Entity Framework.

When I click on the "update" button, I want to update page and make it does not become empty.

This is my view:

        <form asp-action="OdemeTurGuncelle">

                ID
                <input asp-for="odemetur_id" class="form-control" />

                Ödeme Türü
                <input asp-for="odemetur_adi" class="form-control" />

                <input type="submit" value="Save" class="btn btn-primary" />

        </form>

And my controller :

[HttpGet]
public IActionResult OdemeTurGuncelle()
{
    return View();
}

[HttpPost]
public IActionResult OdemeTurGuncelle(OdemeTur odemeTur)
{
    string constr = Genel.conString;

    using (NpgsqlConnection con = new NpgsqlConnection(constr))
    {
        string query = "UPDATE odemeturleri SET odemetur_adi=@odemetur_adi WHERE odemetur_id=@odemetur_id";

        using (NpgsqlCommand cmd = new NpgsqlCommand(query))
        {
            cmd.Connection = con;
            con.Open();

            cmd.Parameters.AddWithValue("@odemetur_id", odemeTur.odemetur_id);
            cmd.Parameters.AddWithValue("@odemetur_adi", odemeTur.odemetur_adi);

            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    // return View(ders);
    return RedirectToAction("Index");
}

I can do it with Entity Framework, but I want to do it without EF


问:
SELECT value don't want to be inserted into table through INSER INTO table_name VALUES(SELECT...). ANY TIPS?
So I have a table and into that table I want to insert some values. And everything is working but when I come to my subquery:

INSERT INTO `gb.uträckning`(of_bostäder_objekt, typ_av_objekt, objekttyp, antal_kvm, relativt_hyrestal_bastal)
VALUES(22105859, 'B', 'B2K' , 64,
(SELECT
IF(t1.typ_av_objekt = 'B' OR typ_av_objekt = 'NyB', t1.antal_kvm +
IF(t1.balkong_uteplats_saknas = 1, t2.`2`, IF(t1.balkong_uteplats_saknas = 2, t2.`1`, IF(t1.balkong_uteplats_saknas = 3, t2.`3`, t2.`2`))), NULL)
FROM `gb.uträckning` t1, `nh.lägenhetstyp` t2
WHERE t1.objekttyp = t2.lägenhetstyp));
```

So my subquery return the value I want but don't want to be inserted into the table. I don't get an error. But if my query return more than 1 value then an error pop up saying "Subquery returns more than 1 row".My Table, value should be inserted into column_name 'relativt_hyrestal_bastal'What my subquery returns

I have tried to change the equal operator in Where clause but get an syntax error or that my subquery returns more than 1 row. I have also tried to assign the selected value into an varaible and then into insert but it doesn't work. My query returns what I want but the problem is that it does not want to insert it into the table and it don't want to insert if my query returns more than 1 value. Because I want to use this subquery in a trigger later on to use for multiple rows at once.

Body:
So I have a table and into that table I want to insert some values. And everything is working but when I come to my subquery:

INSERT INTO `gb.uträckning`(of_bostäder_objekt, typ_av_objekt, objekttyp, antal_kvm, relativt_hyrestal_bastal)
VALUES(22105859, 'B', 'B2K' , 64,
(SELECT
IF(t1.typ_av_objekt = 'B' OR typ_av_objekt = 'NyB', t1.antal_kvm +
IF(t1.balkong_uteplats_saknas = 1, t2.`2`, IF(t1.balkong_uteplats_saknas = 2, t2.`1`, IF(t1.balkong_uteplats_saknas = 3, t2.`3`, t2.`2`))), NULL)
FROM `gb.uträckning` t1, `nh.lägenhetstyp` t2
WHERE t1.objekttyp = t2.lägenhetstyp));

So my subquery return the value I want but don't want to be inserted into the table. I don't get an error. But if my query return more than 1 value then an error pop up saying "Subquery returns more than 1 row".My Table, value should be inserted into column_name 'relativt_hyrestal_bastal'What my subquery returns

I have tried to change the equal operator in Where clause but get an syntax error or that my subquery returns more than 1 row. I have also tried to assign the selected value into an varaible and then into insert but it doesn't work. My query returns what I want but the problem is that it does not want to insert it into the table and it don't want to insert if my query returns more than 1 value. Because I want to use this subquery in a trigger later on to use for multiple rows at once.


问:
How do I test a sequelize database updating function like this?
Hi I can I test a function like this? I cannot test it properly because it says that relation "facilities" does not exist, however I now it exists because I can add a new record.
I should I test this code:

```<code>export async function postMemberController(req, res) {
  try {
    if (req.decodedToken.user_id || req.decodedToken.id) {
      const facility = await db.facility.findOne({
        where: { id: req.body.facility_id },
        raw: true,
      });

      if (!facility?.id) {
        res.send(
          "no facilities"
        );
      } else {

        let member = await db.member.findOne({
          where: { id_no: Number(req.body.id_no) },
          raw: true,
        });

        const admin = await db.user.findOne({
          where: { facility_id: req.body.facility_id },
          raw: true,
        });
        const data = await db.sequelize.transaction(async t => {
          if (member?.id_no) {
            await db.member
              .update(
                {
                  ...req.body,
                  facility_id: [...new Set([...member.facility_id, req.body.facility_id])],
                },
                { where: { id_no: member.id_no } },
                { transaction: t }
              )
              .catch(e => console.log('error : creation MEMBER??? ', e));

            const adminToken = await tokenCreator({ ...admin }, 3);
            !req.body?.from &&
              (await axios
                .put(
                  `${process.env.CENTRAL_URL}/members`,
                  {
                    body: {
                      ...req.body,
                      facility_id: [...new Set([...member.facility_id, req.body.facility_id])],
                      from: 'web',
                    },
                    where: { id: member.id },
                  },
                  {
                    headers: { authorization: 'Bearer ' + adminToken },
                  }
                )
                .catch(e => console.log('erorr ', e.response.data, e.config.url)));
          } else {
            const auth = adminFirebase.auth;

            const firebaseToken = await auth.createCustomToken(generateUUID());

            member = await db.member
              .create(
                {
                  ...req.body,
                  firebase_token: firebaseToken,
                  facility_id: [req.body.facility_id],
                  creator: admin.user_id,
                  updater: admin.user_id,
                },
                { transaction: t }
              )
              .catch(e => console.log('error : creation MEMBER??? ', e));
            if (member) {
              const card = await db.card.findOne({
                where: { card_id: member.dataValues.card_id },
                raw: true,
              });
              if (card) {
                await db.card.update(
                  { card_number: req.body.card_number },
                  {
                    where: {
                      card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
                    },
                  },
                  { transaction: t }
                );
              } else {
                const newCard = await db.card.create(
                  {
                    card_number: req.body?.card_number,
                    card_id: member?.dataValues?.card_id,
                    creator: admin.user_id,
                    updater: admin.user_id,
                    facility_id: req.body.facility_id,
                    credits: 0,
                  },
                  { transaction: t }
                );
              }
            }

            const adminToken = await tokenCreator({ ...admin }, 3);
            !req.body?.from &&
              (await axios
                .post(
                  `${process.env.CENTRAL_URL}/members`,
                  {
                    ...req.body,
                    id: member.dataValues.id,
                    card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
                    facility_id: req.body.facility_id,
                    from: 'web',
                  },
                  {
                    headers: { authorization: 'Bearer ' + adminToken },
                  }
                )
                .catch(e => console.log('erorr ', e, e?.response?.data, e.config.url)));

            !req.body?.from &&
              (await axios
                .put(
                  `${process.env.CENTRAL_URL}/cards`,
                  {
                    body: {
                      card_number: req.body.card_number.toString(),
                      facility_id: req.body.facility_id,
                      from: 'web',
                    },
                    where: {
                      card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
                    },
                  },
                  {
                    headers: { authorization: 'Bearer ' + adminToken },
                  }
                )
                .catch(e => console.log('erorr ', e.response.data, e.config.url)));
          }

          return member;
        });
        delete data.dataValues?.password;
        delete data?.password;

        const memberToken = await tokenCreator({ ...data.dataValues }, 3);
        return res
          .status(200)
          .json({ data, session_id: data.id_no || data.dataValues.id_no, token: memberToken });
      }
    } else {
      return res.sendStatus(401);
    }
  } catch (error) {
    res.status(500).send(error.message);
  }
}
</code>```

this is how I try to test it:

```<code>
  it('post member from web terminal', async () => {
    try {
      jest.mock('../db/models/index.js', () => {
        const SequelizeMock = require('sequelize-mock');
        const dbMock = new SequelizeMock();
        const facility = dbMock.define('facilities', {
          id: '6-30189',
        })
        const member = dbMock.define('members', {});
        const card = dbMock.card('cards', {});
      });
      const req = {
        decodedToken: { user_id: makeId() },
        body: member,
      };

      const res = {
        sendStatus(num) {},
        status(num) {
          return { json(payload) {}, send(payload) {} };
        },
      };

      const request = await postMemberController(req, res);
      delete member.from;
      expect(request).toHaveBeenCalledWith({ ...member });
    } catch (error) {
      console.log('ERROR post member ', error);
      throw new Error(error);
    }
  });
</code>```

How do I write a test for this???? when I call postMemberController inside jest it seems that can't find the relations in the table, I tried to console.log db.facility object from jest test output, there is nothing, not even empty object or null or undefined. I don't understand why? How can I solve this??

Here is the object  I am sending:

```<code> const card_number = 11111111111111;
  const card_id = makeId();
  const schedule = makeId();
  const club = makeId();
  const trainer = makeId();
  const user = makeId();
  const facility_id = '6-30189';

  const member = {
    from: 'central',
    card_number: card_number,
    id: makeId(),
    first_name: 'Demo',
    last_name: 'Demo',
    id_no: card_number,
    card_id,
    home_phone: null,
    urgent_phone: null,
    email: null,
    registered: true,
    schedule,
    club,
    trainer,
    birthplace: 'Gölbaşı/Ankara',
    birthdate: new Date().toISOString(),
    father_name: null,
    mother_name: null,
    gender: null,
    profession: null,
    address: null,
    phone_number: null,
    hes_code: null,
    blood_type: null,
    nationality: null,
    profile_photo: null,
    is_employee: false,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    firebase_token: null,
    file: null,
    session_ids: null,
    facility_id,
    following: null,
    creator: user,
    updater: user,
  };

</code>```

Body:
Hi I can I test a function like this? I cannot test it properly because it says that relation "facilities" does not exist, however I now it exists because I can add a new record.
I should I test this code:

export async function postMemberController(req, res) {
  try {
    if (req.decodedToken.user_id || req.decodedToken.id) {
      const facility = await db.facility.findOne({
        where: { id: req.body.facility_id },
        raw: true,
      });

      if (!facility?.id) {
        res.send(
          "no facilities"
        );
      } else {

        let member = await db.member.findOne({
          where: { id_no: Number(req.body.id_no) },
          raw: true,
        });

        const admin = await db.user.findOne({
          where: { facility_id: req.body.facility_id },
          raw: true,
        });
        const data = await db.sequelize.transaction(async t => {
          if (member?.id_no) {
            await db.member
              .update(
                {
                  ...req.body,
                  facility_id: [...new Set([...member.facility_id, req.body.facility_id])],
                },
                { where: { id_no: member.id_no } },
                { transaction: t }
              )
              .catch(e => console.log('error : creation MEMBER??? ', e));

            const adminToken = await tokenCreator({ ...admin }, 3);
            !req.body?.from &&
              (await axios
                .put(
                  `${process.env.CENTRAL_URL}/members`,
                  {
                    body: {
                      ...req.body,
                      facility_id: [...new Set([...member.facility_id, req.body.facility_id])],
                      from: 'web',
                    },
                    where: { id: member.id },
                  },
                  {
                    headers: { authorization: 'Bearer ' + adminToken },
                  }
                )
                .catch(e => console.log('erorr ', e.response.data, e.config.url)));
          } else {
            const auth = adminFirebase.auth;

            const firebaseToken = await auth.createCustomToken(generateUUID());

            member = await db.member
              .create(
                {
                  ...req.body,
                  firebase_token: firebaseToken,
                  facility_id: [req.body.facility_id],
                  creator: admin.user_id,
                  updater: admin.user_id,
                },
                { transaction: t }
              )
              .catch(e => console.log('error : creation MEMBER??? ', e));
            if (member) {
              const card = await db.card.findOne({
                where: { card_id: member.dataValues.card_id },
                raw: true,
              });
              if (card) {
                await db.card.update(
                  { card_number: req.body.card_number },
                  {
                    where: {
                      card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
                    },
                  },
                  { transaction: t }
                );
              } else {
                const newCard = await db.card.create(
                  {
                    card_number: req.body?.card_number,
                    card_id: member?.dataValues?.card_id,
                    creator: admin.user_id,
                    updater: admin.user_id,
                    facility_id: req.body.facility_id,
                    credits: 0,
                  },
                  { transaction: t }
                );
              }
            }

            const adminToken = await tokenCreator({ ...admin }, 3);
            !req.body?.from &&
              (await axios
                .post(
                  `${process.env.CENTRAL_URL}/members`,
                  {
                    ...req.body,
                    id: member.dataValues.id,
                    card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
                    facility_id: req.body.facility_id,
                    from: 'web',
                  },
                  {
                    headers: { authorization: 'Bearer ' + adminToken },
                  }
                )
                .catch(e => console.log('erorr ', e, e?.response?.data, e.config.url)));

            !req.body?.from &&
              (await axios
                .put(
                  `${process.env.CENTRAL_URL}/cards`,
                  {
                    body: {
                      card_number: req.body.card_number.toString(),
                      facility_id: req.body.facility_id,
                      from: 'web',
                    },
                    where: {
                      card_id: member.dataValues ? member.dataValues.card_id : member.card_id,
                    },
                  },
                  {
                    headers: { authorization: 'Bearer ' + adminToken },
                  }
                )
                .catch(e => console.log('erorr ', e.response.data, e.config.url)));
          }

          return member;
        });
        delete data.dataValues?.password;
        delete data?.password;

        const memberToken = await tokenCreator({ ...data.dataValues }, 3);
        return res
          .status(200)
          .json({ data, session_id: data.id_no || data.dataValues.id_no, token: memberToken });
      }
    } else {
      return res.sendStatus(401);
    }
  } catch (error) {
    res.status(500).send(error.message);
  }
}

this is how I try to test it:

  it('post member from web terminal', async () => {
    try {
      jest.mock('../db/models/index.js', () => {
        const SequelizeMock = require('sequelize-mock');
        const dbMock = new SequelizeMock();
        const facility = dbMock.define('facilities', {
          id: '6-30189',
        })
        const member = dbMock.define('members', {});
        const card = dbMock.card('cards', {});
      });
      const req = {
        decodedToken: { user_id: makeId() },
        body: member,
      };

      const res = {
        sendStatus(num) {},
        status(num) {
          return { json(payload) {}, send(payload) {} };
        },
      };

      const request = await postMemberController(req, res);
      delete member.from;
      expect(request).toHaveBeenCalledWith({ ...member });
    } catch (error) {
      console.log('ERROR post member ', error);
      throw new Error(error);
    }
  });

How do I write a test for this???? when I call postMemberController inside jest it seems that can't find the relations in the table, I tried to console.log db.facility object from jest test output, there is nothing, not even empty object or null or undefined. I don't understand why? How can I solve this??

Here is the object  I am sending:

 const card_number = 11111111111111;
  const card_id = makeId();
  const schedule = makeId();
  const club = makeId();
  const trainer = makeId();
  const user = makeId();
  const facility_id = '6-30189';

  const member = {
    from: 'central',
    card_number: card_number,
    id: makeId(),
    first_name: 'Demo',
    last_name: 'Demo',
    id_no: card_number,
    card_id,
    home_phone: null,
    urgent_phone: null,
    email: null,
    registered: true,
    schedule,
    club,
    trainer,
    birthplace: 'Gölbaşı/Ankara',
    birthdate: new Date().toISOString(),
    father_name: null,
    mother_name: null,
    gender: null,
    profession: null,
    address: null,
    phone_number: null,
    hes_code: null,
    blood_type: null,
    nationality: null,
    profile_photo: null,
    is_employee: false,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    firebase_token: null,
    file: null,
    session_ids: null,
    facility_id,
    following: null,
    creator: user,
    updater: user,
  };


问:
Boost final score after should clause in mongodb atlas search
I have few fields in which I want to search for users like: username, fullname, about, desgination.

Apart from this some of the users are marked as { type: 'EXPERT' }

Now my query looks like this:

```<code>    const docs = await this.userModel
      .aggregate()
      .search({
        index: 'User',
        count: { type: 'total' },
        compound: {
          should: [
            {
              text: {
                query: searchQuery,
                path: 'fullname',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 5 } },
              },
            },
            {
              text: {
                query: searchQuery,
                path: 'username',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 3 } },
              },
            },
            {
              text: {
                query: searchQuery,
                path: 'designation',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 5 } },
              },
            },
            {
              text: {
                query: searchQuery,
                path: 'about',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 1 } },
              },
            },
            {
              text: {
                query: 'EXPERT',
                path: 'type',
                score: { boost: { value: 5 } },
              },
            },
          ],
        },
      })
</code>```

Now this works fine until I search something rubbish like 'XYZ' and the { type: "EXPERT" } still comes on top.

What I want instead is to search in the fields: username, fullname, designation, about. And the searchQuery must match atleast one of the fields and if does match then apply the boost in the final results if any of the user in final results is of type 'EXPERT'

Body:
I have few fields in which I want to search for users like: username, fullname, about, desgination.

Apart from this some of the users are marked as { type: 'EXPERT' }

Now my query looks like this:

    const docs = await this.userModel
      .aggregate()
      .search({
        index: 'User',
        count: { type: 'total' },
        compound: {
          should: [
            {
              text: {
                query: searchQuery,
                path: 'fullname',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 5 } },
              },
            },
            {
              text: {
                query: searchQuery,
                path: 'username',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 3 } },
              },
            },
            {
              text: {
                query: searchQuery,
                path: 'designation',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 5 } },
              },
            },
            {
              text: {
                query: searchQuery,
                path: 'about',
                fuzzy: { prefixLength: 2 },
                score: { boost: { value: 1 } },
              },
            },
            {
              text: {
                query: 'EXPERT',
                path: 'type',
                score: { boost: { value: 5 } },
              },
            },
          ],
        },
      })

Now this works fine until I search something rubbish like 'XYZ' and the { type: "EXPERT" } still comes on top.

What I want instead is to search in the fields: username, fullname, designation, about. And the searchQuery must match atleast one of the fields and if does match then apply the boost in the final results if any of the user in final results is of type 'EXPERT'


问:
How to create hidden text field based on 'Yes' or 'No' response
I have an Interactive Report which includes a select list of 'yes' and 'no' for a box labelled 'DAS submitted'. Is it possible to use the dynamic action for select list that when the user selects 'yes', another text field appears which allows the user to input the 'DAS ID', but stays hidden if user selects 'no'?

I have tried playing around with the action buttons but can't seem to link it properly. As well as trying to follow these instructions (https://community.oracle.com/tech/developers/discussion/3703262/how-to-hide-text-field-item-based-on-true-or-false-cases-in-oracle-apex) but cannot find them clear enough from step 2. I am using Oracle Apex 22.2


问:
The gradle error on Build forge 1.8.9 mod
i used gradle to build my forge mod but i got these error

```<code>* Exception is:
org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'net.minecraftforge.gradle.forge', artifact: 'com.github.asbyth:ForgeGradle:ddb1eb0'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'com.github.asbyth:ForgeGradle:ddb1eb0')
  Searched in the following repositories:
    MavenRepo
    Gradle Central Plugin Repository
    maven(https://maven.minecraftforge.net/)
    maven2(https://jitpack.io/)
    maven3(https://repo.spongepowered.org/repository/maven-public/)
</code>```

also, is it due to my country internet filtering ?

Body:
i used gradle to build my forge mod but i got these error

* Exception is:
org.gradle.api.plugins.UnknownPluginException: Plugin [id: 'net.minecraftforge.gradle.forge', artifact: 'com.github.asbyth:ForgeGradle:ddb1eb0'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'com.github.asbyth:ForgeGradle:ddb1eb0')
  Searched in the following repositories:
    MavenRepo
    Gradle Central Plugin Repository
    maven(https://maven.minecraftforge.net/)
    maven2(https://jitpack.io/)
    maven3(https://repo.spongepowered.org/repository/maven-public/)

also, is it due to my country internet filtering ?


问:
How to check if Developer option is enabled or not in iOS using Xamarin forms?
For Android I used this "int devOptions = Settings.Secure.GetInt(this.ContentResolver, Settings.Global.DevelopmentSettingsEnabled, 0);" but how to do this in iOS devices?

I'm out of ideas here, Help me folks.


问:
Node.js firebase function, getting whatsapp media binary no data
As the title suggest, i'm not getting any data from the code below:

```<code>exports.getWhatsappBinaryData = functions.https.onCall((data, context) => {

    const urlHostName = data.hostName;
    const urlPath = data.path;
    const token = data.token;

    console.log('host: ' + urlHostName);
    console.log('path: ' + urlPath);
    console.log('token: ' + token);

    const https = require('https');
    const qs = require('querystring');

    let options = {
      'method': 'GET',
      'hostname': urlHostName,
      'path': urlPath,
      'headers': {
        'Authorization': 'Bearer ' + token,
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, DELETE, HEAD, OPTIONS',
        'Access-Control-Allow-Credentials': 'true',
      },
      'maxRedirects': 20
    };

    return new Promise((resolve, reject) => {
        let req = https.request(options, function (res) {
          let chunks = [];
          res.setEncoding('binary');

          res.on("data", function (chunk) {
            console.log('on chunk');
            chunks.push(Buffer.from(chunk, 'binary'));
          });

          res.on("end", function (chunk) {
            let binary = Buffer.concat(chunks);
            console.log('end ' + binary);
            resolve(binary);
          });

          res.on("error", function (error) {
            console.log('error');
            reject(JSON.parse(error));
          });
        });

        req.end();
    });

});

</code>```

"console.log('on chunk');" is never called and

"console.log('end ' + binary);" only prints "end".

urlHostname, urlPath and the token are correct, and running in postman the call with the url and the token returns the right data.

What am i missing?

Body:
As the title suggest, i'm not getting any data from the code below:

exports.getWhatsappBinaryData = functions.https.onCall((data, context) => {

    const urlHostName = data.hostName;
    const urlPath = data.path;
    const token = data.token;

    console.log('host: ' + urlHostName);
    console.log('path: ' + urlPath);
    console.log('token: ' + token);

    const https = require('https');
    const qs = require('querystring');

    let options = {
      'method': 'GET',
      'hostname': urlHostName,
      'path': urlPath,
      'headers': {
        'Authorization': 'Bearer ' + token,
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, DELETE, HEAD, OPTIONS',
        'Access-Control-Allow-Credentials': 'true',
      },
      'maxRedirects': 20
    };

    return new Promise((resolve, reject) => {
        let req = https.request(options, function (res) {
          let chunks = [];
          res.setEncoding('binary');

          res.on("data", function (chunk) {
            console.log('on chunk');
            chunks.push(Buffer.from(chunk, 'binary'));
          });

          res.on("end", function (chunk) {
            let binary = Buffer.concat(chunks);
            console.log('end ' + binary);
            resolve(binary);
          });

          res.on("error", function (error) {
            console.log('error');
            reject(JSON.parse(error));
          });
        });

        req.end();
    });

});

"console.log('on chunk');" is never called and

"console.log('end ' + binary);" only prints "end".

urlHostname, urlPath and the token are correct, and running in postman the call with the url and the token returns the right data.

What am i missing?


问:
React JS - call function however you get to a page/component
I'm working on a page fetching data and then showing a list of results. I have a main App component with a navbar and 3 possible sub-pages. The first is the home, where you can also do a research as i mentioned. When you do that, i made it so that the beginning of the list scrolls to the top of the browser window (banner, navbar and such get out of the screen, on the top). Now, if you click one of the results, you get to a detailed page about that.
What i'm trying to achieve is to call the page scroll i mentioned also when you get back to the home, by using "previous page" button or even by clicking home in the navbar. The results list is still there, so i want to scroll it again on the top.
The function i use for the scroll is

```<code>  const scrollPage = () => {
    setTimeout(function () {
    const element = document.getElementById("comment");
    element.scrollIntoView({
      behavior: "smooth",
      block: "start",
    });
  }, 1000); }
</code>```

and this works when i do the research, since i call it inside the search function. i tried calling the same function with useEffect() but it didn't work, also i tried like

```<code>useEffect(() => {
window.addEventListener('load', scrollPage);
return () => {
  window.removeEventListener('load', scrollPage);
 }}, []);
</code>```

but it doesn't work. if i click home in the navbar it goes on top of the page and if i use the "previous page" button i get back at the same Y of the list and the beginning of the list doesn't get scrolled.

Body:
I'm working on a page fetching data and then showing a list of results. I have a main App component with a navbar and 3 possible sub-pages. The first is the home, where you can also do a research as i mentioned. When you do that, i made it so that the beginning of the list scrolls to the top of the browser window (banner, navbar and such get out of the screen, on the top). Now, if you click one of the results, you get to a detailed page about that.
What i'm trying to achieve is to call the page scroll i mentioned also when you get back to the home, by using "previous page" button or even by clicking home in the navbar. The results list is still there, so i want to scroll it again on the top.
The function i use for the scroll is

  const scrollPage = () => {
    setTimeout(function () {
    const element = document.getElementById("comment");
    element.scrollIntoView({
      behavior: "smooth",
      block: "start",
    });
  }, 1000); }

and this works when i do the research, since i call it inside the search function. i tried calling the same function with useEffect() but it didn't work, also i tried like

useEffect(() => {
window.addEventListener('load', scrollPage);
return () => {
  window.removeEventListener('load', scrollPage);
 }}, []);

but it doesn't work. if i click home in the navbar it goes on top of the page and if i use the "previous page" button i get back at the same Y of the list and the beginning of the list doesn't get scrolled.


问:
ffmpeg: How to reduce video size with keeping tv quality
I have the following video

```<code>Input #0, mpeg, from '1_part1_2min.mpg':
  Duration: 00:02:00.08, start: 0.500000, bitrate: 31975 kb/s
    Stream #0:0[0x1c0]: Audio: mp2, 48000 Hz, stereo, s16p, 224 kb/s
    Stream #0:1[0x1e0]: Video: mpeg2video (High), yuv420p(tv, progressive), 1920x1080 [SAR 1:1 DAR 16:9], 31776 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc
</code>```

Its currenlty 400MB

I want to play the video on tv. but i want to reduce its size to 200MB

How can do that using ffmpeg

Body:
I have the following video

Input #0, mpeg, from '1_part1_2min.mpg':
  Duration: 00:02:00.08, start: 0.500000, bitrate: 31975 kb/s
    Stream #0:0[0x1c0]: Audio: mp2, 48000 Hz, stereo, s16p, 224 kb/s
    Stream #0:1[0x1e0]: Video: mpeg2video (High), yuv420p(tv, progressive), 1920x1080 [SAR 1:1 DAR 16:9], 31776 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc

Its currenlty 400MB

I want to play the video on tv. but i want to reduce its size to 200MB

How can do that using ffmpeg


问:
How to download/open a BLOB URL?
I have an excel file on a website that I am trying to download and open on Excel from a URL. The download link has a "blob:https". Not sure how to do this.</p>

Title: How to download/open a BLOB URL?


问:
React Native tab view lazy is not loading last scene
Here is my tabview:

```<code> <TabView
            navigationState={{index, routes}}
            renderTabBar={renderTabBar}
            renderScene={renderScene}
            initialLayout={{width: layout.width}}
            onIndexChange={() => {}}
            lazy
          />

 const renderScene =({route})=>{
    if (route.key == 'first') {
      return <FirstRoute />;
    }
    if (route.key == 'second') {
      return <SecondRoute />;
    }
    if (route.key == 'third') {
      return <ThirdRoute />;
    }
  }

 const FirstRoute = () => (
    <View style={{flex: 1}}>
      {visible == true ? (
        <RenderNoContent />
      ) : (
        <CustomerDetails
          walletDataList={walletDataList}
          customerData={contactData}
          navigation={navigation}
        />
      )}
    </View>
  );

 const SecondRoute = () => (
    <View style={{flex: 1}}>
      <InvoiceDashboard
        navigation={navigation}
        index={index}
        customerId={route.params.id}
      />
    </View>
  );

  const ThirdRoute = () => (
    <View style={{flex: 1}}>
      <Notes
        navigation={navigation}
        index={index}
        customerId={route.params.id}
      />
    </View>
  );
</code>```

I am implementing React Native tab view with three tabs. If I enable lazy option the thirdroute is not rendering. If I disable lazy all the three tabs are rendering the UI but I am facing performance issue when loading data in all the tabs it's taking too much time.

I want to load data initially on first tab; later, if I change page, the second and third tab should load data. How can I fix this issue?

Body:
Here is my tabview:

 <TabView
            navigationState={{index, routes}}
            renderTabBar={renderTabBar}
            renderScene={renderScene}
            initialLayout={{width: layout.width}}
            onIndexChange={() => {}}
            lazy
          />

 const renderScene =({route})=>{
    if (route.key == 'first') {
      return <FirstRoute />;
    }
    if (route.key == 'second') {
      return <SecondRoute />;
    }
    if (route.key == 'third') {
      return <ThirdRoute />;
    }
  }

 const FirstRoute = () => (
    <View style={{flex: 1}}>
      {visible == true ? (
        <RenderNoContent />
      ) : (
        <CustomerDetails
          walletDataList={walletDataList}
          customerData={contactData}
          navigation={navigation}
        />
      )}
    </View>
  );

 const SecondRoute = () => (
    <View style={{flex: 1}}>
      <InvoiceDashboard
        navigation={navigation}
        index={index}
        customerId={route.params.id}
      />
    </View>
  );

  const ThirdRoute = () => (
    <View style={{flex: 1}}>
      <Notes
        navigation={navigation}
        index={index}
        customerId={route.params.id}
      />
    </View>
  );

I am implementing React Native tab view with three tabs. If I enable lazy option the thirdroute is not rendering. If I disable lazy all the three tabs are rendering the UI but I am facing performance issue when loading data in all the tabs it's taking too much time.

I want to load data initially on first tab; later, if I change page, the second and third tab should load data. How can I fix this issue?


问:
Internationalization issue with formsflow.ai
is there a problem or am I missing something?

When I select bg (bulgarian) for example as language and then trying to save and preview a form that is named in Bulgarian then I get a validation error. I've tried the same in Chinese. Is it allowed to name forms and form elements in a different language than English or is not allowed?

Thanks in advance.

see example


问:
Create fiscal calendar in pyspark
I did create a fiscal calendar that can be later improvised to create a function in spark. is there a better and simple way that I can change is it more dynamic like first day to choose as starting fiscal date</p>
```<code>from fiscalyear import *
beginDate = '2016-01-01'
endDate = '2021-12-31'
#create empty dataframe
df = spark.createDataFrame([()])
#create date from given date range
df1 = df.withColumn("date",explode(expr(f"sequence(to_date('{beginDate}'), to_date('{endDate}'), interval 1 day)")))
# get week
df1 = df1.withColumn('week',weekofyear(col("date"))).withColumn('year',year(col("date")))

#translate to use pandas in python
df1 = df1.toPandas()
#get fiscal year
df1['financial_year'] = df1['date'].map(lambda x: x.year if x.month > 3 else x.year-1)
df1['date'] = pd.to_datetime(df1['date'])
#get calendar qtr
df1['quarter_old'] = df1['date'].dt.quarter
#get fiscal calendar
df1['quarter'] = np.where(df1['financial_year']< (df1['year']),df1['quarter_old']+3,df1['quarter_old'])
df1['quarter'] = np.where(df1['financial_year'] == (df1['year']),df1['quarter_old']-1,df1['quarter'])
#get fiscal week by shiftin gas per number of months different from usual calendar
df1["fiscal_week"] = df1.week.shift(91)
df1 = df1.loc[(df1['date'] >= '2020-01-01')]
df1.display()
</code>```

Title: Create fiscal calendar in pyspark

Body:
I did create a fiscal calendar that can be later improvised to create a function in spark. is there a better and simple way that I can change is it more dynamic like first day to choose as starting fiscal date

from fiscalyear import *
beginDate = '2016-01-01'
endDate = '2021-12-31'
#create empty dataframe
df = spark.createDataFrame([()])
#create date from given date range
df1 = df.withColumn("date",explode(expr(f"sequence(to_date('{beginDate}'), to_date('{endDate}'), interval 1 day)")))
# get week
df1 = df1.withColumn('week',weekofyear(col("date"))).withColumn('year',year(col("date")))

#translate to use pandas in python
df1 = df1.toPandas()
#get fiscal year
df1['financial_year'] = df1['date'].map(lambda x: x.year if x.month > 3 else x.year-1)
df1['date'] = pd.to_datetime(df1['date'])
#get calendar qtr
df1['quarter_old'] = df1['date'].dt.quarter
#get fiscal calendar
df1['quarter'] = np.where(df1['financial_year']< (df1['year']),df1['quarter_old']+3,df1['quarter_old'])
df1['quarter'] = np.where(df1['financial_year'] == (df1['year']),df1['quarter_old']-1,df1['quarter'])
#get fiscal week by shiftin gas per number of months different from usual calendar
df1["fiscal_week"] = df1.week.shift(91)
df1 = df1.loc[(df1['date'] >= '2020-01-01')]
df1.display()


问:
How to organise tests for multiples implementations with mocha (JS)?
I have an object A with some methods (abc(), def(), ...), that are tested with Mocha (describe(), it()...) : that's fine.

Now I work on an object B that has the same methods, but provide another implementation (in Java, I would have created an interface).

How do I organize my tests to test my object A and B (and future others implementations) against the same tests, without modifiing them ?