问:
Roman to Integer Question. Problem with my Python solution
```<code>class Solution:
    def romanToInt(self, s: str) -> int:
        num = 0
        for i in range(len(s)):
            if s[i] == "I":
                try:
                    if s[i+1] == "V" or s[i+1] == "X":
                        num -= 1
                        continue
                except:
                    num += 1
                    continue
                else:
                    num += 1
                    continue
            elif s[i] == "X":
                try:
                    if s[i+1] == "L" or s[i+1] == "C":
                        num -= 10
                        continue
                except:
                    num += 10
                    continue
                else:
                    num += 10
                    continue
            elif s[i] == "C":
                try:
                    if s[i+1] == "D" or s[i+1] == "M":
                        num -= 100
                    continue
                except:
                    num += 100
                    continue
                else:
                    num += 100
                    continue
            elif s[i] == "V":
                num += 5
                continue
            elif s[i] == "L":
                num += 50
                continue
            elif s[i] == "D":
                num += 500
                continue
            else:
                num += 1000
                continue
        return num

</code>```

This is obviously not the most optimal approach, but I want to understand what's wrong with it...
I know this is wrong because here were the 3 testcases from Leetcode

"III" --> 3 worked
"LVIII" ---> 58 worked

BUT "MCMXCIV" --> 1884 expected 1984

This code basically gives each iteration a specific amount that will be added/substracted from the totalsum. But somehow 100 was deducted and I dont get how...

Body:
class Solution:
    def romanToInt(self, s: str) -> int:
        num = 0
        for i in range(len(s)):
            if s[i] == "I":
                try:
                    if s[i+1] == "V" or s[i+1] == "X":
                        num -= 1
                        continue
                except:
                    num += 1
                    continue
                else:
                    num += 1
                    continue
            elif s[i] == "X":
                try:
                    if s[i+1] == "L" or s[i+1] == "C":
                        num -= 10
                        continue
                except:
                    num += 10
                    continue
                else:
                    num += 10
                    continue
            elif s[i] == "C":
                try:
                    if s[i+1] == "D" or s[i+1] == "M":
                        num -= 100
                    continue
                except:
                    num += 100
                    continue
                else:
                    num += 100
                    continue
            elif s[i] == "V":
                num += 5
                continue
            elif s[i] == "L":
                num += 50
                continue
            elif s[i] == "D":
                num += 500
                continue
            else:
                num += 1000
                continue
        return num

This is obviously not the most optimal approach, but I want to understand what's wrong with it...
I know this is wrong because here were the 3 testcases from Leetcode

"III" --> 3 worked
"LVIII" ---> 58 worked

BUT "MCMXCIV" --> 1884 expected 1984

This code basically gives each iteration a specific amount that will be added/substracted from the totalsum. But somehow 100 was deducted and I dont get how...


来源: stackexchange

问:
Error in the adjacency list passed as a parameter
I was solving a graph-based problem that uses the DFS paradigm.
So I was passing the adjacency list as a parameter to dfs function which is showing some kind of error. Below is the same code:

```<code>void dfs(int node,vector<int>&ans, vector<int>&adj){
    for(auto it:adj[node]){
        ans[it]++;
        dfs(it,ans,adj);
    }

}
</code>```

On the other hand, I tweaked a little bit in the way I was passing the adjacency list and my solution got AC.
Below is the accepted code:

```<code>void dfs(int node,vector<int>&ans, vector<int>*adj){
    for(auto it:adj[node]){
        ans[it]++;
        dfs(it,ans,adj);
    }

}
</code>```

Why this is happening??

ContentLicense: CC BY-SA 4.0

Body:
I was solving a graph-based problem that uses the DFS paradigm.
So I was passing the adjacency list as a parameter to dfs function which is showing some kind of error. Below is the same code:

void dfs(int node,vector<int>&ans, vector<int>&adj){
    for(auto it:adj[node]){
        ans[it]++;
        dfs(it,ans,adj);
    }

}

On the other hand, I tweaked a little bit in the way I was passing the adjacency list and my solution got AC.
Below is the accepted code:

void dfs(int node,vector<int>&ans, vector<int>*adj){
    for(auto it:adj[node]){
        ans[it]++;
        dfs(it,ans,adj);
    }

}

Why this is happening??


问:
express-flash is not displaying any messages
I'm new in node.js and currently I'm working on user authentication with passport.js & JWT I also add express-flash for displaying error messages. when I enter correct information it works fine but when I enter wrong information it just give me unauthorized error and not displaying the custom error messages.

This is validation logic

```<code>const passportInit = (passport, getUserByEmail, getUserById) => {
  const authenticateUser = async (email, password, done) => {
    const user = await getUserByEmail(email);
    // console.log('user', user);

    if (user == null) return done(null, false, { message: 'No user with that email' });
    try {
      if (!(await bcrypt.compare(password, user.password))) return done(null, false, { message: 'Incorrect password' });

      return done(null, user);
    } catch (err) {
      return done(err);
    }
  };
  passport.use('local', new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, authenticateUser));
}
</code>```

I also add the express-flash middleware and set the session & failureFlash to true in passport.authenticate('local', { session: true, failureFlash: true }).

```<code>app.use(flash());
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(cookieParser());
</code>```

any suggestion will be helpful.

Body:
I'm new in node.js and currently I'm working on user authentication with passport.js & JWT I also add express-flash for displaying error messages. when I enter correct information it works fine but when I enter wrong information it just give me unauthorized error and not displaying the custom error messages.

This is validation logic

const passportInit = (passport, getUserByEmail, getUserById) => {
  const authenticateUser = async (email, password, done) => {
    const user = await getUserByEmail(email);
    // console.log('user', user);

    if (user == null) return done(null, false, { message: 'No user with that email' });
    try {
      if (!(await bcrypt.compare(password, user.password))) return done(null, false, { message: 'Incorrect password' });

      return done(null, user);
    } catch (err) {
      return done(err);
    }
  };
  passport.use('local', new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, authenticateUser));
}

I also add the express-flash middleware and set the session & failureFlash to true in passport.authenticate('local', { session: true, failureFlash: true }).

app.use(flash());
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(cookieParser());

any suggestion will be helpful.


问:
Can running .pyc speed up execution, compared to running .py?
I overheard that running compiled .pyc can speed up execution, in contrast to running raw .py. But in my little experiment, it turns little or no improvement:

```<code># hello.py

import pandas as pd
import numpy as np
import time

if __name__ == '__main__':

    loop = 100000

    print('Hello World')
    start = time.time()
    for l in range(loop):
        df = pd.DataFrame([[np.random.uniform(0,np.random.uniform(0,1)),np.random.uniform(0,np.random.uniform(1,10))],
                        [np.random.uniform(0,np.random.uniform(10,100)),np.random.uniform(0,np.random.uniform(100,1000))]],index=[0,1],columns=['A','B'])
    print(f'Time cost for {loop} iteration: {time.time()-start:.4f} sec')
</code>```
```<code># (bash) python hello.py
Hello World
Time cost for 100000 iteration: 28.2506 sec
</code>```
```<code># (bash) python -O -m compileall -b .
python hello.pyc
Hello World
Time cost for 100000 iteration: 26.9610 sec
</code>```

Specification:

Python 3.9.13

[GCC 11.2.0] :: Anaconda, on linux (Redhat, centOS)

Can .pyc really cut runtime in general, or just for some cases, or no effect at all? Or am I missing some conducts?

Body:
I overheard that running compiled .pyc can speed up execution, in contrast to running raw .py. But in my little experiment, it turns little or no improvement:

# hello.py

import pandas as pd
import numpy as np
import time

if __name__ == '__main__':

    loop = 100000

    print('Hello World')
    start = time.time()
    for l in range(loop):
        df = pd.DataFrame([[np.random.uniform(0,np.random.uniform(0,1)),np.random.uniform(0,np.random.uniform(1,10))],
                        [np.random.uniform(0,np.random.uniform(10,100)),np.random.uniform(0,np.random.uniform(100,1000))]],index=[0,1],columns=['A','B'])
    print(f'Time cost for {loop} iteration: {time.time()-start:.4f} sec')

# (bash) python hello.py
Hello World
Time cost for 100000 iteration: 28.2506 sec

# (bash) python -O -m compileall -b .
python hello.pyc
Hello World
Time cost for 100000 iteration: 26.9610 sec

Specification:

Python 3.9.13

[GCC 11.2.0] :: Anaconda, on linux (Redhat, centOS)

Can .pyc really cut runtime in general, or just for some cases, or no effect at all? Or am I missing some conducts?


问:
How do you make the TextInput secure entry/password refer to a specific user?
When using <TextInput secureEntry={true} /> to show password entry, the Apple Keyboard offers to help fill the password, but because I am using the app with multiple test accounts it shows me the users possible in alphabetical order rather than making the one specified in the user field one of the suggestions.

Is there a way of making telling React Native's Text Input to accept a user name field so that it will promote that value first in the suggestions if available.


问:
Which git workflow to use if develop and master cannot be synced
We have a repo to which multiple teams are working together. There are three branches - master, develop and feature branches. The master is in sync with the production environment and develop in sync with development environment. I am new to git and I want to understand what is the right git workflow here since develop and master cannot be synced - meaning all the changes in develop cannot go into master.

Suppose my team is working on a feature A, then should this branch be created on top of master and then first merged into develop. And if I want to move it into master, I will merge the same branch to master as well?

I have also been into a scenario where I have created a feature branch of master, made my changes, then when I tried to merge the PR to develop, I got merge conflicts, so I fixed the merge conflicts from Github which actually merged develop into my branch. So the problem now is when I try to merge this branch to master it will have all the commits from develop which is not what I want. Can someone help me understand this as well?


问:
In non episodic RL problems, when should the "DONE" variable (in step function) become true?
Suppose that there is a non episodic RL problem (for example trader agent, or traffic light controller agent). We want to use DQN algorithm for it. In the step function of the environment, when should the "DONE" variable become true?
Just at the end of training data? or not?

if  <Which condition???>:
done = True

Sometimes I set the DONE variable to true at the end of training, and sometimes I did it after a certain amount of training data had passed. But I don't know what is the correct solution for it?


问:
How backup automated process to my WordPress Sites using code?
I have used the code below on the c-panel WordPress repository and created a backup folder in the public HTML folder.  But not working on  I need to know code issue and where I should customize to get my site automatedly by using code.

```<code>`function create_backup() {
  // Get the site's URL and name
  $site_url = get_site_url();
  $site_name = get_bloginfo('name');

  // Create a filename for the backup using the site's URL and current date
  $filename = $site_name . '-' . $site_url . '-' . date('Y-m-d') . '.zip';

  // Create a ZIP archive of the site's files
  $zip = new ZipArchive;
  $zip->open($filename, ZipArchive::CREATE);
  $zip->addGlob(ABSPATH . '/*');
  $zip->close();

  // Send the ZIP archive to a remote location
  // Replace "example.com" with the URL of your remote location
  $response = wp_remote_post('http://example.com/backups/', array(
    'method' => 'POST',
    'timeout' => 45,
    'redirection' => 5,
    'httpversion' => '1.0',
    'blocking' => true,
    'headers' => array(
      'Content-Type' => 'application/zip'
    ),
    'body' => file_get_contents($filename),
  ));
}`
</code>```

Use the wp_schedule_event() or wp_schedule_single_event() function to schedule the custom function to run at a specific time or interval.

And use this Bloew of this code in functions.php

```<code>`if ( ! wp_next_scheduled( 'create_backup_event' ) ) {
  wp_schedule_event( time(), 'daily', 'create_backup_event' );
}

add_action( 'create_backup_event', 'create_backup' );`
</code>```

Please notify me where I need to add my domain name and customization needs!

I have tried this on my Name Cheap Hosting.  But My inquiry is where should I need to create the Back Folder in the Public Html folder or anywhere else?

Body:
I have used the code below on the c-panel WordPress repository and created a backup folder in the public HTML folder.  But not working on  I need to know code issue and where I should customize to get my site automatedly by using code.

`function create_backup() {
  // Get the site's URL and name
  $site_url = get_site_url();
  $site_name = get_bloginfo('name');

  // Create a filename for the backup using the site's URL and current date
  $filename = $site_name . '-' . $site_url . '-' . date('Y-m-d') . '.zip';

  // Create a ZIP archive of the site's files
  $zip = new ZipArchive;
  $zip->open($filename, ZipArchive::CREATE);
  $zip->addGlob(ABSPATH . '/*');
  $zip->close();

  // Send the ZIP archive to a remote location
  // Replace "example.com" with the URL of your remote location
  $response = wp_remote_post('http://example.com/backups/', array(
    'method' => 'POST',
    'timeout' => 45,
    'redirection' => 5,
    'httpversion' => '1.0',
    'blocking' => true,
    'headers' => array(
      'Content-Type' => 'application/zip'
    ),
    'body' => file_get_contents($filename),
  ));
}`

Use the wp_schedule_event() or wp_schedule_single_event() function to schedule the custom function to run at a specific time or interval.

And use this Bloew of this code in functions.php

`if ( ! wp_next_scheduled( 'create_backup_event' ) ) {
  wp_schedule_event( time(), 'daily', 'create_backup_event' );
}

add_action( 'create_backup_event', 'create_backup' );`

Please notify me where I need to add my domain name and customization needs!

I have tried this on my Name Cheap Hosting.  But My inquiry is where should I need to create the Back Folder in the Public Html folder or anywhere else?


问:
Some inserts are not appearing in DB table
I am trying to insert the records after reading them from a file. There are bunch of files, I read/parse one file at a time and insert all the records from that file at a time. This works fine in most cases, but I have noticed, there is one file which has 879 records which are not getting inserted or not appearing in DB table. The same code works fine, if I remove or add any 1 record from the file. DB is Oracle 12c.
The file whose records are not inserted is not throwing any error.
Can anybody please point out what could cause such a behavior?

This is how the code looks like..

```<code>ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
List<CompletableFuture<Void>> completableFutures =
     pnlFiles.stream().map(pnlFileForTheBook ->    CompletableFuture.runAsync(() -> {
            String pnlFileName = "";
            String cobDate = "";
            String filePath = "";
            try {
                File localPnlFile = nasDataLoader.downloadFile(pnlFileForTheBook, filePath);
                if(localPnlFile != null) {
                    List<PnlFile> pnlFileLines = parse(localPnlFile, PnlFile.class);
                    List<PnlFileDsl> pnlFileDsls = pnlFileLines.stream().map(line -> {
                        return new PnlFileDsl(line, cobDate);
                    }).collect(Collectors.toList());
                    persistenceManager.persist(pnlFileDsls);
                }
            }
              catch () {}
           }, executorService)).collect(Collectors.toList());

        List<Void> result = completableFutures.stream().map(CompletableFuture::join)
                                                       .collect(Collectors.toList());

</code>```

The same code works with all other files, the file whose records are not appearing has no issues.

Body:
I am trying to insert the records after reading them from a file. There are bunch of files, I read/parse one file at a time and insert all the records from that file at a time. This works fine in most cases, but I have noticed, there is one file which has 879 records which are not getting inserted or not appearing in DB table. The same code works fine, if I remove or add any 1 record from the file. DB is Oracle 12c.
The file whose records are not inserted is not throwing any error.
Can anybody please point out what could cause such a behavior?

This is how the code looks like..

ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
List<CompletableFuture<Void>> completableFutures =
     pnlFiles.stream().map(pnlFileForTheBook ->    CompletableFuture.runAsync(() -> {
            String pnlFileName = "";
            String cobDate = "";
            String filePath = "";
            try {
                File localPnlFile = nasDataLoader.downloadFile(pnlFileForTheBook, filePath);
                if(localPnlFile != null) {
                    List<PnlFile> pnlFileLines = parse(localPnlFile, PnlFile.class);
                    List<PnlFileDsl> pnlFileDsls = pnlFileLines.stream().map(line -> {
                        return new PnlFileDsl(line, cobDate);
                    }).collect(Collectors.toList());
                    persistenceManager.persist(pnlFileDsls);
                }
            }
              catch () {}
           }, executorService)).collect(Collectors.toList());

        List<Void> result = completableFutures.stream().map(CompletableFuture::join)
                                                       .collect(Collectors.toList());

The same code works with all other files, the file whose records are not appearing has no issues.


问:
Simulink: Reading complex data from workspace
When using from workspace in Matlab Simulink to read a complex set of data returns the following error

```<code>Unsupported input format for From Workspace block 'untitled/From Workspace1'. Available formats are double non-complex matrix, a structure with or without time, or a structure with MATLAB timeseries as leaf nodes. All formats require the data to be finite (not Inf or NaN).
</code>```

Is there any work around to solve this issue?

Body:
When using from workspace in Matlab Simulink to read a complex set of data returns the following error

Unsupported input format for From Workspace block 'untitled/From Workspace1'. Available formats are double non-complex matrix, a structure with or without time, or a structure with MATLAB timeseries as leaf nodes. All formats require the data to be finite (not Inf or NaN).

Is there any work around to solve this issue?


问:
How to pause a animation
I have implement a rotation Animation. On the click of a button its start rotating and on the click of another button its stop rotating. I want that on that on the click of pause button it should stop where it is and the click of the same button it should resume from the same place.
In the main activity I have a button on the click of that button rotation activity will open.

How can I do that?
Here is the xml file

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".rotation">
    <ImageView
        android:id="@+id/imgbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_boximage"
        android:layout_centerInParent="true"
        ></ImageView>

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnrotation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/rorationbtn"
        android:layout_below="@+id/imgbox"
        android:layout_centerInParent="true"
        android:layout_marginTop="50dp">
    </androidx.appcompat.widget.AppCompatButton>
    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnrotationp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause Animation"
        android:layout_below="@+id/btnrotation"
        android:layout_centerInParent="true"
        android:layout_marginTop="50dp">
    </androidx.appcompat.widget.AppCompatButton>

</RelativeLayout>
</code>```

here is the Animation file

```<code><set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0"
        android:toDegrees="3600"
        android:duration="4000"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatMode="reverse"
        android:repeatCount="infinite">

    </rotate>

</set>
</code>```

here is the java file

```<code>public class rotation extends AppCompatActivity {
    AppCompatButton rotate,rotatep;
    ImageView imgbox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rotation);
        getSupportActionBar().setTitle("Rotation");
        imgbox=findViewById(R.id.imgbox);
        rotate=findViewById(R.id.btnrotation);
        rotatep=findViewById(R.id.btnrotationp);
        Animation rotate1= AnimationUtils.loadAnimation(rotation.this,R.anim.rotation);
        rotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                imgbox.startAnimation(rotate1);
            }
        });
        rotatep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imgbox.clearAnimation();
            }
        });

    }
}
</code>```

Title: How to pause a animation

Body:
I have implement a rotation Animation. On the click of a button its start rotating and on the click of another button its stop rotating. I want that on that on the click of pause button it should stop where it is and the click of the same button it should resume from the same place.
In the main activity I have a button on the click of that button rotation activity will open.

How can I do that?
Here is the xml file

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".rotation">
    <ImageView
        android:id="@+id/imgbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_boximage"
        android:layout_centerInParent="true"
        ></ImageView>

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnrotation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/rorationbtn"
        android:layout_below="@+id/imgbox"
        android:layout_centerInParent="true"
        android:layout_marginTop="50dp">
    </androidx.appcompat.widget.AppCompatButton>
    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnrotationp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause Animation"
        android:layout_below="@+id/btnrotation"
        android:layout_centerInParent="true"
        android:layout_marginTop="50dp">
    </androidx.appcompat.widget.AppCompatButton>

</RelativeLayout>

here is the Animation file

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:fromDegrees="0"
        android:toDegrees="3600"
        android:duration="4000"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatMode="reverse"
        android:repeatCount="infinite">

    </rotate>

</set>

here is the java file

public class rotation extends AppCompatActivity {
    AppCompatButton rotate,rotatep;
    ImageView imgbox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rotation);
        getSupportActionBar().setTitle("Rotation");
        imgbox=findViewById(R.id.imgbox);
        rotate=findViewById(R.id.btnrotation);
        rotatep=findViewById(R.id.btnrotationp);
        Animation rotate1= AnimationUtils.loadAnimation(rotation.this,R.anim.rotation);
        rotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                imgbox.startAnimation(rotate1);
            }
        });
        rotatep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imgbox.clearAnimation();
            }
        });

    }
}


问:
ModuleNotFoundError: No module named 'System'
I'm working on an EXE file crypter in python 3.11.1 and I cannot seem to get the System.Reflection import working. I've tried pythonnet and clr, but it just doesn't recognize 'System.'

I've tried to make sure pythonnet and clr are not conflicting, but that hasn't worked either. I tried clearing the cache and reinstalling python entirely. I also made sure there weren't any multiple instances of pip and python. This is the code snippet:

```<code>def crypt(filepath):
    import base64
    import clr
    from System.Reflection import Assembly
</code>```

Body:
I'm working on an EXE file crypter in python 3.11.1 and I cannot seem to get the System.Reflection import working. I've tried pythonnet and clr, but it just doesn't recognize 'System.'

I've tried to make sure pythonnet and clr are not conflicting, but that hasn't worked either. I tried clearing the cache and reinstalling python entirely. I also made sure there weren't any multiple instances of pip and python. This is the code snippet:

def crypt(filepath):
    import base64
    import clr
    from System.Reflection import Assembly


问:
Nodejs can selenium be used to parse html text without opening a browser?
I'm trying to parse an html page I already have as text, and I've used selenium quite a bit before.  I was wondering if it's possible to use selenium without it actually launching a browser.  I don't need js to be run, I don't need to interact with the page, I just need to parse static html.</p>


问:
Is it possible to add custom authentication middleware on python based azure function API
While developing an API using python based azure function. I have come across a situation where I have to implement custom JWT authentication and authorization middleware.

I have tried to use python worker extension pre_invocation_app_level method. However, I am not able to pass the verification result to the endpoint or return from the middleware in case of invalid user.

Sample source code:

```<code>from azure.functions import AppExtensionBase, Context
import typing
from logging import Logger
import azure.functions as func

class AuthMiddleware(AppExtensionBase):
    @classmethod
    def pre_invocation_app_level(
        cls,
        logger: Logger,
        context: Context,
        func_args: typing.Dict[str, object] = ...,
        *args,
        **kwargs,
    ) -> None:
        req = func_args.get("req")
        auth_header = req.headers.get("Authorization")
        if not auth_header:
            return func.HttpResponse(
                "Unauthorized", status_code=401, headers={"WWW-Authenticate": "Custom"}
            )
</code>```

Body:
While developing an API using python based azure function. I have come across a situation where I have to implement custom JWT authentication and authorization middleware.

I have tried to use python worker extension pre_invocation_app_level method. However, I am not able to pass the verification result to the endpoint or return from the middleware in case of invalid user.

Sample source code:

from azure.functions import AppExtensionBase, Context
import typing
from logging import Logger
import azure.functions as func

class AuthMiddleware(AppExtensionBase):
    @classmethod
    def pre_invocation_app_level(
        cls,
        logger: Logger,
        context: Context,
        func_args: typing.Dict[str, object] = ...,
        *args,
        **kwargs,
    ) -> None:
        req = func_args.get("req")
        auth_header = req.headers.get("Authorization")
        if not auth_header:
            return func.HttpResponse(
                "Unauthorized", status_code=401, headers={"WWW-Authenticate": "Custom"}
            )


问:
Validating a webhook signature AND using the body in NextJS
I'm trying to both validate and use the body response in a Lemonqueezy webhook request in NextJS

I'm getting the signature validation to work, but the body object is then empty(presumably consumed by the signature validation).

I tried cloning the request, but this doesn't seem to do anything.

How do I get to validate the signature AND use the request body in NextJS?

Here's my code

```<code>// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import crypto from "crypto";
import getRawBody from "raw-body";
import clone from "clone-deep";
import { json } from "micro";

export const config = { api: { bodyParser: false } };

type Data = { message: string };

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  if (req.method === "POST") {
    const clonedReq = clone(req);

    const rawBody = await getRawBody(clonedReq);
    const hmac = crypto.createHmac(
      "sha256",
      process.env.LEMONSQUEEZY_SIGNING_SECRET
    );

    const digest = Buffer.from(hmac.update(rawBody).digest("hex"), "utf8");
    const signature = Buffer.from(
      req.headers["x-signature"].toString() || "",
      "utf8"
    );

    const valid = crypto.timingSafeEqual(digest, signature);

    console.log("valid", valid);
    if (valid) {
      const body = await json(req);
      console.log("body", body);
      res.status(200).json({ message: "Success" });
    } else {
      res.status(500).json({ message: "Illegal method" });
    }
  } else {
    res.status(500).json({ message: "Illegal method" });
  }
}
</code>```

Body:
I'm trying to both validate and use the body response in a Lemonqueezy webhook request in NextJS

I'm getting the signature validation to work, but the body object is then empty(presumably consumed by the signature validation).

I tried cloning the request, but this doesn't seem to do anything.

How do I get to validate the signature AND use the request body in NextJS?

Here's my code

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import crypto from "crypto";
import getRawBody from "raw-body";
import clone from "clone-deep";
import { json } from "micro";

export const config = { api: { bodyParser: false } };

type Data = { message: string };

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  if (req.method === "POST") {
    const clonedReq = clone(req);

    const rawBody = await getRawBody(clonedReq);
    const hmac = crypto.createHmac(
      "sha256",
      process.env.LEMONSQUEEZY_SIGNING_SECRET
    );

    const digest = Buffer.from(hmac.update(rawBody).digest("hex"), "utf8");
    const signature = Buffer.from(
      req.headers["x-signature"].toString() || "",
      "utf8"
    );

    const valid = crypto.timingSafeEqual(digest, signature);

    console.log("valid", valid);
    if (valid) {
      const body = await json(req);
      console.log("body", body);
      res.status(200).json({ message: "Success" });
    } else {
      res.status(500).json({ message: "Illegal method" });
    }
  } else {
    res.status(500).json({ message: "Illegal method" });
  }
}


问:
Where does AWS OpenSearch domain endpoint points
I am new to OpenSearch or AWS in general. I was trying to debug a recent issue with OpenSearch service when I came across these docs

As per this documentation:

OpenSearch Service assigns each ENI a private IP address from the IPv4 address range of your subnet. The service also assigns a public DNS hostname (which is the domain endpoint) for the IP addresses. You must use a public DNS service to resolve the endpoint (which is a DNS hostname) to the appropriate IP addresses for the data nodes:

While this FAQ section says:

A load balancer sits in front of each OpenSearch Service domain. The load balancer distributes incoming traffic to the data nodes.

Also, this blog says:

When Amazon ES creates your domain, it launches instances into a service-controlled VPC. Those instances are fronted by Elastic Load Balancing (ELB), and the endpoint for the load balancer is published through Route 53. Requests to the domain pass through the ELB load balancer, which routes them to the domain’s EC2 instances.

When I tried dns lookup for the domain endpoint using this tool, I got the same number of A records as my data nodes in the OpenSearch service domain.

So does the OpenSearch domain name point to a load balancer or the data nodes?


问:
GCC Minification not working in AEM for ECMASCRIPT_2020
We are using AEM version 6.5.9

and our js processor config was

```<code>min:gcc;languageIn=ECMASCRIPT_2018;obfuscate=true
</code>```

It works for normal cases but in case we have any optional chaining(e.g. adventurer.dog?.name) then it does not work

You can refer to this link for Online Compiler

In this online compiler if the language is ECMASCRIPT_2020 then it is able to compile else for the lower versions it does not.

The list of allowed language versions is from GitHub Link

So similarly in AEM we changed the js processor config to

```<code>min:gcc;languageIn=ECMASCRIPT_2020;obfuscate=true
</code>```

But then also minification does not work.

My questions are:

Does AEM not support ECMASCRIPT_2020?

Is there any way we can update the gcc version being used by AEM?

Body:
We are using AEM version 6.5.9

and our js processor config was

min:gcc;languageIn=ECMASCRIPT_2018;obfuscate=true

It works for normal cases but in case we have any optional chaining(e.g. adventurer.dog?.name) then it does not work

You can refer to this link for <a href="https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520SIMPLE_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%2540language%2520ECMASCRIPT_2020%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250A%252F%252F%2520ADD%2520YOUR%2520CODE%2520HERE%250Aconst%2520adventurer%2520%253D%2520%257B%250A%2520%2520name%253A%2520%27Alice%27%252C%250A%2520%2520cat%253A%2520%257B%250A%2520%2520%2520%2520name%253A%2520%27Dinah%27%250A%2520%2520%257D%250A%257D%253B%250A%250Aconst%2520catName%2520%253D%2520adventurer.cat%253F.name%253B%250Aconsole.log(catName)%253B%250A%252F%252F%2520expected%2520output%253A%2520undefined%250A%250Aconsole.log(adventurer.someNonExistentMethod%253F.())%253B%250A%252F%252F%2520expected%2520output%253A%2520undefined%250A" rel="nofollow noreferrer">Online Compiler

In this online compiler if the language is ECMASCRIPT_2020 then it is able to compile else for the lower versions it does not.

The list of allowed language versions is from GitHub Link

So similarly in AEM we changed the js processor config to

min:gcc;languageIn=ECMASCRIPT_2020;obfuscate=true

But then also minification does not work.

My questions are:

Does AEM not support ECMASCRIPT_2020?

Is there any way we can update the gcc version being used by AEM?


问:
Optimize VB code for VSTO addin (pivot items compared to list)
My code takes an extremely long time to run. I have 2 list, and I go through every iteration of options in order to find whether the list match.

e.g.

```<code>List 1
A, B, C, X, Y, Z

List 2
X, Y, Z, C
</code>```

The code would check from List 1 to List 2 the following matches:

```<code>(List 1, List 2) -
(A, X) - no match
(A, Y) - no match
(A, Z) - no match
.
.
(C, X) - no match
(C, Y) - no match
(C, C) - match
.
.
.
(Z, C) - no match
</code>```

It takes an excessive amount of time. All I really need a list that just says C matches from List 1 and List 2.

The code I used is this:

For Each pvtItem In PvtFld.PivotItems
    For i = 1 To My.Settings.Filter1List.Count
        j = 0
        Do While j <= My.Settings.Filter1List.Count - 1
            If StrComp(pvtItem.Name, My.Settings.Filter1List.Item(j), vbTextCompare) = 0 Then
                PvtFld.PivotItems(pvtItem.Name).Visible = True
                Exit Do
            Else
                PvtFld.PivotItems(pvtItem.Name).Visible = False
            End If
            j = j + 1
        Loop

    Next i
Next pvtItem
```

This is pretty inefficient. Is there any other solution?

Body:
My code takes an extremely long time to run. I have 2 list, and I go through every iteration of options in order to find whether the list match.

e.g.

List 1
A, B, C, X, Y, Z

List 2
X, Y, Z, C

The code would check from List 1 to List 2 the following matches:

(List 1, List 2) -
(A, X) - no match
(A, Y) - no match
(A, Z) - no match
.
.
(C, X) - no match
(C, Y) - no match
(C, C) - match
.
.
.
(Z, C) - no match

It takes an excessive amount of time. All I really need a list that just says C matches from List 1 and List 2.

The code I used is this:

For Each pvtItem In PvtFld.PivotItems
    For i = 1 To My.Settings.Filter1List.Count
        j = 0
        Do While j <= My.Settings.Filter1List.Count - 1
            If StrComp(pvtItem.Name, My.Settings.Filter1List.Item(j), vbTextCompare) = 0 Then
                PvtFld.PivotItems(pvtItem.Name).Visible = True
                Exit Do
            Else
                PvtFld.PivotItems(pvtItem.Name).Visible = False
            End If
            j = j + 1
        Loop

    Next i
Next pvtItem

This is pretty inefficient. Is there any other solution?


问:
Does accessing and changing element in swift array can cause crash at ArrayBuffer._getElementsSlowPath(Swift.Int)
I got crash log that happen rarely and fixing right now.

```<code>0x0000000104178d04 merged generic specialization <###> of Swift._ArrayBuffer._getElementSlowPath(Swift.Int) -> Swift.AnyObject (in ###)
0x000000010516f9f0 function signature specialization <Arg[1] = Dead> ~~~
</code>```

I printed time(in milliseconds) in getter and setter of the array and the result was array was being write and read in same exact time. Does this can be cause of crash in getElementSlowPath?

In my code, "function signature specialization" crash was CoreData related. So I thought cause of this crash could be Coredata related. Is this caused by CoreDataModel attribute is optional and normalDataModel attribute is not option?
for exameple

```<code>extension CoreDataModel {
  @NSManaged public var message: String?

  func update(model: DataModel) {
    self.message = model.message
  }
}
struct DataModel {
  var message: String
}
</code>```

Body:
I got crash log that happen rarely and fixing right now.

0x0000000104178d04 merged generic specialization <###> of Swift._ArrayBuffer._getElementSlowPath(Swift.Int) -> Swift.AnyObject (in ###)
0x000000010516f9f0 function signature specialization <Arg[1] = Dead> ~~~

I printed time(in milliseconds) in getter and setter of the array and the result was array was being write and read in same exact time. Does this can be cause of crash in getElementSlowPath?

In my code, "function signature specialization" crash was CoreData related. So I thought cause of this crash could be Coredata related. Is this caused by CoreDataModel attribute is optional and normalDataModel attribute is not option?
for exameple

extension CoreDataModel {
  @NSManaged public var message: String?

  func update(model: DataModel) {
    self.message = model.message
  }
}
struct DataModel {
  var message: String
}


问:
NFS share with Autofs not unmounting after the given timeout
OS: Ubuntu 22.04.1 LTS
Automount version: 5.1.8

/etc/auto.master file:

```<code>/home/ubuntu/mydir      /etc/auto.misc  -t 20
</code>```

/etc/auto.misc file:

```<code>myvol   -fstype=nfs4 10.0.1.142:/mnt/myvol
</code>```

I enter into /home/ubuntu/mydir/myvol the NFS share mounted automatically. When I am not in the path /home/ubuntu/mydir/myvol the NFS share must be unmounted after 20 seconds as per my auto.master file, but it's not working. Is it a bug or what. How to solve it.

Body:
OS: Ubuntu 22.04.1 LTS
Automount version: 5.1.8

/etc/auto.master file:

/home/ubuntu/mydir      /etc/auto.misc  -t 20

/etc/auto.misc file:

myvol   -fstype=nfs4 10.0.1.142:/mnt/myvol

I enter into /home/ubuntu/mydir/myvol the NFS share mounted automatically. When I am not in the path /home/ubuntu/mydir/myvol the NFS share must be unmounted after 20 seconds as per my auto.master file, but it's not working. Is it a bug or what. How to solve it.


问:
laravel 9: how to make validation for $jumlahcuti > $sisacuti before the form is submitted
ask, permission all. I want to make a validation before the form is submitted for the type of leave that $sisa_cuti = 0, as in the form above. this is an image for the form, the value for jumlahcuti is taken from the tglmulai and sampai datepicker.

how do you do that?, so for a  jumlah_cuti  >  $sisa_cuti will issue an error message.

I took the $sisa_cuti variable from the controller that I included below:

```<code>  $jeniscuti = DB::table('alokasicuti')
        ->join('jeniscuti','alokasicuti.id_jeniscuti','=','jeniscuti.id')
        ->where('alokasicuti.id_karyawan','=', Auth::user()->id_pegawai)
        ->get();

    $sisacuti = DB::table('alokasicuti')
        ->join('cuti','alokasicuti.id_jeniscuti','cuti.id_jeniscuti')
        ->where('alokasicuti.id_karyawan',Auth::user()->id_pegawai)
        ->where('cuti.id_karyawan',Auth::user()->id_pegawai)
        ->where('cuti.status','=','Disetujui')
        ->selectraw('alokasicuti.durasi - cuti.jml_cuti as sisa,
        cuti.id_jeniscuti,cuti.jml_cuti')
        ->get();
    $sisa_cuti = array();
    foreach ($sisacuti as $data) {
        $sisa_cuti[$data->id_jeniscuti] = $data->sisa;
    }
    return view('karyawan.cuti.index',compact('jeniscuti','sisa_cuti'));
</code>```

I also include the code to display available leave and the rest on the create data form. this is code in view for $sisa_cuti:

```<code><div class="form-group col-sm">
   <label for="id_jeniscuti" class="col-form-label">Kategori Cuti</label>
       <select name="id_jeniscuti" id="id_jeniscuti" class="form-control" required>
           <option>-- Pilih Kategori --</option>
           @foreach ($jeniscuti as $data)
               @if(isset($sisa_cuti[$data->id]) && $sisa_cuti[$data->id] >= 0)
                  <option value="{{ $data->id}}">
                    (sisa cuti: {{ isset($sisa_cuti[$data->id]) ? $sisa_cuti[$data->id] : 0 }} hari) {{ $data->jenis_cuti }}
                  </option>
               @else
                   <option value="{{ $data->id}}">
                      (cuti is available) {{ $data->jenis_cuti }}
                   </option>
               @endif
           @endforeach
       </select>
   </div>
</code>```

and this is the jumlahcuti() function used to calculate the number of days off based on the tanggal_mulai and sampai selected by the user on the form. this is the javascript for jumlah_cuti form proccess:

```<code>     <script type="text/javascript">
     function jumlahcuti()
    {
        var start= $('#datepicker-autoclosea').val();
        var end  = $('#datepicker-autocloseb').val();

        var start_date = new Date(start);
        var end_date   = new Date(end);
        var daysOfYear = [];

        //untuk mendapatkan jumlah hari cuti
        for (var d = start_date; d <= end_date; d.setDate(d.getDate() + 1))
        {
            //cek workdays
            let tanggal = new Date(d);
            if(tanggal.getDay() !=0 && tanggal.getDay() !=6){
                daysOfYear.push(tanggal);
                console.log(tanggal);
            } else{
                console.log(" Hari Libur" + tanggal.getDay());
            }
        }
        //mengambil value tanggal mulai
        $('#start_date').on('change', function() {
            jumlahcuti();
        });

        //mengambil value tanggal selesai
        $('#end_date').on('change', function() {
            jumlahcuti();
        });

        console.info(daysOfYear);
        // alert('test');

        $('#jumlah').val(daysOfYear.length ?? 0);
    };
 </script>
</code>```

before that i tried to make validation in the jumlahcuti() function, like this:

```<code>if (isset($sisa_cuti[request()->id_jeniscuti]) && request()->jumlah_cuti > $sisa_cuti[request()->id_jeniscuti])
    {
     session()->flash('error', 'Jumlah cuti yang diajukan melebihi sisa cuti yang tersisa. Silakan pilih jumlah cuti yang lebih kecil.');
     return redirect()->back();
   }
</code>```

however I got an error like this:

when I use it in a function and try to select a date, the jumlahcuti form will be empty as above. and this is another javascript code that I use to make validation $jumlahcuti > $sisa_cuti:

```<code><script>
    function validate() {
        var sisaCuti = {!! json_encode($sisa_cuti) !!};// getting value
       of sisa_cuti from controller
        // console.log(sisaCuti);
        var jumlah_cuti = document.getElementById("jumlah_cuti").value; // getting input value of jumlah cuti
        var id_jeniscuti = document.getElementById("id_jeniscuti").value; // getting input value of id_jeniscuti

        if (sisa_cuti[id_jeniscuti] < jumlah_cuti) {
            alert("Jumlah cuti yang diajukan melebihi sisa cuti yang tersisa. Silakan pilih jumlah cuti yang lebih kecil.");
            console.info(sisa_cuti[id_jeniscuti] < jumlah_cuti);
            return false;
        }
        return true;
    }
</script>
</code>```

what is the solution, sir?

Body:
ask, permission all. I want to make a validation before the form is submitted for the type of leave that $sisa_cuti = 0, as in the form above. this is an image for the form, the value for jumlahcuti is taken from the tglmulai and sampai datepicker.

how do you do that?, so for a  jumlah_cuti  >  $sisa_cuti will issue an error message.

I took the $sisa_cuti variable from the controller that I included below:

  $jeniscuti = DB::table('alokasicuti')
        ->join('jeniscuti','alokasicuti.id_jeniscuti','=','jeniscuti.id')
        ->where('alokasicuti.id_karyawan','=', Auth::user()->id_pegawai)
        ->get();

    $sisacuti = DB::table('alokasicuti')
        ->join('cuti','alokasicuti.id_jeniscuti','cuti.id_jeniscuti')
        ->where('alokasicuti.id_karyawan',Auth::user()->id_pegawai)
        ->where('cuti.id_karyawan',Auth::user()->id_pegawai)
        ->where('cuti.status','=','Disetujui')
        ->selectraw('alokasicuti.durasi - cuti.jml_cuti as sisa,
        cuti.id_jeniscuti,cuti.jml_cuti')
        ->get();
    $sisa_cuti = array();
    foreach ($sisacuti as $data) {
        $sisa_cuti[$data->id_jeniscuti] = $data->sisa;
    }
    return view('karyawan.cuti.index',compact('jeniscuti','sisa_cuti'));

I also include the code to display available leave and the rest on the create data form. this is code in view for $sisa_cuti:

   Kategori Cuti
       <select name="id_jeniscuti" id="id_jeniscuti" class="form-control" required>
           <option>-- Pilih Kategori --</option>
           @foreach ($jeniscuti as $data)
               @if(isset($sisa_cuti[$data->id]) && $sisa_cuti[$data->id] >= 0)
                  <option value="{{ $data->id}}">
                    (sisa cuti: {{ isset($sisa_cuti[$data->id]) ? $sisa_cuti[$data->id] : 0 }} hari) {{ $data->jenis_cuti }}
                  </option>
               @else
                   <option value="{{ $data->id}}">
                      (cuti is available) {{ $data->jenis_cuti }}
                   </option>
               @endif
           @endforeach
       </select>

and this is the jumlahcuti() function used to calculate the number of days off based on the tanggal_mulai and sampai selected by the user on the form. this is the javascript for jumlah_cuti form proccess:

before that i tried to make validation in the jumlahcuti() function, like this:

if (isset($sisa_cuti[request()->id_jeniscuti]) && request()->jumlah_cuti > $sisa_cuti[request()->id_jeniscuti])
    {
     session()->flash('error', 'Jumlah cuti yang diajukan melebihi sisa cuti yang tersisa. Silakan pilih jumlah cuti yang lebih kecil.');
     return redirect()->back();
   }

however I got an error like this:

when I use it in a function and try to select a date, the jumlahcuti form will be empty as above. and this is another javascript code that I use to make validation $jumlahcuti > $sisa_cuti:

what is the solution, sir?


问:
Get error when set 'isRemoteEnabled' option in dompdf
I am working on Codeigniter3 and using dompdf to generate pdf where I want to use watermark and logo. I set all things but not able to show images on pdf. First I was using img tag in html itself but it was not working so I added the code to apply the appropriate images in Pdf.php file in libraries folder but still it doesn't show images properly.

I did some research on it and found, need to enable 'isRemoteEnabled' option but when I apply this option, it throws error.

Below is my code

Controller function code

```<code>$html = $this->load->view('book_quiz_completion_certificate', $this->data, TRUE);

$this->load->library('pdf');

$this->pdf->createPDF($html, $book_title, true);
</code>```

Pdf function

```<code>function createPDF($html, $filename='', $download=TRUE, $paper='A4', $orientation='portrait')
{
    // Set options to enable embedded PHP
    $options = new Options();

    $options->set('isPhpEnabled', 'true');
    $options->set('isRemoteEnabled', 'true');

    //$options->set('tempDir', __DIR__ . '/site_uploads/dompdf_temp');
    //$options->set('isRemoteEnabled', TRUE);
    //$options->set('debugKeepTemp', TRUE);
    //$options->set('chroot', '/'); // Just for testing :)
    //$options->set('isHtml5ParserEnabled', true);

    //$domPdf->setOptions($options);

    $dompdf = new DOMPDF($options);

    $contxt = stream_context_create([
                'ssl' => [
                    'verify_peer' => FALSE,
                    'verify_peer_name' => FALSE,
                    'allow_self_signed'=> TRUE
                ]
            ]);

    //echo '``` $options :: '; print_r($dompdf->getOptions()); die;

    $dompdf->setHttpContext($contxt);

    $dompdf->load_html($html);

    $dompdf->set_paper($paper, $orientation);

    // Render the HTML as PDF
    $dompdf->render();

    // Instantiate canvas instance
    $canvas = $dompdf->getCanvas();

    // Get height and width of page
    $w = $canvas->get_width();
    $h = $canvas->get_height();

    // Specify oogo image
    $logo_imageURL = FCPATH.'assets/uploads/images/143b8-f0b8b-86.jpg';
    $logo_imgWidth = 20;
    $logo_imgHeight = 20;

    // Specify logo image horizontal and vertical position
    $x = (($w-$logo_imgWidth)/5);
    $y = (($h-$logo_imgHeight)/7);

    // Add logo image to the pdf
    $canvas->image($logo_imageURL, $x, $y, $logo_imgWidth, $logo_imgHeight);

    // Specify watermark image
    $imageURL = URL_PUBLIC_UPLOADS.'images/143b8-f0b8b-86.jpg';
    $imgWidth = 400;
    $imgHeight = 400;

    // Set text opacity
    $canvas->set_opacity(.5);

    // Specify watermark image horizontal and vertical position
    $x = (($w-$imgWidth)/2);
    $y = (($h-$imgHeight)/4);

    // Add watermark image to the pdf
    $canvas->image($imageURL, $x, $y, $imgWidth, $imgHeight);

    // Specify watermark image
    $signature_imageURL = URL_PUBLIC_UPLOADS.'images/download.png';
    //$signature_imageURL = FCPATH.'assets/uploads/images/download.png';
    $signature_imgWidth = 60;
    $signature_imgHeight = 60;

    //$canvas->set_opacity(.5);

    // Specify signature image image horizontal and vertical position
    $x = (($w-$signature_imgWidth)/3);
    $y = (($h+$signature_imgHeight)/2);

    // Add signature image to the pdf
    $canvas->image($signature_imageURL, $x, $y, $signature_imgWidth, $signature_imgHeight);

    if($download)
        $dompdf->stream($filename.'.pdf', array('Attachment' => 1));
    else
        $dompdf->stream($filename.'.pdf', array('Attachment' => 0));
}
```
<p>For html, I am using following template</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: Roboto;
}

.certificate-container {
    padding: 50px;
    width: 1024px;
}
.certificate {
    border: 20px solid #0C5280;
    padding: 25px;
    height: 600px;
    position: relative;
}

.certificate:after {
    content: '';
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    position: absolute;
    background-image: url(https://image.ibb.co/ckrVv7/water_mark_logo.png);
    background-size: 100%;
    z-index: -1;
}

.certificate-header > .logo {
    width: 80px;
    height: 80px;
}

.certificate-title {
    text-align: center;
}

.certificate-body {
    text-align: center;
}

h1 {

    font-weight: 400;
    font-size: 48px;
    color: #0C5280;
}

.student-name {
    font-size: 24px;
}

.certificate-content {
    margin: 0 auto;
    width: 750px;
}

.about-certificate {
    width: 380px;
    margin: 0 auto;
}

.topic-description {

    text-align: center;
}</code>```

RENR NCLEX AND CONTINUING EDUCATION (CME) Review Masters

Certificate of Completion

Matthew Taylor

                has completed [hours] hours on topic title here online on Date [Date of Completion]

                    The Topic consists of [hours] Continuity hours and includes the following:

Contract adminitrator - Types of claim - Claim Strategy - Delay analysis - Thepreliminaries to a claim - The essential elements to a successful claim - Responses - Claim preparation and presentation

Principal: ______________________

                                    Accredited by

                                    Endorsed by

```

Now, Both options for me is ok i.e. if it can allow img tag in html itself or it can add image from function itself.

Any help is really appreciated.

Thanks.

Body:
I am working on Codeigniter3 and using dompdf to generate pdf where I want to use watermark and logo. I set all things but not able to show images on pdf. First I was using img tag in html itself but it was not working so I added the code to apply the appropriate images in Pdf.php file in libraries folder but still it doesn't show images properly.

I did some research on it and found, need to enable 'isRemoteEnabled' option but when I apply this option, it throws error.

Below is my code

Controller function code

$html = $this->load->view('book_quiz_completion_certificate', $this->data, TRUE);

$this->load->library('pdf');

$this->pdf->createPDF($html, $book_title, true);

Pdf function

function createPDF($html, $filename='', $download=TRUE, $paper='A4', $orientation='portrait')
{
    // Set options to enable embedded PHP
    $options = new Options();

    $options->set('isPhpEnabled', 'true');
    $options->set('isRemoteEnabled', 'true');

    //$options->set('tempDir', __DIR__ . '/site_uploads/dompdf_temp');
    //$options->set('isRemoteEnabled', TRUE);
    //$options->set('debugKeepTemp', TRUE);
    //$options->set('chroot', '/'); // Just for testing :)
    //$options->set('isHtml5ParserEnabled', true);

    //$domPdf->setOptions($options);

    $dompdf = new DOMPDF($options);

    $contxt = stream_context_create([
                'ssl' => [
                    'verify_peer' => FALSE,
                    'verify_peer_name' => FALSE,
                    'allow_self_signed'=> TRUE
                ]
            ]);

    //echo '
 $options :: '; print_r($dompdf->getOptions()); die;

    $dompdf->setHttpContext($contxt);

    $dompdf->load_html($html);

    $dompdf->set_paper($paper, $orientation);

    // Render the HTML as PDF
    $dompdf->render();

    // Instantiate canvas instance
    $canvas = $dompdf->getCanvas();

    // Get height and width of page
    $w = $canvas->get_width();
    $h = $canvas->get_height();

    // Specify oogo image
    $logo_imageURL = FCPATH.'assets/uploads/images/143b8-f0b8b-86.jpg';
    $logo_imgWidth = 20;
    $logo_imgHeight = 20;

    // Specify logo image horizontal and vertical position
    $x = (($w-$logo_imgWidth)/5);
    $y = (($h-$logo_imgHeight)/7);

    // Add logo image to the pdf
    $canvas->image($logo_imageURL, $x, $y, $logo_imgWidth, $logo_imgHeight);

    // Specify watermark image
    $imageURL = URL_PUBLIC_UPLOADS.'images/143b8-f0b8b-86.jpg';
    $imgWidth = 400;
    $imgHeight = 400;

    // Set text opacity
    $canvas->set_opacity(.5);

    // Specify watermark image horizontal and vertical position
    $x = (($w-$imgWidth)/2);
    $y = (($h-$imgHeight)/4);

    // Add watermark image to the pdf
    $canvas->image($imageURL, $x, $y, $imgWidth, $imgHeight);

    // Specify watermark image
    $signature_imageURL = URL_PUBLIC_UPLOADS.'images/download.png';
    //$signature_imageURL = FCPATH.'assets/uploads/images/download.png';
    $signature_imgWidth = 60;
    $signature_imgHeight = 60;

    //$canvas->set_opacity(.5);

    // Specify signature image image horizontal and vertical position
    $x = (($w-$signature_imgWidth)/3);
    $y = (($h+$signature_imgHeight)/2);

    // Add signature image to the pdf
    $canvas->image($signature_imageURL, $x, $y, $signature_imgWidth, $signature_imgHeight);

    if($download)
        $dompdf->stream($filename.'.pdf', array('Attachment' => 1));
    else
        $dompdf->stream($filename.'.pdf', array('Attachment' => 0));
}

For html, I am using following template

body {
    font-family: Roboto;
}

.certificate-container {
    padding: 50px;
    width: 1024px;
}
.certificate {
    border: 20px solid #0C5280;
    padding: 25px;
    height: 600px;
    position: relative;
}

.certificate:after {
    content: '';
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    position: absolute;
    background-image: url(https://image.ibb.co/ckrVv7/water_mark_logo.png);
    background-size: 100%;
    z-index: -1;
}

.certificate-header > .logo {
    width: 80px;
    height: 80px;
}

.certificate-title {
    text-align: center;
}

.certificate-body {
    text-align: center;
}

h1 {

    font-weight: 400;
    font-size: 48px;
    color: #0C5280;
}

.student-name {
    font-size: 24px;
}

.certificate-content {
    margin: 0 auto;
    width: 750px;
}

.about-certificate {
    width: 380px;
    margin: 0 auto;
}

.topic-description {

    text-align: center;
}

RENR NCLEX AND CONTINUING EDUCATION (CME) Review Masters

Certificate of Completion

Matthew Taylor

                has completed [hours] hours on topic title here online on Date [Date of Completion]

                    The Topic consists of [hours] Continuity hours and includes the following:

Contract adminitrator - Types of claim - Claim Strategy - Delay analysis - Thepreliminaries to a claim - The essential elements to a successful claim - Responses - Claim preparation and presentation

Principal: ______________________

                                    Accredited by

                                    Endorsed by

Now, Both options for me is ok i.e. if it can allow img tag in html itself or it can add image from function itself.

Any help is really appreciated.

Thanks.


问:
add user to kafka authentication without cluster restart
We want to add authentication to our kafka cluster by using SASL_SSL.
As we see that we want to be able to frequently add users we are looking for at way to do this without having to perform a rolling restart.
server.properties

```<code>
listeners=PLAINTEXT://localhost:9092,SASL_SSL://localhost:9093
advertised.listeners=PLAINTEXT://localhost:9092,SASL_SSL://localhost:9093
listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SASL_SSL:SASL_SSL
#SASL_SSL:Listener with TLS-based encryption and SASL-based authentication.
sasl.mechanism.inter.broker.protocol=SCRAM-SHA-256
sasl.enabled.mechanisms=SCRAM-SHA-256
inter.broker.listener.name=PLAINTEXT
ssl.endpoint.identification.algorithm=
ssl.client.auth=required

ssl.enabled.protocols =  TLSv1.2,TLSv1.1,TLSv1
sasl.mechanism.controller.protocol=SCRAM-SHA-256

ssl.keystore.location=certs\\server.keystore.jks
ssl.keystore.password=******
ssl.truststore.location=certs\\server.truststore.jks
ssl.truststore.password==******
ssl.key.password==******

super.users=User:admin
zookeeper.set.acl=true
allow.everyone.if.no.acl.found=true
</code>```

zookeeper.properties

```<code>authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
authProvider.2=org.apache.zookeeper.server.auth.DigestAuthenticationProvider
requireClientAuthScheme=sasl
sasl.client=true
sasl.clientconfig=Client
</code>```

producer.properties & consumer.properties

```<code>
security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-256
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="alice" password="alice-secret";
ssl.keystore.location=certs\\client.keystore.jks
ssl.keystore.password==******
ssl.key.password==******
ssl.truststore.location=certs\\client.truststore.jks
ssl.truststore.password==******
</code>```

zookeeper and kafka start.....

then add user with below command throw Exception:

sh kafka-configs.sh --zookeeper localhost:2181 --alter --add-config 'SCRAM-SHA-256=[password='testUSer-secret']' --entity-type users --entity-name testUSer

exception:

org.apache.zookeeper.keeperException$NoAuthException:KeeperErrorCode = NoAuth for config/users/testUser

Is it possible to add new users to the SASL JAAS configuration without restarting the Kafka cluster?

Body:
We want to add authentication to our kafka cluster by using SASL_SSL.
As we see that we want to be able to frequently add users we are looking for at way to do this without having to perform a rolling restart.
server.properties

listeners=PLAINTEXT://localhost:9092,SASL_SSL://localhost:9093
advertised.listeners=PLAINTEXT://localhost:9092,SASL_SSL://localhost:9093
listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SASL_SSL:SASL_SSL
#SASL_SSL:Listener with TLS-based encryption and SASL-based authentication.
sasl.mechanism.inter.broker.protocol=SCRAM-SHA-256
sasl.enabled.mechanisms=SCRAM-SHA-256
inter.broker.listener.name=PLAINTEXT
ssl.endpoint.identification.algorithm=
ssl.client.auth=required

ssl.enabled.protocols =  TLSv1.2,TLSv1.1,TLSv1
sasl.mechanism.controller.protocol=SCRAM-SHA-256

ssl.keystore.location=certs\\server.keystore.jks
ssl.keystore.password=******
ssl.truststore.location=certs\\server.truststore.jks
ssl.truststore.password==******
ssl.key.password==******

super.users=User:admin
zookeeper.set.acl=true
allow.everyone.if.no.acl.found=true

zookeeper.properties

authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider
authProvider.2=org.apache.zookeeper.server.auth.DigestAuthenticationProvider
requireClientAuthScheme=sasl
sasl.client=true
sasl.clientconfig=Client

producer.properties & consumer.properties

security.protocol=SASL_SSL
sasl.mechanism=SCRAM-SHA-256
sasl.jaas.config=org.apache.kafka.common.security.scram.ScramLoginModule required username="alice" password="alice-secret";
ssl.keystore.location=certs\\client.keystore.jks
ssl.keystore.password==******
ssl.key.password==******
ssl.truststore.location=certs\\client.truststore.jks
ssl.truststore.password==******

zookeeper and kafka start.....

then add user with below command throw Exception:

sh kafka-configs.sh --zookeeper localhost:2181 --alter --add-config 'SCRAM-SHA-256=[password='testUSer-secret']' --entity-type users --entity-name testUSer

exception:

org.apache.zookeeper.keeperException$NoAuthException:KeeperErrorCode = NoAuth for config/users/testUser

Is it possible to add new users to the SASL JAAS configuration without restarting the Kafka cluster?


问:
DynamoDB conditional write error : Value must be provided when Exists is true for Attribute:
I am getting this error on trying to make an update in local dynamodb
'One or more parameter values were invalid: Value must be provided when Exists is true for Attribute: AssetLabel (Service: null; Status Code: 400; Error Code: ValidationException; Request ID: null; Proxy: null)
[junit] com.amazonaws.AmazonServiceException: One or more parameter values were invalid: Value must be provided when Exists is true for Attribute: AssetLabel (Service: null; Status Code: 400; Error Code: ValidationException; Request ID: null; Proxy: null)'

i can see the attribute assetLabel is present in the object. still the error says assetLabel is missing.

```<code>    @Test
    public void testExecuteBackfill() throws FileNotFoundException {
        // Setup
        AssetRecord assetDetailsRecord = createAssetDetailsRecord(TestConstants.ASSET_LABEL_1, AssetStatusBO.ACTIVE);
        localDynamoMapper.save(assetDetailsRecord);

        // Assert Asset mapping unchanged
        AssetRecord fetchedAssetMappingRecord = loadAssetRecord(TestConstants.ASSET_LABEL_1, TestConstants.RANGE_KEY_LATEST);

        // Assert Asset detail changes
        AssetRecord fetchedAssetDetailsRecord = loadAssetRecord(TestConstants.ASSET_LABEL_1, TestConstants.RANGE_KEY_LATEST);
        System.out.println("fetchedAssetDetailsRecord = " +fetchedAssetDetailsRecord);
        //Mockito.when(assetDAO.getAssetByAssetLabel(TestConstants.ASSET_LABEL_1)).thenReturn(TestConstants.ASSET_BO);
        remarksAndMonitoringStatusBackfillerScriptHelper.executeBackfill(TEST_IOT_DATA_FILE_PATH);

        // Assert Asset detail changes
        fetchedAssetDetailsRecord = loadAssetRecord(TestConstants.ASSET_LABEL_1, TestConstants.RANGE_KEY_LATEST);
    }
</code>```

code for creating table

```<code>    private void createTable() {
        final CreateTableRequest createTableRequest
                = localDynamoMapper.generateCreateTableRequest(AssetRecord.class);
        createTableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
        createTableRequest.getGlobalSecondaryIndexes().forEach(index -> {
            index.setProjection(new Projection().withProjectionType("ALL"));
            index.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
        });
        localDynamo.createTable(createTableRequest);
    }
</code>```

Entity used to create table

```<code>@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@DynamoDBTable(tableName = AssetRecordConstants.TABLE_NAME)
public class AssetRecord {

    @DynamoDBHashKey(attributeName = AssetRecordConstants.ASSET_LABEL)
    private String assetLabel;

    @DynamoDBRangeKey(attributeName = AssetRecordConstants.RANGE_KEY)
    private String rangeKey;

    @DynamoDBAttribute(attributeName = AssetRecordConstants.NODE_ID)
    @DynamoDBIndexHashKey(globalSecondaryIndexNames =
            {AssetRecordConstants.ASSET_TYPE_INDEX, AssetRecordConstants.MAPPED_RESOURCE_LABEL_INDEX})
    private String nodeId;

    @DynamoDBTypeConvertedEnum
    @DynamoDBAttribute(attributeName = AssetRecordConstants.ASSET_TYPE)
    @DynamoDBIndexRangeKey(globalSecondaryIndexName = AssetRecordConstants.ASSET_TYPE_INDEX)
    private AssetTypeBO assetType;
}
</code>```

Body:
I am getting this error on trying to make an update in local dynamodb
'One or more parameter values were invalid: Value must be provided when Exists is true for Attribute: AssetLabel (Service: null; Status Code: 400; Error Code: ValidationException; Request ID: null; Proxy: null)
[junit] com.amazonaws.AmazonServiceException: One or more parameter values were invalid: Value must be provided when Exists is true for Attribute: AssetLabel (Service: null; Status Code: 400; Error Code: ValidationException; Request ID: null; Proxy: null)'

i can see the attribute assetLabel is present in the object. still the error says assetLabel is missing.

    @Test
    public void testExecuteBackfill() throws FileNotFoundException {
        // Setup
        AssetRecord assetDetailsRecord = createAssetDetailsRecord(TestConstants.ASSET_LABEL_1, AssetStatusBO.ACTIVE);
        localDynamoMapper.save(assetDetailsRecord);

        // Assert Asset mapping unchanged
        AssetRecord fetchedAssetMappingRecord = loadAssetRecord(TestConstants.ASSET_LABEL_1, TestConstants.RANGE_KEY_LATEST);

        // Assert Asset detail changes
        AssetRecord fetchedAssetDetailsRecord = loadAssetRecord(TestConstants.ASSET_LABEL_1, TestConstants.RANGE_KEY_LATEST);
        System.out.println("fetchedAssetDetailsRecord = " +fetchedAssetDetailsRecord);
        //Mockito.when(assetDAO.getAssetByAssetLabel(TestConstants.ASSET_LABEL_1)).thenReturn(TestConstants.ASSET_BO);
        remarksAndMonitoringStatusBackfillerScriptHelper.executeBackfill(TEST_IOT_DATA_FILE_PATH);

        // Assert Asset detail changes
        fetchedAssetDetailsRecord = loadAssetRecord(TestConstants.ASSET_LABEL_1, TestConstants.RANGE_KEY_LATEST);
    }

code for creating table

    private void createTable() {
        final CreateTableRequest createTableRequest
                = localDynamoMapper.generateCreateTableRequest(AssetRecord.class);
        createTableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
        createTableRequest.getGlobalSecondaryIndexes().forEach(index -> {
            index.setProjection(new Projection().withProjectionType("ALL"));
            index.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
        });
        localDynamo.createTable(createTableRequest);
    }

Entity used to create table

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@DynamoDBTable(tableName = AssetRecordConstants.TABLE_NAME)
public class AssetRecord {

    @DynamoDBHashKey(attributeName = AssetRecordConstants.ASSET_LABEL)
    private String assetLabel;

    @DynamoDBRangeKey(attributeName = AssetRecordConstants.RANGE_KEY)
    private String rangeKey;

    @DynamoDBAttribute(attributeName = AssetRecordConstants.NODE_ID)
    @DynamoDBIndexHashKey(globalSecondaryIndexNames =
            {AssetRecordConstants.ASSET_TYPE_INDEX, AssetRecordConstants.MAPPED_RESOURCE_LABEL_INDEX})
    private String nodeId;

    @DynamoDBTypeConvertedEnum
    @DynamoDBAttribute(attributeName = AssetRecordConstants.ASSET_TYPE)
    @DynamoDBIndexRangeKey(globalSecondaryIndexName = AssetRecordConstants.ASSET_TYPE_INDEX)
    private AssetTypeBO assetType;
}


问:
how to cache multiple bitmap with Glide
Im having problem with caching image with Glide.

My sample code is like this.

```<code>items.forEach { item ->
    Glide.with(context)
                .asBitmap()
                .apply(requestOptions)
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .load(item.url)
                .into(object : CustomTarget<Bitmap>() {
                    override fun onLoadCleared(placeholder: Drawable?) {

                    }

                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {

                    }
                })
}
</code>```

I want to cache the data in first for loop, and after first loop is over,
the glide should not request to remote url, should use cache.
I tested with the DiskCacheStrategy options, but it didn't work.
Anyone who can solve this problem, please help me...

Title: how to cache multiple bitmap with Glide

Body:
Im having problem with caching image with Glide.

My sample code is like this.

items.forEach { item ->
    Glide.with(context)
                .asBitmap()
                .apply(requestOptions)
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .load(item.url)
                .into(object : CustomTarget<Bitmap>() {
                    override fun onLoadCleared(placeholder: Drawable?) {

                    }

                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {

                    }
                })
}

I want to cache the data in first for loop, and after first loop is over,
the glide should not request to remote url, should use cache.
I tested with the DiskCacheStrategy options, but it didn't work.
Anyone who can solve this problem, please help me...


问:
400 Bad Request | Check Request size on client side before making API call?
I'm looking to add a JavaScript validation on client side before making a GET request to prevent the following 400 Bad Request error from happening, and show a custom message instead.

Example request URL would be as below:

```<code>/api/v1.0/example/?sample_query=Lorem%20Ipsum%20is%20simply%20dummy%20text%20of%20the%20printing%20and%20typesetting%20industry.%20Lorem%20Ipsum%20has%20been%20the%20industry%27s%20standard%20dummy%20text%20ever%20since%20the%201500s%2C%20when%20an%20unknown%20printer%20took%20a%20galley%20of%20type%20and%20scrambled%20it%20to%20make%20a%20type%20specimen%20book.%20It%20has%20survived%20not%20only%20five%20centuries%2C%20but%20also%20the%20leap%20into%20electronic%20typesetting%2C%20remaining%20essentially%20unchanged.%20It%20was%20popularised%20in%20the%201960s%20with%20the%20release%20of%20Letraset%20sheets%20containing%20Lorem%20Ipsum%20passages%2C%20and%20more%20recently%20with%20desktop%20publishing%20software%20like%20Aldus%20PageMaker%20including%20versions%20of%20Lorem%20Ipsum.%20%20Why%20do%20we%20use%20it%3F%20It%20is%20a%20long%20established%20fact%20that%20a%20reader%20will%20be%20distracted%20by%20the%20readable%20content%20of%20a%20page%20when%20looking%20at%20its%20layout.%20The%20point%20of%20using%20Lorem%20Ipsum%20is%20that%20it%20has%20a%20more-or-less%20normal%20distribution%20of%20letters%2C%20as%20opposed%20to%20using%20%27Content%20here%2C%20content%20here%27%2C%20making%20it%20look%20like%20readable%20English.%20Many%20desktop%20publishing%20packages%20and%20web%20page%20editors%20now%20use%20Lorem%20Ipsum%20as%20their%20default%20model%20text%2C%20and%20a%20search%20for%20%27lorem%20ipsum%27%20will%20uncover%20many%20web%20sites%20still%20in%20their%20infancy.%20Various%20versions%20have%20evolved%20over%20the%20years%2C%20sometimes%20by%20accident%2C%20sometimes%20on%20purpose%20(injected%20humour%20and%20the%20like).%20%20%20Where%20does%20it%20come%20from%3F%20Contrary%20to%20popular%20belief%2C%20Lorem%20Ipsum%20is%20not%20simply%20random%20text.%20It%20has%20roots%20in%20a%20piece%20of%20classical%20Latin%20literature%20from%2045%20BC%2C%20making%20it%20over%202000%20years%20old.%20Richard%20McClintock%2C%20a%20Latin%20professor%20at%20Hampden-Sydney%20College%20in%20Virginia%2C%20looked%20up%20one%20of%20the%20more%20obscure%20Latin%20words%2C%20consectetur%2C%20from%20a%20Lorem%20Ipsum%20passage%2C%20and%20going%20through%20the%20cites%20of%20the%20word%20in%20classical%20literature%2C%20discovered%20the%20undoubtable%20source.%20Lorem%20Ipsum%20comes%20from%20sections%201.10.32%20and%201.10.33%20of%20%22de%20Finibus%20Bonorum%20et%20Malorum%22%20(The%20Extremes%20of%20Good%20and%20Evil)%20by%20Cicero%2C%20written%20in%2045%20BC.%20This%20book%20is%20a%20treatise%20on%20the%20theory%20of%20ethics%2C%20very%20popular%20during%20the%20Renaissance.%20The%20first%20line%20of%20Lorem%20Ipsum%2C%20%22Lorem%20ipsum%20dolor%20sit%20amet..%22%2C%20comes%20from%20a%20line%20in%20section%201.10.32.%20%20The%20standard%20chunk%20of%20Lorem%20Ipsum%20used%20since%20the%201500s%20is%20reproduced%20below%20for%20those%20interested.%20Sections%201.10.32%20and%201.10.33%20from%20%22de%20Finibus%20Bonorum%20et%20Malorum%22%20by%20Cicero%20are%20also%20reproduced%20in%20their%20exact%20original%20form%2C%20accompanied%20by%20English%20versions%20from%20the%201914%20translation%20by%20H.%20Rackham.%20%20Where%20can%20I%20get%20some%3F%20There%20are%20many%20variations%20of%20passages%20of%20Lorem%20Ipsum%20available%2C%20but%20the%20majority%20have%20suffered%20alteration%20in%20some%20form%2C%20by%20injected%20humour%2C%20or%20randomised%20words%20which%20don%27t%20look%20even%20slightly%20believable.%20If%20you%20are%20going%20to%20use%20a%20passage%20of%20Lorem%20Ipsum%2C%20you%20need%20to%20be%20sure%20there%20isn%27t%20anything%20embarrassing%20hidden%20in%20the%20middle%20of%20text.%20All%20the%20Lorem%20Ipsum%20generators%20on%20the%20Internet%20tend%20to%20repeat%20predefined%20chunks%20as%20necessary%2C%20making%20this%20the%20first%20true%20generator%20on%20the%20Internet.%20It%20uses%20a%20dictionary%20of%20over%20200%20Latin%20words%2C%20combined%20with%20a%20handful%20of%20model%20sentence%20structures%2C%20to%20generate%20Lorem%20Ipsum%20which%20looks%20reasonable.&page=1&page_size=20
</code>```

What is the proper way to validate the length of the whole request line? I only have the length of Request URL.

Body:
I'm looking to add a JavaScript validation on client side before making a GET request to prevent the following 400 Bad Request error from happening, and show a custom message instead.

Example request URL would be as below:

/api/v1.0/example/?sample_query=Lorem%20Ipsum%20is%20simply%20dummy%20text%20of%20the%20printing%20and%20typesetting%20industry.%20Lorem%20Ipsum%20has%20been%20the%20industry%27s%20standard%20dummy%20text%20ever%20since%20the%201500s%2C%20when%20an%20unknown%20printer%20took%20a%20galley%20of%20type%20and%20scrambled%20it%20to%20make%20a%20type%20specimen%20book.%20It%20has%20survived%20not%20only%20five%20centuries%2C%20but%20also%20the%20leap%20into%20electronic%20typesetting%2C%20remaining%20essentially%20unchanged.%20It%20was%20popularised%20in%20the%201960s%20with%20the%20release%20of%20Letraset%20sheets%20containing%20Lorem%20Ipsum%20passages%2C%20and%20more%20recently%20with%20desktop%20publishing%20software%20like%20Aldus%20PageMaker%20including%20versions%20of%20Lorem%20Ipsum.%20%20Why%20do%20we%20use%20it%3F%20It%20is%20a%20long%20established%20fact%20that%20a%20reader%20will%20be%20distracted%20by%20the%20readable%20content%20of%20a%20page%20when%20looking%20at%20its%20layout.%20The%20point%20of%20using%20Lorem%20Ipsum%20is%20that%20it%20has%20a%20more-or-less%20normal%20distribution%20of%20letters%2C%20as%20opposed%20to%20using%20%27Content%20here%2C%20content%20here%27%2C%20making%20it%20look%20like%20readable%20English.%20Many%20desktop%20publishing%20packages%20and%20web%20page%20editors%20now%20use%20Lorem%20Ipsum%20as%20their%20default%20model%20text%2C%20and%20a%20search%20for%20%27lorem%20ipsum%27%20will%20uncover%20many%20web%20sites%20still%20in%20their%20infancy.%20Various%20versions%20have%20evolved%20over%20the%20years%2C%20sometimes%20by%20accident%2C%20sometimes%20on%20purpose%20(injected%20humour%20and%20the%20like).%20%20%20Where%20does%20it%20come%20from%3F%20Contrary%20to%20popular%20belief%2C%20Lorem%20Ipsum%20is%20not%20simply%20random%20text.%20It%20has%20roots%20in%20a%20piece%20of%20classical%20Latin%20literature%20from%2045%20BC%2C%20making%20it%20over%202000%20years%20old.%20Richard%20McClintock%2C%20a%20Latin%20professor%20at%20Hampden-Sydney%20College%20in%20Virginia%2C%20looked%20up%20one%20of%20the%20more%20obscure%20Latin%20words%2C%20consectetur%2C%20from%20a%20Lorem%20Ipsum%20passage%2C%20and%20going%20through%20the%20cites%20of%20the%20word%20in%20classical%20literature%2C%20discovered%20the%20undoubtable%20source.%20Lorem%20Ipsum%20comes%20from%20sections%201.10.32%20and%201.10.33%20of%20%22de%20Finibus%20Bonorum%20et%20Malorum%22%20(The%20Extremes%20of%20Good%20and%20Evil)%20by%20Cicero%2C%20written%20in%2045%20BC.%20This%20book%20is%20a%20treatise%20on%20the%20theory%20of%20ethics%2C%20very%20popular%20during%20the%20Renaissance.%20The%20first%20line%20of%20Lorem%20Ipsum%2C%20%22Lorem%20ipsum%20dolor%20sit%20amet..%22%2C%20comes%20from%20a%20line%20in%20section%201.10.32.%20%20The%20standard%20chunk%20of%20Lorem%20Ipsum%20used%20since%20the%201500s%20is%20reproduced%20below%20for%20those%20interested.%20Sections%201.10.32%20and%201.10.33%20from%20%22de%20Finibus%20Bonorum%20et%20Malorum%22%20by%20Cicero%20are%20also%20reproduced%20in%20their%20exact%20original%20form%2C%20accompanied%20by%20English%20versions%20from%20the%201914%20translation%20by%20H.%20Rackham.%20%20Where%20can%20I%20get%20some%3F%20There%20are%20many%20variations%20of%20passages%20of%20Lorem%20Ipsum%20available%2C%20but%20the%20majority%20have%20suffered%20alteration%20in%20some%20form%2C%20by%20injected%20humour%2C%20or%20randomised%20words%20which%20don%27t%20look%20even%20slightly%20believable.%20If%20you%20are%20going%20to%20use%20a%20passage%20of%20Lorem%20Ipsum%2C%20you%20need%20to%20be%20sure%20there%20isn%27t%20anything%20embarrassing%20hidden%20in%20the%20middle%20of%20text.%20All%20the%20Lorem%20Ipsum%20generators%20on%20the%20Internet%20tend%20to%20repeat%20predefined%20chunks%20as%20necessary%2C%20making%20this%20the%20first%20true%20generator%20on%20the%20Internet.%20It%20uses%20a%20dictionary%20of%20over%20200%20Latin%20words%2C%20combined%20with%20a%20handful%20of%20model%20sentence%20structures%2C%20to%20generate%20Lorem%20Ipsum%20which%20looks%20reasonable.&page=1&page_size=20

What is the proper way to validate the length of the whole request line? I only have the length of Request URL.


问:
Add remote USDZ file to local RealityKit .rcproject file and display in QLPreviewController
I'm using AR Quick Look.  I have a Reality Composer scene (.rcproject) in my project.  I'd like to add a variety of entities to the .rcproject, define triggers and actions AND add a USDZ file from a file at run time.

I can load a remote USDZ file into a QLPreviewController and display it fine as the single QLPreviewItem. I have the URL, covert it to a local file then open it as a preview item.

There are lots of examples of adding entities to an ARView.

But I do not see how I can have a scene defined in Xcode (.rcproject), that I edited with Reality Composer, add a entity (e.g. USDZ file) at run time and display the revised reality file using QLPreviewController and QLPreviewItem.

I can Entity.load(contentsOf: url) to load the .rcproject scene, get the anchor and add a child, which is the USDZ file I got from a remote URL and converted to a local file, but then how do I save that back (the updated anchor or ???) to a .reality file and pass the temporary local file URL as a QLPreviewItem?

Or is there a way to add an entity (USDZ file) to a running QLPreviewController view at run time?

I'm trying to stay with QLPreviewController because I need users to be able to share this AR Quick Look view with other iPhone users so they can open the view in Safari on the iPhone without needing my app.


问:
In push notifications, images/videos are not showing when the application is running in the background or has been killed?
I am developing an app in React native, want to show image/video in push notification when the app is in background or killed. When the app is in foreground it is doing fine but in background only title and message is showing but not the image/video. For push notification I am using react-native-firebase and @notifee/react-native to achieve this

```<code>export const notificationListener = async () => {
  messaging().onMessage(async remoteMessage => {
    onMessageReceived(remoteMessage);
  });
  async function onMessageReceived(message) {
    notifee.displayNotification({
      title: message.notification.title,
      body: message.notification.body,
      ios: {
        sound: 'default',
        attachments: [
          {
            url: message.data.video,
            thumbnailTime: 3,
          },
        ],
      },
    });
  }
  messaging().setBackgroundMessageHandler(async remoteMessage => {
    onMessageReceived(remoteMessage);
  });
};
</code>```

Body:
I am developing an app in React native, want to show image/video in push notification when the app is in background or killed. When the app is in foreground it is doing fine but in background only title and message is showing but not the image/video. For push notification I am using react-native-firebase and @notifee/react-native to achieve this

export const notificationListener = async () => {
  messaging().onMessage(async remoteMessage => {
    onMessageReceived(remoteMessage);
  });
  async function onMessageReceived(message) {
    notifee.displayNotification({
      title: message.notification.title,
      body: message.notification.body,
      ios: {
        sound: 'default',
        attachments: [
          {
            url: message.data.video,
            thumbnailTime: 3,
          },
        ],
      },
    });
  }
  messaging().setBackgroundMessageHandler(async remoteMessage => {
    onMessageReceived(remoteMessage);
  });
};


问:
Elastic Bean Stalk Real Time Logs
Currently I am working on Heroku, and I want to migrate my Node.js server to Elastic Bean Stalk. But the issue is that after migration, I see that there is no console that provides real-time logs for the whole machine. But Heroku offers this; can anyone tell me how to do the same on AWS?</p>

Title: Elastic Bean Stalk Real Time Logs


问:
How can I further optimize this code regarding matrix factorization?
I am implementing this matrix factorization code found here. How can I further optimize this code or where are the possible choke points or bottlenecks on this code(if there are any)? Thank you.</p>
```<code>
import numpy

def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):

    Q = Q.T

    for step in range(steps):
        for i in range(len(R)):
            for j in range(len(R[i])):
                if R[i][j] > 0:
                    # calculate error
                    eij = R[i][j] - numpy.dot(P[i,:],Q[:,j])

                    for k in range(K):
                        # calculate gradient with a and beta parameter
                        P[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k])
                        Q[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j])

        eR = numpy.dot(P,Q)

        e = 0

        for i in range(len(R)):

            for j in range(len(R[i])):

                if R[i][j] > 0:

                    e = e + pow(R[i][j] - numpy.dot(P[i,:],Q[:,j]), 2)

                    for k in range(K):

                        e = e + (beta/2) * (pow(P[i][k],2) + pow(Q[k][j],2))
        # 0.001: local minimum
        if e < 0.001:

            break

    return P, Q.T
</code>```

Body:
I am implementing this matrix factorization code found here. How can I further optimize this code or where are the possible choke points or bottlenecks on this code(if there are any)? Thank you.

import numpy

def matrix_factorization(R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02):

    Q = Q.T

    for step in range(steps):
        for i in range(len(R)):
            for j in range(len(R[i])):
                if R[i][j] > 0:
                    # calculate error
                    eij = R[i][j] - numpy.dot(P[i,:],Q[:,j])

                    for k in range(K):
                        # calculate gradient with a and beta parameter
                        P[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k])
                        Q[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j])

        eR = numpy.dot(P,Q)

        e = 0

        for i in range(len(R)):

            for j in range(len(R[i])):

                if R[i][j] > 0:

                    e = e + pow(R[i][j] - numpy.dot(P[i,:],Q[:,j]), 2)

                    for k in range(K):

                        e = e + (beta/2) * (pow(P[i][k],2) + pow(Q[k][j],2))
        # 0.001: local minimum
        if e < 0.001:

            break

    return P, Q.T


问:
Jetpack Compose: When does a Coroutine-Scope leave the Composition?
From the official documentation: "rememberCoroutineScope is a composable function that returns a CoroutineScope bound to the point of the Composition where it's called. The scope will be cancelled when the call leaves the Composition."

Please see here for the full text: Documentation

What is meant by "leaving the Composition"?

Can someone provide a concrete example? Currently can't imagine how the bold sentence is meant.


问:
What does "grows along the block dimension to accommodate its content" from MDN mean?
MDN says:

By default, a block level element's content fills the available inline space of the parent element containing it and grows along the block dimension to accommodate its content.

But I don't know what they mean by "grows along the block dimension to accommodate its content".

What grows along the block dimension and what is the block dimension and what is the content?


问:
Run Python from PHP code not executed problem
I have php code and python code and i use visual studio code as code editor, i use xampp apache for personal server. The code is below :

Html run button

```<code><form action="" method="post">
          <div class="card-header py-3 mb-30 mt-20 pb-20 pt-20">
                <div class="center">
                <input type="submit" name="runpython" value="Run" class="btn btn-primary">
          </div>
</div>
</form>
</code>```

This is the run python by php

```<code><?php
if(isset($_POST['runpython'])){
   $output = shell_exec('python3 /xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo $output;
   echo shell_exec('/xampp/htdocs/Klasifikasi_KNN/admin test.py');
   $output = shell_exec('python3 /xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo $output;
   echo shell_exec('xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo shell_exec('/xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo shell_exec('/xampp/htdocs/Klasifikasi_KNN/admin/test.py');
   echo shell_exec('xampp/htdocs/Klasifikasi_KNN/admin/test.py');
   echo shell_exec('python3 xampp/htdocs/Klasifikasi_KNN/admin/test.py');
   echo shell_exec('python3 /xampp/htdocs/Klasifikasi_KNN/admin/test.py');
}
?>
</code>```

This is the test.py

```<code>#! C:/Users/Jessen PC/AppData/Local/Microsoft/WindowsApps/python.exe
print("Hello World")
</code>```

What ive tried :

check if shell_exect is exist

```<code>    if(function_exists('exec')) {
        echo "exec is enabled";
    }
    if(function_exists('shell_exec')) {
        echo "shell_exec is enabled";
    }
</code>```

Prove shell exect is working

```<code>if (exec('echo TEST') == 'TEST')
{
    echo 'exec works!';
}
</code>```

output :
exec works! exec is enabled shell_exec is enabled"

Added handler script in httpd.conf in config xampp

```<code>AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict
</code>```

If i use D drive like this

```<code>$output = shell_exec('D:/xampp/htdocs/Klasifikasi_KNN/admin/test.py');
echo $output;
</code>```

This open like image below

What im aiming is the code is debug by python and display the output in website.

Is there something missing needs to be done to execute python files from php?

Body:
I have php code and python code and i use visual studio code as code editor, i use xampp apache for personal server. The code is below :

Html run button

<form action="" method="post">

                <input type="submit" name="runpython" value="Run" class="btn btn-primary">

</form>

This is the run python by php

<?php
if(isset($_POST['runpython'])){
   $output = shell_exec('python3 /xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo $output;
   echo shell_exec('/xampp/htdocs/Klasifikasi_KNN/admin test.py');
   $output = shell_exec('python3 /xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo $output;
   echo shell_exec('xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo shell_exec('/xampp/htdocs/Klasifikasi_KNN/admin test.py');
   echo shell_exec('/xampp/htdocs/Klasifikasi_KNN/admin/test.py');
   echo shell_exec('xampp/htdocs/Klasifikasi_KNN/admin/test.py');
   echo shell_exec('python3 xampp/htdocs/Klasifikasi_KNN/admin/test.py');
   echo shell_exec('python3 /xampp/htdocs/Klasifikasi_KNN/admin/test.py');
}
?>

This is the test.py

#! C:/Users/Jessen PC/AppData/Local/Microsoft/WindowsApps/python.exe
print("Hello World")

What ive tried :

check if shell_exect is exist

    if(function_exists('exec')) {
        echo "exec is enabled";
    }
    if(function_exists('shell_exec')) {
        echo "shell_exec is enabled";
    }

Prove shell exect is working

if (exec('echo TEST') == 'TEST')
{
    echo 'exec works!';
}

output :
exec works! exec is enabled shell_exec is enabled"

Added handler script in httpd.conf in config xampp

AddHandler cgi-script .py
ScriptInterpreterSource Registry-Strict

If i use D drive like this

$output = shell_exec('D:/xampp/htdocs/Klasifikasi_KNN/admin/test.py');
echo $output;

This open like image below

What im aiming is the code is debug by python and display the output in website.

Is there something missing needs to be done to execute python files from php?


问:
Why LSP restrict that the text edit range of a completion item must be single line?
In LSP spec about the completion item, there is a note says:

```<code>The text edit's range as well as both ranges from an insert
replace edit must be a [single line] and they must contain the position
at which completion has been requested.
</code>```

Is there any reason that the range must be a single line?

When the range is not a single line, the VS Code client will filter them out from the list.

For example:

```<code>
a.|foo(() -> {
    ...
});
</code>```

When triggering completion at |, I hope the completion item can change to code to:

```<code>a.bar(() -> {
    ...
});
</code>```

In this case, the range of the text edit is multiline, but is not allowed in LSP.

Body:
In LSP spec about the completion item, there is a note says:

The text edit's range as well as both ranges from an insert
replace edit must be a [single line] and they must contain the position
at which completion has been requested.

Is there any reason that the range must be a single line?

When the range is not a single line, the VS Code client will filter them out from the list.

For example:

a.|foo(() -> {
    ...
});

When triggering completion at |, I hope the completion item can change to code to:

a.bar(() -> {
    ...
});

In this case, the range of the text edit is multiline, but is not allowed in LSP.


问:
window.onerror / window.addeventlistener do not get triggered in my production environment in react js, but i don't want to use componentDidCatch

`handleError = (message, source, lineno, colno, error) => {

console.log("Error message",error, this.state.redemptionCode);

if (typeof newrelic == 'object') {

eslint-disable-next-line no-undef

newrelic.noticeError(error, { userId: ${this.state.redemptionCode} });

```<code>    }
</code>```

}`

in componentDidMount
window.onerror = this.handleError

it works fine in my other react projects

currenct react version i'm using "react": "^17.0.1", but with these same version other project works

Body:
`handleError = (message, source, lineno, colno, error) => {

console.log("Error message",error, this.state.redemptionCode);

if (typeof newrelic == 'object') {

eslint-disable-next-line no-undef

newrelic.noticeError(error, { userId: ${this.state.redemptionCode} });

    }

}`

in componentDidMount
window.onerror = this.handleError

it works fine in my other react projects

currenct react version i'm using "react": "^17.0.1", but with these same version other project works


问:
"attempt to apply a non function" error when attempting to remove slide in officeR
I am trying to remove a slide and consequently add a slide with content using the OfficeR package. The read_pptx() function read the layout of the template uploaded without error but am running into trouble when modifying the template.

```<code>my_report <- report %>%
  remove_slide(index = 1) %>%
  officer::add_slide(layout = "Player Evaluation", master = "Office Theme") %>%
  officer::ph_with(value = name, location = ph_location_label(ph_label = "Player Name"))
</code>```

The code above yields the follow error:

Error in x$presentation$slide_data() : attempt to apply non-function

Any help is appreciated!

Body:
I am trying to remove a slide and consequently add a slide with content using the OfficeR package. The read_pptx() function read the layout of the template uploaded without error but am running into trouble when modifying the template.

my_report <- report %>%
  remove_slide(index = 1) %>%
  officer::add_slide(layout = "Player Evaluation", master = "Office Theme") %>%
  officer::ph_with(value = name, location = ph_location_label(ph_label = "Player Name"))

The code above yields the follow error:

Error in x$presentation$slide_data() : attempt to apply non-function

Any help is appreciated!