问:
Laravel laradock Unable to connect localhost
After installing Docker in ubuntu and adding laradock to an existing project, I run this below command to start using laradock:

docker-compose up -d nginx mysql phpmyadmin workspace
```
<p>result:</p>
```Creating laradock_mysql_1            ... done
Creating laradock_docker-in-docker_1 ... done
Creating laradock_workspace_1        ... done
Creating laradock_phpmyadmin_1       ... done
Creating laradock_php-fpm_1          ... done
Creating laradock_nginx_1            ... done
```
<p>now after running <code>docker-compose exec bash</code> command I served <code>laravel</code> into that</p>
<pre class="lang-bash prettyprint-override"><code>docker-compose exec workspace bash
root@b3c88be3e389:/var/www# php artisan serve

   INFO  Server running on [http://127.0.0.1:8000].

  Press Ctrl+C to stop the server
</code>```

when I clicked on IP address, I get this message in browser:

```<code>Unable to connect

Firefox can’t establish a connection to the server at 127.0.0.1:8000.

    The site could be temporarily unavailable or too busy. Try again in a few moments.
    If you are unable to load any pages, check your computer’s network connection.
    If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the web.
</code>```

docker-compose ps command result:

```<code>           Name                          Command               State                                                                    Ports
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
laradock_docker-in-docker_1   dockerd-entrypoint.sh            Up      2375/tcp, 2376/tcp
laradock_mysql_1              docker-entrypoint.sh mysqld      Up      0.0.0.0:3306->3306/tcp,:::3306->3306/tcp, 33060/tcp
laradock_nginx_1              /docker-entrypoint.sh /bin ...   Up      0.0.0.0:443->443/tcp,:::443->443/tcp, 0.0.0.0:80->80/tcp,:::80->80/tcp, 0.0.0.0:81->81/tcp,:::81->81/tcp
laradock_php-fpm_1            docker-php-entrypoint php-fpm    Up      9000/tcp
laradock_phpmyadmin_1         /docker-entrypoint.sh apac ...   Up      0.0.0.0:8081->80/tcp,:::8081->80/tcp
laradock_workspace_1          /sbin/my_init                    Up      0.0.0.0:2222->22/tcp,:::2222->22/tcp, 0.0.0.0:3000->3000/tcp,:::3000->3000/tcp, 0.0.0.0:3001->3001/tcp,:::3001->3001/tcp,
                                                                       0.0.0.0:4200->4200/tcp,:::4200->4200/tcp, 0.0.0.0:5173->5173/tcp,:::5173->5173/tcp, 0.0.0.0:8001->8000/tcp,:::8001->8000/tcp,
                                                                       0.0.0.0:8080->8080/tcp,:::8080->8080/tcp
</code>```

nginx definition into docker-compose.yml:

```<code>nginx:
  build:
    context: ./nginx
    args:
      - CHANGE_SOURCE=${CHANGE_SOURCE}
      - PHP_UPSTREAM_CONTAINER=${NGINX_PHP_UPSTREAM_CONTAINER}
      - PHP_UPSTREAM_PORT=${NGINX_PHP_UPSTREAM_PORT}
      - http_proxy
      - https_proxy
      - no_proxy
  volumes:
    - ${APP_CODE_PATH_HOST}:${APP_CODE_PATH_CONTAINER}${APP_CODE_CONTAINER_FLAG}
    - ${NGINX_HOST_LOG_PATH}:/var/log/nginx
    - ${NGINX_SITES_PATH}:/etc/nginx/sites-available
    - ${NGINX_SSL_PATH}:/etc/nginx/ssl
  ports:
    - "${NGINX_HOST_HTTP_PORT}:80"
    - "${NGINX_HOST_HTTPS_PORT}:443"
    - "${VARNISH_BACKEND_PORT}:81"
  depends_on:
    - php-fpm
  networks:
    - frontend
    - backend
</code>```

and nginx Dockerfile:

```<code>FROM nginx:alpine

LABEL maintainer="Mahmoud Zalt <mahmoud@zalt.me>"

COPY nginx.conf /etc/nginx/

# If you're in China, or you need to change sources, will be set CHANGE_SOURCE to true in .env.

ARG CHANGE_SOURCE=false
RUN if [ ${CHANGE_SOURCE} = true ]; then \
    # Change application source from dl-cdn.alpinelinux.org to aliyun source
    sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/' /etc/apk/repositories \
;fi

RUN apk update \
    && apk upgrade \
    && apk --update add logrotate \
    && apk add --no-cache openssl \
    && apk add --no-cache bash

RUN apk add --no-cache curl

RUN set -x ; \
    addgroup -g 82 -S www-data ; \
    adduser -u 82 -D -S -G www-data www-data && exit 0 ; exit 1

ARG PHP_UPSTREAM_CONTAINER=php-fpm
ARG PHP_UPSTREAM_PORT=9000

# Create 'messages' file used from 'logrotate'
RUN touch /var/log/messages

# Copy 'logrotate' config file
COPY logrotate/nginx /etc/logrotate.d/

# Set upstream conf and remove the default conf
RUN echo "upstream php-upstream { server ${PHP_UPSTREAM_CONTAINER}:${PHP_UPSTREAM_PORT}; }" > /etc/nginx/conf.d/upstream.conf \
    && rm /etc/nginx/conf.d/default.conf

ADD ./startup.sh /opt/startup.sh
RUN sed -i 's/\r//g' /opt/startup.sh
CMD ["/bin/bash", "/opt/startup.sh"]

EXPOSE 80 81 443
</code>```

laradock env:

```<code># All volumes driver
VOLUMES_DRIVER=local

# All Networks driver
NETWORKS_DRIVER=bridge
</code>```

Body:
After installing Docker in ubuntu and adding laradock to an existing project, I run this below command to start using laradock:

docker-compose up -d nginx mysql phpmyadmin workspace

result:

Creating laradock_mysql_1            ... done
Creating laradock_docker-in-docker_1 ... done
Creating laradock_workspace_1        ... done
Creating laradock_phpmyadmin_1       ... done
Creating laradock_php-fpm_1          ... done
Creating laradock_nginx_1            ... done

now after running docker-compose exec bash command I served laravel into that

docker-compose exec workspace bash
root@b3c88be3e389:/var/www# php artisan serve

   INFO  Server running on [http://127.0.0.1:8000].

  Press Ctrl+C to stop the server

when I clicked on IP address, I get this message in browser:

Unable to connect

Firefox can’t establish a connection to the server at 127.0.0.1:8000.

    The site could be temporarily unavailable or too busy. Try again in a few moments.
    If you are unable to load any pages, check your computer’s network connection.
    If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the web.

docker-compose ps command result:

           Name                          Command               State                                                                    Ports
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
laradock_docker-in-docker_1   dockerd-entrypoint.sh            Up      2375/tcp, 2376/tcp
laradock_mysql_1              docker-entrypoint.sh mysqld      Up      0.0.0.0:3306->3306/tcp,:::3306->3306/tcp, 33060/tcp
laradock_nginx_1              /docker-entrypoint.sh /bin ...   Up      0.0.0.0:443->443/tcp,:::443->443/tcp, 0.0.0.0:80->80/tcp,:::80->80/tcp, 0.0.0.0:81->81/tcp,:::81->81/tcp
laradock_php-fpm_1            docker-php-entrypoint php-fpm    Up      9000/tcp
laradock_phpmyadmin_1         /docker-entrypoint.sh apac ...   Up      0.0.0.0:8081->80/tcp,:::8081->80/tcp
laradock_workspace_1          /sbin/my_init                    Up      0.0.0.0:2222->22/tcp,:::2222->22/tcp, 0.0.0.0:3000->3000/tcp,:::3000->3000/tcp, 0.0.0.0:3001->3001/tcp,:::3001->3001/tcp,
                                                                       0.0.0.0:4200->4200/tcp,:::4200->4200/tcp, 0.0.0.0:5173->5173/tcp,:::5173->5173/tcp, 0.0.0.0:8001->8000/tcp,:::8001->8000/tcp,
                                                                       0.0.0.0:8080->8080/tcp,:::8080->8080/tcp

nginx definition into docker-compose.yml:

nginx:
  build:
    context: ./nginx
    args:
      - CHANGE_SOURCE=${CHANGE_SOURCE}
      - PHP_UPSTREAM_CONTAINER=${NGINX_PHP_UPSTREAM_CONTAINER}
      - PHP_UPSTREAM_PORT=${NGINX_PHP_UPSTREAM_PORT}
      - http_proxy
      - https_proxy
      - no_proxy
  volumes:
    - ${APP_CODE_PATH_HOST}:${APP_CODE_PATH_CONTAINER}${APP_CODE_CONTAINER_FLAG}
    - ${NGINX_HOST_LOG_PATH}:/var/log/nginx
    - ${NGINX_SITES_PATH}:/etc/nginx/sites-available
    - ${NGINX_SSL_PATH}:/etc/nginx/ssl
  ports:
    - "${NGINX_HOST_HTTP_PORT}:80"
    - "${NGINX_HOST_HTTPS_PORT}:443"
    - "${VARNISH_BACKEND_PORT}:81"
  depends_on:
    - php-fpm
  networks:
    - frontend
    - backend

and nginx Dockerfile:

FROM nginx:alpine

LABEL maintainer="Mahmoud Zalt <mahmoud@zalt.me>"

COPY nginx.conf /etc/nginx/

# If you're in China, or you need to change sources, will be set CHANGE_SOURCE to true in .env.

ARG CHANGE_SOURCE=false
RUN if [ ${CHANGE_SOURCE} = true ]; then \
    # Change application source from dl-cdn.alpinelinux.org to aliyun source
    sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/' /etc/apk/repositories \
;fi

RUN apk update \
    && apk upgrade \
    && apk --update add logrotate \
    && apk add --no-cache openssl \
    && apk add --no-cache bash

RUN apk add --no-cache curl

RUN set -x ; \
    addgroup -g 82 -S www-data ; \
    adduser -u 82 -D -S -G www-data www-data && exit 0 ; exit 1

ARG PHP_UPSTREAM_CONTAINER=php-fpm
ARG PHP_UPSTREAM_PORT=9000

# Create 'messages' file used from 'logrotate'
RUN touch /var/log/messages

# Copy 'logrotate' config file
COPY logrotate/nginx /etc/logrotate.d/

# Set upstream conf and remove the default conf
RUN echo "upstream php-upstream { server ${PHP_UPSTREAM_CONTAINER}:${PHP_UPSTREAM_PORT}; }" > /etc/nginx/conf.d/upstream.conf \
    && rm /etc/nginx/conf.d/default.conf

ADD ./startup.sh /opt/startup.sh
RUN sed -i 's/\r//g' /opt/startup.sh
CMD ["/bin/bash", "/opt/startup.sh"]

EXPOSE 80 81 443

laradock env:

# All volumes driver
VOLUMES_DRIVER=local

# All Networks driver
NETWORKS_DRIVER=bridge


来源: stackexchange

问:
How can I call create a case-insensitive regex for mongoengine query builder?
I have a collection of stock tickers. I am trying to write a query so user can find a stock, lets say AAPL whether she enters AAP or aapl or AaPL

So, far I am able to generate a regex so user is able to find stocks starting with a given text, but only if she enters all caps - the way tickers are stored in the collection.

```<code>        search_string = "^%s" % ticker
        regex = re.compile(search_string)
        stock.objects(ticker=regex).order_by('ticker')

</code>```

How may I make my reg ex case insensitive? Or provide an option to MongoEngine so it searches with case insensitivity.

Thanks

ContentLicense: CC BY-SA 4.0

Body:
I have a collection of stock tickers. I am trying to write a query so user can find a stock, lets say AAPL whether she enters AAP or aapl or AaPL

So, far I am able to generate a regex so user is able to find stocks starting with a given text, but only if she enters all caps - the way tickers are stored in the collection.

        search_string = "^%s" % ticker
        regex = re.compile(search_string)
        stock.objects(ticker=regex).order_by('ticker')

How may I make my reg ex case insensitive? Or provide an option to MongoEngine so it searches with case insensitivity.

Thanks


问:
Can't start Vite dev server on 443 without root, but native node server on 443 works without root
I was trying to use vite in my project and wanted to start the local dev server on 443 port (MacOS) and I'm presented with the following error:

```<code>error when starting dev server:
Error: listen EACCES: permission denied 127.0.0.1:443
    at Server.setupListenHandle [as _listen2] (node:net:1415:21)
    at listenInCluster (node:net:1480:12)
    at GetAddrInfoReqWrap.doListen [as callback] (node:net:1629:7)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:111:8)
</code>```

Now as per *nix systems, I should get this error as ports < 1024 need root access.

But my question is, how am I then able to listen on 443 port on a native node server?

const http = require('http');

const requestListener = function (req, res) {
  res.writeHead(200);
  res.end('Hello, World!');
}

const server = http.createServer(requestListener);
server.listen(443);
```

The code above works without any issue (also works with https module) on my system and without root access.
Can someone explain what is happening?

Body:
I was trying to use vite in my project and wanted to start the local dev server on 443 port (MacOS) and I'm presented with the following error:

error when starting dev server:
Error: listen EACCES: permission denied 127.0.0.1:443
    at Server.setupListenHandle [as _listen2] (node:net:1415:21)
    at listenInCluster (node:net:1480:12)
    at GetAddrInfoReqWrap.doListen [as callback] (node:net:1629:7)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:111:8)

Now as per *nix systems, I should get this error as ports < 1024 need root access.

But my question is, how am I then able to listen on 443 port on a native node server?

const http = require('http');

const requestListener = function (req, res) {
  res.writeHead(200);
  res.end('Hello, World!');
}

const server = http.createServer(requestListener);
server.listen(443);

The code above works without any issue (also works with https module) on my system and without root access.
Can someone explain what is happening?


问:
How to insert this into _id object in mongodb Aggregation
_id Object
_id:638dcf95c891361bd4345748,
firstName:"Pravin",
lastName:"Singh",
date:2022-03-13T08:14:30.000+00:00

fruites Array
0:"Banana"
1:"Orange"
2:"Strawberry"

```<code>{
  _id: {
    _id: "$_id",
    firstName: "$firstName",
    lastName: "$lastName",
    date: "$date",
  },
  fruites: {
    $push: "$fruites",
  }
}
</code>```

Body:
_id Object
_id:638dcf95c891361bd4345748,
firstName:"Pravin",
lastName:"Singh",
date:2022-03-13T08:14:30.000+00:00

fruites Array
0:"Banana"
1:"Orange"
2:"Strawberry"

{
  _id: {
    _id: "$_id",
    firstName: "$firstName",
    lastName: "$lastName",
    date: "$date",
  },
  fruites: {
    $push: "$fruites",
  }
}


问:
Giving this error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable'
This code giving a error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable' how to resolve it.

using (XLWorkbook wb = new XLWorkbook()) this line giving the error.
I have also added assembly reference ClosedXML but its not working

Is there any way to resolved this issue?

```<code>using System.Web;
using System.Data.SqlClient;
using System.IO;
using ClosedXML.Excel;
using System.Web.Mvc;
using SHIPVICTUAL.Controllers;

namespace SHIPVICTUAL.Controllers
{
    public class shipController : Controller
    {

        // GET: ship
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ExportToExcel(FormCollection formCollection)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            try
            {
                SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("DBShipVictual"));

                cmd = new SqlCommand("Reports_rdlc", con);
                cmd.CommandType = CommandType.StoredProcedure;
                da.SelectCommand = cmd;
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    dt.TableName = "Report";
                    using (XLWorkbook wb = new XLWorkbook())
                    {
                        wb.Worksheets.Add(dt);
                        wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                        wb.Style.Font.Bold = true;
                        Response.Clear();
                        Response.Buffer = true;
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.AddHeader("Content-disposition", "attachment;ReportList.xlsx");
                        using (MemoryStream MyMemoryStream = new MemoryStream())
                        {
                            wb.SaveAs(MyMemoryStream);
                            MyMemoryStream.WriteTo(Response.OutputStream);
                            Response.Flush();
                            Response.End();
                            {
                                wb.SaveAs(MyMemoryStream);
                                MyMemoryStream.WriteTo(Response.OutputStream);
                                Response.Flush();
                                Response.End();

                            }
                        }

                    }

                    {

                    }
                }

            }
            catch
            {

            }
            return View();

        }
    }
} ```
```

Body:
This code giving a error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable' how to resolve it.

using (XLWorkbook wb = new XLWorkbook()) this line giving the error.
I have also added assembly reference ClosedXML but its not working

Is there any way to resolved this issue?

using System.Web;
using System.Data.SqlClient;
using System.IO;
using ClosedXML.Excel;
using System.Web.Mvc;
using SHIPVICTUAL.Controllers;

namespace SHIPVICTUAL.Controllers
{
    public class shipController : Controller
    {

        // GET: ship
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ExportToExcel(FormCollection formCollection)
        {
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            try
            {
                SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("DBShipVictual"));

                cmd = new SqlCommand("Reports_rdlc", con);
                cmd.CommandType = CommandType.StoredProcedure;
                da.SelectCommand = cmd;
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    dt.TableName = "Report";
                    using (XLWorkbook wb = new XLWorkbook())
                    {
                        wb.Worksheets.Add(dt);
                        wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                        wb.Style.Font.Bold = true;
                        Response.Clear();
                        Response.Buffer = true;
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.AddHeader("Content-disposition", "attachment;ReportList.xlsx");
                        using (MemoryStream MyMemoryStream = new MemoryStream())
                        {
                            wb.SaveAs(MyMemoryStream);
                            MyMemoryStream.WriteTo(Response.OutputStream);
                            Response.Flush();
                            Response.End();
                            {
                                wb.SaveAs(MyMemoryStream);
                                MyMemoryStream.WriteTo(Response.OutputStream);
                                Response.Flush();
                                Response.End();

                            }
                        }

                    }

                    {

                    }
                }

            }
            catch
            {

            }
            return View();

        }
    }
} ```


问:
How can I test routerLinkActive in standalone component?
If I have a non-standalone component as follows:

```<code>import { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'sb-index',
  template: `
    <a [routerLink]="['routeA']" [routerLinkActive]="'active'">A</a>
    <a [routerLink]="['routeB']" [routerLinkActive]="'active'">B</a>
  `
})
export class IndexComponent {
}
</code>```

I'm able to test the routerLinkActive with the following spec, as seen in SO question:

```<code>import { Component, NgZone } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Router, RouterLinkActive } from '@angular/router';
import { IndexComponent } from './index.component';
import { RouterTestingModule } from '@angular/router/testing';

@Component({
  selector: 'sb-stub'
})
class StubComponent {}

describe('IndexComponent', () => {
  let fixture: ComponentFixture<IndexComponent>;
  let component: IndexComponent;

  beforeEach(() => {
    TestBed
      .configureTestingModule({
        declarations: [
          IndexComponent,
          StubComponent
        ],
        imports: [
          RouterTestingModule.withRoutes([
            { path: 'routeA', component: StubComponent },
            { path: 'routeB', component: StubComponent }
          ])
        ]
      })
      .compileComponents();

    fixture = TestBed.createComponent(IndexComponent);
    component = fixture.componentInstance;
  });

  it('should show "A" route as active', fakeAsync(() => {
    fixture.detectChanges();

    TestBed.inject(NgZone).run(() => {
      TestBed.inject(Router).navigate(['routeA']);
      tick();
      fixture.detectChanges();

      fixture.debugElement
              .queryAll(By.directive(RouterLinkActive))
              .map(debugElement => debugElement.nativeElement as HTMLAnchorElement)
              .forEach(nativeElement => {
                if (nativeElement.textContent === 'A') {
                  expect(nativeElement.classList.contains('active')).toBeTrue();
                } else {
                  expect(nativeElement.classList.contains('active')).toBeFalse();
                }
              });
    });
  }));
});
</code>```

I can't figure out how to setup the same tests, if I change the IndexComponent to be a standalone component as follows:

```<code>import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterModule, RouterOutlet } from '@angular/router';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'sb-index',
  standalone: true,
  template: `
    <a [routerLink]="['routeA']" [routerLinkActive]="'active'">A</a>
    <a [routerLink]="['routeB']" [routerLinkActive]="'active'">B</a>
  `,
  imports: [ RouterLink, RouterLinkActive, RouterOutlet ]
})
export class IndexComponent {
}
</code>```

I've tried a number of different things, mostly focusing on the injection and scoping aspects as I assume that's what's changed as follows:

```<code>import { Component, EnvironmentInjector, NgZone } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { provideRouter, Router, RouterLinkActive, RouterOutlet } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { RouterLinkDirectiveStub } from '@sb/testing';
import { IndexComponent } from './index.component';

@Component({
  standalone: true,
  selector: 'sb-stub'
})
class StubComponent {}

describe('IndexComponent', () => {
  let fixture: ComponentFixture<IndexComponent>;
  let component: IndexComponent;

  beforeEach(() => {
    TestBed
      .configureTestingModule({
        imports: [
          IndexComponent,
          StubComponent
        ],
        providers: [
          provideRouter([
            { path: 'routeA', component: StubComponent },
            { path: 'routeB', component: StubComponent }
          ])
        ]
      })
      .overrideComponent(
        IndexComponent,
        {
          set: {
            imports: [ RouterOutlet, RouterLinkActive, RouterLinkDirectiveStub ]
          }
        }
      )
      .compileComponents();

    fixture = TestBed.createComponent(IndexComponent);
    component = fixture.componentInstance;
  });

  it('should show "A" route as active', fakeAsync(() => {
    fixture.detectChanges();

    fixture.ngZone?.run(() => {
      fixture.componentRef.injector.get(Router).navigate(['routeA']);
    // TestBed.inject(NgZone).run(() => {
      // TestBed.inject(EnvironmentInjector).get(NgZone).run(() => {
        // TestBed.inject(Router).navigate(['routeA']);
        // TestBed.inject(EnvironmentInjector).get(Router).navigate(['routeA']);
        // TestBed.platform.injector.get(Router).navigate(['routeA']);

      tick();
      fixture.detectChanges();

      fixture.debugElement
              .queryAll(By.directive(RouterLinkActive))
              .map(debugElement => debugElement.nativeElement as HTMLAnchorElement)
              .forEach(nativeElement => {
                if (nativeElement.textContent === 'A') {
                  expect(nativeElement.classList.contains('active')).toBeTrue();
                } else {
                  expect(nativeElement.classList.contains('active')).toBeFalse();
                }
              });
    });
  }));
});
</code>```

Almost all of these give me the message: IndexComponent should show "A" route as active FAILED
Expected false to be true.

Through debugging, I can see that the tests are finding the elements with the RouterLinkActive directive, but the routing that is being done at the beginning of the test method doesn't seem to effect the routerLinkActive, so none of the elements are getting the 'active' class.

Is there a way to test the routerLinkActive elements inside of a standalone component?

Body:
If I have a non-standalone component as follows:

import { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'sb-index',
  template: `
    A
    B
  `
})
export class IndexComponent {
}

I'm able to test the routerLinkActive with the following spec, as seen in SO question:

import { Component, NgZone } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Router, RouterLinkActive } from '@angular/router';
import { IndexComponent } from './index.component';
import { RouterTestingModule } from '@angular/router/testing';

@Component({
  selector: 'sb-stub'
})
class StubComponent {}

describe('IndexComponent', () => {
  let fixture: ComponentFixture<IndexComponent>;
  let component: IndexComponent;

  beforeEach(() => {
    TestBed
      .configureTestingModule({
        declarations: [
          IndexComponent,
          StubComponent
        ],
        imports: [
          RouterTestingModule.withRoutes([
            { path: 'routeA', component: StubComponent },
            { path: 'routeB', component: StubComponent }
          ])
        ]
      })
      .compileComponents();

    fixture = TestBed.createComponent(IndexComponent);
    component = fixture.componentInstance;
  });

  it('should show "A" route as active', fakeAsync(() => {
    fixture.detectChanges();

    TestBed.inject(NgZone).run(() => {
      TestBed.inject(Router).navigate(['routeA']);
      tick();
      fixture.detectChanges();

      fixture.debugElement
              .queryAll(By.directive(RouterLinkActive))
              .map(debugElement => debugElement.nativeElement as HTMLAnchorElement)
              .forEach(nativeElement => {
                if (nativeElement.textContent === 'A') {
                  expect(nativeElement.classList.contains('active')).toBeTrue();
                } else {
                  expect(nativeElement.classList.contains('active')).toBeFalse();
                }
              });
    });
  }));
});

I can't figure out how to setup the same tests, if I change the IndexComponent to be a standalone component as follows:

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterModule, RouterOutlet } from '@angular/router';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'sb-index',
  standalone: true,
  template: `
    A
    B
  `,
  imports: [ RouterLink, RouterLinkActive, RouterOutlet ]
})
export class IndexComponent {
}

I've tried a number of different things, mostly focusing on the injection and scoping aspects as I assume that's what's changed as follows:

import { Component, EnvironmentInjector, NgZone } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { provideRouter, Router, RouterLinkActive, RouterOutlet } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { RouterLinkDirectiveStub } from '@sb/testing';
import { IndexComponent } from './index.component';

@Component({
  standalone: true,
  selector: 'sb-stub'
})
class StubComponent {}

describe('IndexComponent', () => {
  let fixture: ComponentFixture<IndexComponent>;
  let component: IndexComponent;

  beforeEach(() => {
    TestBed
      .configureTestingModule({
        imports: [
          IndexComponent,
          StubComponent
        ],
        providers: [
          provideRouter([
            { path: 'routeA', component: StubComponent },
            { path: 'routeB', component: StubComponent }
          ])
        ]
      })
      .overrideComponent(
        IndexComponent,
        {
          set: {
            imports: [ RouterOutlet, RouterLinkActive, RouterLinkDirectiveStub ]
          }
        }
      )
      .compileComponents();

    fixture = TestBed.createComponent(IndexComponent);
    component = fixture.componentInstance;
  });

  it('should show "A" route as active', fakeAsync(() => {
    fixture.detectChanges();

    fixture.ngZone?.run(() => {
      fixture.componentRef.injector.get(Router).navigate(['routeA']);
    // TestBed.inject(NgZone).run(() => {
      // TestBed.inject(EnvironmentInjector).get(NgZone).run(() => {
        // TestBed.inject(Router).navigate(['routeA']);
        // TestBed.inject(EnvironmentInjector).get(Router).navigate(['routeA']);
        // TestBed.platform.injector.get(Router).navigate(['routeA']);

      tick();
      fixture.detectChanges();

      fixture.debugElement
              .queryAll(By.directive(RouterLinkActive))
              .map(debugElement => debugElement.nativeElement as HTMLAnchorElement)
              .forEach(nativeElement => {
                if (nativeElement.textContent === 'A') {
                  expect(nativeElement.classList.contains('active')).toBeTrue();
                } else {
                  expect(nativeElement.classList.contains('active')).toBeFalse();
                }
              });
    });
  }));
});

Almost all of these give me the message: IndexComponent should show "A" route as active FAILED
Expected false to be true.

Through debugging, I can see that the tests are finding the elements with the RouterLinkActive directive, but the routing that is being done at the beginning of the test method doesn't seem to effect the routerLinkActive, so none of the elements are getting the 'active' class.

Is there a way to test the routerLinkActive elements inside of a standalone component?


问:
Plotly: How to plot a heat map from three lists: X, Y, Intensity
I have 3 lists say:
 x=[1,1,2,4,5,6,7,8,9] y=[11,12,13,14,15,16,17,18,19] intensity=[21,22,23,24,25,26,27,28,29]

the value of intensity is 21 at x=1 and y=11 and intensity is 22 at x=1 and y=12.

How to plot this using heat map in plotly express.


问:
How to get Editor value in Reactjs
I am working with React js and I am using Next js. Right now I am trying to get value of "Editor" but giving me following
error:

```<code>"TypeError: editor is null"
</code>```

Where i am wrong? How can i fix this? Below is my handleSubmit function.

```<code>const handleSubmit = async(e: any) => {
        e.preventDefault();
        let editor: any = null;

         <Editor
            onInit={(evt, ed) => {
              editor = ed;
              }}
            initialValue="<p>This is the initial content of the editor.</p>"
            init={{
              height: 500,
              menubar: false,
              plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code help wordcount'
              ],
              toolbar: 'undo redo | formatselect | ' +
              'bold italic backcolor | alignleft aligncenter ' +
              'alignright alignjustify | bullist numlist outdent indent | ' +
              'removeformat | help',
              content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
            }}
      />

       const content = editor.getContent();
        alert('content is ' + content);
};
 return (
    <>
 <form className="forms-sample" onSubmit={handleSubmit}>
        <Editor />
<button type="submit" className='btn btn-primary mr-2'>Submit </button>
);
</code>```

Title: How to get Editor value in Reactjs

Body:
I am working with React js and I am using Next js. Right now I am trying to get value of "Editor" but giving me following
error:

"TypeError: editor is null"

Where i am wrong? How can i fix this? Below is my handleSubmit function.

const handleSubmit = async(e: any) => {
        e.preventDefault();
        let editor: any = null;

         <Editor
            onInit={(evt, ed) => {
              editor = ed;
              }}
            initialValue="
This is the initial content of the editor.
"
            init={{
              height: 500,
              menubar: false,
              plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code help wordcount'
              ],
              toolbar: 'undo redo | formatselect | ' +
              'bold italic backcolor | alignleft aligncenter ' +
              'alignright alignjustify | bullist numlist outdent indent | ' +
              'removeformat | help',
              content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
            }}
      />

       const content = editor.getContent();
        alert('content is ' + content);
};
 return (
    <>
 <form className="forms-sample" onSubmit={handleSubmit}>
        <Editor />
<button type="submit" className='btn btn-primary mr-2'>Submit </button>
);


问:
Adding Product Quantity on wishlist in odoo
In odoo 15 On Website in product details there is a button to increase or decrease the product quantity, and after selecting the quantity, while pressing add to cart the same quantity will be passed to cart along with the product. I want to do that same functionality for wishlist also, on XML part already inhereted and added this to wishlist template

```<code><div class="css_quantity input-group d-inline-flex mr-2 my-1 align-middle">
    <div class="input-group-prepend">
        <a t-attf-href="#" class="btn btn-secondary js_add_cart_json" aria-label="Remove one" title="Remove one">
            <i class="fa fa-minus"></i>
        </a>
    </div>
    <input type="text" class="form-control quantity" data-min="1" name="add_qty" t-att-value="add_qty or 1"/>
    <div class="input-group-append">
        <a t-attf-href="#" class="btn btn-secondary float_left js_add_cart_json" aria-label="Add one" title="Add one">
            <i class="fa fa-plus"></i>
        </a>
    </div>
</div>
</code>```

but is visible the screen but while i increase a product quantity and add it to wishlist the quantity is not getting updated.

i have already gone through this link for reference for adding product quantity to wishlist but still i cannot pass it, if anybody can help will be much appreciated, Thanks

Body:
In odoo 15 On Website in product details there is a button to increase or decrease the product quantity, and after selecting the quantity, while pressing add to cart the same quantity will be passed to cart along with the product. I want to do that same functionality for wishlist also, on XML part already inhereted and added this to wishlist template

    <input type="text" class="form-control quantity" data-min="1" name="add_qty" t-att-value="add_qty or 1"/>

but is visible the screen but while i increase a product quantity and add it to wishlist the quantity is not getting updated.

i have already gone through this link for reference for adding product quantity to wishlist but still i cannot pass it, if anybody can help will be much appreciated, Thanks


问:
Firebase authentication mails go to spam folder every time
I have an app which is available on Google play store. My app uses firebase authenticator for email verification. But every time, the mails are going to spam folder. I can not use any paid verification service because my app does not support the api system.
Is there any solution to recover from this problem?

I did not find any solution of this problem. I am seeking for help.


问:
how do i make a co-occurence frequency table using DTM & co-occurnce matrix?
I am trying to make a co-occurence frequency table using DTM & co-occurence matrix

For example, I hope to find which word co-occur with the term 'juicy' including their words and frequencies as below table; so that the term 'juicy' was co-mentioned with orange 24 times; with lemon 23 times and so on.

| orange | 24 |
| lemon  | 23 |
| grape  | 22 |
| candy  | 20 |

I was able to create dtm with CountVectorizer as below.
and then transformed to matrix as below code

So I have both co-occurence matrix and DTM at my hand.

I would appreciate if I can get feedbacks to create co-occurence word frequencies.

Thanks in advance

```<code>count_vectorizer = CountVectorizer()
DTM = count_vectorizer.fit_transform(df_test['words'])
X = count_vectorizer.fit_transform(df_test['words'])
Xc = (X.T * X)
Xc.setdiag(0)
co_matrix = pd.DataFrame(data = Xc.toarray(), columns = names, index = names)

</code>```

Body:
I am trying to make a co-occurence frequency table using DTM & co-occurence matrix

For example, I hope to find which word co-occur with the term 'juicy' including their words and frequencies as below table; so that the term 'juicy' was co-mentioned with orange 24 times; with lemon 23 times and so on.

| orange | 24 |
| lemon  | 23 |
| grape  | 22 |
| candy  | 20 |

I was able to create dtm with CountVectorizer as below.
and then transformed to matrix as below code

So I have both co-occurence matrix and DTM at my hand.

I would appreciate if I can get feedbacks to create co-occurence word frequencies.

Thanks in advance

count_vectorizer = CountVectorizer()
DTM = count_vectorizer.fit_transform(df_test['words'])
X = count_vectorizer.fit_transform(df_test['words'])
Xc = (X.T * X)
Xc.setdiag(0)
co_matrix = pd.DataFrame(data = Xc.toarray(), columns = names, index = names)


问:
Pandas Styler conditional formatting ( red highlight) on last two rows of a dataframe based off column value
I have a dataframe that i am trying to format certain cell values/the row where the cell value != 0.  I am ONLY looking at rows 2 and 3 based off the index (the last two rows) so I only want the condition and formatting to apply to the last two rows. Ideally, i would only like to highlight a cell under the Findings column but highlighting the row also works.

i'd like to find a condition where if ID and name check findings are ever != 0, i want that row or even just the findings cell to be red to alert me that there is an issue with the data.

Is that possible to do? I am struggling to find a way to update the specific cell value or row to RED instead of a specific column?

```<code>The condition is like
if check == 'ID Check' and findings != 0:
 [code to make cell value/row red]
elif check == 'Name Check' and findings != 0:
  [code to make cell value/row red]
else [default color?]
</code>```

the data frame is built like this:

```<code>def record_count():
    with open('filename.csv', encoding='utf8') as file:
        record_number = len(list(file))
        print("Number of records on file:", record_number)
        return record_number

def user por_count():
    df = pd.read_csv(filename.csv', low_memory=False)
    user_number = df['users'].nunique()
    print("Number of users on file:", str(users))
    return users

def id_check():
    df = pd.read_csv('filename.csv', low_memory=False)
    missing_id = df["id"].isna().sum()
    print("Number of users missing an id:", missing_id)
    return missing_id

def name_check():
    df = pd.read_csv('filename.csv', low_memory=False)
    missing_name = derivs["name"].isna().sum()
    print("Number of users missing a name:", missing_name)
    return missing_name

checks_table = {
    'Check' : ['Record Check', 'ID Check', 'Name Check'],
    'Summary' : ['Number of records on file','Number of records missing an ID', 'Number of users missing a name'],
    'Findings' : [record_count(), id_check(), name_check()]
}

df_checks = pd.DataFrame.from_dict(checks_table)
df_checks.head()
</code>```

Body:
I have a dataframe that i am trying to format certain cell values/the row where the cell value != 0.  I am ONLY looking at rows 2 and 3 based off the index (the last two rows) so I only want the condition and formatting to apply to the last two rows. Ideally, i would only like to highlight a cell under the Findings column but highlighting the row also works.

i'd like to find a condition where if ID and name check findings are ever != 0, i want that row or even just the findings cell to be red to alert me that there is an issue with the data.

Is that possible to do? I am struggling to find a way to update the specific cell value or row to RED instead of a specific column?

The condition is like
if check == 'ID Check' and findings != 0:
 [code to make cell value/row red]
elif check == 'Name Check' and findings != 0:
  [code to make cell value/row red]
else [default color?]

the data frame is built like this:

def record_count():
    with open('filename.csv', encoding='utf8') as file:
        record_number = len(list(file))
        print("Number of records on file:", record_number)
        return record_number

def user por_count():
    df = pd.read_csv(filename.csv', low_memory=False)
    user_number = df['users'].nunique()
    print("Number of users on file:", str(users))
    return users

def id_check():
    df = pd.read_csv('filename.csv', low_memory=False)
    missing_id = df["id"].isna().sum()
    print("Number of users missing an id:", missing_id)
    return missing_id

def name_check():
    df = pd.read_csv('filename.csv', low_memory=False)
    missing_name = derivs["name"].isna().sum()
    print("Number of users missing a name:", missing_name)
    return missing_name

checks_table = {
    'Check' : ['Record Check', 'ID Check', 'Name Check'],
    'Summary' : ['Number of records on file','Number of records missing an ID', 'Number of users missing a name'],
    'Findings' : [record_count(), id_check(), name_check()]
}

df_checks = pd.DataFrame.from_dict(checks_table)
df_checks.head()


问:
ARCore cloud anchors multiple taps
I've been working on cloud anchors from the documentation, and it doesn't allow to place multiple markers. It just allows single tap.

I tried resolving all the anchors at once, but it's not staying persistently. The surface isn't allowing multiple anchors at a time.

Is there some way for placing multiple markers one by one and hosting it?

Title: ARCore cloud anchors multiple taps


问:
Create 5 column grid system using bootstrap
I am newbie to Bootstrap and trying to create the 5 column grid system similar to Exiger, But it's not showing exactly like left and right gap.

I tried with the below code.

```<code><div class="container" style="margin-top: 100px;">
    <div class="row">
        <div class="col-lg-4 col-sm-12 col-xs-12 col-md-12">
            <div class="row">
                <div class="col-lg-12 ">
                    <div class="card">
                        <div class="card-body ">
                            <h5 class="card-title">IT'S ALL ABOUT THE HOW</h5>
                            <hr class="hrmargin_b_10">
                            <h5 class="card-title">IT'S ALL ABOUT THE HOW</h5>
                            <hr class="hrmargin_b_10">
                            <p class="card-text">

                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4 col-sm-12 col-xs-12 col-md-12" style="text-align: center;">
            <div class="row">
                <div class="col-lg-6 col-sm-12 col-xs-12 col-md-6 row_border" style="padding-left: 10px;
    padding-top: 40px;
    padding-right: 10px;
    padding-bottom: 30px;
    min-height: 260px;
    max-height: 260px;" >

                    <div class="card-body menuo-no-borders">
                        <img src="./images/exiger/3rd_part_risk@2x.gif" style="width:70px;height: 70px;">
                        <h5 class="card-title">CMMC Level 1</h5>
                        <p class="card-text" style="display: none;">

                        </p>
                    </div>

                </div>
                <div class="col-lg-6 col-sm-12 col-xs-12 col-md-6 row_border" style="padding-left: 10px;
    padding-top: 40px;
    padding-right: 10px;
    padding-bottom: 30px;
    min-height: 260px;
    max-height: 260px;"  >

                    <div class="card-body menuo-no-borders align-content-center">
                        <img src="./images/exiger/3rd_part_risk@2x.gif"  style="width:70px;height: 70px;">
                        <h5 class="card-title">CMMC Level 2</h5>
                        <p class="card-text" style="display: none;">

                        </p>
                    </div>

                </div>
            </div>
        </div>
        <div class="col-lg-4 col-sm-12 col-xs-12 col-md-12" style="text-align: center;">
            <div class="row">

                <div class="col-lg-6 col-sm-12 col-xs-12 col-md-6 row_border"  style="padding-left: 10px;
    padding-top: 40px;
    padding-right: 10px;
    padding-bottom: 30px;
    min-height: 260px;
    max-height: 260px;" >

                    <div class="card-body menuo-no-borders">
                        <img src="./images/exiger/3rd_part_risk@2x.gif" style="width:70px;height: 70px;">
                        <h5 class="card-title">CMMC Level 1</h5>
                        <p class="card-text" style="display: none;">

                        </p>
                    </div>

                </div>
                <div class="col-lg-6 col-sm-12 col-xs-12 col-md-6 row_border"  style="padding-left: 10px;
    padding-top: 40px;
    padding-right: 10px;
    padding-bottom: 30px;
    min-height: 260px;
    max-height: 260px;" >

                    <div class="card-body menuo-no-borders align-content-center">
                        <img src="./images/exiger/3rd_part_risk@2x.gif"  style="width:70px;height: 70px;">
                        <h5 class="card-title">CMMC Level 2</h5>
                        <p class="card-text" style="display: none;">

                        </p>
                    </div>

                </div>

            </div>
        </div>

    </div>
</div>
</code>```

and the result is below picture. I am trying to set the borders to the left and right of the boxes but it's not working properly.

Any help on this?

Body:
I am newbie to Bootstrap and trying to create the 5 column grid system similar to Exiger, But it's not showing exactly like left and right gap.

I tried with the below code.

IT'S ALL ABOUT THE HOW

IT'S ALL ABOUT THE HOW

CMMC Level 1

CMMC Level 2

CMMC Level 1

CMMC Level 2

and the result is below picture. I am trying to set the borders to the left and right of the boxes but it's not working properly.

Any help on this?


问:
Spring Boot & HikariCP - When lost db connection
I am currently running a web service using Spring boot, HikariCP, and MySQL database.

The database needs to be replaced due to a recent issue. The database address will not change, but the physical database connected to that address will change.

At this time, the DB connection will be disconnected from the Spring boot application during the database replacement. After the database replacement is completed, should the Spring boot application be restarted to properly reflect the DB?

Or, is there a way to automatically reconnect in the Spring boot application after the DB replacement is complete using HikariCP?
Example) Using specific options of HikariCP, etc.

Address and connection information before and after database replacement are the same. For applications, the impact of restarting the database server is expected to be the same.

[Main Question]
Is there a way to automatically reconnect in the Spring boot application after the DB replacement is complete using HikariCP?
Example) Using specific options of HikariCP, etc.


问:
Test cases to cover Arc.container().instance()
I am trying create an object of the given class but am not able to cover the Arc.container().instance() lines. Could you please check what I am missing here. The code is given below;

```<code>/**
 * Track Tag handler
 */
@Slf4j
@ApplicationScoped
@Unremovable
@SuppressWarnings({
        "checkstyle:BooleanExpressionComplexity",
        "PMD.ExcessiveClassLength",
        "PMD.ExcessiveImports",
        "PMD.GodClass",
        "PMD.TooManyMethods"
})
public class TrackTagHandler implements TrackTagEventHandler
{
    /**
     * Tag service to handle business logic
     */
    private final TagBusinessService tagBusinessService;

    /**
     * Number pool for generating new tag id
     */
    private final NumberPoolService numberPoolService;

    /**
     * Topology data service for retrieving device entities
     */
    private final TopologyLookupService topologyLookupService;

    /**
     * Device management gram service for creating device state request gram
     */
    private final DeviceManagementService deviceManagementService;

    /**
     * Track handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagTrackProvider trackTagTrackProvider;

    /**
     * Switch handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagSwitchProvider trackTagSwitchProvider;

    /**
     * Roadway Worker & Blue Signal handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagRoadwayBlueSignalProvider trackTagRoadwayBlueSignalProvider;

    /**
     * On Station handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagOSProvider trackTagOSProvider;

    /**
     * Signal handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagSignalProvider trackTagSignalProvider;

    /**
     * Misc. Device handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagMiscDeviceProvider trackTagMiscDeviceProvider;

    /**
     * TrackTagHandler constructor<br>
     * Use constructor injection to get the required services
     *
     * @param trackTagTrackProvider Track handler for returning the track-tag form
     * @param trackTagSwitchProvider Switch handler for returning the track-tag form
     * @param trackTagRoadwayBlueSignalProvider Roadway Worker & Blue Signal handler for returning the track-tag form
     * @param trackTagOSProvider On Station handler for returning the track-tag form
     * @param trackTagSignalProvider Signal handler for returning the track-tag form
     * @param trackTagMiscDeviceProvider Misc. Device handler for returning the track-tag form
     */
    @Inject
    public TrackTagHandler(
            final TrackTagTrackProvider trackTagTrackProvider,
            final TrackTagSwitchProvider trackTagSwitchProvider,
            final TrackTagRoadwayBlueSignalProvider trackTagRoadwayBlueSignalProvider,
            final TrackTagOSProvider trackTagOSProvider,
            final TrackTagSignalProvider trackTagSignalProvider,
            final TrackTagMiscDeviceProvider trackTagMiscDeviceProvider)
    {
        this.trackTagTrackProvider = trackTagTrackProvider;
        this.trackTagSwitchProvider = trackTagSwitchProvider;
        this.trackTagRoadwayBlueSignalProvider = trackTagRoadwayBlueSignalProvider;
        this.trackTagOSProvider = trackTagOSProvider;
        this.trackTagSignalProvider = trackTagSignalProvider;
        this.trackTagMiscDeviceProvider = trackTagMiscDeviceProvider;
        this.tagBusinessService = Arc.container().instance(TagBusinessService.class).get();
        this.numberPoolService = Arc.container().instance(NumberPoolService.class).get();
        this.topologyLookupService = Arc.container().instance(TopologyLookupService.class).get();
        this.deviceManagementService = Arc.container().instance(DeviceManagementService.class).get();
    }

    /**
     * Handle event requesting
     */
    @Override
    @SuppressWarnings({
            "PMD.ExcessiveMethodLength", "PMD.CyclomaticComplexity"
    })
    public TagEventContext handleEvent(final TagEventContext event)
    {
        event.setRequestInfo(event.getEvent().getBinding());
        final RequestInfo requestInfo = event.getRequestInfo();

        if (Optional.ofNullable(requestInfo).isEmpty())
        {
            throw new BadRequestException(MessageConstants.INVALID_REQUEST);
        }

        log.info("Calling track tag event handler for {}", event.getEvent());

        switch (event.getEvent())
        {
        case Read:
            final TagInfo tagInfo = getActiveTag(requestInfo.getTagId());
            event.setTrackTag(setToTrackTag(tagInfo, event));
            break;
        case Pending:
            // Set initials
            final String dispatcherInitials =
                    event.getProperties().get(InitializeProperty.rtcInitials.getBinding()).toString();
            final PendingRequestInfo pendingRequestInfo = PendingRequestInfo.builder()
                .deviceIds(requestInfo.getDeviceIds())
                .logicalPosition(requestInfo.getLogicalPosition())
                .userId(requestInfo.getUserId())
                .deviceType(requestInfo.getDeviceType())
                .tagType(requestInfo.getTagType())
                .build();
            event.setTrackTag(createPendingTag(pendingRequestInfo, dispatcherInitials, event));
            break;
        case Update:
            final UpdateRequestInfo updateRequestInfo = UpdateRequestInfo.builder()
                .comments(requestInfo.getComments())
                .estimatedRemovalTime(requestInfo.getEstimatedRemovalTime())
                .logicalPosition(requestInfo.getLogicalPosition())
                .name(requestInfo.getName())
                .pseudo(requestInfo.isPseudo())
                .tagId(requestInfo.getTagId())
                .timeZone(requestInfo.getTimeZone())
                .userId(requestInfo.getUserId())
                .build();
            final TagData tagData = getTagData(requestInfo.getTagId());
            if (tagData.getCurrentTagInfo().getStatus() == TagStatus.PENDING)
            {
                createActiveTag(updateRequestInfo, event);
            }
            else
            {
                updateTag(updateRequestInfo, event);
            }
            break;
        case Remove:
            final DeleteRequestInfo deleteRequestInfo = DeleteRequestInfo.builder()
                .comments(requestInfo.getComments())
                .logicalPosition(requestInfo.getLogicalPosition())
                .tagId(requestInfo.getTagId())
                .userId(requestInfo.getUserId())
                .build();
            deleteTag(deleteRequestInfo, event);
            break;
        case RemovalComments:
            final UpdateDeleteRequestInfo updateDeleteRequestInfo = UpdateDeleteRequestInfo.builder()
                .action(requestInfo.getAction())
                .removalComments(requestInfo.getRemovalComments())
                .tagId(requestInfo.getTagId())
                .build();
            updateRemovalCommentsToDeleteTag(updateDeleteRequestInfo, event);
            break;
        case Reset:
            final TagInfo resetTagInfo = resetTag(requestInfo.getTagId(), event);
            event.setTrackTag(setToTrackTag(resetTagInfo, event));
            break;
        case Cancel:
            cancelTag(requestInfo.getTagId(), event);
            break;
        case DeviceRecord:
            final DeviceUpdateRequestInfo deviceUpdateRequestInfo = DeviceUpdateRequestInfo.builder()
                .deviceAction(requestInfo.getDeviceAction())
                .logicalPosition(requestInfo.getLogicalPosition())
                .recordId(requestInfo.getRecordId())
                .userId(requestInfo.getUserId())
                .build();
            updateDeviceRecord(deviceUpdateRequestInfo);
            break;
        case TagTypeChange:
            final TagTypeUpdateRequestInfo tagTypeUpdateRequestInfo = TagTypeUpdateRequestInfo.builder()
                .logicalPosition(requestInfo.getLogicalPosition())
                .tagId(requestInfo.getTagId())
                .deviceType(requestInfo.getDeviceType())
                .tagType(requestInfo.getTagType())
                .userId(requestInfo.getUserId())
                .build();
            final TagInfo modifiedTagInfo = updateTagType(tagTypeUpdateRequestInfo);
            event.setTrackTag(setToTrackTag(modifiedTagInfo, event));
            break;
        default:
        }

        return event;
    }
}
</code>```

TrackTagEvent

```<code>/**
 * Track Tag form events with handlers
 */
public enum TrackTagEvent implements DynamicFormEvent<TagEventContext>
{
    /** **/
    Read
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Pending
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Update
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Remove
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    RemovalComments
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Reset
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Cancel
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    DeviceRecord
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    TagTypeChange
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    };

    /** The binding value */
    @Getter
    private final String binding;

    /** Constructor to set binding to property name */
    TrackTagEvent()
    {
        this.binding = name();
    }

    /** Constructor to set binding to given value */
    TrackTagEvent(final String binding)
    {
        this.binding = binding;
    }
}

</code>```

TagEventContext

```<code>/**
 * Track Tag Event
 */
@Slf4j
@Data
@NoArgsConstructor
public class TagEventContext implements TrackTagEventContext<TrackTag>
{
    /**
     * Serializable
     */
    private static final long serialVersionUID = 1L;

    /**
     * Id
     */
    private long id;

    /**
     * Form id
     */
    private String formId;

    /**
     * Form version
     */
    private String version;

    /**
     * Event
     */
    private TrackTagEvent event;

    /**
     * Control list
     */
    private List<ControlListItem> controlList;

    /**
     * Properties
     */
    private Map<String, Object> properties;

    /**
     * Dynamic Form update
     */
    private DynamicForm dynamicForm;

    /**
     * Feedback
     */
    private Feedback feedback;

    /**
     * The Track Tag Information
     */
    @JsonIgnore
    private TrackTag trackTag;

    /**
     * Request Information
     */
    @JsonIgnore
    private RequestInfo requestInfo;

    /**
     * The publish type
     */
    @JsonIgnore
    private PublishType publishType = PublishType.NO_PUBLISH;

    /**
     * Set dynamic form and copy required fields to context
     */
    @Override
    public void setDynamicForm(final DynamicForm form)
    {
        this.dynamicForm = form;
        if (form != null && form.getMetadata() != null)
        {
            this.formId = form.getMetadata().getFormId();
            this.version = Integer.toString(form.getVersion());
        }
    }

    /**
     * Update control list
     */
    @Override
    public List<ControlListItem> updateControlListFromTrackTag()
    {
        if (trackTag == null)
        {
            log.debug("No tag specified");
            return controlList;
        }

        id = trackTag.getTagId();

        updateControlListWithDefaultValues();

        return controlList;
    }

    /**
     * Get RequestInfo object from properties based on request
     */
    private RequestInfo fetchRequestInfo(final String request)
    {
        final ObjectMapper mapper = new ObjectMapper();
        try
        {
            mapper.registerModule(new JavaTimeModule());
            final String jsonValue = mapper.writeValueAsString(( properties.get(request) ));
            return mapper.readValue(jsonValue, RequestInfo.class);
        }
        catch (final JsonProcessingException ex)
        {
            log.error(ex.getMessage());
            return null;
        }
    }

    /**
     * Set RequestInfo object to context
     */
    public void setRequestInfo(final String request)
    {
        final RequestInfo info = fetchRequestInfo(request);
        this.requestInfo = info;
    }
}

</code>```

After covering the costructor, I am supposed to cover the handleEvent() method. But am stuck at the initial place only.

I tried writing few testcases, but unable to understand how to cover that Arc.container().instance(). Below is what I have tried so far;

```<code>class TrackTagHandlerTest
{
    final ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

      @Inject TrackTagHandler trackTagHandler;

      @Inject TrackTagProvider trackTagProvider;

      @Inject TrackTagSwitchProvider trackTagSwitchProvider;

      @Inject TrackTagRoadwayBlueSignalProvider trackTagRoadwayBlueSignalProvider;

      @Inject TrackTagOSProvider trackTagOSProvider;

      @Inject TrackTagSignalProvider trackTagSignalProvider;

      @Inject TrackTagMiscDeviceProvider trackTagMiscDeviceProvider;

      @Inject TagBusinessService tagBusinessService;

    @Test
    void testTrackTagHandleEvent() throws IOException
    {
        InputData request = mapper
            .readValue(Thread.currentThread().getContextClassLoader().getResource("request.json"), InputData.class);

        TrackTagTrackProvider trackTagProvider = new TrackTagTrackProvider();
        TagEventContext context = trackTagProvider.createEvent(TrackTagEvent.Read, request);
        context.setDynamicForm(new DynamicForm());
        context.setFeedback(new Feedback());
        assertNotNull(context.getProperties());

        TrackTagHandler th = new TrackTagHandler(trackTagProvider, trackTagSwitchProvider, trackTagRoadwayBlueSignalProvider, trackTagOSProvider, trackTagSignalProvider, trackTagMiscDeviceProvider);

        TagEventContext returnContext = TrackTagEvent.Read.handleEvent(context);
    }
}

</code>```

Body:
I am trying create an object of the given class but am not able to cover the Arc.container().instance() lines. Could you please check what I am missing here. The code is given below;

/**
 * Track Tag handler
 */
@Slf4j
@ApplicationScoped
@Unremovable
@SuppressWarnings({
        "checkstyle:BooleanExpressionComplexity",
        "PMD.ExcessiveClassLength",
        "PMD.ExcessiveImports",
        "PMD.GodClass",
        "PMD.TooManyMethods"
})
public class TrackTagHandler implements TrackTagEventHandler
{
    /**
     * Tag service to handle business logic
     */
    private final TagBusinessService tagBusinessService;

    /**
     * Number pool for generating new tag id
     */
    private final NumberPoolService numberPoolService;

    /**
     * Topology data service for retrieving device entities
     */
    private final TopologyLookupService topologyLookupService;

    /**
     * Device management gram service for creating device state request gram
     */
    private final DeviceManagementService deviceManagementService;

    /**
     * Track handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagTrackProvider trackTagTrackProvider;

    /**
     * Switch handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagSwitchProvider trackTagSwitchProvider;

    /**
     * Roadway Worker & Blue Signal handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagRoadwayBlueSignalProvider trackTagRoadwayBlueSignalProvider;

    /**
     * On Station handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagOSProvider trackTagOSProvider;

    /**
     * Signal handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagSignalProvider trackTagSignalProvider;

    /**
     * Misc. Device handler for returning the track-tag form
     */
    @SuppressWarnings("checkstyle:VisibilityModifier")
    TrackTagMiscDeviceProvider trackTagMiscDeviceProvider;

    /**
     * TrackTagHandler constructor

     * Use constructor injection to get the required services
     *
     * @param trackTagTrackProvider Track handler for returning the track-tag form
     * @param trackTagSwitchProvider Switch handler for returning the track-tag form
     * @param trackTagRoadwayBlueSignalProvider Roadway Worker & Blue Signal handler for returning the track-tag form
     * @param trackTagOSProvider On Station handler for returning the track-tag form
     * @param trackTagSignalProvider Signal handler for returning the track-tag form
     * @param trackTagMiscDeviceProvider Misc. Device handler for returning the track-tag form
     */
    @Inject
    public TrackTagHandler(
            final TrackTagTrackProvider trackTagTrackProvider,
            final TrackTagSwitchProvider trackTagSwitchProvider,
            final TrackTagRoadwayBlueSignalProvider trackTagRoadwayBlueSignalProvider,
            final TrackTagOSProvider trackTagOSProvider,
            final TrackTagSignalProvider trackTagSignalProvider,
            final TrackTagMiscDeviceProvider trackTagMiscDeviceProvider)
    {
        this.trackTagTrackProvider = trackTagTrackProvider;
        this.trackTagSwitchProvider = trackTagSwitchProvider;
        this.trackTagRoadwayBlueSignalProvider = trackTagRoadwayBlueSignalProvider;
        this.trackTagOSProvider = trackTagOSProvider;
        this.trackTagSignalProvider = trackTagSignalProvider;
        this.trackTagMiscDeviceProvider = trackTagMiscDeviceProvider;
        this.tagBusinessService = Arc.container().instance(TagBusinessService.class).get();
        this.numberPoolService = Arc.container().instance(NumberPoolService.class).get();
        this.topologyLookupService = Arc.container().instance(TopologyLookupService.class).get();
        this.deviceManagementService = Arc.container().instance(DeviceManagementService.class).get();
    }

    /**
     * Handle event requesting
     */
    @Override
    @SuppressWarnings({
            "PMD.ExcessiveMethodLength", "PMD.CyclomaticComplexity"
    })
    public TagEventContext handleEvent(final TagEventContext event)
    {
        event.setRequestInfo(event.getEvent().getBinding());
        final RequestInfo requestInfo = event.getRequestInfo();

        if (Optional.ofNullable(requestInfo).isEmpty())
        {
            throw new BadRequestException(MessageConstants.INVALID_REQUEST);
        }

        log.info("Calling track tag event handler for {}", event.getEvent());

        switch (event.getEvent())
        {
        case Read:
            final TagInfo tagInfo = getActiveTag(requestInfo.getTagId());
            event.setTrackTag(setToTrackTag(tagInfo, event));
            break;
        case Pending:
            // Set initials
            final String dispatcherInitials =
                    event.getProperties().get(InitializeProperty.rtcInitials.getBinding()).toString();
            final PendingRequestInfo pendingRequestInfo = PendingRequestInfo.builder()
                .deviceIds(requestInfo.getDeviceIds())
                .logicalPosition(requestInfo.getLogicalPosition())
                .userId(requestInfo.getUserId())
                .deviceType(requestInfo.getDeviceType())
                .tagType(requestInfo.getTagType())
                .build();
            event.setTrackTag(createPendingTag(pendingRequestInfo, dispatcherInitials, event));
            break;
        case Update:
            final UpdateRequestInfo updateRequestInfo = UpdateRequestInfo.builder()
                .comments(requestInfo.getComments())
                .estimatedRemovalTime(requestInfo.getEstimatedRemovalTime())
                .logicalPosition(requestInfo.getLogicalPosition())
                .name(requestInfo.getName())
                .pseudo(requestInfo.isPseudo())
                .tagId(requestInfo.getTagId())
                .timeZone(requestInfo.getTimeZone())
                .userId(requestInfo.getUserId())
                .build();
            final TagData tagData = getTagData(requestInfo.getTagId());
            if (tagData.getCurrentTagInfo().getStatus() == TagStatus.PENDING)
            {
                createActiveTag(updateRequestInfo, event);
            }
            else
            {
                updateTag(updateRequestInfo, event);
            }
            break;
        case Remove:
            final DeleteRequestInfo deleteRequestInfo = DeleteRequestInfo.builder()
                .comments(requestInfo.getComments())
                .logicalPosition(requestInfo.getLogicalPosition())
                .tagId(requestInfo.getTagId())
                .userId(requestInfo.getUserId())
                .build();
            deleteTag(deleteRequestInfo, event);
            break;
        case RemovalComments:
            final UpdateDeleteRequestInfo updateDeleteRequestInfo = UpdateDeleteRequestInfo.builder()
                .action(requestInfo.getAction())
                .removalComments(requestInfo.getRemovalComments())
                .tagId(requestInfo.getTagId())
                .build();
            updateRemovalCommentsToDeleteTag(updateDeleteRequestInfo, event);
            break;
        case Reset:
            final TagInfo resetTagInfo = resetTag(requestInfo.getTagId(), event);
            event.setTrackTag(setToTrackTag(resetTagInfo, event));
            break;
        case Cancel:
            cancelTag(requestInfo.getTagId(), event);
            break;
        case DeviceRecord:
            final DeviceUpdateRequestInfo deviceUpdateRequestInfo = DeviceUpdateRequestInfo.builder()
                .deviceAction(requestInfo.getDeviceAction())
                .logicalPosition(requestInfo.getLogicalPosition())
                .recordId(requestInfo.getRecordId())
                .userId(requestInfo.getUserId())
                .build();
            updateDeviceRecord(deviceUpdateRequestInfo);
            break;
        case TagTypeChange:
            final TagTypeUpdateRequestInfo tagTypeUpdateRequestInfo = TagTypeUpdateRequestInfo.builder()
                .logicalPosition(requestInfo.getLogicalPosition())
                .tagId(requestInfo.getTagId())
                .deviceType(requestInfo.getDeviceType())
                .tagType(requestInfo.getTagType())
                .userId(requestInfo.getUserId())
                .build();
            final TagInfo modifiedTagInfo = updateTagType(tagTypeUpdateRequestInfo);
            event.setTrackTag(setToTrackTag(modifiedTagInfo, event));
            break;
        default:
        }

        return event;
    }
}

TrackTagEvent

/**
 * Track Tag form events with handlers
 */
public enum TrackTagEvent implements DynamicFormEvent<TagEventContext>
{
    /** **/
    Read
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Pending
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Update
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Remove
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    RemovalComments
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Reset
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    Cancel
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    DeviceRecord
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    },
    /** **/
    TagTypeChange
    {
        @Override
        public TagEventContext handleEvent(final TagEventContext event)
        {
            return Arc.container().instance(TrackTagHandler.class).get().handleEvent(event);
        }
    };

    /** The binding value */
    @Getter
    private final String binding;

    /** Constructor to set binding to property name */
    TrackTagEvent()
    {
        this.binding = name();
    }

    /** Constructor to set binding to given value */
    TrackTagEvent(final String binding)
    {
        this.binding = binding;
    }
}

TagEventContext

/**
 * Track Tag Event
 */
@Slf4j
@Data
@NoArgsConstructor
public class TagEventContext implements TrackTagEventContext<TrackTag>
{
    /**
     * Serializable
     */
    private static final long serialVersionUID = 1L;

    /**
     * Id
     */
    private long id;

    /**
     * Form id
     */
    private String formId;

    /**
     * Form version
     */
    private String version;

    /**
     * Event
     */
    private TrackTagEvent event;

    /**
     * Control list
     */
    private List<ControlListItem> controlList;

    /**
     * Properties
     */
    private Map<String, Object> properties;

    /**
     * Dynamic Form update
     */
    private DynamicForm dynamicForm;

    /**
     * Feedback
     */
    private Feedback feedback;

    /**
     * The Track Tag Information
     */
    @JsonIgnore
    private TrackTag trackTag;

    /**
     * Request Information
     */
    @JsonIgnore
    private RequestInfo requestInfo;

    /**
     * The publish type
     */
    @JsonIgnore
    private PublishType publishType = PublishType.NO_PUBLISH;

    /**
     * Set dynamic form and copy required fields to context
     */
    @Override
    public void setDynamicForm(final DynamicForm form)
    {
        this.dynamicForm = form;
        if (form != null && form.getMetadata() != null)
        {
            this.formId = form.getMetadata().getFormId();
            this.version = Integer.toString(form.getVersion());
        }
    }

    /**
     * Update control list
     */
    @Override
    public List<ControlListItem> updateControlListFromTrackTag()
    {
        if (trackTag == null)
        {
            log.debug("No tag specified");
            return controlList;
        }

        id = trackTag.getTagId();

        updateControlListWithDefaultValues();

        return controlList;
    }

    /**
     * Get RequestInfo object from properties based on request
     */
    private RequestInfo fetchRequestInfo(final String request)
    {
        final ObjectMapper mapper = new ObjectMapper();
        try
        {
            mapper.registerModule(new JavaTimeModule());
            final String jsonValue = mapper.writeValueAsString(( properties.get(request) ));
            return mapper.readValue(jsonValue, RequestInfo.class);
        }
        catch (final JsonProcessingException ex)
        {
            log.error(ex.getMessage());
            return null;
        }
    }

    /**
     * Set RequestInfo object to context
     */
    public void setRequestInfo(final String request)
    {
        final RequestInfo info = fetchRequestInfo(request);
        this.requestInfo = info;
    }
}

After covering the costructor, I am supposed to cover the handleEvent() method. But am stuck at the initial place only.

I tried writing few testcases, but unable to understand how to cover that Arc.container().instance(). Below is what I have tried so far;

class TrackTagHandlerTest
{
    final ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

      @Inject TrackTagHandler trackTagHandler;

      @Inject TrackTagProvider trackTagProvider;

      @Inject TrackTagSwitchProvider trackTagSwitchProvider;

      @Inject TrackTagRoadwayBlueSignalProvider trackTagRoadwayBlueSignalProvider;

      @Inject TrackTagOSProvider trackTagOSProvider;

      @Inject TrackTagSignalProvider trackTagSignalProvider;

      @Inject TrackTagMiscDeviceProvider trackTagMiscDeviceProvider;

      @Inject TagBusinessService tagBusinessService;

    @Test
    void testTrackTagHandleEvent() throws IOException
    {
        InputData request = mapper
            .readValue(Thread.currentThread().getContextClassLoader().getResource("request.json"), InputData.class);

        TrackTagTrackProvider trackTagProvider = new TrackTagTrackProvider();
        TagEventContext context = trackTagProvider.createEvent(TrackTagEvent.Read, request);
        context.setDynamicForm(new DynamicForm());
        context.setFeedback(new Feedback());
        assertNotNull(context.getProperties());

        TrackTagHandler th = new TrackTagHandler(trackTagProvider, trackTagSwitchProvider, trackTagRoadwayBlueSignalProvider, trackTagOSProvider, trackTagSignalProvider, trackTagMiscDeviceProvider);

        TagEventContext returnContext = TrackTagEvent.Read.handleEvent(context);
    }
}


问:
Java: The import de could not be resolved
I am trying to run the code from the github repository of UNLT

It is throwing an error in import de.tud.kom.stringmatching.gst.GST; that The import de could not be resolved

How can I handle this issue?

Click to see the screenshot

I am running following JDK settings.

openjdk version "17.0.5" 2022-10-18 OpenJDK Runtime Environment Temurin-17.0.5+8 (build 17.0.5+8) OpenJDK 64-Bit Server VM Temurin-17.0.5+8 (build 17.0.5+8, mixed mode, sharing)


问:
Efficient flow graph algorithm that routes its flow more evenly
This problem I recently came back to after putting it on a backburner for a while - and that's the one of trying to create a program to calculate the flow rates of some kind of resource through a network of pipes from resource sources to resource sinks, each of which can only pass so much resource per unit of time. This is, of course, a classic problem called the "network flow problem", and in particular the typical aim is to find a flow pattern that maximizes the flow going from the sources to the sinks. And I made a program that uses a common algorithm called the Ford-Fulkerson Max-Flow Method to do this, but I found that while this algorithm certainly does a nice job at finding a flow solution, it doesn't necessarily do a good job at making one that is particularly "natural" in terms of the flow pattern.

That is to say, consider a graph like the one below.

```<code>                ------------- SINK 1
         0 / 8  |  0 / 5
SOURCE ---------X
                |  0 / 5
                ------------- SINK 2
</code>```

where the numbers represent the current flow rate on that particular edge or "pipe", here in "units" per second, versus the maximum flow the pipe can support, the "X" is a junction node, and the other labels should be self-explanatory.

When we solve this using F-F (which requires us to temporarily add an "aggregate sink" node that ties the two sinks on the right together), we find the max flow rate is indeed 8 U/s, which should be obvious just from simple inspection for such a simple graph. However, the flow pattern it gives may look something like either

```<code>                ------------- SINK 1
         8 / 8  |  5 / 5
SOURCE ---------X
                |  3 / 5
                ------------- SINK 2
</code>```

or

```<code>                ------------- SINK 1
         8 / 8  |  3 / 5
SOURCE ---------X
                |  5 / 5
                ------------- SINK 2
</code>```

depending on the order on which it encounters the edges during the depth-first walk used in the calculation. Trouble is, not only is that behavior itself not ideal, that flow doesn't "feel natural" in a certain sense. Intuitively, if we were imagining pushing a fluid, we'd expect 4 U/s of flow to go to sink 1 and another 4 to go to sink 2 by symmetry. Indeed, if we actually shrink the capacity of the edge leading out of the source to 5, the Ford-Fulkerson algorithm will starve one sink entirely, and that is also a behavior I'd like to avoid - if there's not enough flow to keep everybody as happy as they'd like to be, then at least try to distribute it as evenly as possible. In this case, that'd mean that if the max flow is, say, as here, 80% of the flow needed to fully satiate all the sinks, then 80% should go to each sink, unless there's a constriction somewhere in the graph that prevents sending even that much to that sink, in which case excess flow should back up and go to the other sinks while that one still gets the maximum it can get.

So my question is, what sort of algorithms would have either this behavior or a behavior similar to it? Or, to put it another way, if F-F is a good tool to just find a maximum flow, what is a good tool for tailoring the pattern of that maximum flow to some "desirable" form like this?

One simple solution I thought of is to just repeatedly apply F-F, only instead of routing from the source to the fictitious aggregate sink, apply it from the source to each individual sink, thus giving the max flow that is capable of making it through the constrictions, then work out from that how much each sink can actually get fed based on its demand and the whole-graph max flow. Trouble is, that means running the algorithm as many times as there are sinks, so the Big-O goes up, perhaps too much. Is there a more efficient way to achieve this?

Body:
This problem I recently came back to after putting it on a backburner for a while - and that's the one of trying to create a program to calculate the flow rates of some kind of resource through a network of pipes from resource sources to resource sinks, each of which can only pass so much resource per unit of time. This is, of course, a classic problem called the "network flow problem", and in particular the typical aim is to find a flow pattern that maximizes the flow going from the sources to the sinks. And I made a program that uses a common algorithm called the Ford-Fulkerson Max-Flow Method to do this, but I found that while this algorithm certainly does a nice job at finding a flow solution, it doesn't necessarily do a good job at making one that is particularly "natural" in terms of the flow pattern.

That is to say, consider a graph like the one below.

                ------------- SINK 1
         0 / 8  |  0 / 5
SOURCE ---------X
                |  0 / 5
                ------------- SINK 2

where the numbers represent the current flow rate on that particular edge or "pipe", here in "units" per second, versus the maximum flow the pipe can support, the "X" is a junction node, and the other labels should be self-explanatory.

When we solve this using F-F (which requires us to temporarily add an "aggregate sink" node that ties the two sinks on the right together), we find the max flow rate is indeed 8 U/s, which should be obvious just from simple inspection for such a simple graph. However, the flow pattern it gives may look something like either

                ------------- SINK 1
         8 / 8  |  5 / 5
SOURCE ---------X
                |  3 / 5
                ------------- SINK 2

or

                ------------- SINK 1
         8 / 8  |  3 / 5
SOURCE ---------X
                |  5 / 5
                ------------- SINK 2

depending on the order on which it encounters the edges during the depth-first walk used in the calculation. Trouble is, not only is that behavior itself not ideal, that flow doesn't "feel natural" in a certain sense. Intuitively, if we were imagining pushing a fluid, we'd expect 4 U/s of flow to go to sink 1 and another 4 to go to sink 2 by symmetry. Indeed, if we actually shrink the capacity of the edge leading out of the source to 5, the Ford-Fulkerson algorithm will starve one sink entirely, and that is also a behavior I'd like to avoid - if there's not enough flow to keep everybody as happy as they'd like to be, then at least try to distribute it as evenly as possible. In this case, that'd mean that if the max flow is, say, as here, 80% of the flow needed to fully satiate all the sinks, then 80% should go to each sink, unless there's a constriction somewhere in the graph that prevents sending even that much to that sink, in which case excess flow should back up and go to the other sinks while that one still gets the maximum it can get.

So my question is, what sort of algorithms would have either this behavior or a behavior similar to it? Or, to put it another way, if F-F is a good tool to just find a maximum flow, what is a good tool for tailoring the pattern of that maximum flow to some "desirable" form like this?

One simple solution I thought of is to just repeatedly apply F-F, only instead of routing from the source to the fictitious aggregate sink, apply it from the source to each individual sink, thus giving the max flow that is capable of making it through the constrictions, then work out from that how much each sink can actually get fed based on its demand and the whole-graph max flow. Trouble is, that means running the algorithm as many times as there are sinks, so the Big-O goes up, perhaps too much. Is there a more efficient way to achieve this?


问:
How to solve simultaneous equations without using any packages
I'm trying to solve a 3x3 matrix using cramer's rule and as I'm new to python I'm finding it difficult to figure out my answer alone I've been doing research on how to do it using different methods but I've came to a stop near the end of it.  The reason on why that it has to be with no packages is because I have to do it for homework and I have to find out for every possible matrix I've altered the one I originally had to try and find every matrix but since I'm still learning python it hasn't gone to plan

```<code>
``
# determinant of Matrix
def determinantOfMatrix(mat):
    ans = (mat[0][0] * mat[1][1] * mat[2][2] +
           (mat[0][1] * mat[1][2] * mat[2][0])
           + (mat[0][2] * mat[1][0] * mat[2][1] -
              (mat[0][2] * mat[1][1] * mat[2][0]
               + mat[0][0] * mat[1][2] * mat[2][1] +
               mat[0][1] * (mat[1][0] * mat[2][2]))))
    return ans

# linear equations using cramer's rule
def findSolution(coeff):
    # Matrix d

    d = [[coeff[0][0], coeff[0][1], coeff[0][2]],
         [coeff[1][0], coeff[1][1], coeff[1][2]],
         [coeff[2][0], coeff[2][1], coeff[2][2]]]

    # Matrix d1 using coeff as given in
    # cramer's rule
    d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]],
          [coeff[1][3], coeff[1][1], coeff[1][2]],
          [coeff[2][3], coeff[2][1], coeff[2][2]]]

    # Matrix d2 using coeff as given in
    # cramer's rule
    d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]],
          [coeff[1][0], coeff[1][3], coeff[1][2]],
          [coeff[2][0], coeff[2][3], coeff[2][2]]]

    # Matrix d3 using coeff as given in
    # cramer's rule
    d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]],
          [coeff[1][0], coeff[1][1], coeff[1][3]],
          [coeff[2][0], coeff[2][1], coeff[2][3]]]

    # Calculating Determinant of Matrices
    # d, d1, d2, d3
    D = determinantOfMatrix(d)
    D1 = determinantOfMatrix(d1)
    D2 = determinantOfMatrix(d2)
    D3 = determinantOfMatrix(d3)

    #    print("D is : ", D)
    print("D1 is : ", D1)
    print("D2 is : ", D2)
    print("D3 is : ", D3)

    # Case 1
    if D != 0:

        x = D1 / D
        y = D2 / D
        z = D3 / D

        print("Value of x is : ", x)
        print("Value of y is : ", y)
        print("Value of z is : ", z)

    # Case 2
    else:
        if (D1 == 0 and D2 == 0 and
                D3 == 0):
            print("Infinite solutions")

        elif (D1 != 0 or D2 != 0 or
              D3 != 0):
            print("No solutions")

if __name__ == "__main__":
    row = int(input("Enter number of rows you want: "))
    col = int(input("Enter number of columns you want: "))
    coeff = []
    for m in range(row):
        a = []
        for n in range(col):
            a.append(0)
        coeff.append(a)
    for i in range(len(coeff)):
        for j in range(len(coeff[0])):
            coeff[i][j] = int(input("Input element: "))
    print("Your Matrix is :", coeff)
    findSolution(coeff)

</code>```

``

What's expected is that I'm trying to find out x,y and z from every possible matrix that the user inputs if its a 3x3 matrix but I can't figure out on how I can have two different matrices on the same memory"[0][0]" using this method and I can't find any solutions on my problem. The error message that I get is that the list index is out of range because there is no [3] within my matrix if there's anyone that can help me I will appreciate it greatly

Body:
I'm trying to solve a 3x3 matrix using cramer's rule and as I'm new to python I'm finding it difficult to figure out my answer alone I've been doing research on how to do it using different methods but I've came to a stop near the end of it.  The reason on why that it has to be with no packages is because I have to do it for homework and I have to find out for every possible matrix I've altered the one I originally had to try and find every matrix but since I'm still learning python it hasn't gone to plan

``
# determinant of Matrix
def determinantOfMatrix(mat):
    ans = (mat[0][0] * mat[1][1] * mat[2][2] +
           (mat[0][1] * mat[1][2] * mat[2][0])
           + (mat[0][2] * mat[1][0] * mat[2][1] -
              (mat[0][2] * mat[1][1] * mat[2][0]
               + mat[0][0] * mat[1][2] * mat[2][1] +
               mat[0][1] * (mat[1][0] * mat[2][2]))))
    return ans

# linear equations using cramer's rule
def findSolution(coeff):
    # Matrix d

    d = [[coeff[0][0], coeff[0][1], coeff[0][2]],
         [coeff[1][0], coeff[1][1], coeff[1][2]],
         [coeff[2][0], coeff[2][1], coeff[2][2]]]

    # Matrix d1 using coeff as given in
    # cramer's rule
    d1 = [[coeff[0][3], coeff[0][1], coeff[0][2]],
          [coeff[1][3], coeff[1][1], coeff[1][2]],
          [coeff[2][3], coeff[2][1], coeff[2][2]]]

    # Matrix d2 using coeff as given in
    # cramer's rule
    d2 = [[coeff[0][0], coeff[0][3], coeff[0][2]],
          [coeff[1][0], coeff[1][3], coeff[1][2]],
          [coeff[2][0], coeff[2][3], coeff[2][2]]]

    # Matrix d3 using coeff as given in
    # cramer's rule
    d3 = [[coeff[0][0], coeff[0][1], coeff[0][3]],
          [coeff[1][0], coeff[1][1], coeff[1][3]],
          [coeff[2][0], coeff[2][1], coeff[2][3]]]

    # Calculating Determinant of Matrices
    # d, d1, d2, d3
    D = determinantOfMatrix(d)
    D1 = determinantOfMatrix(d1)
    D2 = determinantOfMatrix(d2)
    D3 = determinantOfMatrix(d3)

    #    print("D is : ", D)
    print("D1 is : ", D1)
    print("D2 is : ", D2)
    print("D3 is : ", D3)

    # Case 1
    if D != 0:

        x = D1 / D
        y = D2 / D
        z = D3 / D

        print("Value of x is : ", x)
        print("Value of y is : ", y)
        print("Value of z is : ", z)

    # Case 2
    else:
        if (D1 == 0 and D2 == 0 and
                D3 == 0):
            print("Infinite solutions")

        elif (D1 != 0 or D2 != 0 or
              D3 != 0):
            print("No solutions")

if __name__ == "__main__":
    row = int(input("Enter number of rows you want: "))
    col = int(input("Enter number of columns you want: "))
    coeff = []
    for m in range(row):
        a = []
        for n in range(col):
            a.append(0)
        coeff.append(a)
    for i in range(len(coeff)):
        for j in range(len(coeff[0])):
            coeff[i][j] = int(input("Input element: "))
    print("Your Matrix is :", coeff)
    findSolution(coeff)

``

What's expected is that I'm trying to find out x,y and z from every possible matrix that the user inputs if its a 3x3 matrix but I can't figure out on how I can have two different matrices on the same memory"[0][0]" using this method and I can't find any solutions on my problem. The error message that I get is that the list index is out of range because there is no [3] within my matrix if there's anyone that can help me I will appreciate it greatly


问:
How can I serve Blazor Wasm static files?
When I publish the standalone Blazor Wasm application, I get the following output:

"wwwroot" folder, looks like this:
wwwroot_folder

web.config file

However, if I just take the content from wwwroot and upload it to my servers website root.
All it gives me is the following error:
Loading...
An unhandled error has occurred. Reload

Is there any tutorial or document that will take me through the correct steps to serve the files from my servers website root.

I have successfully deployed my wasm application to Azure Static Web Apps via github, however, I really really want to serve the files from/as my website.


问:
How do you find the coordinates of a plane with a minimized distance strictly above a 3D dataset (python)?
As the title states, I need to make a plane above a 3D dataset in Python. There should be no data points above such plane, and the distances between the plane and the dataset should be optimized such that the plane somehow generalizes the whole data.

this is the 3d surface plot

(this is another example) the plane should look like this

I've been stuck for months on how to start/approach this problem. Should I start looking for the maximums in the data? Should I start on finding the peak in the middle and tamper around the possible slopes of the plane? Or are there other appropriate mathematical methods for this?

Thanks ahead.


问:
GR setup for casandra in webscale environment
We are trying to do GR setup for our application which has casandra pods(deployed within application namespace) deployed in two different clusters on two
sites of webscale environment. All external routing from the cluster is done via F5/spk.

How can we setup casandra data replication via F5/SPK between primary and secondary .

Multus is not allowed on platform ...


问:
Python-magic not recognized while trying to import in Django
I am trying to check the file type of the uploaded data using magic but pylance is not recognizing it
I keep getting this error pylance error

I installed python-magic 0.4.27
My python version is- 3.9
Django-version- 4.1.3

I tried adding python-magic to Installed Apps in Settings after Installing it locally on my command prompt
I also Installed python-magic-bin-0.4.14 but it still gives me that error.
pylance error