问:
connecting to arduino atmega328p using usart , but the sender pin is acting as input
I'm trying to send a number in binary from one Arduino atmega328p to another using USART and then use the received data to display it on a seven segments display (7seg-mpx1-cc)
here is  the code on the sender part:

```<code>.INCLUDE "m328pdef.inc"
.ORG 0X00

// Intialize USART
SBI DDRD,1 // Set Tx pin as output
LDI R17,0
STS UBRR0H, R17
LDI R17, 0X67
STS UBRR0L, R17

// Enable transmitter
LDI R17,0X08
STS UCSR0B, R17

MAIN:
  // Wait for the transmit buffer to be empty
  LDS R17, UCSR0A
  SBRS R17, UDRE0
  RJMP MAIN

  // Transmit the 6 with a delay between each letter
  LDI R18, 0b11111110
  STS UDR0,R18
  CALL DELAY

HERE:
  RJMP HERE

DELAY:
  LDI R20, 30

DELAY_LOOP_1:
  LDI R21,30

DELAY_LOOP_2:
  LDI R22,30

DELAY_LOOP_3:
  DEC R22
  NOP
  BRNE DELAY_LOOP_3

  DEC R21
  BRNE DELAY_LOOP_2

  DEC R20
  BRNE DELAY_LOOP_1
  RET

</code>```

here is the code at the receiver part:

```<code>
.INCLUDE "m328pdef.inc"
.ORG 0X00

// set portC at output
LDI R16 , 0xFF
out DDRB , R16

// Intialize USART
SBI DDRD,0 // Set Rx pin as input
LDI R17,0
STS UBRR0H, R17
LDI R17, 0X67
STS UBRR0L, R17
LDI R17, 0X06
STS UCSR0C, R17

// Enable receiver and receive interrupt
LDI R17, 0X90
STS UCSR0B, R17

// Enable global interrupts
SEI

MAIN:
  // Wait for data to be received
  LDS R17, UCSR0A
  SBRS R17, RXC0
  RJMP MAIN

  // Read the received data from the receive buffer
  LDS R17, UDR0

  // Output the received data to Port C
  out PORTB , R17

  RJMP MAIN

delay:

    LDI R16 , 200
    loop1:
        LDI R17 , 30
        loop2:
            LDI R19 , 30
            loop3:
                nop
                dec R19
            BRNE loop3
            dec R17
        BRNE loop2
        dec R16
    BRNE loop1
RET

</code>```

here is the circuit connection but as you can see both RX TX are acting like inputs

what should I do to fix it?

any help is appreciated, thanks.

Body:
I'm trying to send a number in binary from one Arduino atmega328p to another using USART and then use the received data to display it on a seven segments display (7seg-mpx1-cc)
here is  the code on the sender part:

.INCLUDE "m328pdef.inc"
.ORG 0X00

// Intialize USART
SBI DDRD,1 // Set Tx pin as output
LDI R17,0
STS UBRR0H, R17
LDI R17, 0X67
STS UBRR0L, R17

// Enable transmitter
LDI R17,0X08
STS UCSR0B, R17

MAIN:
  // Wait for the transmit buffer to be empty
  LDS R17, UCSR0A
  SBRS R17, UDRE0
  RJMP MAIN

  // Transmit the 6 with a delay between each letter
  LDI R18, 0b11111110
  STS UDR0,R18
  CALL DELAY

HERE:
  RJMP HERE

DELAY:
  LDI R20, 30

DELAY_LOOP_1:
  LDI R21,30

DELAY_LOOP_2:
  LDI R22,30

DELAY_LOOP_3:
  DEC R22
  NOP
  BRNE DELAY_LOOP_3

  DEC R21
  BRNE DELAY_LOOP_2

  DEC R20
  BRNE DELAY_LOOP_1
  RET

here is the code at the receiver part:

.INCLUDE "m328pdef.inc"
.ORG 0X00

// set portC at output
LDI R16 , 0xFF
out DDRB , R16

// Intialize USART
SBI DDRD,0 // Set Rx pin as input
LDI R17,0
STS UBRR0H, R17
LDI R17, 0X67
STS UBRR0L, R17
LDI R17, 0X06
STS UCSR0C, R17

// Enable receiver and receive interrupt
LDI R17, 0X90
STS UCSR0B, R17

// Enable global interrupts
SEI

MAIN:
  // Wait for data to be received
  LDS R17, UCSR0A
  SBRS R17, RXC0
  RJMP MAIN

  // Read the received data from the receive buffer
  LDS R17, UDR0

  // Output the received data to Port C
  out PORTB , R17

  RJMP MAIN

delay:

    LDI R16 , 200
    loop1:
        LDI R17 , 30
        loop2:
            LDI R19 , 30
            loop3:
                nop
                dec R19
            BRNE loop3
            dec R17
        BRNE loop2
        dec R16
    BRNE loop1
RET

here is the circuit connection but as you can see both RX TX are acting like inputs

what should I do to fix it?

any help is appreciated, thanks.


来源: stackexchange

问:
Branch and Bound algorithm for Max Clique returns empty set
Hello I am trying to find the max clique of a graph using the algorithm 1 from p.2 of that paper
so far the algorithm returns just an empty set and I can't seem to find the mistake in my code. Any suggestions would be appreciated. Cheers!

my graph

```<code>import networkx as nx
graph_2 = nx.Graph()
graph_2.add_edges_from([('1','2'), ('1','3'), ('1','4'),
                        ('2', '3'), ('2', '4'), ('3', '4'), ('4','5'),
                        ('4', '6'), ('5', '6')])
</code>```

algorithm 1

```<code>R, R_best = [], []
S = list(graph_2.nodes)

def bnb(S):
    global R
    global R_best
    while len(S) != 0:
        if len(R) + len(S) <= len(R_best):
            return 0
        v = S.pop(0)
        R.append(v)
        S_mark = list(set(S).intersection(set(graph_2.adj[v])))
        if len(S_mark) != 0:
            bnb(S_mark)
        elif len(R) > len(R_best):
            R_best = R
        try:
            R.remove(v)
            S.remove(v)
        except:
            continue
    return R_best

print(bnb(S))   # prints []
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hello I am trying to find the max clique of a graph using the algorithm 1 from p.2 of that paper
so far the algorithm returns just an empty set and I can't seem to find the mistake in my code. Any suggestions would be appreciated. Cheers!

my graph

import networkx as nx
graph_2 = nx.Graph()
graph_2.add_edges_from([('1','2'), ('1','3'), ('1','4'),
                        ('2', '3'), ('2', '4'), ('3', '4'), ('4','5'),
                        ('4', '6'), ('5', '6')])

algorithm 1

R, R_best = [], []
S = list(graph_2.nodes)

def bnb(S):
    global R
    global R_best
    while len(S) != 0:
        if len(R) + len(S) <= len(R_best):
            return 0
        v = S.pop(0)
        R.append(v)
        S_mark = list(set(S).intersection(set(graph_2.adj[v])))
        if len(S_mark) != 0:
            bnb(S_mark)
        elif len(R) > len(R_best):
            R_best = R
        try:
            R.remove(v)
            S.remove(v)
        except:
            continue
    return R_best

print(bnb(S))   # prints []


问:
How to access website on machine behind firewall accessed via reverse SSH tunnel?
I’ve set up a permanent reverse SSH tunnel between a machine behind a firewall (fixed local IP  192.168.0.7) and a server (Jelastic without root access).

I can login to the server and then SSH from there to access the machine behind firewall:

ssh jelastic@jelastic-server.com -p 3001

followed by

ssh -p 5001 user@localhost

Additionally, I would like to access websites on the machine (served on https via NGINX). How can I achieve that?

My setup for the tunnel (tunnel.service run via systemctl):

```<code>[Unit]
Description=Persistent SSH reverse Tunnel (for encrypted traffic)
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=60
ExecStart=/usr/bin/ssh -qNn -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /etc/sshtunnel/id_rsa -R :5001:localhost:22 jelastic@jelastic-server.com -p 3001

[Install]
WantedBy=multi-user.target
</code>```

What I’ve tried so far:

setting up a second reverse SSH tunnel from port 443 instead of 22

ssh with –L option:
ssh -L 8090:192.168.0.7:443 user@192.168.0.7

Body:
I’ve set up a permanent reverse SSH tunnel between a machine behind a firewall (fixed local IP  192.168.0.7) and a server (Jelastic without root access).

I can login to the server and then SSH from there to access the machine behind firewall:

ssh jelastic@jelastic-server.com -p 3001

followed by

ssh -p 5001 user@localhost

Additionally, I would like to access websites on the machine (served on https via NGINX). How can I achieve that?

My setup for the tunnel (tunnel.service run via systemctl):

[Unit]
Description=Persistent SSH reverse Tunnel (for encrypted traffic)
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=60
ExecStart=/usr/bin/ssh -qNn -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /etc/sshtunnel/id_rsa -R :5001:localhost:22 jelastic@jelastic-server.com -p 3001

[Install]
WantedBy=multi-user.target

What I’ve tried so far:

setting up a second reverse SSH tunnel from port 443 instead of 22

ssh with –L option:
ssh -L 8090:192.168.0.7:443 user@192.168.0.7


问:
PYTHON How to extract a fragment from video by giving start frame and end frame or exact timestamps in float?
I'm trying to cut out a fragment from video with the given start and end frames indexes or theirs timestamps (preferably frame indexes). So far I've found this Q but it takes floats and convert them to integers hence the output video has inaccurate frames

this is a sample of what I've tried which gives me inaccurate output video

```<code>def extract_fragment(input_path, output_path):
    start_time = 3.453453
    end_time = 6.8768678

    ffmpeg_extract_subclip(
        filename=input_path,
        t1=start_time,
        t2=end_time,
        targetname=output_path,
    )
</code>```

And I also tried to use ffmpeg directly

with duration

```<code>    subprocess.call(
        [
            "ffmpeg",
            "-start_at_zero",
            "-copyts",
            "-ss",
            start_time,
            "-t",
            end_time - start_time,
            "-i",
            f"{path_to_video}",
            "-c",
            "copy",
            f"{output_video_path}",
        ]
    )
</code>```
```<code>    subprocess.call(
        [
            "ffmpeg",
            "-y",
            "-ss",
            str(start_time),
            "-i",
            path_to_video,
            "-t",
            str(end_time),
            "-map",
            "0",
            "-vcodec",
            "copy",
            "-acodec",
            "copy",
            output_video_path,
        ]
    )
</code>```

Body:
I'm trying to cut out a fragment from video with the given start and end frames indexes or theirs timestamps (preferably frame indexes). So far I've found this Q but it takes floats and convert them to integers hence the output video has inaccurate frames

this is a sample of what I've tried which gives me inaccurate output video

def extract_fragment(input_path, output_path):
    start_time = 3.453453
    end_time = 6.8768678

    ffmpeg_extract_subclip(
        filename=input_path,
        t1=start_time,
        t2=end_time,
        targetname=output_path,
    )

And I also tried to use ffmpeg directly

with duration

    subprocess.call(
        [
            "ffmpeg",
            "-start_at_zero",
            "-copyts",
            "-ss",
            start_time,
            "-t",
            end_time - start_time,
            "-i",
            f"{path_to_video}",
            "-c",
            "copy",
            f"{output_video_path}",
        ]
    )

    subprocess.call(
        [
            "ffmpeg",
            "-y",
            "-ss",
            str(start_time),
            "-i",
            path_to_video,
            "-t",
            str(end_time),
            "-map",
            "0",
            "-vcodec",
            "copy",
            "-acodec",
            "copy",
            output_video_path,
        ]
    )


问:
EF Core timeout with using view
When I query view that contain SELECT statemant with join like this: left join (select top (1) with ties, it can take a lot of time and sometimes bring timeout exception on container. Query can processed more then 30 seconds on ef core, while same query direct executed on sql take only few seconds.
Please help resolve this problem.

View configured like this:

modelBuilder.Entity<EntityName>()
            .ToView("VW_NAME")
            .HasKey(e => e.Id);
```
<p>When I remove <code>left join (select top (1) with ties</code>, it executing fast on EF Core.</p>
<p>View look like this (this is my real view with changed fields names):</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    Field1 = p.[Field1],
    Field2 = p.[Field2],
    Field3 = p.[Field3],
    Field4 = ISNULL(vf.FieldA, ISNULL(ad.FieldB, ISNULL(p.FieldC, FieldD)))
FROM
    dbo.Table p WITH (NOLOCK)
    LEFT JOIN dbo.[TableVF] vf WITH (NOLOCK)
        ON vf.Id = p.Id
    LEFT JOIN (
        SELECT TOP (1) WITH TIES  Id, FieldB
        FROM dbo.[TableAD] WITH(NOLOCK)
        ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY modified DESC)
    ) ad
        ON p.Id = ad.Id
</code>```

From C# this called like:

var data = await _db.ViewsDatas.FirstOrDefaultAsync(p => p.Id== request.Id);
```
<p>or in query like this:</p>
<pre class="lang-cs prettyprint-override"><code>var data = from vacancy in _context.SomeTable1.Include(v => v.Skill)
    join offer in _context.SomeTable2.Include(o => o.Employee)
        on vacancy.Id equals offer.Id
    join viewData in _context.ViewsData
        on offer.Id equals viewData.Id  //problem view
    select new { Vacancy = vacancy, Offer = offer, ViewsData = viewData, Ext = ext };
</code>```

Title: EF Core timeout with using view

Body:
When I query view that contain SELECT statemant with join like this: left join (select top (1) with ties, it can take a lot of time and sometimes bring timeout exception on container. Query can processed more then 30 seconds on ef core, while same query direct executed on sql take only few seconds.
Please help resolve this problem.

View configured like this:

modelBuilder.Entity<EntityName>()
            .ToView("VW_NAME")
            .HasKey(e => e.Id);

When I remove left join (select top (1) with ties, it executing fast on EF Core.

View look like this (this is my real view with changed fields names):

SELECT
    Field1 = p.[Field1],
    Field2 = p.[Field2],
    Field3 = p.[Field3],
    Field4 = ISNULL(vf.FieldA, ISNULL(ad.FieldB, ISNULL(p.FieldC, FieldD)))
FROM
    dbo.Table p WITH (NOLOCK)
    LEFT JOIN dbo.[TableVF] vf WITH (NOLOCK)
        ON vf.Id = p.Id
    LEFT JOIN (
        SELECT TOP (1) WITH TIES  Id, FieldB
        FROM dbo.[TableAD] WITH(NOLOCK)
        ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY modified DESC)
    ) ad
        ON p.Id = ad.Id

From C# this called like:

var data = await _db.ViewsDatas.FirstOrDefaultAsync(p => p.Id== request.Id);

or in query like this:

var data = from vacancy in _context.SomeTable1.Include(v => v.Skill)
    join offer in _context.SomeTable2.Include(o => o.Employee)
        on vacancy.Id equals offer.Id
    join viewData in _context.ViewsData
        on offer.Id equals viewData.Id  //problem view
    select new { Vacancy = vacancy, Offer = offer, ViewsData = viewData, Ext = ext };


问:
Duplicate users created on stripe
I wrote a code on user registeration , when signup stripe created more than one account with the same email but stripe API hits only one time from my side

I debuged the issue but there is nothing wrong in my code a it only happened with one user or 2 users only

Title: Duplicate users created on stripe


问:
Access CloudWatch Evidently Cross-Account?
I have a cloudwatch evidently project in one account and have a lambda in another account that wants to call EvaluateFeature on the cross-account Evidently project. Is this possible?

I've been using this client https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/evidently/EvidentlyClient.html

and even though I give it the project arn of the target account's project (in the project parameter of EvaluateFeatureRequest), it seems to re-route the EvaluateFeature request into the account the lambda resides in. Not sure if anyone has done something similar before.

I have a role in the Evidently account that can be assumed by Lambda service principal. With the stsAssumeRole permission also part of the Lambda's role policy. I just can't get EvaluateFeature to direct itself to the correct Arn/project.

Thanks.


问:
Multi-threading(Maybe Threads not running at my will.)
I want to perform a single-task(finding sum of 1st 100 positive integers) using multiple threads in java. That's why I'm using a single run() method. I've seen multiple sites which shows single-tasking using multithreading by using only single run method(they put the task in same run() method), but I found that it will only only do same task multiple times everytime a new thread is started. That is why I'm using a static variable count.
The task is divided into 3 sub-tasks-

sum 1 to 50(will be performed by thread1 object)

sum 51 to 75(will be performed by thread2 object)

sum 76 to 100(will be performed by thread1 object)
So this is the code which I wrote.

```<code>//In this single tasking will be done using multiple thread
public class SingleTasking extends Thread {
    static int count=0;
    static int sum=0;                                  //global variable to store total sum
    //private static long startTime = System.currentTimeMillis();
    public void run(){
        if(count==0) {
        //System.out.println(getName());
        sum+=sum1to50();
        count++;
        //currentThread().stop();
    }
    else if(count==1) {
        //System.out.println(getName());
        sum+=sum51to75();
        count++;
        //currentThread().stop();
    }
    else {
        //System.out.println(Thread.currentThread().getName());
        sum+=sum76to100();
        System.out.println("Sum of 1st 100 integers:"+sum);
        count++;
    }
    }
    int sum1to50() {               //1st part of the task
        int sum=0;                      //local variable to store sum 1 to 50
    for(int i=1;i<=50;i++)
        sum+=i;
    return sum;
    }
    int sum51to75() {              //2nd part of the task
    int sum=0;          //local variable to store sum 51 to 75
    for(int i=51;i<=75;i++)
        sum+=i;
    return sum;
    }
    int sum76to100() {             //3rd part of the task
    int sum=0;          //local variable to store sum 76 to 100
    for(int i=76;i<=100;i++)
        sum+=i;
    return sum;
    }
    public static void main(String args[]){
        System.out.println("Task is to find sum of first 100 integers.");
        System.out.println("1st thread will find sum of 1-50.");
        System.out.println("2nd thread will find sum of 51-75.");
        System.out.println("3rd thread will find sum of 76-100.");
        SingleTasking thread1=new SingleTasking();
        SingleTasking thread2=new SingleTasking();
        SingleTasking thread3=new SingleTasking();
        //thread1.setPriority(9);
        //thread2.setPriority(5);
        //thread3.setPriority(1);
        thread1.start();
        //thread1.stop();
        thread2.start();
        //thread2.stop();
        thread3.start();
        //System.out.println("Sum of 1st 100 integers:"+sum);
        //You can't print sum here as no priority is set to threads
        //and therefore it can print any value of static variable sum
        //like 0,sum1to50, sum1to75, sum 76to100 depending on
        //default main thread execution order.
        //Below are the statements to calculate sum
        //long endTime = System.currentTimeMillis();
        //System.out.println("It took " + (endTime - startTime) + " milliseconds");
    }
}
</code>```

although the output is what I needed most of the times, but sometimes it differs too.

I tried many things(commented in the code) like giving priority to threads, sleeping threads, stopping them but nothing works.

Can you explain me why it not working properly?
It would be helpful if you  give me a better solution.
I do not want to threads run in a particular order but what I want is a single thread will perform a single sub-task(i.e. call any of the sum1to50(), sum51to75(),sum76to100() methods).

Body:
I want to perform a single-task(finding sum of 1st 100 positive integers) using multiple threads in java. That's why I'm using a single run() method. I've seen multiple sites which shows single-tasking using multithreading by using only single run method(they put the task in same run() method), but I found that it will only only do same task multiple times everytime a new thread is started. That is why I'm using a static variable count.
The task is divided into 3 sub-tasks-

sum 1 to 50(will be performed by thread1 object)

sum 51 to 75(will be performed by thread2 object)

sum 76 to 100(will be performed by thread1 object)
So this is the code which I wrote.

//In this single tasking will be done using multiple thread
public class SingleTasking extends Thread {
    static int count=0;
    static int sum=0;                                  //global variable to store total sum
    //private static long startTime = System.currentTimeMillis();
    public void run(){
        if(count==0) {
        //System.out.println(getName());
        sum+=sum1to50();
        count++;
        //currentThread().stop();
    }
    else if(count==1) {
        //System.out.println(getName());
        sum+=sum51to75();
        count++;
        //currentThread().stop();
    }
    else {
        //System.out.println(Thread.currentThread().getName());
        sum+=sum76to100();
        System.out.println("Sum of 1st 100 integers:"+sum);
        count++;
    }
    }
    int sum1to50() {               //1st part of the task
        int sum=0;                      //local variable to store sum 1 to 50
    for(int i=1;i<=50;i++)
        sum+=i;
    return sum;
    }
    int sum51to75() {              //2nd part of the task
    int sum=0;          //local variable to store sum 51 to 75
    for(int i=51;i<=75;i++)
        sum+=i;
    return sum;
    }
    int sum76to100() {             //3rd part of the task
    int sum=0;          //local variable to store sum 76 to 100
    for(int i=76;i<=100;i++)
        sum+=i;
    return sum;
    }
    public static void main(String args[]){
        System.out.println("Task is to find sum of first 100 integers.");
        System.out.println("1st thread will find sum of 1-50.");
        System.out.println("2nd thread will find sum of 51-75.");
        System.out.println("3rd thread will find sum of 76-100.");
        SingleTasking thread1=new SingleTasking();
        SingleTasking thread2=new SingleTasking();
        SingleTasking thread3=new SingleTasking();
        //thread1.setPriority(9);
        //thread2.setPriority(5);
        //thread3.setPriority(1);
        thread1.start();
        //thread1.stop();
        thread2.start();
        //thread2.stop();
        thread3.start();
        //System.out.println("Sum of 1st 100 integers:"+sum);
        //You can't print sum here as no priority is set to threads
        //and therefore it can print any value of static variable sum
        //like 0,sum1to50, sum1to75, sum 76to100 depending on
        //default main thread execution order.
        //Below are the statements to calculate sum
        //long endTime = System.currentTimeMillis();
        //System.out.println("It took " + (endTime - startTime) + " milliseconds");
    }
}

although the output is what I needed most of the times, but sometimes it differs too.

I tried many things(commented in the code) like giving priority to threads, sleeping threads, stopping them but nothing works.

Can you explain me why it not working properly?
It would be helpful if you  give me a better solution.
I do not want to threads run in a particular order but what I want is a single thread will perform a single sub-task(i.e. call any of the sum1to50(), sum51to75(),sum76to100() methods).


问:
I am writing a chat app in android studio and Firebase as the DBMS, and I'm including notifications, however I'm receiving none at all
I have included the NotificationCompat builder, the FCM service and declared it in my AndroidManifest.xml file, but I'm getting nothing. The app works fine otherwise but I'm receiving no notifications at all. I'm not sure what exactly is wrong

This is my FirebaseMessaging Class.

```<code>public class FirebaseMessaging extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

    SharedPreferences preferences = getSharedPreferences("SP_USER", MODE_PRIVATE);
    String savedCurrentUser = preferences.getString("Current_USERID", "None");

    String sent = remoteMessage.getData().get("sent");
    String user = remoteMessage.getData().get("user");
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if(firebaseUser != null && sent.equals(firebaseUser.getUid())){
        if (!savedCurrentUser.equals(user)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                sendOAndAboveNotification(remoteMessage);

            }
            else {
                sendNormalNotification(remoteMessage);
            }
        }
    }
}

    private void sendOAndAboveNotification(RemoteMessage remoteMessage) {
        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        OreoAndAboveNotification oreoAndAboveNotification = new OreoAndAboveNotification(this);
        Notification.Builder builder = oreoAndAboveNotification.getONotifications(title, body, pendingIntent,defSoundUri, icon);

        int j = 0;
        if (i > 0){
            j=1;
        }
        oreoAndAboveNotification.getNotificationManager().notify(j, builder.build());

    }

    private void sendNormalNotification(RemoteMessage remoteMessage) {

        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(Integer.parseInt(icon))
                .setContentText(body)
                .setContentTitle(title)
                .setAutoCancel(true)
                .setSound(defSoundUri)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int j = 0;
        if (i > 0){
            j=1;
        }
        notificationManager.notify(j, builder.build());
    }
}
</code>```

This is my  FirebaseService class

```<code>public class FirebaseMessaging extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

    SharedPreferences preferences = getSharedPreferences("SP_USER", MODE_PRIVATE);
    String savedCurrentUser = preferences.getString("Current_USERID", "None");

    String sent = remoteMessage.getData().get("sent");
    String user = remoteMessage.getData().get("user");
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if(firebaseUser != null && sent.equals(firebaseUser.getUid())){
        if (!savedCurrentUser.equals(user)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                sendOAndAboveNotification(remoteMessage);

            }
            else {
                sendNormalNotification(remoteMessage);
            }
        }
    }
}

    private void sendOAndAboveNotification(RemoteMessage remoteMessage) {
        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        OreoAndAboveNotification oreoAndAboveNotification = new OreoAndAboveNotification(this);
        Notification.Builder builder = oreoAndAboveNotification.getONotifications(title, body, pendingIntent,defSoundUri, icon);

        int j = 0;
        if (i > 0){
            j=1;
        }
        oreoAndAboveNotification.getNotificationManager().notify(j, builder.build());

    }

    private void sendNormalNotification(RemoteMessage remoteMessage) {

        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(Integer.parseInt(icon))
                .setContentText(body)
                .setContentTitle(title)
                .setAutoCancel(true)
                .setSound(defSoundUri)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int j = 0;
        if (i > 0){
            j=1;
        }
        notificationManager.notify(j, builder.build());
    }
}
</code>```
```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.vibe">
    <!-- Internet Connection -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logocrop"
        android:label="@string/app_name"
        android:roundIcon="@drawable/logocrop"
        android:supportsRtl="true"
        android:theme="@style/Theme.Vibe">
        <activity
            android:name=".ChatActivity"
            android:theme="@style/AppThemeNo"
            android:exported="false" />
        <activity
            android:name=".LoginActivity"
            android:exported="true" />
        <activity
            android:name=".DashboardActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".RegisterActivity"
            android:exported="true" />
        <activity
            android:name=".MainActivity"
            android:exported="true" />

        <service android:name=".notifications.FirebaseService"
            android:enabled="true"
            android:exported="true">

            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_SERVICE"/>
            </intent-filter>

        </service>
        <service android:name=".notifications.FirebaseMessaging"
            android:enabled="true"
            android:exported="true">
            <intent-filter>

                <action android:name="com.google.firebase.MESSAGING_EVENT"/>

            </intent-filter>
        </service>
    </application>

</manifest>
</code>```

I was expecting to receive some notification, but I get nothing, and there's no error being flagged either. Any help would be appreciated.

Body:
I have included the NotificationCompat builder, the FCM service and declared it in my AndroidManifest.xml file, but I'm getting nothing. The app works fine otherwise but I'm receiving no notifications at all. I'm not sure what exactly is wrong

This is my FirebaseMessaging Class.

public class FirebaseMessaging extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

    SharedPreferences preferences = getSharedPreferences("SP_USER", MODE_PRIVATE);
    String savedCurrentUser = preferences.getString("Current_USERID", "None");

    String sent = remoteMessage.getData().get("sent");
    String user = remoteMessage.getData().get("user");
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if(firebaseUser != null && sent.equals(firebaseUser.getUid())){
        if (!savedCurrentUser.equals(user)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                sendOAndAboveNotification(remoteMessage);

            }
            else {
                sendNormalNotification(remoteMessage);
            }
        }
    }
}

    private void sendOAndAboveNotification(RemoteMessage remoteMessage) {
        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        OreoAndAboveNotification oreoAndAboveNotification = new OreoAndAboveNotification(this);
        Notification.Builder builder = oreoAndAboveNotification.getONotifications(title, body, pendingIntent,defSoundUri, icon);

        int j = 0;
        if (i > 0){
            j=1;
        }
        oreoAndAboveNotification.getNotificationManager().notify(j, builder.build());

    }

    private void sendNormalNotification(RemoteMessage remoteMessage) {

        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(Integer.parseInt(icon))
                .setContentText(body)
                .setContentTitle(title)
                .setAutoCancel(true)
                .setSound(defSoundUri)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int j = 0;
        if (i > 0){
            j=1;
        }
        notificationManager.notify(j, builder.build());
    }
}

This is my  FirebaseService class

public class FirebaseMessaging extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

    SharedPreferences preferences = getSharedPreferences("SP_USER", MODE_PRIVATE);
    String savedCurrentUser = preferences.getString("Current_USERID", "None");

    String sent = remoteMessage.getData().get("sent");
    String user = remoteMessage.getData().get("user");
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if(firebaseUser != null && sent.equals(firebaseUser.getUid())){
        if (!savedCurrentUser.equals(user)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                sendOAndAboveNotification(remoteMessage);

            }
            else {
                sendNormalNotification(remoteMessage);
            }
        }
    }
}

    private void sendOAndAboveNotification(RemoteMessage remoteMessage) {
        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        OreoAndAboveNotification oreoAndAboveNotification = new OreoAndAboveNotification(this);
        Notification.Builder builder = oreoAndAboveNotification.getONotifications(title, body, pendingIntent,defSoundUri, icon);

        int j = 0;
        if (i > 0){
            j=1;
        }
        oreoAndAboveNotification.getNotificationManager().notify(j, builder.build());

    }

    private void sendNormalNotification(RemoteMessage remoteMessage) {

        String user = remoteMessage.getData().get("user");
        String icon = remoteMessage.getData().get("icon");
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");

        RemoteMessage.Notification notification = remoteMessage.getNotification();
        int i = Integer.parseInt(user.replaceAll("[\\D]", ""));
        Intent intent = new Intent(this, ChatActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("", user);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, i, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(Integer.parseInt(icon))
                .setContentText(body)
                .setContentTitle(title)
                .setAutoCancel(true)
                .setSound(defSoundUri)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int j = 0;
        if (i > 0){
            j=1;
        }
        notificationManager.notify(j, builder.build());
    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.vibe">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logocrop"
        android:label="@string/app_name"
        android:roundIcon="@drawable/logocrop"
        android:supportsRtl="true"
        android:theme="@style/Theme.Vibe">
        <activity
            android:name=".ChatActivity"
            android:theme="@style/AppThemeNo"
            android:exported="false" />
        <activity
            android:name=".LoginActivity"
            android:exported="true" />
        <activity
            android:name=".DashboardActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".RegisterActivity"
            android:exported="true" />
        <activity
            android:name=".MainActivity"
            android:exported="true" />

        <service android:name=".notifications.FirebaseService"
            android:enabled="true"
            android:exported="true">

            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_SERVICE"/>
            </intent-filter>

        </service>
        <service android:name=".notifications.FirebaseMessaging"
            android:enabled="true"
            android:exported="true">
            <intent-filter>

                <action android:name="com.google.firebase.MESSAGING_EVENT"/>

            </intent-filter>
        </service>
    </application>

</manifest>

I was expecting to receive some notification, but I get nothing, and there's no error being flagged either. Any help would be appreciated.


问:
Flutter web - webview ERR_BLOCKED_BY_RESPONSE
Im trying to create an discord auth on my flutter website using oauth2, webview_flutter & webview_flutter_web.
After click connect button it should redirect user to discord login site, but then this error pops out

Error pops out also on other browsers like chrome or edge.

I was trying to run it in different project, but on android this time and it works fine. So the error must be related to the web version.
I read somewhere that it might be related to iFrame, but it wasn't really explained there.
Any ideas what this error might be related to or how to fix it?

this also happens with other websites.


问:
react - using css files inside global design system library gives error
I have global design system library which allows to use buttons, logo and things like.

I have imported this library to my react application and tried to use logo component.

logo component gives an error when i tried to open page :

```<code>SyntaxError: Unexpected token ':'
</code>```

If i comment this requeire code inside from the components dist folder it works but i don't have styles.

I know that Next.js have solution like next-global-css but on React do we have any library - loader or configuration that allows using libraries css files automatically?

I am excepting loader or solution for see styles.

Body:
I have global design system library which allows to use buttons, logo and things like.

I have imported this library to my react application and tried to use logo component.

logo component gives an error when i tried to open page :

SyntaxError: Unexpected token ':'

If i comment this requeire code inside from the components dist folder it works but i don't have styles.

I know that Next.js have solution like next-global-css but on React do we have any library - loader or configuration that allows using libraries css files automatically?

I am excepting loader or solution for see styles.


问:
Custom webgl engine with Cannon.js , How to resolve jumping, blocking and walk

I look at stackoverflow other people similar problems a they have very similar solution but all examples are done in three.js (Not in my case).

Jump is relative good working at the moment, i powered gravity (double it).
Stairs also works fine even without jumping it is ok for me.
I put one big cube to make blocking volume but i dont now how to make player to simple stops because i use WASD for body set position. My player in big cube just have big jump , i wanna prevent WASD body set position in moment of first touch.

Some solutions [not yet tested]:

1] To make movement only with force [not set position] => [possible not nature movements]

2] Make collide detection then prevent set position => [possible angle problems]

3] Some other solution....

All related code is visible in example.
Matrix-engine example for FPS:

import App from '../program/manifest';
import * as CANNON from 'cannon';
import {ENUMERATORS, ORBIT_FROM_ARRAY, OSCILLATOR, randomFloatFromTo} from '../lib/utility';

export var runThis = (world) => {

  // Camera
  canvas.style.cursor = 'none';
  App.camera.FirstPersonController = true;
  matrixEngine.Events.camera.fly = false;
  App.camera.speedAmp = 0.01;
  matrixEngine.Events.camera.yPos = 2;

  // Audio effects
  App.sounds.createAudio('shoot', 'res/music/single-gunshot.mp3', 5);

  // Prevent right click context menu
  window.addEventListener("contextmenu", (e) => {
    e.preventDefault();
  });

  // Override mouse up
  App.events.CALCULATE_TOUCH_UP_OR_MOUSE_UP = () => {
    App.scene.FPSTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
    App.scene.FPSTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
    App.scene.FPSTarget.geometry.setScale(0.1);
    App.scene.xrayTarget.visible = false;
  };

  // Override right mouse down
  matrixEngine.Events.SYS.MOUSE.ON_RIGHT_BTN_PRESSED = (e) => {
    App.scene.FPSTarget.geometry.setScale(0.6);
    App.scene.FPSTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
    App.scene.FPSTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
    App.scene.xrayTarget.visible = true;
  };

  // Override mouse down
  App.events.CALCULATE_TOUCH_DOWN_OR_MOUSE_DOWN = (ev, mouse) => {
    // `checkingProcedure` gets secound optimal argument
    // for custom ray origin target.
    if(mouse.BUTTON_PRESSED == 'RIGHT') {
      // Zoom
    } else {
      // This call represent `SHOOT` Action.
      // And it is center of screen
      matrixEngine.raycaster.checkingProcedure(ev, {
        clientX: ev.target.width / 2,
        clientY: ev.target.height / 2
      });
      App.sounds.play('shoot');
    }
  };

  window.addEventListener('ray.hit.event', (ev) => {
    console.log("You shoot the object! Nice!", ev);
    // Physics force apply also change ambienty light.
    if(ev.detail.hitObject.physics.enabled == true) {
      // Shoot the object - apply force
      ev.detail.hitObject.physics.currentBody.force.set(0, 0, 1000);
      // Apply random diff color
      if(ev.detail.hitObject.LightsData) ev.detail.hitObject.LightsData.ambientLight.set(
        randomFloatFromTo(0, 2), randomFloatFromTo(0, 2), randomFloatFromTo(0, 2));
    }
  });

  // Load obj seq animation
  const createObjSequence = (objName) => {

    function onLoadObj(meshes) {

      for(let key in meshes) {
        matrixEngine.objLoader.initMeshBuffers(world.GL.gl, meshes[key]);
      }

      var textuteImageSamplers2 = {
        source: [
          "res/bvh-skeletal-base/swat-guy/textures/Ch15_1001_Diffuse.png" // ,
          // "res/bvh-skeletal-base/swat-guy/textures/Ch15_1001_Diffuse.png"
        ],
        mix_operation: "multiply", // ENUM : multiply , divide
      };

      var animArg = {
        id: objName,
        meshList: meshes,
        currentAni: 0,
        animations: {
          active: 'walk',
          walk: {
            from: 0,
            to: 20,
            speed: 3
          }
        }
      };

      world.Add("obj", 1, objName, textuteImageSamplers2, meshes[objName], animArg);

      // Fix object orientation - this can be fixed also in blender.
      matrixEngine.Events.camera.yaw = 0;

      // Add collision cube to the local player.
      world.Add("cube", 0.5, "playerCollisonBox");
      var collisionBox = new CANNON.Body({
        mass: 500,
        linearDamping: 0.001,
        position: new CANNON.Vec3(0, 0, 0),
        shape: new CANNON.Box(new CANNON.Vec3(3, 3, 3))// new CANNON.Sphere(2)
      });
      physics.world.addBody(collisionBox);
      App.scene.playerCollisonBox.physics.currentBody = collisionBox;
      App.scene.playerCollisonBox.physics.enabled = true;
      App.scene.playerCollisonBox.physics.currentBody.fixedRotation = true;
      App.scene.playerCollisonBox.geometry.setScale(0.02);

      App.scene.playerCollisonBox.glBlend.blendEnabled = true;
      App.scene.playerCollisonBox.glBlend.blendParamSrc = ENUMERATORS.glBlend.param[5];
      App.scene.playerCollisonBox.glBlend.blendParamDest = ENUMERATORS.glBlend.param[6];

      // test
      addEventListener('hit.keyDown', (e) => {
        // console.log('Bring to the top level', e.detail.keyCode);
        // dont mess in events
        if(e.detail.keyCode == 32) {
          setTimeout(() => {
            App.scene.playerCollisonBox.physics.currentBody.force.set(0, 0, 111)
          }, 250)
        } else if(e.detail.keyCode == 87) {
          // Good place for blocking volume
          // App.scene.playerCollisonBox.physics.currentBody.force.set(0,10,0)
          setTimeout(() => {
            // App.scene.playerCollisonBox.physics.currentBody.force.set(0,100,0)
          }, 100);
        }
      });

      var playerUpdater = {
        UPDATE: () => {
          App.scene[objName].rotation.rotateY(
            matrixEngine.Events.camera.yaw + 180)

          var detPitch;
          var limit = 2;
          if(matrixEngine.Events.camera.pitch < limit &&
            matrixEngine.Events.camera.pitch > -limit) {
            detPitch = matrixEngine.Events.camera.pitch * 2;
          } else if(matrixEngine.Events.camera.pitch > limit) {
            detPitch = limit * 2;
          } else if(matrixEngine.Events.camera.pitch < -(limit + 2)) {
            detPitch = -(limit + 2) * 2;
          }

          if(matrixEngine.Events.camera.virtualJumpActive == true) {
            // invert logic
            // Scene object set
            App.scene[objName].rotation.rotateX(-detPitch);
            var detPitchPos = matrixEngine.Events.camera.pitch;
            if(detPitchPos > 4) detPitchPos = 4;

            App.scene.playerCollisonBox.physics.currentBody.mass = 10;
            App.scene.playerCollisonBox.physics.currentBody.force.set(0, 0, 700);

            App.scene[objName].position.setPosition(
              App.scene.playerCollisonBox.physics.currentBody.position.x,
              App.scene.playerCollisonBox.physics.currentBody.position.z,
              App.scene.playerCollisonBox.physics.currentBody.position.y
            )
            // Cannonjs object set / Switched  Z - Y
            matrixEngine.Events.camera.xPos = App.scene.playerCollisonBox.physics.currentBody.position.x;
            matrixEngine.Events.camera.zPos = App.scene.playerCollisonBox.physics.currentBody.position.y;
            matrixEngine.Events.camera.yPos = App.scene.playerCollisonBox.physics.currentBody.position.z;

            App.scene.playerCollisonBox.
              physics.currentBody.angularVelocity.set(0, 0, 0);

            setTimeout(() => {
              matrixEngine.Events.camera.virtualJumpActive = false;
              App.scene.playerCollisonBox.physics.currentBody.mass = 550;
            }, 1350);

          } else {

            // Make more stable situation
            App.scene.playerCollisonBox.physics.currentBody.mass = 500;
            App.scene.playerCollisonBox.physics.currentBody.quaternion.setFromEuler(0,0,0)

            // Tamo tu iznad duge nebo zri...
            // Cannonjs object set
            // Switched  Z - Y
            matrixEngine.Events.camera.yPos = App.scene.playerCollisonBox.physics.currentBody.position.z;

            // Scene object set
            App.scene[objName].rotation.rotateX(-detPitch);
            var detPitchPos = matrixEngine.Events.camera.pitch;
            if(detPitchPos > 4) detPitchPos = 4;

            App.scene[objName].position.setPosition(
              matrixEngine.Events.camera.xPos,
              matrixEngine.Events.camera.yPos, // - 0.3 + detPitchPos / 50,
              // App.scene.playerCollisonBox.physics.currentBody.position.y,
              matrixEngine.Events.camera.zPos,
            )

            // Cannonjs object set
            // Switched  Z - Y
            App.scene.playerCollisonBox.
              physics.currentBody.position.set(
                matrixEngine.Events.camera.xPos,
                matrixEngine.Events.camera.zPos,
                matrixEngine.Events.camera.yPos)
            // App.scene.playerCollisonBox.physics.currentBody.position.y)
          }
        }
      };
      App.updateBeforeDraw.push(playerUpdater);

      // Player Energy status
      App.scene.player.energy = {};

      for(let key in App.scene.player.meshList) {
        App.scene.player.meshList[key].setScale(1.85);
      }

      // Target scene object
      var texTarget = {
        source: [
          "res/bvh-skeletal-base/swat-guy/target.png",
          "res/bvh-skeletal-base/swat-guy/target.png"
        ],
        mix_operation: "multiply",
      };
      world.Add("squareTex", 0.25, 'FPSTarget', texTarget);
      App.scene.FPSTarget.position.setPosition(0, 0, -4);
      App.scene.FPSTarget.glBlend.blendEnabled = true;
      App.scene.FPSTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
      App.scene.FPSTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
      App.scene.FPSTarget.isHUD = true;
      App.scene.FPSTarget.geometry.setScale(0.1);

      // Energy active bar
      // Custom generic textures. Micro Drawing.
      // Example for arg shema square for now only.
      var options = {
        squareShema: [8, 8],
        pixels: new Uint8Array(8 * 8 * 4)
      };
      // options.pixels.fill(0);
      App.scene.player.energy.value = 8;
      App.scene.player.updateEnergy = function(v) {
        this.energy.value = v;
        var t = App.scene.energyBar.preparePixelsTex(App.scene.energyBar.specialValue);
        App.scene.energyBar.textures.pop()
        App.scene.energyBar.textures.push(App.scene.energyBar.createPixelsTex(t));
      };

      function preparePixelsTex(options) {
        var I = 0, R = 0, G = 0, B = 0, localCounter = 0;
        for(var funny = 0;funny < 8 * 8 * 4;funny += 4) {
          if(localCounter > 7) {
            localCounter = 0;
          }
          if(localCounter < App.scene.player.energy.value) {
            I = 128;
            if(App.scene.player.energy.value < 3) {
              R = 255;
              G = 0;
              B = 0;
              I = 0;
            } else if(App.scene.player.energy.value > 2 && App.scene.player.energy.value < 5) {
              R = 255;
              G = 255;
              B = 0;
            } else {
              R = 0;
              G = 255;
              B = 0;
            }
          } else {
            I = 0;
            R = 0;
            G = 0;
            B = 0;
          }
          options.pixels[funny] = R;
          options.pixels[funny + 1] = G;
          options.pixels[funny + 2] = B;
          options.pixels[funny + 3] = 0;
          localCounter++;
        }
        return options;
      }

      var tex2 = {
        source: [
          "res/images/hud/energy-bar.png",
          "res/images/hud/energy-bar.png"
        ],
        mix_operation: "multiply",
      };

      world.Add("squareTex", 1, 'energyBar', tex2);
      App.scene.energyBar.glBlend.blendEnabled = true;
      App.scene.energyBar.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
      App.scene.energyBar.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
      App.scene.energyBar.isHUD = true;
      // App.scene.energy.visible = false;
      App.scene.energyBar.position.setPosition(0, 1.1, -3);
      App.scene.energyBar.geometry.setScaleByX(1)
      App.scene.energyBar.geometry.setScaleByY(0.05)
      App.scene.energyBar.preparePixelsTex = preparePixelsTex;
      options = preparePixelsTex(options);
      // App.scene.energyBar.textures[0] = App.scene.energyBar.createPixelsTex(options);
      App.scene.energyBar.textures.push(App.scene.energyBar.createPixelsTex(options));
      App.scene.energyBar.specialValue = options;

    }

    matrixEngine.objLoader.downloadMeshes(
      matrixEngine.objLoader.makeObjSeqArg(
        {
          id: objName,
          // path: "res/bvh-skeletal-base/swat-guy/anims/swat-multi",
          path: "res/bvh-skeletal-base/swat-guy/FPShooter-hands/FPShooter-hands",
          from: 1,
          to: 20
        }),
      onLoadObj
    );

  };

  let promiseAllGenerated = [];

  const objGenerator = (n) => {
    for(var j = 0;j < n;j++) {
      promiseAllGenerated.push(new Promise((resolve) => {
        setTimeout(() => {
          world.Add("cubeLightTex", 1, "CUBE" + j, tex);
          var b2 = new CANNON.Body({
            mass: 1,
            linearDamping: 0.01,
            position: new CANNON.Vec3(1, -14.5, 15),
            shape: new CANNON.Box(new CANNON.Vec3(1, 1, 1))
          });
          physics.world.addBody(b2);
          App.scene['CUBE' + j].physics.currentBody = b2;
          App.scene['CUBE' + j].physics.enabled = true;
          resolve();
        }, 1000 * j);
      }));
    }
  }

  // objGenerator(15);

  createObjSequence('player');

  Promise.all(promiseAllGenerated).then((what) => {
    console.info(`Runtime wait for some generetion of scene objects,
                  then swap scene array index for target ->
                  must be manual setup for now!`, what);
    // swap(5, 19, matrixEngine.matrixWorld.world.contentList);
  });

  // Add ground for physics bodies.
  var tex = {
    source: ["res/images/complex_texture_1/diffuse.png"],
    mix_operation: "multiply",
  };
  // Load Physics world.
  // let gravityVector = [0, 0, -9.82];
  let gravityVector = [0, 0, -29.82];
  let physics = world.loadPhysics(gravityVector);

  // Add ground
  var groundBody = new CANNON.Body({
    mass: 0, // mass == 0 makes the body static
    position: new CANNON.Vec3(0, -15, -2)
  });
  var groundShape = new CANNON.Plane();
  groundBody.addShape(groundShape);
  physics.world.addBody(groundBody);
  // Matrix engine visual
  world.Add("squareTex", 1, "FLOOR_STATIC", tex);
  App.scene.FLOOR_STATIC.geometry.setScaleByX(20);
  App.scene.FLOOR_STATIC.geometry.setScaleByY(20);
  App.scene.FLOOR_STATIC.position.SetY(-2);
  App.scene.FLOOR_STATIC.position.SetZ(-15);
  App.scene.FLOOR_STATIC.rotation.rotx = 90;

  // Target x-ray
  // See through the objects.
  // In webGL context it is object how was drawn before others.
  var texTarget = {
    source: [
      "res/bvh-skeletal-base/swat-guy/target-night.png"
    ],
    mix_operation: "multiply",
  };
  world.Add("squareTex", 0.18, 'xrayTarget', texTarget);
  App.scene.xrayTarget.glBlend.blendEnabled = true;
  App.scene.xrayTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.xrayTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.xrayTarget.isHUD = true;
  App.scene.xrayTarget.visible = false;
  App.scene.xrayTarget.position.setPosition(-0.3, 0.27, -4);

  // Energy
  var tex1 = {
    source: [
      "res/images/hud/energy.png"
    ],
    mix_operation: "multiply",
  };
  world.Add("squareTex", 0.5, 'energy', tex1);
  App.scene.energy.glBlend.blendEnabled = true;
  App.scene.energy.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.energy.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.energy.isHUD = true;
  // App.scene.energy.visible = false;
  App.scene.energy.position.setPosition(-1, 1.15, -3);
  App.scene.energy.geometry.setScaleByX(0.35)
  App.scene.energy.geometry.setScaleByY(0.1)

  // good for fix rotation in future
  world.Add("cubeLightTex", 1, "FLOOR2", tex);
  var b2 = new CANNON.Body({
    mass: 0,
    linearDamping: 0.01,
    position: new CANNON.Vec3(1, -14.5, -1),
    shape: new CANNON.Box(new CANNON.Vec3(3, 1, 1))
  });
  physics.world.addBody(b2);
  App.scene['FLOOR2'].position.setPosition(1, -1, -14.5)
  App.scene['FLOOR2'].geometry.setScaleByX(3);

  App.scene['FLOOR2'].physics.currentBody = b2;
  App.scene['FLOOR2'].physics.enabled = true;

  world.Add("cubeLightTex", 2, "FLOOR3", tex);
  var b3 = new CANNON.Body({
    mass: 0,
    linearDamping: 0.01,
    position: new CANNON.Vec3(0, -19, 0),
    shape: new CANNON.Box(new CANNON.Vec3(3, 3, 3))
  });
  physics.world.addBody(b3);
  App.scene['FLOOR3'].position.setPosition(0, 0, -19)
  // App.scene['FLOOR3'].geometry.setScaleByX(3);

  App.scene['FLOOR3'].physics.currentBody = b3;
  App.scene['FLOOR3'].physics.enabled = true;

  world.Add("cubeLightTex", 5, "WALL_BLOCK", tex);
  var b5 = new CANNON.Body({
    mass: 0,
    linearDamping: 0.01,
    position: new CANNON.Vec3(10, -19, 0),
    shape: new CANNON.Box(new CANNON.Vec3(5, 5, 5))
  });
  physics.world.addBody(b5);
  App.scene['WALL_BLOCK'].position.setPosition(10, 0, -19)
  // App.scene['WALL_BLOCK'].geometry.setScaleByX(3);
  App.scene['WALL_BLOCK'].physics.currentBody = b5;
  App.scene['WALL_BLOCK'].physics.enabled = true;

};

```

Any suggestion ?

Body:
I look at stackoverflow other people similar problems a they have very similar solution but all examples are done in three.js (Not in my case).

Jump is relative good working at the moment, i powered gravity (double it).
Stairs also works fine even without jumping it is ok for me.
I put one big cube to make blocking volume but i dont now how to make player to simple stops because i use WASD for body set position. My player in big cube just have big jump , i wanna prevent WASD body set position in moment of first touch.

Some solutions [not yet tested]:

1] To make movement only with force [not set position] => [possible not nature movements]

2] Make collide detection then prevent set position => [possible angle problems]

3] Some other solution....

All related code is visible in example.
Matrix-engine example for FPS:

import App from '../program/manifest';
import * as CANNON from 'cannon';
import {ENUMERATORS, ORBIT_FROM_ARRAY, OSCILLATOR, randomFloatFromTo} from '../lib/utility';

export var runThis = (world) => {

  // Camera
  canvas.style.cursor = 'none';
  App.camera.FirstPersonController = true;
  matrixEngine.Events.camera.fly = false;
  App.camera.speedAmp = 0.01;
  matrixEngine.Events.camera.yPos = 2;

  // Audio effects
  App.sounds.createAudio('shoot', 'res/music/single-gunshot.mp3', 5);

  // Prevent right click context menu
  window.addEventListener("contextmenu", (e) => {
    e.preventDefault();
  });

  // Override mouse up
  App.events.CALCULATE_TOUCH_UP_OR_MOUSE_UP = () => {
    App.scene.FPSTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
    App.scene.FPSTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
    App.scene.FPSTarget.geometry.setScale(0.1);
    App.scene.xrayTarget.visible = false;
  };

  // Override right mouse down
  matrixEngine.Events.SYS.MOUSE.ON_RIGHT_BTN_PRESSED = (e) => {
    App.scene.FPSTarget.geometry.setScale(0.6);
    App.scene.FPSTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
    App.scene.FPSTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
    App.scene.xrayTarget.visible = true;
  };

  // Override mouse down
  App.events.CALCULATE_TOUCH_DOWN_OR_MOUSE_DOWN = (ev, mouse) => {
    // `checkingProcedure` gets secound optimal argument
    // for custom ray origin target.
    if(mouse.BUTTON_PRESSED == 'RIGHT') {
      // Zoom
    } else {
      // This call represent `SHOOT` Action.
      // And it is center of screen
      matrixEngine.raycaster.checkingProcedure(ev, {
        clientX: ev.target.width / 2,
        clientY: ev.target.height / 2
      });
      App.sounds.play('shoot');
    }
  };

  window.addEventListener('ray.hit.event', (ev) => {
    console.log("You shoot the object! Nice!", ev);
    // Physics force apply also change ambienty light.
    if(ev.detail.hitObject.physics.enabled == true) {
      // Shoot the object - apply force
      ev.detail.hitObject.physics.currentBody.force.set(0, 0, 1000);
      // Apply random diff color
      if(ev.detail.hitObject.LightsData) ev.detail.hitObject.LightsData.ambientLight.set(
        randomFloatFromTo(0, 2), randomFloatFromTo(0, 2), randomFloatFromTo(0, 2));
    }
  });

  // Load obj seq animation
  const createObjSequence = (objName) => {

    function onLoadObj(meshes) {

      for(let key in meshes) {
        matrixEngine.objLoader.initMeshBuffers(world.GL.gl, meshes[key]);
      }

      var textuteImageSamplers2 = {
        source: [
          "res/bvh-skeletal-base/swat-guy/textures/Ch15_1001_Diffuse.png" // ,
          // "res/bvh-skeletal-base/swat-guy/textures/Ch15_1001_Diffuse.png"
        ],
        mix_operation: "multiply", // ENUM : multiply , divide
      };

      var animArg = {
        id: objName,
        meshList: meshes,
        currentAni: 0,
        animations: {
          active: 'walk',
          walk: {
            from: 0,
            to: 20,
            speed: 3
          }
        }
      };

      world.Add("obj", 1, objName, textuteImageSamplers2, meshes[objName], animArg);

      // Fix object orientation - this can be fixed also in blender.
      matrixEngine.Events.camera.yaw = 0;

      // Add collision cube to the local player.
      world.Add("cube", 0.5, "playerCollisonBox");
      var collisionBox = new CANNON.Body({
        mass: 500,
        linearDamping: 0.001,
        position: new CANNON.Vec3(0, 0, 0),
        shape: new CANNON.Box(new CANNON.Vec3(3, 3, 3))// new CANNON.Sphere(2)
      });
      physics.world.addBody(collisionBox);
      App.scene.playerCollisonBox.physics.currentBody = collisionBox;
      App.scene.playerCollisonBox.physics.enabled = true;
      App.scene.playerCollisonBox.physics.currentBody.fixedRotation = true;
      App.scene.playerCollisonBox.geometry.setScale(0.02);

      App.scene.playerCollisonBox.glBlend.blendEnabled = true;
      App.scene.playerCollisonBox.glBlend.blendParamSrc = ENUMERATORS.glBlend.param[5];
      App.scene.playerCollisonBox.glBlend.blendParamDest = ENUMERATORS.glBlend.param[6];

      // test
      addEventListener('hit.keyDown', (e) => {
        // console.log('Bring to the top level', e.detail.keyCode);
        // dont mess in events
        if(e.detail.keyCode == 32) {
          setTimeout(() => {
            App.scene.playerCollisonBox.physics.currentBody.force.set(0, 0, 111)
          }, 250)
        } else if(e.detail.keyCode == 87) {
          // Good place for blocking volume
          // App.scene.playerCollisonBox.physics.currentBody.force.set(0,10,0)
          setTimeout(() => {
            // App.scene.playerCollisonBox.physics.currentBody.force.set(0,100,0)
          }, 100);
        }
      });

      var playerUpdater = {
        UPDATE: () => {
          App.scene[objName].rotation.rotateY(
            matrixEngine.Events.camera.yaw + 180)

          var detPitch;
          var limit = 2;
          if(matrixEngine.Events.camera.pitch < limit &&
            matrixEngine.Events.camera.pitch > -limit) {
            detPitch = matrixEngine.Events.camera.pitch * 2;
          } else if(matrixEngine.Events.camera.pitch > limit) {
            detPitch = limit * 2;
          } else if(matrixEngine.Events.camera.pitch < -(limit + 2)) {
            detPitch = -(limit + 2) * 2;
          }

          if(matrixEngine.Events.camera.virtualJumpActive == true) {
            // invert logic
            // Scene object set
            App.scene[objName].rotation.rotateX(-detPitch);
            var detPitchPos = matrixEngine.Events.camera.pitch;
            if(detPitchPos > 4) detPitchPos = 4;

            App.scene.playerCollisonBox.physics.currentBody.mass = 10;
            App.scene.playerCollisonBox.physics.currentBody.force.set(0, 0, 700);

            App.scene[objName].position.setPosition(
              App.scene.playerCollisonBox.physics.currentBody.position.x,
              App.scene.playerCollisonBox.physics.currentBody.position.z,
              App.scene.playerCollisonBox.physics.currentBody.position.y
            )
            // Cannonjs object set / Switched  Z - Y
            matrixEngine.Events.camera.xPos = App.scene.playerCollisonBox.physics.currentBody.position.x;
            matrixEngine.Events.camera.zPos = App.scene.playerCollisonBox.physics.currentBody.position.y;
            matrixEngine.Events.camera.yPos = App.scene.playerCollisonBox.physics.currentBody.position.z;

            App.scene.playerCollisonBox.
              physics.currentBody.angularVelocity.set(0, 0, 0);

            setTimeout(() => {
              matrixEngine.Events.camera.virtualJumpActive = false;
              App.scene.playerCollisonBox.physics.currentBody.mass = 550;
            }, 1350);

          } else {

            // Make more stable situation
            App.scene.playerCollisonBox.physics.currentBody.mass = 500;
            App.scene.playerCollisonBox.physics.currentBody.quaternion.setFromEuler(0,0,0)

            // Tamo tu iznad duge nebo zri...
            // Cannonjs object set
            // Switched  Z - Y
            matrixEngine.Events.camera.yPos = App.scene.playerCollisonBox.physics.currentBody.position.z;

            // Scene object set
            App.scene[objName].rotation.rotateX(-detPitch);
            var detPitchPos = matrixEngine.Events.camera.pitch;
            if(detPitchPos > 4) detPitchPos = 4;

            App.scene[objName].position.setPosition(
              matrixEngine.Events.camera.xPos,
              matrixEngine.Events.camera.yPos, // - 0.3 + detPitchPos / 50,
              // App.scene.playerCollisonBox.physics.currentBody.position.y,
              matrixEngine.Events.camera.zPos,
            )

            // Cannonjs object set
            // Switched  Z - Y
            App.scene.playerCollisonBox.
              physics.currentBody.position.set(
                matrixEngine.Events.camera.xPos,
                matrixEngine.Events.camera.zPos,
                matrixEngine.Events.camera.yPos)
            // App.scene.playerCollisonBox.physics.currentBody.position.y)
          }
        }
      };
      App.updateBeforeDraw.push(playerUpdater);

      // Player Energy status
      App.scene.player.energy = {};

      for(let key in App.scene.player.meshList) {
        App.scene.player.meshList[key].setScale(1.85);
      }

      // Target scene object
      var texTarget = {
        source: [
          "res/bvh-skeletal-base/swat-guy/target.png",
          "res/bvh-skeletal-base/swat-guy/target.png"
        ],
        mix_operation: "multiply",
      };
      world.Add("squareTex", 0.25, 'FPSTarget', texTarget);
      App.scene.FPSTarget.position.setPosition(0, 0, -4);
      App.scene.FPSTarget.glBlend.blendEnabled = true;
      App.scene.FPSTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
      App.scene.FPSTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[4];
      App.scene.FPSTarget.isHUD = true;
      App.scene.FPSTarget.geometry.setScale(0.1);

      // Energy active bar
      // Custom generic textures. Micro Drawing.
      // Example for arg shema square for now only.
      var options = {
        squareShema: [8, 8],
        pixels: new Uint8Array(8 * 8 * 4)
      };
      // options.pixels.fill(0);
      App.scene.player.energy.value = 8;
      App.scene.player.updateEnergy = function(v) {
        this.energy.value = v;
        var t = App.scene.energyBar.preparePixelsTex(App.scene.energyBar.specialValue);
        App.scene.energyBar.textures.pop()
        App.scene.energyBar.textures.push(App.scene.energyBar.createPixelsTex(t));
      };

      function preparePixelsTex(options) {
        var I = 0, R = 0, G = 0, B = 0, localCounter = 0;
        for(var funny = 0;funny < 8 * 8 * 4;funny += 4) {
          if(localCounter > 7) {
            localCounter = 0;
          }
          if(localCounter < App.scene.player.energy.value) {
            I = 128;
            if(App.scene.player.energy.value < 3) {
              R = 255;
              G = 0;
              B = 0;
              I = 0;
            } else if(App.scene.player.energy.value > 2 && App.scene.player.energy.value < 5) {
              R = 255;
              G = 255;
              B = 0;
            } else {
              R = 0;
              G = 255;
              B = 0;
            }
          } else {
            I = 0;
            R = 0;
            G = 0;
            B = 0;
          }
          options.pixels[funny] = R;
          options.pixels[funny + 1] = G;
          options.pixels[funny + 2] = B;
          options.pixels[funny + 3] = 0;
          localCounter++;
        }
        return options;
      }

      var tex2 = {
        source: [
          "res/images/hud/energy-bar.png",
          "res/images/hud/energy-bar.png"
        ],
        mix_operation: "multiply",
      };

      world.Add("squareTex", 1, 'energyBar', tex2);
      App.scene.energyBar.glBlend.blendEnabled = true;
      App.scene.energyBar.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
      App.scene.energyBar.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
      App.scene.energyBar.isHUD = true;
      // App.scene.energy.visible = false;
      App.scene.energyBar.position.setPosition(0, 1.1, -3);
      App.scene.energyBar.geometry.setScaleByX(1)
      App.scene.energyBar.geometry.setScaleByY(0.05)
      App.scene.energyBar.preparePixelsTex = preparePixelsTex;
      options = preparePixelsTex(options);
      // App.scene.energyBar.textures[0] = App.scene.energyBar.createPixelsTex(options);
      App.scene.energyBar.textures.push(App.scene.energyBar.createPixelsTex(options));
      App.scene.energyBar.specialValue = options;

    }

    matrixEngine.objLoader.downloadMeshes(
      matrixEngine.objLoader.makeObjSeqArg(
        {
          id: objName,
          // path: "res/bvh-skeletal-base/swat-guy/anims/swat-multi",
          path: "res/bvh-skeletal-base/swat-guy/FPShooter-hands/FPShooter-hands",
          from: 1,
          to: 20
        }),
      onLoadObj
    );

  };

  let promiseAllGenerated = [];

  const objGenerator = (n) => {
    for(var j = 0;j < n;j++) {
      promiseAllGenerated.push(new Promise((resolve) => {
        setTimeout(() => {
          world.Add("cubeLightTex", 1, "CUBE" + j, tex);
          var b2 = new CANNON.Body({
            mass: 1,
            linearDamping: 0.01,
            position: new CANNON.Vec3(1, -14.5, 15),
            shape: new CANNON.Box(new CANNON.Vec3(1, 1, 1))
          });
          physics.world.addBody(b2);
          App.scene['CUBE' + j].physics.currentBody = b2;
          App.scene['CUBE' + j].physics.enabled = true;
          resolve();
        }, 1000 * j);
      }));
    }
  }

  // objGenerator(15);

  createObjSequence('player');

  Promise.all(promiseAllGenerated).then((what) => {
    console.info(`Runtime wait for some generetion of scene objects,
                  then swap scene array index for target ->
                  must be manual setup for now!`, what);
    // swap(5, 19, matrixEngine.matrixWorld.world.contentList);
  });

  // Add ground for physics bodies.
  var tex = {
    source: ["res/images/complex_texture_1/diffuse.png"],
    mix_operation: "multiply",
  };
  // Load Physics world.
  // let gravityVector = [0, 0, -9.82];
  let gravityVector = [0, 0, -29.82];
  let physics = world.loadPhysics(gravityVector);

  // Add ground
  var groundBody = new CANNON.Body({
    mass: 0, // mass == 0 makes the body static
    position: new CANNON.Vec3(0, -15, -2)
  });
  var groundShape = new CANNON.Plane();
  groundBody.addShape(groundShape);
  physics.world.addBody(groundBody);
  // Matrix engine visual
  world.Add("squareTex", 1, "FLOOR_STATIC", tex);
  App.scene.FLOOR_STATIC.geometry.setScaleByX(20);
  App.scene.FLOOR_STATIC.geometry.setScaleByY(20);
  App.scene.FLOOR_STATIC.position.SetY(-2);
  App.scene.FLOOR_STATIC.position.SetZ(-15);
  App.scene.FLOOR_STATIC.rotation.rotx = 90;

  // Target x-ray
  // See through the objects.
  // In webGL context it is object how was drawn before others.
  var texTarget = {
    source: [
      "res/bvh-skeletal-base/swat-guy/target-night.png"
    ],
    mix_operation: "multiply",
  };
  world.Add("squareTex", 0.18, 'xrayTarget', texTarget);
  App.scene.xrayTarget.glBlend.blendEnabled = true;
  App.scene.xrayTarget.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.xrayTarget.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.xrayTarget.isHUD = true;
  App.scene.xrayTarget.visible = false;
  App.scene.xrayTarget.position.setPosition(-0.3, 0.27, -4);

  // Energy
  var tex1 = {
    source: [
      "res/images/hud/energy.png"
    ],
    mix_operation: "multiply",
  };
  world.Add("squareTex", 0.5, 'energy', tex1);
  App.scene.energy.glBlend.blendEnabled = true;
  App.scene.energy.glBlend.blendParamSrc = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.energy.glBlend.blendParamDest = matrixEngine.utility.ENUMERATORS.glBlend.param[5];
  App.scene.energy.isHUD = true;
  // App.scene.energy.visible = false;
  App.scene.energy.position.setPosition(-1, 1.15, -3);
  App.scene.energy.geometry.setScaleByX(0.35)
  App.scene.energy.geometry.setScaleByY(0.1)

  // good for fix rotation in future
  world.Add("cubeLightTex", 1, "FLOOR2", tex);
  var b2 = new CANNON.Body({
    mass: 0,
    linearDamping: 0.01,
    position: new CANNON.Vec3(1, -14.5, -1),
    shape: new CANNON.Box(new CANNON.Vec3(3, 1, 1))
  });
  physics.world.addBody(b2);
  App.scene['FLOOR2'].position.setPosition(1, -1, -14.5)
  App.scene['FLOOR2'].geometry.setScaleByX(3);

  App.scene['FLOOR2'].physics.currentBody = b2;
  App.scene['FLOOR2'].physics.enabled = true;

  world.Add("cubeLightTex", 2, "FLOOR3", tex);
  var b3 = new CANNON.Body({
    mass: 0,
    linearDamping: 0.01,
    position: new CANNON.Vec3(0, -19, 0),
    shape: new CANNON.Box(new CANNON.Vec3(3, 3, 3))
  });
  physics.world.addBody(b3);
  App.scene['FLOOR3'].position.setPosition(0, 0, -19)
  // App.scene['FLOOR3'].geometry.setScaleByX(3);

  App.scene['FLOOR3'].physics.currentBody = b3;
  App.scene['FLOOR3'].physics.enabled = true;

  world.Add("cubeLightTex", 5, "WALL_BLOCK", tex);
  var b5 = new CANNON.Body({
    mass: 0,
    linearDamping: 0.01,
    position: new CANNON.Vec3(10, -19, 0),
    shape: new CANNON.Box(new CANNON.Vec3(5, 5, 5))
  });
  physics.world.addBody(b5);
  App.scene['WALL_BLOCK'].position.setPosition(10, 0, -19)
  // App.scene['WALL_BLOCK'].geometry.setScaleByX(3);
  App.scene['WALL_BLOCK'].physics.currentBody = b5;
  App.scene['WALL_BLOCK'].physics.enabled = true;

};

Any suggestion ?


问:
Implicit multiplication in maple from terminal
I have a project, where I create a maple script in another language, that solves polynomial equations, and put it in .mpl file. But in this script multiplication is implicit, i.e. 3 * x represented as "3x".

When I run maple script from terminal (using maple filename) maple provides me with "syntax error: missing operator". I googled and found out that it happens with "1-D Math" mode in Maple, because of implicit multiplication (in 1-D Math you must do it explicitly).

Is there a way to change maple to 2-D Math in terminal? Or maybe there is another way to allow implicit multiplication?

Thanks


问:
PyTorch TypeError: only integer tensors of a single element can be converted to an index
I am writing a CNN with PyTorch using my custom dataset consisting of 10 classes. Here is my code:

```<code>import random
model.eval()
randomIndex = random.randint(0, len(dataset_val) - 1)
test = dataset_val[randomIndex]
from matplotlib.pyplot import imshow
import matplotlib.pylab as plt
labels = ["5","10","20","30","40","50","75","100","150","200"]
def show_data(data_sample, size):
   plt.imshow(data_sample[0].numpy().reshape(size,size), cmap='gray')
   plt.title(f"Real Label = {labels[data_sample[0]]}")
for n,data_sample in enumerate(dataset):
   show_data(data_sample, IMAGE_SIZE)
   plt.show()
   if n==0:
       break
show_data(test, IMAGE_SIZE)
# Turn image of (C, H, W) into (B, C, H, W) to pass into the model
# Take the index of the highest probability from the output tensor and grab the corresponding classification
print("AI's Prediction: " + labels[torch.argmax(model(test[0].view(-1, 1, 16, 16)), 1)])
</code>```

I get an error because of the show_data function. If I change the bottom data_sample[0] to data_sample[1] and don't change the top one, It doesn't show an error but the wrong label.

Here is how I created my dataset:

```<code>import torch
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
from matplotlib.pyplot import imshow
import matplotlib.pylab as plt
IMAGE_SIZE = 16
# Load the dataset using the ImageFolder class
dataset = datasets.ImageFolder('/content/gdrive/MyDrive/Dataset',
                              transforms.Compose([
                                  transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
                                  transforms.ToTensor(),
                                  transforms.Grayscale()]))

train_dataset = DataLoader(dataset, batch_size=16, shuffle=True)
train_size = int(0.8 * len(dataset))
test_size = len(dataset) - train_size
dataset_train, dataset_val = torch.utils.data.random_split(dataset, [train_size, test_size])
labels = ["5","10","20","30","40","50","75","100","150","200"]

for batch in train_dataset:
   print(batch)
   break
</code>```

Can you please help me fix this? Thank you so much.

I tried to change both of the indexes to 1, and I got this error:

```<code>'int' object has no attribute 'numpy'
</code>```

Body:
I am writing a CNN with PyTorch using my custom dataset consisting of 10 classes. Here is my code:

import random
model.eval()
randomIndex = random.randint(0, len(dataset_val) - 1)
test = dataset_val[randomIndex]
from matplotlib.pyplot import imshow
import matplotlib.pylab as plt
labels = ["5","10","20","30","40","50","75","100","150","200"]
def show_data(data_sample, size):
   plt.imshow(data_sample[0].numpy().reshape(size,size), cmap='gray')
   plt.title(f"Real Label = {labels[data_sample[0]]}")
for n,data_sample in enumerate(dataset):
   show_data(data_sample, IMAGE_SIZE)
   plt.show()
   if n==0:
       break
show_data(test, IMAGE_SIZE)
# Turn image of (C, H, W) into (B, C, H, W) to pass into the model
# Take the index of the highest probability from the output tensor and grab the corresponding classification
print("AI's Prediction: " + labels[torch.argmax(model(test[0].view(-1, 1, 16, 16)), 1)])

I get an error because of the show_data function. If I change the bottom data_sample[0] to data_sample[1] and don't change the top one, It doesn't show an error but the wrong label.

Here is how I created my dataset:

import torch
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
from matplotlib.pyplot import imshow
import matplotlib.pylab as plt
IMAGE_SIZE = 16
# Load the dataset using the ImageFolder class
dataset = datasets.ImageFolder('/content/gdrive/MyDrive/Dataset',
                              transforms.Compose([
                                  transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
                                  transforms.ToTensor(),
                                  transforms.Grayscale()]))

train_dataset = DataLoader(dataset, batch_size=16, shuffle=True)
train_size = int(0.8 * len(dataset))
test_size = len(dataset) - train_size
dataset_train, dataset_val = torch.utils.data.random_split(dataset, [train_size, test_size])
labels = ["5","10","20","30","40","50","75","100","150","200"]

for batch in train_dataset:
   print(batch)
   break

Can you please help me fix this? Thank you so much.

I tried to change both of the indexes to 1, and I got this error:

'int' object has no attribute 'numpy'


问:
How to train/fine tune with images containing multiple languages?
When extracting wordstrboxes I supply the languages the image contains, for example "eng+deu", however lstmf is created per language.

tesseract.exe image.png image --psm 4 -l eng+deu wordstrbox

So what is the correct path forward here? Use the images both in training for English and for German? Or something else?

Thanks


问:
I'm trying to get stock prices from Yahoo Finance API, getting an java.io.FileNotFoundException
I'm trying to get stock prices from Yahoo Finance,

but I'm getting an error. This was the code I wrote before, and it worked well before, but after a long time, it doesn't work, returning the following error code.

java.io.FileNotFoundException while trying to execute YahooFinance.get operation
I found a question similar to my problem, and I tried to update Java according to the comments to correct the Java version,but the problem was not resolved.

When I click the URL given with the error code, it seems to get the data from Yahoo Finance, but it doesn't work programmatically.

```<code>package com.jym.yftest

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.jym.yftest.databinding.ActivityMainBinding
import yahoofinance.YahooFinance

class MainActivity : AppCompatActivity() {
    private val vBinding by lazy { ActivityMainBinding.inflate(layoutInflater)}
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)

        vBinding.testBtn.setOnClickListener {
            Thread(Runnable {
                try{
                    val stock = YahooFinance.get("APL")
                    Log.d("test", stock.toString())

                }catch(err:Exception){
                    Log.d("test", err.toString())
                }
                this@MainActivity.runOnUiThread(java.lang.Runnable {
                })
            }).start()
        }
    }

}
</code>```

build.gradle(module)

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 33

    defaultConfig {
        applicationId "com.jym.yftest"
        minSdk 22
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'

    buildFeatures{
        viewBinding true
    }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
}
</code>```

build.gradle(project)

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Body:
I'm trying to get stock prices from Yahoo Finance,

but I'm getting an error. This was the code I wrote before, and it worked well before, but after a long time, it doesn't work, returning the following error code.

java.io.FileNotFoundException while trying to execute YahooFinance.get operation
I found a question similar to my problem, and I tried to update Java according to the comments to correct the Java version,but the problem was not resolved.

When I click the URL given with the error code, it seems to get the data from Yahoo Finance, but it doesn't work programmatically.

package com.jym.yftest

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.jym.yftest.databinding.ActivityMainBinding
import yahoofinance.YahooFinance

class MainActivity : AppCompatActivity() {
    private val vBinding by lazy { ActivityMainBinding.inflate(layoutInflater)}
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)

        vBinding.testBtn.setOnClickListener {
            Thread(Runnable {
                try{
                    val stock = YahooFinance.get("APL")
                    Log.d("test", stock.toString())

                }catch(err:Exception){
                    Log.d("test", err.toString())
                }
                this@MainActivity.runOnUiThread(java.lang.Runnable {
                })
            }).start()
        }
    }

}

build.gradle(module)

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 33

    defaultConfig {
        applicationId "com.jym.yftest"
        minSdk 22
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'

    buildFeatures{
        viewBinding true
    }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.core:core-ktx:1.9.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
}

build.gradle(project)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
A review of the validation criteria in `ed25519-dalek` when compared with `ed25519-consensus` in some edge cases?
I am working with informal systems on a tendermint light client to be used in the ibc protocol in  parachains, we need use the polkadot host function for ed25519 signature verification for performance benefits, but we need substrate to migrate to ed25519-consensus instead of ed25519-dalek due to some inconsistencies in signature validation criteria in the ed25519-dalek's implementation of the ed25519 scheme, the issues are better explained in this article. https://hdevalence.ca/blog/2020-10-04-its-25519am

More details are specified in the readme here. https://github.com/penumbra-zone/ed25519-consensus


问:
How to encrypt post request body in flutter web client and php backend
Consider I have a map, that created by my flutter web application and my dart code, something like this:

```<code>  var data = {
    "name": "amir abbas",
    "user_name": "amir_a14",
  };
</code>```

And I need send it to my backend, currently I am send it like this:

```<code>var url = Uri.parse('https://my-domain.test/myApi.php');
http.post(url, body: data);
</code>```

And users can see all of the requests, including headers, tokens, bodies and urls in inspect element, and they can modify bodies and send fake requests to my backend.

My goal is that users can't modify request bodies, I need encrypt bodies before sending and decrypt it on my backend server.

But is there any way to encrypt the bodies that users can't change my map values at all?
How can I do that?

My backend server written in php.

Body:
Consider I have a map, that created by my flutter web application and my dart code, something like this:

  var data = {
    "name": "amir abbas",
    "user_name": "amir_a14",
  };

And I need send it to my backend, currently I am send it like this:

var url = Uri.parse('https://my-domain.test/myApi.php');
http.post(url, body: data);

And users can see all of the requests, including headers, tokens, bodies and urls in inspect element, and they can modify bodies and send fake requests to my backend.

My goal is that users can't modify request bodies, I need encrypt bodies before sending and decrypt it on my backend server.

But is there any way to encrypt the bodies that users can't change my map values at all?
How can I do that?

My backend server written in php.


问:
Nginx Case Insensitive
I have a wordpress site up and running on Nginx. However, I must have a sub url like "www.mysite.com/subsite"
Got this all working except that the url is case sensitive.

I am using the "sites-enabled" and have a location block like this:

```<code> location /MySubSite {
                alias /home/MySubSite/public_html/test;
                index index.html;
                }
</code>```

I have tried location ~* /MySubSite, (?i)..nothing works.
I keep getting a 404

What is the correct syntax to get nginx to stop being case sensitive?

THanks all.

Title: Nginx Case Insensitive

Body:
I have a wordpress site up and running on Nginx. However, I must have a sub url like "www.mysite.com/subsite"
Got this all working except that the url is case sensitive.

I am using the "sites-enabled" and have a location block like this:

 location /MySubSite {
                alias /home/MySubSite/public_html/test;
                index index.html;
                }

I have tried location ~* /MySubSite, (?i)..nothing works.
I keep getting a 404

What is the correct syntax to get nginx to stop being case sensitive?

THanks all.


问:
Unsupported operation in Flutter web just_audio library
I've debugged the issue and came to a problem in the audio_service.dart at line 969. In this line the the File object has been used from dart.io library which is not supported in the Flutter web. Am I using the library in a wrong way or is this a bug?

Error: Unsupported operation: _Namespace
dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49  throw
dart-sdk/lib/_internal/js_dev_runtime/patch/io_patch.dart 200:5               get _namespace
dart-sdk/lib/io/file_impl.dart 376:45                                         lengthSync
packages/audio_service/audio_service.dart 969:30                              _observeMediaItem
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50
dart-sdk/lib/async/zone.dart 1653:54                                          runUnary
dart-sdk/lib/async/future_impl.dart 147:18                                    handleValue
dart-sdk/lib/async/future_impl.dart 766:44                                    handleValueCallback
dart-sdk/lib/async/future_impl.dart 795:13                                    _propagateToListeners
dart-sdk/lib/async/future_impl.dart 557:7                                     [_complete]
dart-sdk/lib/async/stream_pipe.dart 61:11                                     _cancelAndValue
dart-sdk/lib/async/stream.dart 1718:11
dart-sdk/lib/async/stream_pipe.dart 11:14                                     _runUserCode
dart-sdk/lib/async/stream.dart 1716:7
dart-sdk/lib/async/zone.dart 1586:10                                          runUnaryGuarded
dart-sdk/lib/async/stream_impl.dart 339:11                                    [_sendData]
dart-sdk/lib/async/stream_impl.dart 515:13                                    perform
dart-sdk/lib/async/stream_impl.dart 620:10                                    handleNext
dart-sdk/lib/async/stream_impl.dart 591:7                                     callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                              _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                               _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15