问:
Entity Framework, How can I get the actual data of my class to another class
My problem is in my dbo.MyQueues if you can see my ServiceLetter data is
showing number instead of showing letters.

My dbo.Services database looks like this.

```<code>ServiceId - ServicesName - ServiceLetter
1 - Admin Concerns - A
2 - Engineering - B
3 - Payments - C

public class Service
{
    public int ServiceId { get; set; }
    public string ServiceName { get; set; }
    public string ServiceLetter { get; set; }
}
</code>```

My dbo.MyQueues database looks like this.

```<code>MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter
1 - John - 1001 - 1 - 1
2 - Doe - 1002 - 2 - 2
3 - Jack - 1003 - 3 - 3

    public class MyQueue
    {
        public int MyQueueId { get; set; }
        public string Name { get; set; }
        public string QueueNumber
        {
            get
            {
                return string.Format("{0}{1:000}", ServiceLetter ?? "?", MyQueueId);
            }
            set { }
        }
        public static Queue<MyQueue> todayQueue = new Queue<MyQueue>();
        public int ServiceId { get; set; }
        public string ServiceLetter { get; set; }
        public virtual Service Service { get; set; }
    }
</code>```

I want my dbo.MyQueues data to look like this.

```<code>MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter
    1 - John - A001 - 1 - A
    2 - Doe - B002 - 2 - B
    3 - Jack - C003 - 3 - C
</code>```

my QueueNumber is combination of my ServiceLetter + MyQueueId thats why I want my Service letter to save as A letter not as A number so that I can have a QueueNumber data like A001, B002. In other words I need to make my ServiceLetter on my dbo.MyQueue to become letter right now its showing number.

Here is my Controller:

```<code>public class KiosksController : Controller
{
    private DBContext db = new DBContext();

    public ActionResult Index()
    {
        var services = db.Services;
        return View(services.ToList());
    }

    [HttpGet]
    public ActionResult GetQueueInfo(int? id, string ServiceLetter)
    {
        ViewBag.ServiceLetter = new SelectList(db.Services, "ServiceId", "ServiceLetter", id, ServiceLetter);
        ViewBag.ServiceId = new SelectList(db.Services, "ServiceId", "ServiceName", id);
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SetQueueInfo([Bind(Include = "QueueId,Name,QueueNumber,ServiceId,ServiceLetter")] MyQueue queue/*, int? id,string Name, string QueueNumber, string ServiceLetter, int ServiceId*/, int? id)
    {
        if (ModelState.IsValid)
        {
            MyQueue.todayQueue.Enqueue(queue);
            MyQueue.todayQueue.Count();
            db.Queues.Add(queue);
            db.SaveChanges();

            return View(queue);
        }
        return View();
    }
}
</code>```

The scenario here is this.
in my index() there is button of my services that when click will go to my GetQueueInfo then in my GetQueueInfo's view you enter your name then click confirm button to go to SetQueueInfo and generate A queuenumber.

queuenumber is combination of ServiceLetter + MyQueueId as of now Its generating me that but instead of letter on the beggining its showing me number like 1001 instead of A001. badly need help here, i'm stuck.

答:
A structure like that with your QueueNumber isn't a good idea relying on the possible presence of another entity. In EF6, and possibly future versions of EF Core this may work thanks to lazy loading, but even then it's not ideal because lazy loading will lead to performance issues.

Suggestion 1: If ServiceLetter is unique and important, and Service acts like a lookup table, and you want to use the ServiceLetter as part of another key; Use ServiceLetter as the PK.

```<code>public class Service
{
    [Key]
    public char ServiceLetter { get; set; }
    public string ServiceName { get; set; }
}

public class MyQueue
{
    public int MyQueueId { get; set; }
    public string Name { get; set; }

    [ForeignKey("Service")]
    public char? ServiceLetter { get; set; }
    public virtual Service Service { get; set; }
    [NotMapped]
    public string QueueNumber
    {
        get
        {
            return string.Format("{0}{1:000}", ServiceLetter.HasValue ? ServiceLetter.Value : "?", MyQueueId);
        }
    }
}
</code>```

In this way the service letter is known by the queue and can be accessed while maintaining integrity as the FK to the service.

Suggestion 2: If your application is the sole custodian of the data (no other system/process modifies data) then adopt a DDD pattern to manage references to the Service so that the Queue can reliably track and persist a QueueNumber.

```<code>public class Service
{
    [Key]
    public int ServiceId { get; set; }
    public char ServiceLetter { get; set; }
    public string ServiceName { get; set; }
}

public class MyQueue
{
    public int MyQueueId { get; internal set; }
    public string Name { get; internal set; }

    public virtual Service Service { get; internal set; }
    // Persisted to the MyQueue table.
    public string QueueNumber { get; internal set; }

    public void UpdateService(Service service)
    {
        Service = service;
        QueueNumber = string.Format("{0}{1:000}", service?.ServiceLetter ?? "?", MyQueueId);
    }
}
</code>```

The DDD approach restricts updates to methods whereby the method to update a service can compute the Queue Number. If it is possible to update a service letter on an existing service you would need logic to trigger the UpdateService on all Queue entries that reference that specific service.

If other systems can update the service reference or the service letter then you can utilize a health check process running on the database to search for Queue numbers that do not reflect their service reference and update those affected queue numbers. Normally I structure these to insert into an audit table where incorrect data is found followed by the update to the data to correct the inconsistency.

Body:
My problem is in my dbo.MyQueues if you can see my ServiceLetter data is
showing number instead of showing letters.

My dbo.Services database looks like this.

ServiceId - ServicesName - ServiceLetter
1 - Admin Concerns - A
2 - Engineering - B
3 - Payments - C

public class Service
{
    public int ServiceId { get; set; }
    public string ServiceName { get; set; }
    public string ServiceLetter { get; set; }
}

My dbo.MyQueues database looks like this.

MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter
1 - John - 1001 - 1 - 1
2 - Doe - 1002 - 2 - 2
3 - Jack - 1003 - 3 - 3

    public class MyQueue
    {
        public int MyQueueId { get; set; }
        public string Name { get; set; }
        public string QueueNumber
        {
            get
            {
                return string.Format("{0}{1:000}", ServiceLetter ?? "?", MyQueueId);
            }
            set { }
        }
        public static Queue<MyQueue> todayQueue = new Queue<MyQueue>();
        public int ServiceId { get; set; }
        public string ServiceLetter { get; set; }
        public virtual Service Service { get; set; }
    }

I want my dbo.MyQueues data to look like this.

MyQueueId - Name - QueueNumber - ServiceId - ServiceLetter
    1 - John - A001 - 1 - A
    2 - Doe - B002 - 2 - B
    3 - Jack - C003 - 3 - C

my QueueNumber is combination of my ServiceLetter + MyQueueId thats why I want my Service letter to save as A letter not as A number so that I can have a QueueNumber data like A001, B002. In other words I need to make my ServiceLetter on my dbo.MyQueue to become letter right now its showing number.

Here is my Controller:

public class KiosksController : Controller
{
    private DBContext db = new DBContext();

    public ActionResult Index()
    {
        var services = db.Services;
        return View(services.ToList());
    }

    [HttpGet]
    public ActionResult GetQueueInfo(int? id, string ServiceLetter)
    {
        ViewBag.ServiceLetter = new SelectList(db.Services, "ServiceId", "ServiceLetter", id, ServiceLetter);
        ViewBag.ServiceId = new SelectList(db.Services, "ServiceId", "ServiceName", id);
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SetQueueInfo([Bind(Include = "QueueId,Name,QueueNumber,ServiceId,ServiceLetter")] MyQueue queue/*, int? id,string Name, string QueueNumber, string ServiceLetter, int ServiceId*/, int? id)
    {
        if (ModelState.IsValid)
        {
            MyQueue.todayQueue.Enqueue(queue);
            MyQueue.todayQueue.Count();
            db.Queues.Add(queue);
            db.SaveChanges();

            return View(queue);
        }
        return View();
    }
}

The scenario here is this.
in my index() there is button of my services that when click will go to my GetQueueInfo then in my GetQueueInfo's view you enter your name then click confirm button to go to SetQueueInfo and generate A queuenumber.

queuenumber is combination of ServiceLetter + MyQueueId as of now Its generating me that but instead of letter on the beggining its showing me number like 1001 instead of A001. badly need help here, i'm stuck.

Body:
A structure like that with your QueueNumber isn't a good idea relying on the possible presence of another entity. In EF6, and possibly future versions of EF Core this may work thanks to lazy loading, but even then it's not ideal because lazy loading will lead to performance issues.

Suggestion 1: If ServiceLetter is unique and important, and Service acts like a lookup table, and you want to use the ServiceLetter as part of another key; Use ServiceLetter as the PK.

public class Service
{
    [Key]
    public char ServiceLetter { get; set; }
    public string ServiceName { get; set; }
}

public class MyQueue
{
    public int MyQueueId { get; set; }
    public string Name { get; set; }

    [ForeignKey("Service")]
    public char? ServiceLetter { get; set; }
    public virtual Service Service { get; set; }
    [NotMapped]
    public string QueueNumber
    {
        get
        {
            return string.Format("{0}{1:000}", ServiceLetter.HasValue ? ServiceLetter.Value : "?", MyQueueId);
        }
    }
}

In this way the service letter is known by the queue and can be accessed while maintaining integrity as the FK to the service.

Suggestion 2: If your application is the sole custodian of the data (no other system/process modifies data) then adopt a DDD pattern to manage references to the Service so that the Queue can reliably track and persist a QueueNumber.

public class Service
{
    [Key]
    public int ServiceId { get; set; }
    public char ServiceLetter { get; set; }
    public string ServiceName { get; set; }
}

public class MyQueue
{
    public int MyQueueId { get; internal set; }
    public string Name { get; internal set; }

    public virtual Service Service { get; internal set; }
    // Persisted to the MyQueue table.
    public string QueueNumber { get; internal set; }

    public void UpdateService(Service service)
    {
        Service = service;
        QueueNumber = string.Format("{0}{1:000}", service?.ServiceLetter ?? "?", MyQueueId);
    }
}

The DDD approach restricts updates to methods whereby the method to update a service can compute the Queue Number. If it is possible to update a service letter on an existing service you would need logic to trigger the UpdateService on all Queue entries that reference that specific service.

If other systems can update the service reference or the service letter then you can utilize a health check process running on the database to search for Queue numbers that do not reflect their service reference and update those affected queue numbers. Normally I structure these to insert into an audit table where incorrect data is found followed by the update to the data to correct the inconsistency.


来源: stackexchange

问:
org.hibernate.MappingException could not determine type for table
here are the files and all the code
https://www.dropbox.com/sh/n78k0nrkpsrnyqp/AAColiDvxHrI1U2eHocV3GO1a?dl=0

it seems like the problem i am having is with the product entity; i am getting an error because the field Category is of type private Category

ERROR shows up when i engage hibernate after i annotate product with @entity and @Table

the only way i can get the error to go away is if i annotate
@Transient
private Category category

but i need to persist Category in a table

so how do you suggest to fix this problem please

```<code> Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-30 21:04:03.739 ERROR 7256 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

     org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.1.5.RELEASE.jar:2.1.5.RELEASE]
Caused by: javax.persistence.PersistenceException:

====================== the ERROR ============================

[PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.restaumart.helper.Category, at table: products, for columns: [org.hibernate.mapping.Column(category)]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:402) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 21 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: com.restaumart.helper.Category, at table: products, for columns: [org.hibernate.mapping.Column(category)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:486) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.Property.isValid(Property.java:226) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:267) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:466) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 25 common frames omitted

Process finished with exit code 0
</code>```

答: If Category is an Entity than you should annotate Category class with @Entity and in Product class you should provide relation like 1-to-M or other.

ContentLicense: CC BY-SA 4.0

Body:
here are the files and all the code
https://www.dropbox.com/sh/n78k0nrkpsrnyqp/AAColiDvxHrI1U2eHocV3GO1a?dl=0

it seems like the problem i am having is with the product entity; i am getting an error because the field Category is of type private Category

ERROR shows up when i engage hibernate after i annotate product with @entity and @Table

the only way i can get the error to go away is if i annotate
@Transient
private Category category

but i need to persist Category in a table

so how do you suggest to fix this problem please

 Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-30 21:04:03.739 ERROR 7256 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

     org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.1.5.RELEASE.jar:2.1.5.RELEASE]
Caused by: javax.persistence.PersistenceException:

====================== the ERROR ============================

[PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.restaumart.helper.Category, at table: products, for columns: [org.hibernate.mapping.Column(category)]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:402) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 21 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: com.restaumart.helper.Category, at table: products, for columns: [org.hibernate.mapping.Column(category)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:486) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.Property.isValid(Property.java:226) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:267) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:466) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 25 common frames omitted

Process finished with exit code 0


问:
Ext-json is missing in composer.json
I cannot use json_encode() function in my Laravel project, it says ext-json is missing in composer.json. Any help please!

答:
For this problem, JetBrains PHP Storm blog  provide a solution

```<code>"ext-json": "*"
</code>```

It is important to list PHP extensions your project requires. Not all PHP installations are created equal: some may miss extensions you may consider as standard (such as ext-mysqliwhich is not installed by default in Fedora/CentOS minimal installation systems). Failure to list required PHP extensions may lead to a bad user experience: Composer will install your package without any errors but it will then fail at run-time. The show — platform command lists all PHP extensions available on your system. You may use it to help you compile the list of extensions you use and require. Alternatively you may use third party tools to analyze your project for the list of extensions used.

Read more here

Title: Ext-json is missing in composer.json

Body:
For this problem, JetBrains PHP Storm blog  provide a solution

"ext-json": "*"

It is important to list PHP extensions your project requires. Not all PHP installations are created equal: some may miss extensions you may consider as standard (such as ext-mysqliwhich is not installed by default in Fedora/CentOS minimal installation systems). Failure to list required PHP extensions may lead to a bad user experience: Composer will install your package without any errors but it will then fail at run-time. The show — platform command lists all PHP extensions available on your system. You may use it to help you compile the list of extensions you use and require. Alternatively you may use third party tools to analyze your project for the list of extensions used.

Read more here


问:
Error Failed to process phase POST_MODULE of deployment while updating from jboss6 to wildfly15
While upgrading from jboss6 to wildfly15 and from java6 to java8 in jsf project with hibernate ORM i faced some issues we solved it but we have another one </p>

```<code>4:34:43,718 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC000001: Failed to start service jboss.deployment.unit."nts.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."nts.war".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment "nts.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:151)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1738)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1700)
    at org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1558)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1364)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module "deployment.nts.war" from Service Module Loader]
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.checkDeclaredApplicationClassAsServlet(JaxrsScanningProcessor.java:437)
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.scanWebDeployment(JaxrsScanningProcessor.java:278)
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.deploy(JaxrsScanningProcessor.java:109)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:144)
    ... 8 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module "deployment.nts.war" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.checkDeclaredApplicationClassAsServlet(JaxrsScanningProcessor.java:435)
    ... 11 more

14:35:07,319 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "nts.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"nts.war\".POST_MODULE" => "WFLYSRV0153: Failed to process phase POST_MODULE of deployment \"nts.war\"
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module \"deployment.nts.war\" from Service Module Loader]
    Caused by: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module \"deployment.nts.war\" from Service Module Loader]"}}
14:35:07,361 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 43) WFLYSRV0010: Deployed "nts.war" (runtime-name : "nts.war")
14:35:07,373 INFO  [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0183: Service status report
WFLYCTL0186:   Services which failed to start:      service jboss.deployment.unit."nts.war".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment "nts.war"

14:35:07,483 INFO  [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0212: Resuming server
14:35:07,488 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
14:35:07,489 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
14:35:07,490 ERROR [org.jboss.as] (Controller Boot Thread) WFLYSRV0026: WildFly Full 15.0.1.Final (WildFly Core 7.0.0.Final) started (with errors) in 70466ms - Started 372 of 583 services (1 services failed or missing dependencies, 324 services are lazy, passive or on-demand)
14:35:08,034 INFO  [org.jboss.as.protocol] (management I/O-1) WFLYPRT0057:  cancelled task by interrupting thread Thread[management-handler-thread - 1,5,management-handler-thread]
</code>```

答:
The root cause of the deployment is following exception

```<code>java.lang.ClassNotFoundException:
    com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</code>```

I'm assuming you are deploying a JAX-WS web service and  JAX-WS dependency library jaxws-rt.jar is missing. TO solve the issue download JAX-WS RI distribution,
unzip it and copy jaxws-rt.jar to your classpath.

Body:
While upgrading from jboss6 to wildfly15 and from java6 to java8 in jsf project with hibernate ORM i faced some issues we solved it but we have another one

4:34:43,718 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC000001: Failed to start service jboss.deployment.unit."nts.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."nts.war".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment "nts.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:151)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1738)
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1700)
    at org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1558)
    at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1364)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module "deployment.nts.war" from Service Module Loader]
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.checkDeclaredApplicationClassAsServlet(JaxrsScanningProcessor.java:437)
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.scanWebDeployment(JaxrsScanningProcessor.java:278)
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.deploy(JaxrsScanningProcessor.java:109)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:144)
    ... 8 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module "deployment.nts.war" from Service Module Loader]
    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
    at org.jboss.as.jaxrs.deployment.JaxrsScanningProcessor.checkDeclaredApplicationClassAsServlet(JaxrsScanningProcessor.java:435)
    ... 11 more

14:35:07,319 ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "nts.war")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"nts.war\".POST_MODULE" => "WFLYSRV0153: Failed to process phase POST_MODULE of deployment \"nts.war\"
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module \"deployment.nts.war\" from Service Module Loader]
    Caused by: java.lang.ClassNotFoundException: com.sun.xml.ws.transport.http.servlet.WSServlet from [Module \"deployment.nts.war\" from Service Module Loader]"}}
14:35:07,361 INFO  [org.jboss.as.server] (ServerService Thread Pool -- 43) WFLYSRV0010: Deployed "nts.war" (runtime-name : "nts.war")
14:35:07,373 INFO  [org.jboss.as.controller] (Controller Boot Thread) WFLYCTL0183: Service status report
WFLYCTL0186:   Services which failed to start:      service jboss.deployment.unit."nts.war".POST_MODULE: WFLYSRV0153: Failed to process phase POST_MODULE of deployment "nts.war"

14:35:07,483 INFO  [org.jboss.as.server] (Controller Boot Thread) WFLYSRV0212: Resuming server
14:35:07,488 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0060: Http management interface listening on http://127.0.0.1:9990/management
14:35:07,489 INFO  [org.jboss.as] (Controller Boot Thread) WFLYSRV0051: Admin console listening on http://127.0.0.1:9990
14:35:07,490 ERROR [org.jboss.as] (Controller Boot Thread) WFLYSRV0026: WildFly Full 15.0.1.Final (WildFly Core 7.0.0.Final) started (with errors) in 70466ms - Started 372 of 583 services (1 services failed or missing dependencies, 324 services are lazy, passive or on-demand)
14:35:08,034 INFO  [org.jboss.as.protocol] (management I/O-1) WFLYPRT0057:  cancelled task by interrupting thread Thread[management-handler-thread - 1,5,management-handler-thread]

Body:
The root cause of the deployment is following exception

java.lang.ClassNotFoundException:
    com.sun.xml.ws.transport.http.servlet.WSServletContextListener

I'm assuming you are deploying a JAX-WS web service and  JAX-WS dependency library jaxws-rt.jar is missing. TO solve the issue download JAX-WS RI distribution,
unzip it and copy jaxws-rt.jar to your classpath.


问:
How to create a new row after 3 column in my code
I am customizing a theme in which there was a option to add only three services sections. I had added more three sections and are getting reflected on my HTML. defacult is is createing somthing like this :

row > col1 > col1 > col1 > col1 > col1 > col1

I want to create Like this :

row > col1 > col1 > col1
row > col1 > col1 > col1

Kindly help me with this

```<code><?php
/**
 * lessons Section
 *
 * @package Preschool_and_Kindergarten
*/
     $title        = get_theme_mod( 'preschool_and_kindergarten_lessons_section_title' );
     $description  = get_theme_mod( 'preschool_and_kindergarten_lessons_section_description' );
     $lesson_one   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_one' );
     $lesson_two   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_two' );
     $lesson_three = get_theme_mod( 'preschool_and_kindergarten_lesson_post_three' );
     $lesson_four = get_theme_mod( 'preschool_and_kindergarten_lesson_post_four' );
     $lesson_five = get_theme_mod( 'preschool_and_kindergarten_lesson_post_five' );
     $lesson_six = get_theme_mod( 'preschool_and_kindergarten_lesson_post_six' );
     $lessons_posts = array( $lesson_one, $lesson_two, $lesson_three, $lesson_four, $lesson_five, $lesson_six );
     $lessons_posts = array_diff( array_unique( $lessons_posts ), array('') );
?>
<section class="section-2">
    <div class="container">
        <?php
            preschool_and_kindergarten_get_section_header( $title, $description );

            if( $lessons_posts ):

                $lesson_qry = new WP_Query(array(
                    'post__in'   => $lessons_posts,
                    'orderby'   => 'post__in',
                    'posts_per_page' => -1,
                    'ignore_sticky_posts' => true
                    ));

                if( $lesson_qry->have_posts() ){ ?>
                    <div class="row">

                       <?php
                        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                            <div class="col">

                                <?php
                                    if( has_post_thumbnail() ){ ?>
                                        <div class="img-holder">
                                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                        </div>
                                <?php } ?>

                                <div class="text-holder">
                                    <h3 class="title"><?php the_title(); ?></h3>
                                    <?php the_content(); ?>
                                </div>

                            </div>

                        <?php } ?>

                    </div>
                <?php }
            wp_reset_postdata();
        endif; ?>
    </div>
</section>
</code>```

答:
A very crude and simple solution will be to include a counter and use a modulus operator to close and reopen the row div as mentioned below:</p>

```<code>if( $lesson_qry->have_posts() ){
  $counter = 0;
   ?>
                <div class="row">

                   <?php
                    while( $lesson_qry->have_posts() ){ $lesson_qry->the_post();
                      if ($counter%3 == 0) {
                       ?>
                       </div>
                       <div class="row">
                      <?php }?>
                        <div class="col">

                            <?php
                                if( has_post_thumbnail() ){ ?>
                                    <div class="img-holder">
                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                    </div>
                            <?php } ?>

                            <div class="text-holder">
                                <h3 class="title"><?php the_title(); ?></h3>
                                <?php the_content(); ?>
                            </div>

                        </div>

                    <?php
                     $counter++;
                     } ?>

                </div>
            <?php }
</code>```

Body:
I am customizing a theme in which there was a option to add only three services sections. I had added more three sections and are getting reflected on my HTML. defacult is is createing somthing like this :

row > col1 > col1 > col1 > col1 > col1 > col1

I want to create Like this :

row > col1 > col1 > col1
row > col1 > col1 > col1

Kindly help me with this

<?php
/**
 * lessons Section
 *
 * @package Preschool_and_Kindergarten
*/
     $title        = get_theme_mod( 'preschool_and_kindergarten_lessons_section_title' );
     $description  = get_theme_mod( 'preschool_and_kindergarten_lessons_section_description' );
     $lesson_one   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_one' );
     $lesson_two   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_two' );
     $lesson_three = get_theme_mod( 'preschool_and_kindergarten_lesson_post_three' );
     $lesson_four = get_theme_mod( 'preschool_and_kindergarten_lesson_post_four' );
     $lesson_five = get_theme_mod( 'preschool_and_kindergarten_lesson_post_five' );
     $lesson_six = get_theme_mod( 'preschool_and_kindergarten_lesson_post_six' );
     $lessons_posts = array( $lesson_one, $lesson_two, $lesson_three, $lesson_four, $lesson_five, $lesson_six );
     $lessons_posts = array_diff( array_unique( $lessons_posts ), array('') );
?>

        <?php
            preschool_and_kindergarten_get_section_header( $title, $description );

            if( $lessons_posts ):

                $lesson_qry = new WP_Query(array(
                    'post__in'   => $lessons_posts,
                    'orderby'   => 'post__in',
                    'posts_per_page' => -1,
                    'ignore_sticky_posts' => true
                    ));

                if( $lesson_qry->have_posts() ){ ?>

                       <?php
                        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                                <?php
                                    if( has_post_thumbnail() ){ ?>

                                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>

                                <?php } ?>

<?php the_title(); ?>

                                    <?php the_content(); ?>

                        <?php } ?>

                <?php }
            wp_reset_postdata();
        endif; ?>

Body:
A very crude and simple solution will be to include a counter and use a modulus operator to close and reopen the row div as mentioned below:

if( $lesson_qry->have_posts() ){
  $counter = 0;
   ?>
                <div class="row">

                   <?php
                    while( $lesson_qry->have_posts() ){ $lesson_qry->the_post();
                      if ($counter%3 == 0) {
                       ?>
                       </div>
                       <div class="row">
                      <?php }?>
                        <div class="col">

                            <?php
                                if( has_post_thumbnail() ){ ?>
                                    <div class="img-holder">
                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                    </div>
                            <?php } ?>

                            <div class="text-holder">
                                <h3 class="title"><?php the_title(); ?></h3>
                                <?php the_content(); ?>
                            </div>

                        </div>

                    <?php
                     $counter++;
                     } ?>

                </div>
            <?php }


问:
Querying the same column for 3 different values
I'm trying hard to extract the data in the format I need, but unsuccessful til now.

I have the following table

id_ticket, date_ticket, office_ticket, status_ticket

I need the query to return me, for EVERY MONTH, and always for the same OFFICE:

the number of tickets (COUNT) with any status

the number of tickets (COUNT) with status = 5

the number of tickets (COUNT) with status = 6

Month

Year

The query I made to return ONLY the total amount of tickets with any status was this. It worked!

```<code>SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
</code>```

Returning the total amount of ticket with status=5

```<code>SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1 AND status_ticket = 5
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
</code>```

But I need the return to be something like:

```<code>Year Month Total Status5 Status6
2018   1     15      5        3

2018   2     14      4        5

2018   3     19      2        8
</code>```

Thank you for your help.

答:
The following code builds off JNevill's answer to include summary rows for "missing" months, i.e. those with no tickets, as well as months with tickets. The basic idea is to create a table of all of the months from the first to the last ticket, outer join the ticket data with the months and then summarize the data. (Tally table, numbers table and calendar table are more or less applicable terms.)

It is a Common Table Expression (CTE) that contains several queries that work step-by-step toward the result. You can see the results of the intermediate steps by replacing the final select statement with one of the ones commented out above it.

```<code>-- Sample data.
declare @crm_vw_Tickets as Table ( id_ticket Int Identity, date_ticket Date, office_ticket Int, status_ticket Int );
insert into @crm_vw_Tickets ( date_ticket, office_ticket, status_ticket ) values
  ( '20190305', 1, 6 ), -- Shrove Tuesday.
  ( '20190501', 1, 5 ), -- May Day.
  ( '20190525', 1, 5 ); -- Towel Day.
select * from @crm_vw_Tickets;

-- Summarize the data.
with
  -- Get the minimum and maximum ticket dates for   office_ticket   1.
  Limits as (
    select Min( date_ticket ) as MinDateTicket, Max( date_ticket ) as MaxDateTicket
      from @crm_vw_Tickets
      where office_ticket = 1 ),
  -- 0 to 9.
  Ten ( Number ) as ( select * from ( values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9) ) as Digits( Number ) ),
  -- 100 rows.
  TenUp2 ( Number ) as ( select 42 from Ten as L cross join Ten as R ),
  -- 10000 rows.  We'll assume that 10,000 months should cover the reporting range.
  TenUp4 ( Number ) as ( select 42 from TenUp2 as L cross join TenUp2 as R ),
  -- 1 to the number of months to summarize.
  Numbers ( Number ) as ( select top ( select DateDiff( month, MinDateTicket, MaxDateTicket ) + 1 from Limits ) Row_Number() over ( order by ( select NULL ) ) from TenUp4 ),
  -- Starting date of each month to summarize.
  Months as (
    select DateAdd( month, N.Number - 1, DateAdd( day, 1 - Day( L.MinDateTicket ), L.MinDateTicket ) ) as StartOfMonth
      from Limits as L cross join
        Numbers as N ),
  -- All tickets assigned to the appropriate month and a row with NULL ticket data
  --   for each month without tickets.
  MonthsAndTickets as (
    select M.StartOfMonth, T.*
      from Months as M left outer join
        @crm_vw_Tickets as T on M.StartOfMonth <= T.date_ticket and T.date_ticket < DateAdd( month, 1, M.StartOfMonth ) )
  -- Use one of the following   select   statements to see the intermediate or final results:
  --select * from Limits;
  --select * from Ten;
  --select * from TenUp2;
  --select * from TenUp4;
  --select * from Numbers;
  --select * from Months;
  --select * from MonthsAndTickets;
  select Year( StartOfMonth ) as SummaryYear, Month( StartOfMonth ) as SummaryMonth,
    Count( id_ticket ) as TotalTickets,
    Coalesce( Sum( case when status_ticket = 5 then 1 end ), 0 ) as Status5Tickets,
    Coalesce( Sum( case when status_ticket = 6 then 1 end ), 0 ) as Status6Tickets
    from MonthsAndTickets
    where office_ticket = 1 or office_ticket is NULL -- Handle months with no tickets.
    group by StartOfMonth
    order by StartOfMonth;
</code>```

Note that the final select uses Count( id_ticket ), Coalesce and an explicit check for NULL to produce appropriate output values (0) for months with no tickets.

Body:
I'm trying hard to extract the data in the format I need, but unsuccessful til now.

I have the following table

id_ticket, date_ticket, office_ticket, status_ticket

I need the query to return me, for EVERY MONTH, and always for the same OFFICE:

the number of tickets (COUNT) with any status

the number of tickets (COUNT) with status = 5

the number of tickets (COUNT) with status = 6

Month

Year

The query I made to return ONLY the total amount of tickets with any status was this. It worked!

SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC

Returning the total amount of ticket with status=5

SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1 AND status_ticket = 5
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC

But I need the return to be something like:

Year Month Total Status5 Status6
2018   1     15      5        3

2018   2     14      4        5

2018   3     19      2        8

Thank you for your help.

Body:
The following code builds off JNevill's answer to include summary rows for "missing" months, i.e. those with no tickets, as well as months with tickets. The basic idea is to create a table of all of the months from the first to the last ticket, outer join the ticket data with the months and then summarize the data. (Tally table, numbers table and calendar table are more or less applicable terms.)

It is a Common Table Expression (CTE) that contains several queries that work step-by-step toward the result. You can see the results of the intermediate steps by replacing the final select statement with one of the ones commented out above it.

-- Sample data.
declare @crm_vw_Tickets as Table ( id_ticket Int Identity, date_ticket Date, office_ticket Int, status_ticket Int );
insert into @crm_vw_Tickets ( date_ticket, office_ticket, status_ticket ) values
  ( '20190305', 1, 6 ), -- Shrove Tuesday.
  ( '20190501', 1, 5 ), -- May Day.
  ( '20190525', 1, 5 ); -- Towel Day.
select * from @crm_vw_Tickets;

-- Summarize the data.
with
  -- Get the minimum and maximum ticket dates for   office_ticket   1.
  Limits as (
    select Min( date_ticket ) as MinDateTicket, Max( date_ticket ) as MaxDateTicket
      from @crm_vw_Tickets
      where office_ticket = 1 ),
  -- 0 to 9.
  Ten ( Number ) as ( select * from ( values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9) ) as Digits( Number ) ),
  -- 100 rows.
  TenUp2 ( Number ) as ( select 42 from Ten as L cross join Ten as R ),
  -- 10000 rows.  We'll assume that 10,000 months should cover the reporting range.
  TenUp4 ( Number ) as ( select 42 from TenUp2 as L cross join TenUp2 as R ),
  -- 1 to the number of months to summarize.
  Numbers ( Number ) as ( select top ( select DateDiff( month, MinDateTicket, MaxDateTicket ) + 1 from Limits ) Row_Number() over ( order by ( select NULL ) ) from TenUp4 ),
  -- Starting date of each month to summarize.
  Months as (
    select DateAdd( month, N.Number - 1, DateAdd( day, 1 - Day( L.MinDateTicket ), L.MinDateTicket ) ) as StartOfMonth
      from Limits as L cross join
        Numbers as N ),
  -- All tickets assigned to the appropriate month and a row with NULL ticket data
  --   for each month without tickets.
  MonthsAndTickets as (
    select M.StartOfMonth, T.*
      from Months as M left outer join
        @crm_vw_Tickets as T on M.StartOfMonth <= T.date_ticket and T.date_ticket < DateAdd( month, 1, M.StartOfMonth ) )
  -- Use one of the following   select   statements to see the intermediate or final results:
  --select * from Limits;
  --select * from Ten;
  --select * from TenUp2;
  --select * from TenUp4;
  --select * from Numbers;
  --select * from Months;
  --select * from MonthsAndTickets;
  select Year( StartOfMonth ) as SummaryYear, Month( StartOfMonth ) as SummaryMonth,
    Count( id_ticket ) as TotalTickets,
    Coalesce( Sum( case when status_ticket = 5 then 1 end ), 0 ) as Status5Tickets,
    Coalesce( Sum( case when status_ticket = 6 then 1 end ), 0 ) as Status6Tickets
    from MonthsAndTickets
    where office_ticket = 1 or office_ticket is NULL -- Handle months with no tickets.
    group by StartOfMonth
    order by StartOfMonth;

Note that the final select uses Count( id_ticket ), Coalesce and an explicit check for NULL to produce appropriate output values (0) for months with no tickets.


问:
What does the [Intrinsic] attribute in C# do?
A quick Google search for "instrinsic attribute c#" only returns articles about other attributes, such as [Serializable]. Apparently these are called "intrinsic attributes".

However, there is also an attribute in C# that is itself called [Intrinsic] and I'm trying to figure out what exactly it is and how it works. It doesn't exist on the common attributes page of the .NET Documentation, or anywhere else in the documentation as far as I can see.

This attribute is used inside of .NET Core in several places, for example, in the System.Numerics.Vectors folder, such as Vector2_Intrinsics.cs. Code snippet:

[Intrinsic]
public Vector2(float x, float y)
{
    X = x;
    Y = y;
}
```

答:
Explanation:

Special types are indicated to the compiler using the
  IntrinsicAttribute custom attribute. If a type is annotated with the
  IntrinsicAttribute attribute, the compiler knows not that the
  implementation for the given type will be present at runtime.
  Methods for types marked as Intrinsic can declare methods to be
  extern, in which case the implementation is assumed to be available at
  runtime.

Source: MSIL to JavaScript Compiler, section 4.4.1.1

Link: http://tenpow.com/Academics/MSIL2JS/MSIL2JS.pdf

In general, I would suggest not to care about it, nor use it for your own classes.


问:
Most efficient way to run a function on every time a timer finishes, but with a large number of timers (thousands/millions)
I'm running a service where users upload a duration and a function must be repeatedly executed every time the timer runs out.

For example, the user says "Run every 5 minutes" and then this function must be run every 5 minutes. This is done through an API.

For a small numbers of timers, this is trivial:

```<code>func doEvery(d time.Duration, f func(time.Time)) {
    for x := range time.Tick(d) {
        f(x) // Run the function every d duration
    }
}
</code>```

I can run each timer in a goroutine, and that works fine. I can start and stop everything with some basic WaitGroups and sync functionality.

But what if I have thousands or millions of timers? I can create a goroutine for each one, but that feels very inefficient. This isn't Erlang.

Should I have multiple work queues, sorted by the "delay", and simply allocate more workers for the more frequent functions? If the timer isn't ready, then it's put back on the queue.

This also isn't ideal, because the workers are busy-waiting (popping off, checking times, pushing on the queue) rather than blocking until the next timer finishes.

Maybe I could have some sort of map, indexed by the remaining duration? I'm not sure what the best approach is here.

答:
I recently built this kind of solution where the user gets notification based on their interval settings. I make a worker pool model using rabbitMQ and two go script. Where one go script uses below cron module to create jobs in a message queue

https://github.com/robfig/cron

Another go script is the worker script consuming message queue and taking action.
To scale, I'm running multiple instances of worker script. Autoscale of worker script can be done by the number of messages in rabbitMQ

Body:
I'm running a service where users upload a duration and a function must be repeatedly executed every time the timer runs out.

For example, the user says "Run every 5 minutes" and then this function must be run every 5 minutes. This is done through an API.

For a small numbers of timers, this is trivial:

func doEvery(d time.Duration, f func(time.Time)) {
    for x := range time.Tick(d) {
        f(x) // Run the function every d duration
    }
}

I can run each timer in a goroutine, and that works fine. I can start and stop everything with some basic WaitGroups and sync functionality.

But what if I have thousands or millions of timers? I can create a goroutine for each one, but that feels very inefficient. This isn't Erlang.

Should I have multiple work queues, sorted by the "delay", and simply allocate more workers for the more frequent functions? If the timer isn't ready, then it's put back on the queue.

This also isn't ideal, because the workers are busy-waiting (popping off, checking times, pushing on the queue) rather than blocking until the next timer finishes.

Maybe I could have some sort of map, indexed by the remaining duration? I'm not sure what the best approach is here.


问:
Angular 7 popover loading
I am using fabricjs to load image and textcontents.

I have many textcontents on canvas with fabricjs.

now on click of textcontents of fabricjs I want to open Angular 7 popover may be (ngbPopover).

how to open that on click of textcontents, like we are opening dialogbox?

because I can not inject popover config anywhere in fabricjs.

答:
Actually I was trying to say something like this, And I found solution here.</p>

```<code>const showImageTools = (e) => {
                                    const content = '<div id="imageDialog" class="container">\n' +
                                        '        <mat-form-field class="example-full-width">\n' +
                                        '            <input value="' + pngText.texts + '" id="textInputField" style="width: 400px;\n' +
                                        '    box-shadow: 2px 4px 5px 3px #bdc3bdee;height: 50px;\n' +
                                        '    padding: 5px;\n' +
                                        '    border-radius: 5px;" matInput placeholder="Add your texts"/>\n' +
                                        '        </mat-form-field>\n' +
                                        '    </div>';
                                    $("body").append(content);
                                    moveImageTools();
                                };

                                this.canvas.add(pngText).renderAll();
                                pngText.on('mousedown', event => {
                                    showImageTools(event);
                                });
</code>```

Title: Angular 7 popover loading

Body:
Actually I was trying to say something like this, And I found solution here.

const showImageTools = (e) => {
                                    const content = '<div id="imageDialog" class="container">\n' +
                                        '        <mat-form-field class="example-full-width">\n' +
                                        '            <input value="' + pngText.texts + '" id="textInputField" style="width: 400px;\n' +
                                        '    box-shadow: 2px 4px 5px 3px #bdc3bdee;height: 50px;\n' +
                                        '    padding: 5px;\n' +
                                        '    border-radius: 5px;" matInput placeholder="Add your texts"/>\n' +
                                        '        </mat-form-field>\n' +
                                        '    </div>';
                                    $("body").append(content);
                                    moveImageTools();
                                };

                                this.canvas.add(pngText).renderAll();
                                pngText.on('mousedown', event => {
                                    showImageTools(event);
                                });


问:
Concatenate a string on map function javascript
I have an object lengthOfStay in which I'm trying to concatenate the values inside it and put it on customerApplication.lengthOfStay

```<code>lengthOfStay:{
    yrs: '',
    mos:''
},
customerApplication: {
    length_of_stay: this.lengthOfStayYrsMos
}

computed: {
     lengthOfStayYrsMos(){
        return this.customerApplication.length_of_stay =
        Object.keys(this.lengthOfStay).map(k =>  this.lengthOfStay[k]).join(" ")
      }
}
</code>```

so for the concatenation looks good and the result for example is

```<code>lengthOfStay:{
    yrs: '2',
    mos:'2'
},
//result
customerApplication: {
    length_of_stay: "2 2"
}
</code>```

how can I concatenate a string on it ? so that the result would be

```<code>customerApplication: {
    length_of_stay: "2 Yrs. & 2 Mos."
}
</code>```

答:
Try this:

Object.keys(this.lengthOfStay).map(k =>  {
   return `${this.lengthOfStay[k]} ${k}.`
}).join(" & ")
```

<p><strong>FOR FIRST KEY UPPERCASE</strong></p>

<pre class="lang-js prettyprint-override"><code>Object.keys(this.lengthOfStay).map(k =>  {
   return `${this.lengthOfStay[k]} ${k.charAt(0).toUpperCase() + k.slice(1)}.`
}).join(" & ")
</code>```

Body:
I have an object lengthOfStay in which I'm trying to concatenate the values inside it and put it on customerApplication.lengthOfStay

lengthOfStay:{
    yrs: '',
    mos:''
},
customerApplication: {
    length_of_stay: this.lengthOfStayYrsMos
}

computed: {
     lengthOfStayYrsMos(){
        return this.customerApplication.length_of_stay =
        Object.keys(this.lengthOfStay).map(k =>  this.lengthOfStay[k]).join(" ")
      }
}

so for the concatenation looks good and the result for example is

lengthOfStay:{
    yrs: '2',
    mos:'2'
},
//result
customerApplication: {
    length_of_stay: "2 2"
}

how can I concatenate a string on it ? so that the result would be

customerApplication: {
    length_of_stay: "2 Yrs. & 2 Mos."
}

Body:
Try this:

Object.keys(this.lengthOfStay).map(k =>  {
   return `${this.lengthOfStay[k]} ${k}.`
}).join(" & ")

FOR FIRST KEY UPPERCASE

Object.keys(this.lengthOfStay).map(k =>  {
   return `${this.lengthOfStay[k]} ${k.charAt(0).toUpperCase() + k.slice(1)}.`
}).join(" & ")


问:
Layout with 2 columns and 2 rows
I have a .container
with 2 columns and in the second column .right I want to have 2 rows
but the first row .content should use the remaining space

this is the HTML markup

```<code><div class="container">
    <div class="left">left</div>
    <div class="right">
        <div class="content">content</div>
        <div class="footer">footer</div>
    </div>
</div>
</code>```

this is the CSS

```<code>.container {
    display: flex;
    flex-direction: row;
    height: 400px; /* the remaining space  in the screen will be nice */
}

.left {
    width: 300px;
}

.right {
    flex-grow: 1;
}

.content {
    align-self: stretch; /* this is not doing anything*/
}

.footer {

}
</code>```

and this is how it should look

```<code>+--------+----------------------+
|        |                      |
|        |                      |
|        |       content        |
|  left  |                      |
|        |                      |
|        +----------------------+
|        |       footer         |
+--------+----------------------+
</code>```

答:
Flexbox works just fine here but I wanted to point out this is also a perfect situation for CSS Grid.  With grid you can get rid of the extra container div.right.

```<code><div class="container">
    <div class="left">left</div>
    <div class="content">content</div>
    <div class="footer">footer</div>
</div>

.container {
    display: grid;
    grid-template-columns: 300px 1fr;
    grid-template-rows: 1fr 100px; /* change the 100px to your desired height of the footer*/
    grid-template-areas:
      'left content'
      'left footer';
    height: 400px; /* height OP selected */
}

.left {
  grid-area: left;
}

.content {
  grid-area: content;
}

.footer {
 grid-area: footer;
}
</code>```

A CodePen just for fun.

Title: Layout with 2 columns and 2 rows

Body:
I have a .container
with 2 columns and in the second column .right I want to have 2 rows
but the first row .content should use the remaining space

this is the HTML markup

left

content

footer

this is the CSS

.container {
    display: flex;
    flex-direction: row;
    height: 400px; /* the remaining space  in the screen will be nice */
}

.left {
    width: 300px;
}

.right {
    flex-grow: 1;
}

.content {
    align-self: stretch; /* this is not doing anything*/
}

.footer {

}

and this is how it should look

+--------+----------------------+
|        |                      |
|        |                      |
|        |       content        |
|  left  |                      |
|        |                      |
|        +----------------------+
|        |       footer         |
+--------+----------------------+

Body:
Flexbox works just fine here but I wanted to point out this is also a perfect situation for CSS Grid.  With grid you can get rid of the extra container div.right.

<div class="container">
    <div class="left">left</div>
    <div class="content">content</div>
    <div class="footer">footer</div>
</div>

.container {
    display: grid;
    grid-template-columns: 300px 1fr;
    grid-template-rows: 1fr 100px; /* change the 100px to your desired height of the footer*/
    grid-template-areas:
      'left content'
      'left footer';
    height: 400px; /* height OP selected */
}

.left {
  grid-area: left;
}

.content {
  grid-area: content;
}

.footer {
 grid-area: footer;
}

A CodePen just for fun.


问:
xmpp and facebook, cant get clear list of online users
I using this code to connect to facebook chat. When I try to retrieve list of online users instead of user name I get negative number for example: -1479115148@chat.facebook.com

How can I get the original (Letters) user name?

答:
After you request the roster, iterate through all the elements and send a vcard request for each person. You will get a response with the full name and icon </p>

```<code><iq
    id='v3'
    to='-1479115148@chat.facebook.com'
    type='get'>
  <vCard xmlns='vcard-temp'/>
</iq>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
After you request the roster, iterate through all the elements and send a vcard request for each person. You will get a response with the full name and icon

<iq
    id='v3'
    to='-1479115148@chat.facebook.com'
    type='get'>
  <vCard xmlns='vcard-temp'/>
</iq>

ContentLicense: CC BY-SA 3.0


问:
Unable to pull/push in git repository
```<code>$ git pull origin master
fatal: unable to access 'https://xxxxxxxxxxxxxxx':
      error setting certificate verify locations:
CAfile: C:/Users/abc/AppData/Local/Programs/Git/usr/bin/curl-ca-bundle.crt
CApath: none
</code>```

I am getting this error when I pull or push my code.

Please guide me to fix this.

答:
This thread is a lot of blind-leading-the-blind answers.
I'm just one more blind man here, but I just had the same issue and solved it by following this easy article. As I understand the original question, git is trying to find an SSL cert file in order to use the HTTPS protocol, and failing to find the file. Most of the answers here seem to focus on "well, just disable SSL then," rather than replacing the file correctly.

This incantation should generate the cert file and put it in the correct location for git on cygwin:

```<code>$ curl -sL http://ca.pdinc.us > /etc/pki/ca-trust/source/anchors/ca.pdinc.us.pem \
&& update-ca-trust
</code>```

In case you monkeyed with your git config (like I did) and need to set it BACK, this should do it:

```<code>$ git config --global http.sslcainfo "/etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt"
</code>```

One other side note which could be impacting many of the people reading this thread: The expected location of the cert file depends on which git executable you're running. Since we're talking about Cygwin, some (most?) of us probably have a Windows-native flavor of git installed too. If your Cygwin paths are set up to find the Windows git executable, your mileage may vary in terms of where to point the http.sslcainfo configuration. To check which executable is getting picked up for you:

```<code>$ which git
</code>```

Title: Unable to pull/push in git repository

Body:
$ git pull origin master
fatal: unable to access 'https://xxxxxxxxxxxxxxx':
      error setting certificate verify locations:
CAfile: C:/Users/abc/AppData/Local/Programs/Git/usr/bin/curl-ca-bundle.crt
CApath: none

I am getting this error when I pull or push my code.

Please guide me to fix this.

Body:
This thread is a lot of blind-leading-the-blind answers.
I'm just one more blind man here, but I just had the same issue and solved it by following this easy article. As I understand the original question, git is trying to find an SSL cert file in order to use the HTTPS protocol, and failing to find the file. Most of the answers here seem to focus on "well, just disable SSL then," rather than replacing the file correctly.

This incantation should generate the cert file and put it in the correct location for git on cygwin:

$ curl -sL http://ca.pdinc.us > /etc/pki/ca-trust/source/anchors/ca.pdinc.us.pem \
&& update-ca-trust

In case you monkeyed with your git config (like I did) and need to set it BACK, this should do it:

$ git config --global http.sslcainfo "/etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt"

One other side note which could be impacting many of the people reading this thread: The expected location of the cert file depends on which git executable you're running. Since we're talking about Cygwin, some (most?) of us probably have a Windows-native flavor of git installed too. If your Cygwin paths are set up to find the Windows git executable, your mileage may vary in terms of where to point the http.sslcainfo configuration. To check which executable is getting picked up for you:

$ which git


问:
Filter out the repeated items of my queryset
In my Django project, when I query a QuerySet list, there have 5 same item unexpectedly, you can check the below snapshot.

if this is a Set, there should only have two items: (SE01-A3, SE01-A4)

this is my part of my test code:

```<code>qs = qs.annotate(letters=Substr('name', 1, 6),
length=Length('name')).order_by('letters', 'length', 'name') # you can ignore this sort code.

    from django.forms.models import model_to_dict

    for a_qs in qs:
        jsonstr = model_to_dict(a_qs)

        print(jsonstr)
</code>```

the output of the print(jsonstr):

```<code>{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 62, 'whmcs_tblorders_id': None, 'expire_time': None, 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 27, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': None, 'name': 'SE01-A4', 'pay_time': None, 'switches': 3, 'ipmi_addr': '172.16.30.4', 'ipmi_pwd': None, 'desc': '', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
</code>```

Is there any way to filter out the repeated items, in my case only left my requirement (SE01-A3, SE01-A4) set?

答:
To skip duplicates we have to use distinct method on queryset like below

```<code>from django.forms.models import model_to_dict

qs = qs.annotate(
    letters=Substr('name', 1, 6),
    length=Length('name')
).order_by('letters', 'length', 'name').distinct()
for a_qs in qs:
    jsonstr = model_to_dict(a_qs)
    print(jsonstr)
</code>```

Body:
In my Django project, when I query a QuerySet list, there have 5 same item unexpectedly, you can check the below snapshot.

if this is a Set, there should only have two items: (SE01-A3, SE01-A4)

this is my part of my test code:

qs = qs.annotate(letters=Substr('name', 1, 6),
length=Length('name')).order_by('letters', 'length', 'name') # you can ignore this sort code.

    from django.forms.models import model_to_dict

    for a_qs in qs:
        jsonstr = model_to_dict(a_qs)

        print(jsonstr)

the output of the print(jsonstr):

{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 60, 'whmcs_tblorders_id': None, 'expire_time': datetime.datetime(2018, 6, 30, 16, 0, tzinfo=<UTC>), 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 26, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': 126, 'name': 'SE01-A3', 'pay_time': datetime.datetime(2018, 4, 30, 16, 0, tzinfo=<UTC>), 'switches': 3, 'ipmi_addr': '172.16.30.3', 'ipmi_pwd': None, 'desc': 'ip: 43.243.33.25 【As】', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}
{'physical_server_model': 5, 'switchesport': 62, 'whmcs_tblorders_id': None, 'expire_time': None, 'cabinet': 3, 'ram': 'Supermicro  DDR4___16', 'ipmi_account': None, 'intranet_ip': None, 'cpu': 'Intel Xeon E3-1230 v5', 'task': None, 'has_intranet': False, 'user': 12, 'id': 27, 'price': Decimal('1000.00'), 'customer_desc': None, 'trade_record': None, 'name': 'SE01-A4', 'pay_time': None, 'switches': 3, 'ipmi_addr': '172.16.30.4', 'ipmi_pwd': None, 'desc': '', 'server_status': 'active', 'disk': 'Seagate SATA___1000'}

Is there any way to filter out the repeated items, in my case only left my requirement (SE01-A3, SE01-A4) set?

Body:
To skip duplicates we have to use distinct method on queryset like below

from django.forms.models import model_to_dict

qs = qs.annotate(
    letters=Substr('name', 1, 6),
    length=Length('name')
).order_by('letters', 'length', 'name').distinct()
for a_qs in qs:
    jsonstr = model_to_dict(a_qs)
    print(jsonstr)


问:
Get User Agent in my app which doesn't contain a webview
I can ask WebView.getWebSettings().getUserAgentString() to get the user
agent, but this doesn't work all that well for my app as I need to
instantiate a WebView first even though I don't need.

Is there another way to get to the User Agent without using a WebView.getSetting, because in my application, I don't need a webView?

Help me please

答: You either initialize a Webview and then destroy it, or just hardcode the user agent as a string (and replace at run-time language etc).</p>


问:
How can I create a group by on part of a string using LINQ?
I have a list of ViewsHistory objects that's sorted by UtcNow:

```<code>var views = List<ViewHistory>
</code>```

ViewHistory Class:

```<code>public class ViewHistory
{
    [PrimaryKey]
    public string YYMMDD { get; set; }
    public int UtcNow { get; set; }
    public int Learn { get; set; }
    public int Practice { get; set; }
    public int Quiz { get; set; }
}
</code>```

Is there a way using LINQ that I can create a new list summing up the totals for Learn, Practice and Quiz by YYMM?

答:
Solution

```<code>var views = new List<ViewHistory>
{
    new ViewHistory {YYMMDD = "190515", Learn = 1, Practice = 2, Quiz = 3},
    new ViewHistory {YYMMDD = "190514", Learn = 5, Practice = 6, Quiz = 7},
    new ViewHistory {YYMMDD = "190415", Learn = 100, Practice = 110, Quiz = 120},
    new ViewHistory {YYMMDD = "190414", Learn = 150, Practice = 160, Quiz = 170}
};

var monthlyTotals = views.GroupBy(
    v => v.YYMMDD.Substring(0, 4),
    v => v,
    (yearMonth, groupedViews) =>
        new
        {
            YearMonth = yearMonth,
            LearnSum = groupedViews.Sum(view => view.Learn),
            PracticeSum = groupedViews.Sum(view => view.Practice),
            QuizSum = groupedViews.Sum(view => view.Quiz)
        }).ToList();
</code>```

Results

monthlyTotals (copied from Visual Studio Locals window while debugging)

monthlyTotals   Count = 2   System.Collections.Generic.List<<>f__AnonymousType0<string, int, int, int>>
    [0] { YearMonth = "1905", LearnSum = 6, PracticeSum = 8, QuizSum = 10 } <Anonymous Type>
    [1] { YearMonth = "1904", LearnSum = 250, PracticeSum = 270, QuizSum = 290 } <Anonymous Type>
```

<h3>Rather not use anonymous types?</h3>

<p>And, of course, if you prefer not to use an anonymous type, you could define a new class (let's say <code>MonthlyViewTotals</code> for example) and instantiate a list of those for your <code>monthlyTotals</code> instead like this:</p>

```var monthlyTotals = views.GroupBy(
    v => v.YYMMDD.Substring(0, 4),
    v => v,
    (yearMonth, groupedViews) =>
        new MonthlyViewTotals        // <-- no more anonymous types
        {
            YearMonth = yearMonth,
            LearnSum = groupedViews.Sum(view => view.Learn),
            PracticeSum = groupedViews.Sum(view => view.Practice),
            QuizSum = groupedViews.Sum(view => view.Quiz)
        }).ToList();
```

Body:
I have a list of ViewsHistory objects that's sorted by UtcNow:

var views = List<ViewHistory>

ViewHistory Class:

public class ViewHistory
{
    [PrimaryKey]
    public string YYMMDD { get; set; }
    public int UtcNow { get; set; }
    public int Learn { get; set; }
    public int Practice { get; set; }
    public int Quiz { get; set; }
}

Is there a way using LINQ that I can create a new list summing up the totals for Learn, Practice and Quiz by YYMM?

Body:
Solution

var views = new List<ViewHistory>
{
    new ViewHistory {YYMMDD = "190515", Learn = 1, Practice = 2, Quiz = 3},
    new ViewHistory {YYMMDD = "190514", Learn = 5, Practice = 6, Quiz = 7},
    new ViewHistory {YYMMDD = "190415", Learn = 100, Practice = 110, Quiz = 120},
    new ViewHistory {YYMMDD = "190414", Learn = 150, Practice = 160, Quiz = 170}
};

var monthlyTotals = views.GroupBy(
    v => v.YYMMDD.Substring(0, 4),
    v => v,
    (yearMonth, groupedViews) =>
        new
        {
            YearMonth = yearMonth,
            LearnSum = groupedViews.Sum(view => view.Learn),
            PracticeSum = groupedViews.Sum(view => view.Practice),
            QuizSum = groupedViews.Sum(view => view.Quiz)
        }).ToList();

Results

monthlyTotals (copied from Visual Studio Locals window while debugging)

monthlyTotals   Count = 2   System.Collections.Generic.List<<>f__AnonymousType0<string, int, int, int>>
    [0] { YearMonth = "1905", LearnSum = 6, PracticeSum = 8, QuizSum = 10 } <Anonymous Type>
    [1] { YearMonth = "1904", LearnSum = 250, PracticeSum = 270, QuizSum = 290 } <Anonymous Type>

Rather not use anonymous types?

And, of course, if you prefer not to use an anonymous type, you could define a new class (let's say MonthlyViewTotals for example) and instantiate a list of those for your monthlyTotals instead like this:

var monthlyTotals = views.GroupBy(
    v => v.YYMMDD.Substring(0, 4),
    v => v,
    (yearMonth, groupedViews) =>
        new MonthlyViewTotals        // <-- no more anonymous types
        {
            YearMonth = yearMonth,
            LearnSum = groupedViews.Sum(view => view.Learn),
            PracticeSum = groupedViews.Sum(view => view.Practice),
            QuizSum = groupedViews.Sum(view => view.Quiz)
        }).ToList();


问:
ASP.NET Core 2.2 kestrel server's performance issue
I'm facing problem with kestrel server's performance. I have following scenario :

```<code>    TestClient(JMeter) -> DemoAPI-1(Kestrel) -> DemoAPI-2(IIS)
</code>```

I'm trying to create a sample application that could get the file content as and when requested.
TestClient(100 Threads) requests to DemoAPI-1 which in turn request to DemoAPI-2. DemoAPI-2 reads a fixed XML file(1 MB max) and returns it's content as a response(In production DemoAPI-2 is not going to be exposed to outside world).

When I tested direct access from TestClient -> DemoAPI-2 I got expected result(good) which is following :

Average : 368ms

Minimum : 40ms

Maximum : 1056ms

Throughput : 40.1/sec

But when I tried to access it through DemoAPI-1 I got following result :

Average : 48232ms

Minimum : 21095ms

Maximum : 49377ms

Throughput : 2.0/sec

As you can see there is a huge difference.I'm not getting even the 10% throughput of DemoAPI-2. I was told has kestrel is more efficient and fast compared to traditional IIS. Also because there is no problem in direct access, I think we can eliminate the possible of problem on DemoAPI-2.

※Code of DemoAPI-1 :

string base64Encoded = null;
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var response = await this.httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);

            if (response.StatusCode.Equals(HttpStatusCode.OK))
            {
                var content = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                base64Encoded = Convert.ToBase64String(content);
            }
return base64Encoded;
```
<p>※Code of DemoAPI-2 :</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet("Demo2")]
    public async Task<IActionResult> Demo2Async(int wait)
    {
        try
        {
            if (wait > 0)
            {
                await Task.Delay(wait);
            }
            var path = Path.Combine(Directory.GetCurrentDirectory(), "test.xml");
            var file = System.IO.File.ReadAllText(path);
            return Content(file);
        }
        catch (System.Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }
</code>```

Some additional information :

Both APIs are async.

Both APIs are hosted on different EC2 instances(C5.xlarge Windows Server 2016).

DemoAPI-1(kestrel) is a self-contained API(without reverse proxy)

TestClient(jMeter) is set to 100 thread for this testing.

No other configuration is done for kestrel server as of now.

There are no action filter, middleware or logging that could effect the performance as of now.

Communication is done using SSL on 5001 port.

Wait parameter for DemoAPI2 is set to 0 as of now.

The CPU usage of DEMOAPI-1 is not over 40%.

答:
DEMOAPI-1 performs a non-asynchronous read of the streams:

var bytes = stream.Read(read, 0, DataChunkSize);

while (bytes > 0)
{
  buffer += System.Text.Encoding.UTF8.GetString(read, 0, bytes);
  // Replace with ReadAsync
  bytes = stream.Read(read, 0, DataChunkSize);
}
```

That can be an issue with throughput on a lot of requests.

Also, I'm not fully aware of why are you not testing the same code with IIS and Kestrel, I would assume you need to make only environmental changes and not the code.

Body:
I'm facing problem with kestrel server's performance. I have following scenario :

    TestClient(JMeter) -> DemoAPI-1(Kestrel) -> DemoAPI-2(IIS)

I'm trying to create a sample application that could get the file content as and when requested.
TestClient(100 Threads) requests to DemoAPI-1 which in turn request to DemoAPI-2. DemoAPI-2 reads a fixed XML file(1 MB max) and returns it's content as a response(In production DemoAPI-2 is not going to be exposed to outside world).

When I tested direct access from TestClient -> DemoAPI-2 I got expected result(good) which is following :

Average : 368ms

Minimum : 40ms

Maximum : 1056ms

Throughput : 40.1/sec

But when I tried to access it through DemoAPI-1 I got following result :

Average : 48232ms

Minimum : 21095ms

Maximum : 49377ms

Throughput : 2.0/sec

As you can see there is a huge difference.I'm not getting even the 10% throughput of DemoAPI-2. I was told has kestrel is more efficient and fast compared to traditional IIS. Also because there is no problem in direct access, I think we can eliminate the possible of problem on DemoAPI-2.

※Code of DemoAPI-1 :

string base64Encoded = null;
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var response = await this.httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);

            if (response.StatusCode.Equals(HttpStatusCode.OK))
            {
                var content = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                base64Encoded = Convert.ToBase64String(content);
            }
return base64Encoded;

※Code of DemoAPI-2 :

[HttpGet("Demo2")]
    public async Task<IActionResult> Demo2Async(int wait)
    {
        try
        {
            if (wait > 0)
            {
                await Task.Delay(wait);
            }
            var path = Path.Combine(Directory.GetCurrentDirectory(), "test.xml");
            var file = System.IO.File.ReadAllText(path);
            return Content(file);
        }
        catch (System.Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }

Some additional information :

Both APIs are async.

Both APIs are hosted on different EC2 instances(C5.xlarge Windows Server 2016).

DemoAPI-1(kestrel) is a self-contained API(without reverse proxy)

TestClient(jMeter) is set to 100 thread for this testing.

No other configuration is done for kestrel server as of now.

There are no action filter, middleware or logging that could effect the performance as of now.

Communication is done using SSL on 5001 port.

Wait parameter for DemoAPI2 is set to 0 as of now.

The CPU usage of DEMOAPI-1 is not over 40%.

Body:
DEMOAPI-1 performs a non-asynchronous read of the streams:

var bytes = stream.Read(read, 0, DataChunkSize);

while (bytes > 0)
{
  buffer += System.Text.Encoding.UTF8.GetString(read, 0, bytes);
  // Replace with ReadAsync
  bytes = stream.Read(read, 0, DataChunkSize);
}

That can be an issue with throughput on a lot of requests.

Also, I'm not fully aware of why are you not testing the same code with IIS and Kestrel, I would assume you need to make only environmental changes and not the code.


问:
Dotnet upgrade - 2.0 to 3.5 - performance
We have a number of winforms apps that are written in dotnet 2.0.  Are there any performance upgrades that we would expect when taking transistion to 3.5 runtime?  Any particular benefits we will get, besides the language features?</p>

答: There are probably a few minor performance improvements and bug fixes but the biggest benefit would be the improvements you can gain from the new language features. You can also take advantage of the .NET Client Profile install for your client applications, which is essentially a subset of the .NET Framework that includes the bits that are most relevant to client client applications, which means a smaller download/install size.</p>

OwnerDisplayName: mek

OwnerDisplayName: Scott Dorman


问:
Is there a function to copy an array in C/C++?
I know that Java has a function System.arraycopy(); to copy an array. I was wondering if there is a function in C or C++ to copy an array. I was only able to find implementations to copy an array by using for loops, pointers, etc. But is there a library function that I can use to copy an array?

答:
Just include the standard library in your code.

```<code>#include<algorithm>
</code>```

Array size will be denoted as n

Your old Array

```<code>int oldArray[n]={10,20,30,40,50};
</code>```

Declare New Array in which you have to copy your old array value

```<code>int newArray[n];
</code>```

Use this

```<code>copy_n(oldArray,n,newArray);
</code>```

Body:
Just include the standard library in your code.

#include<algorithm>

Array size will be denoted as n

Your old Array

int oldArray[n]={10,20,30,40,50};

Declare New Array in which you have to copy your old array value

int newArray[n];

Use this

copy_n(oldArray,n,newArray);


答:
Change

```<code>                if( $lesson_qry->have_posts() ){ ?>
                <div class="row">

                   <?php
                    while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                        <div class="col">

                            <?php
                                if( has_post_thumbnail() ){ ?>
                                    <div class="img-holder">
                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                    </div>
                            <?php } ?>

                            <div class="text-holder">
                                <h3 class="title"><?php the_title(); ?></h3>
                                <?php the_content(); ?>
                            </div>

                        </div>

                    <?php } ?>

                </div>
            <?php }
</code>```

to

```<code>            if( $lesson_qry->have_posts() ){ ?>
               <?php
               $i=3;
                while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>
                    <?php if($i%3==0) echo '<div class="row">';
                        <div class="col">
                            <?php
                                if( has_post_thumbnail() ){ ?>
                                    <div class="img-holder">
                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                    </div>
                            <?php } ?>
                            <div class="text-holder">
                                <h3 class="title"><?php the_title(); ?></h3>
                                <?php the_content(); ?>
                            </div>
                        </div>
                    <?php $i++; if($i%3==0) echo '</div>';
                <?php }if($i%3!=0) echo '</div>'; ?>
            <?php }
</code>```

Title: How to create a new row after 3 column in my code

Body:
I am customizing a theme in which there was a option to add only three services sections. I had added more three sections and are getting reflected on my HTML. defacult is is createing somthing like this :

row > col1 > col1 > col1 > col1 > col1 > col1

I want to create Like this :

row > col1 > col1 > col1
row > col1 > col1 > col1

Kindly help me with this

<?php
/**
 * lessons Section
 *
 * @package Preschool_and_Kindergarten
*/
     $title        = get_theme_mod( 'preschool_and_kindergarten_lessons_section_title' );
     $description  = get_theme_mod( 'preschool_and_kindergarten_lessons_section_description' );
     $lesson_one   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_one' );
     $lesson_two   = get_theme_mod( 'preschool_and_kindergarten_lesson_post_two' );
     $lesson_three = get_theme_mod( 'preschool_and_kindergarten_lesson_post_three' );
     $lesson_four = get_theme_mod( 'preschool_and_kindergarten_lesson_post_four' );
     $lesson_five = get_theme_mod( 'preschool_and_kindergarten_lesson_post_five' );
     $lesson_six = get_theme_mod( 'preschool_and_kindergarten_lesson_post_six' );
     $lessons_posts = array( $lesson_one, $lesson_two, $lesson_three, $lesson_four, $lesson_five, $lesson_six );
     $lessons_posts = array_diff( array_unique( $lessons_posts ), array('') );
?>

        <?php
            preschool_and_kindergarten_get_section_header( $title, $description );

            if( $lessons_posts ):

                $lesson_qry = new WP_Query(array(
                    'post__in'   => $lessons_posts,
                    'orderby'   => 'post__in',
                    'posts_per_page' => -1,
                    'ignore_sticky_posts' => true
                    ));

                if( $lesson_qry->have_posts() ){ ?>

                       <?php
                        while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                                <?php
                                    if( has_post_thumbnail() ){ ?>

                                            <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>

                                <?php } ?>

<?php the_title(); ?>

                                    <?php the_content(); ?>

                        <?php } ?>

                <?php }
            wp_reset_postdata();
        endif; ?>

Body:
Change

                if( $lesson_qry->have_posts() ){ ?>
                <div class="row">

                   <?php
                    while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>

                        <div class="col">

                            <?php
                                if( has_post_thumbnail() ){ ?>
                                    <div class="img-holder">
                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                    </div>
                            <?php } ?>

                            <div class="text-holder">
                                <h3 class="title"><?php the_title(); ?></h3>
                                <?php the_content(); ?>
                            </div>

                        </div>

                    <?php } ?>

                </div>
            <?php }

to

            if( $lesson_qry->have_posts() ){ ?>
               <?php
               $i=3;
                while( $lesson_qry->have_posts() ){ $lesson_qry->the_post(); ?>
                    <?php if($i%3==0) echo '<div class="row">';
                        <div class="col">
                            <?php
                                if( has_post_thumbnail() ){ ?>
                                    <div class="img-holder">
                                        <?php the_post_thumbnail( 'preschool-and-kindergarten-lesson-thumb', array( 'itemprop' => 'image' ) ); ?>
                                    </div>
                            <?php } ?>
                            <div class="text-holder">
                                <h3 class="title"><?php the_title(); ?></h3>
                                <?php the_content(); ?>
                            </div>
                        </div>
                    <?php $i++; if($i%3==0) echo '</div>';
                <?php }if($i%3!=0) echo '</div>'; ?>
            <?php }


问:
Display 2 tables in 1 view
I want to display 2 tables in 1 view

like this:

```<code>{{ $match->title }}
{{ $distance->distance }}
</code>```

but I can't get it to work.

This is my controller:

```<code>public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}
</code>```

why does the $distances return to null when I dd(): it?

this is my view:

```<code><th scope="col" class="text-center"><strong>Game Title:</strong>
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach
              </th>
                <th scope="col" class="text-center"><strong>Target: Distance</strong>
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach
</th>
</code>```

If I do this the view gives me 404

```<code>$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();
</code>```

What am I doing wrong here?

答:
Try this changes

```<code>$matches = BikeGame::where('id',$request->id)->first();
$distances = Distance::where('id',$request->id)->first();
</code>```

Hope it useful for you.

Title: Display 2 tables in 1 view

Body:
I want to display 2 tables in 1 view

like this:

{{ $match->title }}
{{ $distance->distance }}

but I can't get it to work.

This is my controller:

public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}

why does the $distances return to null when I dd(): it?

this is my view:

Game Title:
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach

                Target: Distance
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach

If I do this the view gives me 404

$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();

What am I doing wrong here?

Body:
Try this changes

$matches = BikeGame::where('id',$request->id)->first();
$distances = Distance::where('id',$request->id)->first();

Hope it useful for you.