问:
Spring Data JPA Hibernate query cache is not working
I use spring boot starter data jpa 2.6.4

Hibernate Second level query cache doesn't work, every time the sql query gets called.

Not able to understand what actually got missed.

If anyone has faced a similar issue, please post your answers

application.properties:

```<code>#HIBERNATE SECOND LEVEL CACHE
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true
</code>```

pom.xml:

```<code><dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-ehcache</artifactId>
   <version>5.6.5.Final</version>
</dependency>
</code>```

Entity.class:

```<code>package com.dhre.realconnect.notificationService.notificationEntities;

import com.dhre.realconnect.common.dto.BaseObject;
import lombok.Data;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serial;
import java.sql.Timestamp;

/**
 * Entity class for event to lookup up from list of all type of event and map to
 * eventID
 *
 * @author M1081522
 *
 */
@Entity
@Data
@Table(name = "Events")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Events extends BaseObject {

   @Serial
   private static final long serialVersionUID = 1L;
   @Id
   @Column
   private int eventID;
   @Column
   private String eventCode;
   @Column
   private int categoryID;
   @Column
   private int eventCategoryID;
   @Column
   private boolean isMandatory;
   @Column
   private String eventDescription;
   @Column
   private Timestamp lastUpdated;
   @Column
   private boolean includeAttachments;
   @Column
   private boolean isCustomerEvent;
   @Column
   private boolean useDefaultSender;
}
</code>```

Repository:

```<code>package com.dhre.realconnect.notificationService.notificationRepository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.stereotype.Repository;

import com.dhre.realconnect.notificationService.notificationEntities.Events;

import javax.persistence.QueryHint;

/**
 * Repository for Event table in Notification database
 * @author M1081522
 *
 */
@Repository
public interface EventRepository extends JpaRepository<Events, Integer>{

   @Query(value = "SELECT * FROM Events WHERE EventCode=:eventCode", nativeQuery = true)
   @QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
   Optional<Events> getByEventCode(String eventCode);

}
</code>```

Configuration:

```<code>package com.dhre.realconnect.notificationService.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.dhre.realconnect.notificationService.notificationEntities.MessageEntity;
/**
 * Notification Database config class
 *
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "notificationEntityManagerFactory", transactionManagerRef = "notificationTransactionManager", basePackages = {
        "com.dhre.realconnect.notificationService.notificationRepository" })
public class NotificationDataSourceConfig {

    @Value("${spring.datasource.notification.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.notification.url}")
    private String databaseUrl;
    @Value("${spring.datasource.notification.username}")
    private String databaseUserName;
    @Value("${spring.datasource.notification.password}")
    private String databasePassword;
    @Value("${spring.jpa.show-sql}")
    private String hibernateShowSql;
    @Value("${spring.jpa.properties.hibernate.dialect}")
    private String hibernateDialect;

    // TODO add multiple data source needs to be added

    @Primary
    @Bean(name="notificationEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean notificationEntityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(getDataSource());
        em.setPackagesToScan(new String[] { MessageEntity.class.getPackageName() });

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    @Primary
    @Bean
    public DataSource getDataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();

        // make rest calls here to fetch username and password from the configration
        // server

        dataSourceBuilder.driverClassName(driverClassName);
        dataSourceBuilder.url(databaseUrl);
        dataSourceBuilder.username(databaseUserName);
        dataSourceBuilder.password(databasePassword);
        return dataSourceBuilder.build();
    }

    @Primary
    @Bean(name="notificationTransactionManager")
    public PlatformTransactionManager notificationTransactionManager() {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(notificationEntityManagerFactory().getObject());
        return jpaTransactionManager;
    }

    @Primary
    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.show_sql", hibernateShowSql);
        properties.setProperty("hibernate.properties.dialect", hibernateDialect);

        return properties;
    }

}
</code>```

I have tried the hibernate second level query caching, but it is not working

Body:
I use spring boot starter data jpa 2.6.4

Hibernate Second level query cache doesn't work, every time the sql query gets called.

Not able to understand what actually got missed.

If anyone has faced a similar issue, please post your answers

application.properties:

#HIBERNATE SECOND LEVEL CACHE
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.jpa.properties.javax.persistence.sharedCache.mode=ENABLE_SELECTIVE
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.use_query_cache=true

pom.xml:

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-ehcache</artifactId>
   <version>5.6.5.Final</version>
</dependency>

Entity.class:

package com.dhre.realconnect.notificationService.notificationEntities;

import com.dhre.realconnect.common.dto.BaseObject;
import lombok.Data;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serial;
import java.sql.Timestamp;

/**
 * Entity class for event to lookup up from list of all type of event and map to
 * eventID
 *
 * @author M1081522
 *
 */
@Entity
@Data
@Table(name = "Events")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Events extends BaseObject {

   @Serial
   private static final long serialVersionUID = 1L;
   @Id
   @Column
   private int eventID;
   @Column
   private String eventCode;
   @Column
   private int categoryID;
   @Column
   private int eventCategoryID;
   @Column
   private boolean isMandatory;
   @Column
   private String eventDescription;
   @Column
   private Timestamp lastUpdated;
   @Column
   private boolean includeAttachments;
   @Column
   private boolean isCustomerEvent;
   @Column
   private boolean useDefaultSender;
}

Repository:

package com.dhre.realconnect.notificationService.notificationRepository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.stereotype.Repository;

import com.dhre.realconnect.notificationService.notificationEntities.Events;

import javax.persistence.QueryHint;

/**
 * Repository for Event table in Notification database
 * @author M1081522
 *
 */
@Repository
public interface EventRepository extends JpaRepository<Events, Integer>{

   @Query(value = "SELECT * FROM Events WHERE EventCode=:eventCode", nativeQuery = true)
   @QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
   Optional<Events> getByEventCode(String eventCode);

}

Configuration:

package com.dhre.realconnect.notificationService.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.dhre.realconnect.notificationService.notificationEntities.MessageEntity;
/**
 * Notification Database config class
 *
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "notificationEntityManagerFactory", transactionManagerRef = "notificationTransactionManager", basePackages = {
        "com.dhre.realconnect.notificationService.notificationRepository" })
public class NotificationDataSourceConfig {

    @Value("${spring.datasource.notification.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.notification.url}")
    private String databaseUrl;
    @Value("${spring.datasource.notification.username}")
    private String databaseUserName;
    @Value("${spring.datasource.notification.password}")
    private String databasePassword;
    @Value("${spring.jpa.show-sql}")
    private String hibernateShowSql;
    @Value("${spring.jpa.properties.hibernate.dialect}")
    private String hibernateDialect;

    // TODO add multiple data source needs to be added

    @Primary
    @Bean(name="notificationEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean notificationEntityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(getDataSource());
        em.setPackagesToScan(new String[] { MessageEntity.class.getPackageName() });

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());
        return em;
    }

    @Primary
    @Bean
    public DataSource getDataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();

        // make rest calls here to fetch username and password from the configration
        // server

        dataSourceBuilder.driverClassName(driverClassName);
        dataSourceBuilder.url(databaseUrl);
        dataSourceBuilder.username(databaseUserName);
        dataSourceBuilder.password(databasePassword);
        return dataSourceBuilder.build();
    }

    @Primary
    @Bean(name="notificationTransactionManager")
    public PlatformTransactionManager notificationTransactionManager() {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(notificationEntityManagerFactory().getObject());
        return jpaTransactionManager;
    }

    @Primary
    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.show_sql", hibernateShowSql);
        properties.setProperty("hibernate.properties.dialect", hibernateDialect);

        return properties;
    }

}

I have tried the hibernate second level query caching, but it is not working


来源: stackexchange

问:
I am unable to install npm package
I have made an empty folder and trying to install the npm package inside the folder so I can start to write an application. I have been attempting to install package JSON with npm install -y but it only installs the package-lock-JSON but it's showing me the following error. I even reinstalled the node on my PC didn't work.

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\hasan\Desktop\Githubfiles\node _express_mongodb/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\hasan\Desktop\Githubfiles\node _express_mongodb\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\hasan\AppData\Local\npm-cache_logs\2022-12-06T12_18_28_964Z-debug-0.log
PS C:\Users\hasan\Desktop\Githubfiles\node _express_mongodb>

ContentLicense: CC BY-SA 4.0

Title: I am unable to install npm package


问:
BigQuery: Trying to recognize scheduled queries in INFORMATION_SCHEMA. Possible idea: Add key:value label
I try to recognize scheduled queries on gcp to see which scheduled query is costing me the most.

But if I run the following query, I can only see the job_id which is not really informative, and the labels also don't contain the resource name of the scheduled query.

SELECT creation_time, job_id, parent_job_id, user_email, labels, bytes_billed
FROM `my_project_id.region-eu.INFORMATION_SCHEMA.JOBS`
WHERE starts_with(job_id, 'scheduled_query') and parent_job_id is null
ORDER BY creation_time desc
```

One solution could be to add labels to the scheduled query.

I tried adding a label to a session, by adding this to my scheduled query, but this only added the query_key and label to a child job:

SET @@query_label = "scheduled_query:some_name_that_i_like";

https://cloud.google.com/bigquery/docs/adding-labels#adding-label-to-session

I also tried the bq cli client, but this also didn't work:

bq update --set_label scheduled_query:some_name_that_i_like --transfer_config projects/some_project_id_number/locations/europe/transferConfigs/some_transfer_config_number

How can I make it easier to recognize which scheduled query was run?

This question is (somewhat) related:

BigQuery - Get the display name of scheduled query from INFORMATION_SCHEMA

Body:
I try to recognize scheduled queries on gcp to see which scheduled query is costing me the most.

But if I run the following query, I can only see the job_id which is not really informative, and the labels also don't contain the resource name of the scheduled query.

SELECT creation_time, job_id, parent_job_id, user_email, labels, bytes_billed
FROM `my_project_id.region-eu.INFORMATION_SCHEMA.JOBS`
WHERE starts_with(job_id, 'scheduled_query') and parent_job_id is null
ORDER BY creation_time desc

One solution could be to add labels to the scheduled query.

I tried adding a label to a session, by adding this to my scheduled query, but this only added the query_key and label to a child job:

SET @@query_label = "scheduled_query:some_name_that_i_like";

https://cloud.google.com/bigquery/docs/adding-labels#adding-label-to-session

I also tried the bq cli client, but this also didn't work:

bq update --set_label scheduled_query:some_name_that_i_like --transfer_config projects/some_project_id_number/locations/europe/transferConfigs/some_transfer_config_number

How can I make it easier to recognize which scheduled query was run?

This question is (somewhat) related:

BigQuery - Get the display name of scheduled query from INFORMATION_SCHEMA


问:
How to emulate Keyboard and Mouse on a loced VDI
i have a problem and can't find a solution so far.
So i thought maybe you can help me? :)

I'm working on an virtuel Citrix Client.
Everytime when i lock the VDI, the screen, the Keyboard & Mouse Input is also locked/stopped.

Is there a way in vb.net to monitor or start an KVM emulation when the VDI is locked?

I found a way to monitor, when the VDI is locked with "SystemEvents.SessionSwitch".
But so far i did not found a way to controll the Emulation of an KVM Input.


问:
How can I Specify TLS 1.3 Signature Algorithms in C# HttpClient and SetPointManager?
With the help of a colleague, I have discovered some differences in some Windows 11 clients where the TLS 1.3 signature algorithms defined in the registry under ...

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Cryptography\Configuration\Local\SSL\00010003\Functions

... can vary a lot. Specifically I'm missing the RFC-8446 required signature algorithms that will result in a critical encryption alert from the service if a client attempts to connect without these:

RSAE-PSS/SHA256

RSAE-PSS/SHA384

RSAE-PSS/SHA512

Ideally, I'd prefer not to edit the user's registry. Is there a way to add these signature algorithms if missing temporarily in my System.Net.HttpClient? I see there's a Properties property (dictionary) for the System.Net.HttpClientHandler, but nothing specific I can find on helping here. For cases where I'm using third party libraries where the System.Net.ServicePointManager might be more appropriate, is there a way to do something similar here?

Thanks for any advice anyone can offer. Much appreciated. I could not find any classes, properties, etc. to help inject any of the required but missing TLS 1.3 signature algorithms.


问:
Terraform Import creating duplicate configurations
I am trying to import some s3 buckets under terraform state. However, importing an S3 bucket creates conflict for configs that used to be arguments under "aws_s3_bucket" but now have been deprecated and are resources on their own.

The problem is that arguments like: aws_s3_bucket_server_side_encryption_configuration" can mess things up. While I define a "aws_s3_bucket_server_side_encryption_configuration" resource for example to specify the encryption of the bucket, when I do a terraform import on the bucket it appears also as a configuration under the "aws_s3_bucket" resource. That creates a game of cat and mouse where "aws_s3_bucket_server_side_encryption_configuration" creates encryption for S3 -> "aws_s3_bucket" doesn't have S3 encryption in its state -> "aws_s3_bucket" deletes the encryption on the next plan.


问:
How to deal with dimension change when the keyboard pops up using Quasar+capacitor for mobile apps
I am currently building a mobile app using Quasar+capacitor. And it is great. But, when I tap on a input field and keyboard comes, the UI is all over the place. How do I deal with it?

Normal UI

When Keyboard input is open

I wanted the keyboard to push the UI up, like how it works in react native or flutter


问:
Changing Apache2 configuration to access icinga2 on root domain
I am trying to configure icinga using Apache2 web server on Unbutu OS, so the icinga dashboard is available on the root domain (http://example.com) and not on path (http://example.com/icingaweb2).

I had changed the DocumentRoot in /etc/apache2/sites-available/000-default.conf to point to /usr/share/icingaweb2/public from /var/www/html. But this gives me empty response when navigating to http://example.com and http://example.com/icingaweb2 still working.

Can someone help with correct Apache2 configuration so the root domain (without path) shows icinga dashboard?


问:
Undefined variable $title in laravel
I am getting subject error on web hosting in regard to adding component in laravel, while same code is working on XAMPP. please guide what is the possible solution to it.

Component File *.php

```<code>    //Creating  title variable which is public
    public $title="";
    public function __construct($componentName)
    {
        $this->title=$componentName;
    }

</code>```

Component file *.blade.php

```<code><div>
    <h1 style="color:blueviolet;">Header from Component for page {{$title}}</h1>
</div>
</code>```

Welcome File *.blade.php

```<code><x-header componentName="Welcome Page" />
</code>```

I am getting below error on webhosting

Undefined variable $title

Title: Undefined variable $title in laravel

Body:
I am getting subject error on web hosting in regard to adding component in laravel, while same code is working on XAMPP. please guide what is the possible solution to it.

Component File *.php

    //Creating  title variable which is public
    public $title="";
    public function __construct($componentName)
    {
        $this->title=$componentName;
    }

Component file *.blade.php

Header from Component for page {{$title}}

Welcome File *.blade.php

<x-header componentName="Welcome Page" />

I am getting below error on webhosting

Undefined variable $title


问:
Call React functions from a page with external js (Chrome Extension)
I am making a Chrome extension that adds a button to a React page (whatsapp web). And I want this button to call an existing function, exactly as another already existing button that is inside a menu.

My extension was built using React.js too.

What I already know, is that that existing function is named handleSelectMessages() (I used the React Developer Tools to see that), but I cant find a way to call this function.

How can it be made? (Keep in mind that I cant make changes to the original react page, I can only inject new js)

I`ve tryed the very basic:

```<code><button onClick={() => handleSelectMessages()}/>
</code>```

But as expected it didnt do anything.

I`ve tryed also:

```<code><button onClick={() => window.handleSelectMessages()}/>
</code>```

But it seems it is not avaliable globally.

Body:
I am making a Chrome extension that adds a button to a React page (whatsapp web). And I want this button to call an existing function, exactly as another already existing button that is inside a menu.

My extension was built using React.js too.

What I already know, is that that existing function is named handleSelectMessages() (I used the React Developer Tools to see that), but I cant find a way to call this function.

How can it be made? (Keep in mind that I cant make changes to the original react page, I can only inject new js)

I`ve tryed the very basic:

<button onClick={() => handleSelectMessages()}/>

But as expected it didnt do anything.

I`ve tryed also:

<button onClick={() => window.handleSelectMessages()}/>

But it seems it is not avaliable globally.


问:
Selenium Python | Explicit Waits - Properly Using
I was watching YouTube video where I'd noticed that the following code:

import time
from selenium import webdriver

driver = webdriver.Chrome(executable_path="...") # here just creates new Chrome driver

try:
   driver.get(URI)
   time.sleep(3)

   respond = driver.page_source
   print(respond)

except Exception as _ex:
   print(_ex)
finally:
   driver.close()
   driver.quit()
```

But at the same time it says that you don't have to use time.sleep statement. Instead you can use WebDriverWait.

So my question is how could we refactor this code using WebDriverWait and why do we need to use wait here in general?

Body:
I was watching YouTube video where I'd noticed that the following code:

import time
from selenium import webdriver

driver = webdriver.Chrome(executable_path="...") # here just creates new Chrome driver

try:
   driver.get(URI)
   time.sleep(3)

   respond = driver.page_source
   print(respond)

except Exception as _ex:
   print(_ex)
finally:
   driver.close()
   driver.quit()

But at the same time it says that you don't have to use time.sleep statement. Instead you can use WebDriverWait.

So my question is how could we refactor this code using WebDriverWait and why do we need to use wait here in general?


问:
Drop partition ORA-00905
In the procedure I want to set up to drop the partition in an hour. To prevent the procedure from falling, there will be no partitions, added IF EXISITS. But after starting the procedure, it displays an error ORA-00905 Missing keyword:</p>
```<code>EXECUTE IMMEDIATE 'ALTER TABLE TEST_TABLE DROP IF EXISTS PARTITION FOR (TO_DATE(''' ||
TO_CHAR(trunc(sysdate, 'hh'),
                   'YYYY-MM-DD HH24:MI') ||
                   ''', ''YYYY-MM-DD HH24:MI''))';
</code>```

Title: Drop partition ORA-00905

Body:
In the procedure I want to set up to drop the partition in an hour. To prevent the procedure from falling, there will be no partitions, added IF EXISITS. But after starting the procedure, it displays an error ORA-00905 Missing keyword:

EXECUTE IMMEDIATE 'ALTER TABLE TEST_TABLE DROP IF EXISTS PARTITION FOR (TO_DATE(''' ||
TO_CHAR(trunc(sysdate, 'hh'),
                   'YYYY-MM-DD HH24:MI') ||
                   ''', ''YYYY-MM-DD HH24:MI''))';


问:
Create excel workbook from byte array of sub part of existing excel file
I would like to create a Apache POI excel workbook from the byte[] of partially read existing excel file. Please find the details as below

Download big excel file in multiple small parts from API. returns byte[]

Downloaded part-1 needs to convert to excel workbook and process the records

above will continue till the end of file

I am using Apache POI using Java but getting below exception
org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file

```<code>byte[] downloadPart = downloadFile(rangeDetails);

InputStream targetStream = new ByteArrayInputStream(downloadPart);

Workbook workbook = new XSSFWorkbook(targetStream);
</code>```

Can someone please help me to create a new workbook for every sub part of big excel file.

Body:
I would like to create a Apache POI excel workbook from the byte[] of partially read existing excel file. Please find the details as below

Download big excel file in multiple small parts from API. returns byte[]

Downloaded part-1 needs to convert to excel workbook and process the records

above will continue till the end of file

I am using Apache POI using Java but getting below exception
org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file

byte[] downloadPart = downloadFile(rangeDetails);

InputStream targetStream = new ByteArrayInputStream(downloadPart);

Workbook workbook = new XSSFWorkbook(targetStream);

Can someone please help me to create a new workbook for every sub part of big excel file.


问:
Updated excel chart in word document not getting reflected - apache poi
I want to update charts in word document using Apache POI-3.17 in Java.
I am able to update underlying excel sheet related to chart using below code.
But when I open the word document charts are not getting reflected as per updated values
When I click on chart and do "Edit Data" at that time chart is reflected.
Code is as below</p>
```<code>import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.POIXMLDocumentPart.RelationPart;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

public class SherlockApp {

public static void main(String[] args) {

    String fileName = "D:\\Circular Economy Report Template.docx";

    try (XWPFDocument doc = new XWPFDocument(Files.newInputStream(Paths.get(fileName)))) {

        // output the same as 8.1
        List<XWPFParagraph> list = doc.getParagraphs();
        for (XWPFParagraph paragraph : list) {
            // System.out.println(paragraph.getText());
        }

        for (POIXMLDocumentPart part : doc.getRelations()) {
            if (!StringUtils.equalsIgnoreCase(part.getPackagePart().getContentTypeDetails().getSubType(),
                    "vnd.openxmlformats-officedocument.drawingml.chart+xml")) {
                continue;
            }
            int i=1;

            for(RelationPart p : part.getRelationParts()) {
                System.out.println("Test -> "+p.getDocumentPart());

                InputStream str = p.getDocumentPart().getPackagePart().getInputStream();

                XSSFWorkbook book = new XSSFWorkbook(str);

                XSSFSheet sheet = book.getSheetAt(0);

                Iterator<Row> itr = sheet.iterator();

                while (itr.hasNext()) {
                    Row row = itr.next();
                    Iterator<Cell> cellIterator = row.cellIterator(); // iterating over each column
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING: // field that represents string cell type
                            System.out.print(cell.getStringCellValue() + "\t\t\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC: // field that represents number cell type
                            System.out.print(cell.getNumericCellValue() + "\t\t\t");
                            break;
                        default:
                        }
                    }
                    System.out.println("");
                }

                Cell cell = null;

                //update the details
                cell = sheet.getRow(1).getCell(2);
                cell.setCellValue(0.1);

                cell = sheet.getRow(1).getCell(1);
                cell.setCellValue(0.9);

                System.out.println("Cell Value -> "+cell.getNumericCellValue());

                str.close();

                OutputStream oStr = p.getDocumentPart().getPackagePart().getOutputStream();
                book.write(oStr);
                book.close();

                //Update word document
                try (FileOutputStream out = new FileOutputStream(fileName)) {
                    doc.write(out);
                }
            }
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}
</code>```

Body:
I want to update charts in word document using Apache POI-3.17 in Java.
I am able to update underlying excel sheet related to chart using below code.
But when I open the word document charts are not getting reflected as per updated values
When I click on chart and do "Edit Data" at that time chart is reflected.
Code is as below

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.POIXMLDocumentPart.RelationPart;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

public class SherlockApp {

public static void main(String[] args) {

    String fileName = "D:\\Circular Economy Report Template.docx";

    try (XWPFDocument doc = new XWPFDocument(Files.newInputStream(Paths.get(fileName)))) {

        // output the same as 8.1
        List<XWPFParagraph> list = doc.getParagraphs();
        for (XWPFParagraph paragraph : list) {
            // System.out.println(paragraph.getText());
        }

        for (POIXMLDocumentPart part : doc.getRelations()) {
            if (!StringUtils.equalsIgnoreCase(part.getPackagePart().getContentTypeDetails().getSubType(),
                    "vnd.openxmlformats-officedocument.drawingml.chart+xml")) {
                continue;
            }
            int i=1;

            for(RelationPart p : part.getRelationParts()) {
                System.out.println("Test -> "+p.getDocumentPart());

                InputStream str = p.getDocumentPart().getPackagePart().getInputStream();

                XSSFWorkbook book = new XSSFWorkbook(str);

                XSSFSheet sheet = book.getSheetAt(0);

                Iterator<Row> itr = sheet.iterator();

                while (itr.hasNext()) {
                    Row row = itr.next();
                    Iterator<Cell> cellIterator = row.cellIterator(); // iterating over each column
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING: // field that represents string cell type
                            System.out.print(cell.getStringCellValue() + "\t\t\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC: // field that represents number cell type
                            System.out.print(cell.getNumericCellValue() + "\t\t\t");
                            break;
                        default:
                        }
                    }
                    System.out.println("");
                }

                Cell cell = null;

                //update the details
                cell = sheet.getRow(1).getCell(2);
                cell.setCellValue(0.1);

                cell = sheet.getRow(1).getCell(1);
                cell.setCellValue(0.9);

                System.out.println("Cell Value -> "+cell.getNumericCellValue());

                str.close();

                OutputStream oStr = p.getDocumentPart().getPackagePart().getOutputStream();
                book.write(oStr);
                book.close();

                //Update word document
                try (FileOutputStream out = new FileOutputStream(fileName)) {
                    doc.write(out);
                }
            }
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}


问:
Make a multilayered circos plot in R from a dataframe
I want to make a circos plot from a data frame consisting name of country (first column), fruit (second column) and category (third column). My rule is that if the row of second and third column matches, the corresponding countries are considered to be connected. I have 400x3 dataframe and want to make a plot. Here is example of data:

```<code>mydf <- data.frame(country=c('China','Shree Lanka','China','Australia','China','China','Australia','Australia','Australia'),
   Item=c('Apple','Avacado','Avacado','Avacado','Apple','Organge','Apple','Organge','Apple'),
                   Features=c('a','a','c','c','d','d','d','d','a'))
</code>```

In above example, China and Australia are connected for matching cases, So is between China and Australia, but different combinations (I want to show these combination as well in plot)

Body:
I want to make a circos plot from a data frame consisting name of country (first column), fruit (second column) and category (third column). My rule is that if the row of second and third column matches, the corresponding countries are considered to be connected. I have 400x3 dataframe and want to make a plot. Here is example of data:

mydf <- data.frame(country=c('China','Shree Lanka','China','Australia','China','China','Australia','Australia','Australia'),
   Item=c('Apple','Avacado','Avacado','Avacado','Apple','Organge','Apple','Organge','Apple'),
                   Features=c('a','a','c','c','d','d','d','d','a'))

In above example, China and Australia are connected for matching cases, So is between China and Australia, but different combinations (I want to show these combination as well in plot)


问:
my boolean is turning true before i want it to be
enter image description here

I have 2 moving squares(drawn from left top corner) that should turn color when they overlap. I made this boolean function to check if they overlap.

But when I run my code the boolean doesn't seem to be entirely correct because they change color before they overlap.

```<code>boolean overlap(float posx1, float posx2, float posy1, float posy2)
{
  if (posx1 > pos x 2 + size || posx1 + size < posx2 || posy1 > posy2 + size || posy1 + size < posy2)
  {
    return false;
  } else {
    return true;
  }
}
</code>```

The boolean works for the y-positions but not the x.

Body:
enter image description here

I have 2 moving squares(drawn from left top corner) that should turn color when they overlap. I made this boolean function to check if they overlap.

But when I run my code the boolean doesn't seem to be entirely correct because they change color before they overlap.

boolean overlap(float posx1, float posx2, float posy1, float posy2)
{
  if (posx1 > pos x 2 + size || posx1 + size < posx2 || posy1 > posy2 + size || posy1 + size < posy2)
  {
    return false;
  } else {
    return true;
  }
}

The boolean works for the y-positions but not the x.


问:
Combine simple JS /CSS Snippets
I have the following two snippets which im trying to combine.

Snippet #1: simple Tabs with a slider-animation when clicked. No swiping on mobile.

Snippet #2: same simple tabs without slider-animation when clicked. But swipeable on mobile.

Since i want to offer both features,

Tab-Content should change in a sliding-animation

and

Tab-Content should be swipable on mobile,

I need to combine both of these snippes.

Snippet#1:

const btn = [].slice.call(document.getElementsByTagName('button'))
btn.forEach((item, index) => {
  item.addEventListener('click',function(){
    btn.forEach((item) => {item.classList.remove('active')})
    item.classList.add('active')
    document.getElementById('tab').setAttribute('data-tab', index)
  })
}
)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    overflow: hidden;
}

.tabs {
    position: relative;
    -webkit-transition: all .9s ease-in-out;
    -moz-transition: all .9s ease-in-out;
    -ms-transition: all .9s ease-in-out;
    -o-transition: all .9s ease-in-out;
    transition: all .9s ease-in-out;

}

.tabs> * {
    width: 100%;
}

.tabs[data-tab='1'] {
    transform: translateX(-100%);
}

.tabs[data-tab='2'] {
    transform: translateX(-200%);
}
.tabs[data-tab='3'] {
    transform: translateX(-300%);
}
.tabs[data-tab='4'] {
    transform: translateX(-400%);
}

.inliner {

    white-space: nowrap;
}

.inliner > * {
    display: inline-block;
    *display: inline;
    *zoom: 1;
}</code>```

      <button> Tab 1</button>
       <button> Tab 2</button>
       <button> Tab 3</button>

Content 1

Content 2

Content 3

```
</div>
</div>
</p>
<p>Snippet#2:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const btn = [].slice.call(document.getElementsByTagName("button"));
    btn.forEach((item, index) => {
      item.addEventListener("click", function () {
        document.getElementById("tab").children[index].scrollIntoView();
      });
    });</code>```

* {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      #tab {
        display: flex;
        overflow: auto;
        scroll-behavior: smooth;
        scroll-snap-type: x mandatory;
      }
      #tab > * {
        flex-shrink: 0;
        width: 100%;
        scroll-snap-align: start;
        scroll-margin-top: 1rem;

        padding: 1rem 0.4rem;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
      <button>Tab 1</button>
      <button>Tab 2</button>
      <button>Tab 3</button>

      <div id="tab" class="tabs inliner">
        <div>
          <h2>Content 1</h2>
        </div>
        <div>
          <h2>Content 2</h2>
        </div>
        <div>
          <h2>Content 3</h2>
        </div>
      </div>
    </div></code>```

Title: Combine simple JS /CSS Snippets

Body:
I have the following two snippets which im trying to combine.

Snippet #1: simple Tabs with a slider-animation when clicked. No swiping on mobile.

Snippet #2: same simple tabs without slider-animation when clicked. But swipeable on mobile.

Since i want to offer both features,

Tab-Content should change in a sliding-animation

and

Tab-Content should be swipable on mobile,

I need to combine both of these snippes.

Snippet#1:

const btn = [].slice.call(document.getElementsByTagName('button'))
btn.forEach((item, index) => {
  item.addEventListener('click',function(){
    btn.forEach((item) => {item.classList.remove('active')})
    item.classList.add('active')
    document.getElementById('tab').setAttribute('data-tab', index)
  })
}
)

.wrapper {
    overflow: hidden;
}

.tabs {
    position: relative;
    -webkit-transition: all .9s ease-in-out;
    -moz-transition: all .9s ease-in-out;
    -ms-transition: all .9s ease-in-out;
    -o-transition: all .9s ease-in-out;
    transition: all .9s ease-in-out;

}

.tabs> * {
    width: 100%;
}

.tabs[data-tab='1'] {
    transform: translateX(-100%);
}

.tabs[data-tab='2'] {
    transform: translateX(-200%);
}
.tabs[data-tab='3'] {
    transform: translateX(-300%);
}
.tabs[data-tab='4'] {
    transform: translateX(-400%);
}

.inliner {

    white-space: nowrap;
}

.inliner > * {
    display: inline-block;
    *display: inline;
    *zoom: 1;
}

      <button> Tab 1</button>
       <button> Tab 2</button>
       <button> Tab 3</button>

Content 1

Content 2

Content 3

Snippet#2:

const btn = [].slice.call(document.getElementsByTagName("button"));
    btn.forEach((item, index) => {
      item.addEventListener("click", function () {
        document.getElementById("tab").children[index].scrollIntoView();
      });
    });

* {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      #tab {
        display: flex;
        overflow: auto;
        scroll-behavior: smooth;
        scroll-snap-type: x mandatory;
      }
      #tab > * {
        flex-shrink: 0;
        width: 100%;
        scroll-snap-align: start;
        scroll-margin-top: 1rem;

        padding: 1rem 0.4rem;
      }

      <button>Tab 1</button>
      <button>Tab 2</button>
      <button>Tab 3</button>

Content 1

Content 2

Content 3


问:
celery beat crashes while running
Trying to run celery beat and facing this issue:</p>
```<code>[2022-12-06 15:18:33,284 CRITICAL/MainProcess ???] <-> <> celery.beat:107 start_scheduler() - beat raised exception <class '_pickle.UnpicklingError'>:
 UnpicklingError("invalid load key, '\\x00'.")
Traceback (most recent call last):
  File "/usr/lib/python3.10/shelve.py", line 111, in __getitem__
    value = self.cache[key]
KeyError: 'entries'
</code>```

Title: celery beat crashes while running

Body:
Trying to run celery beat and facing this issue:

[2022-12-06 15:18:33,284 CRITICAL/MainProcess ???] <-> <> celery.beat:107 start_scheduler() - beat raised exception <class '_pickle.UnpicklingError'>:
 UnpicklingError("invalid load key, '\\x00'.")
Traceback (most recent call last):
  File "/usr/lib/python3.10/shelve.py", line 111, in __getitem__
    value = self.cache[key]
KeyError: 'entries'


问:
How do I make a comboxbox event able to calculate fields in a datagridview in vb.net
How do I make a comboxbox event able to calculate fields in a datagridview in vb.net?.

previously I used bunifuDataGridView1_CellEndEdit for column calculations in datagridview but now I use ComboBox1_SelectionChangeCommitted but I don't know how to do column calculations in datagridview so please solution.

Thanks

```<code> Private Sub bunifuDataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles bunifuDataGridView1.CellEndEdit
            'calcutalte
            If e.ColumnIndex = 2 OrElse e.ColumnIndex = 3 Then
                Dim row = bunifuDataGridView1.Rows(e.RowIndex)
                row.Cells(4).Value = Double.Parse(row.Cells(2).Value.ToString()) * Double.Parse(row.Cells(3).Value.ToString())
                Calculate()
            End If
        End Sub

        Private Sub Calculate()
            Dim tot As Double = 0
            Dim cash As Double = Double.Parse(txtCash.Text)
            For Each item As DataGridViewRow In bunifuDataGridView1.Rows
                tot += Double.Parse(item.Cells(4).Value.ToString())
            Next item

            lblTotal.Text = tot.ToString("N2")

            lblChange.Text = (cash - tot).ToString("N2")
        End Sub
       Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
            fillDataGridView1()

        End Sub
Private Sub fillDataGridView1()
            Try
                Dim query As String = "SELECT NOD,ITM,CIU,QTY FROM RPD WHERE QTY > 0 AND PNM=@PNM"
                'Dim query As String = "SELECT * FROM GSDTS WHERE QTY > 0"
                Using con As OleDbConnection = New OleDbConnection(cn)
                    Using cmd As OleDbCommand = New OleDbCommand(query, con)
                        cmd.Parameters.AddWithValue("@PNM", ComboBox1.SelectedValue)
                        Using da As New OleDbDataAdapter(cmd)
                            Dim dt As DataTable = New DataTable()
                            da.Fill(dt)
                            da.Dispose()
                            source1.DataSource = dt
                            Me.bunifuDataGridView1.DataSource = source1
                      dt.Columns("Total").Expression = "[CIU]*[QTY]"          Me.bunifuDataGridView1.Refresh()
                        End Using
                    End Using
                End Using
            Catch ex As Exception
            End Try
        End Sub
  Private Sub PopulateComboBox()
            Dim query As String = "SELECT DISTINCT PNM FROM RPD "
            Try
                Using con As OleDbConnection = New OleDbConnection(cn)
                    Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
                        'Fill the DataTable with records from Table.
                        Dim dt As DataTable = New DataTable()
                        sda.Fill(dt)

                        'Insert the Default Item to DataTable.
                        Dim row As DataRow = dt.NewRow()

                        row(0) = ""

                        dt.Rows.InsertAt(row, 0)

                        'Assign DataTable as DataSource.
                        ComboBox1.DataSource = dt
                        ComboBox1.DisplayMember = "PNM"
                        ComboBox1.ValueMember = "PNM"
                    End Using
                End Using
            Catch myerror As OleDbException
                MessageBox.Show("Error: " & myerror.Message)
            Finally

            End Try
        End Sub
</code>```

Body:
How do I make a comboxbox event able to calculate fields in a datagridview in vb.net?.

previously I used bunifuDataGridView1_CellEndEdit for column calculations in datagridview but now I use ComboBox1_SelectionChangeCommitted but I don't know how to do column calculations in datagridview so please solution.

Thanks

 Private Sub bunifuDataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles bunifuDataGridView1.CellEndEdit
            'calcutalte
            If e.ColumnIndex = 2 OrElse e.ColumnIndex = 3 Then
                Dim row = bunifuDataGridView1.Rows(e.RowIndex)
                row.Cells(4).Value = Double.Parse(row.Cells(2).Value.ToString()) * Double.Parse(row.Cells(3).Value.ToString())
                Calculate()
            End If
        End Sub

        Private Sub Calculate()
            Dim tot As Double = 0
            Dim cash As Double = Double.Parse(txtCash.Text)
            For Each item As DataGridViewRow In bunifuDataGridView1.Rows
                tot += Double.Parse(item.Cells(4).Value.ToString())
            Next item

            lblTotal.Text = tot.ToString("N2")

            lblChange.Text = (cash - tot).ToString("N2")
        End Sub
       Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
            fillDataGridView1()

        End Sub
Private Sub fillDataGridView1()
            Try
                Dim query As String = "SELECT NOD,ITM,CIU,QTY FROM RPD WHERE QTY > 0 AND PNM=@PNM"
                'Dim query As String = "SELECT * FROM GSDTS WHERE QTY > 0"
                Using con As OleDbConnection = New OleDbConnection(cn)
                    Using cmd As OleDbCommand = New OleDbCommand(query, con)
                        cmd.Parameters.AddWithValue("@PNM", ComboBox1.SelectedValue)
                        Using da As New OleDbDataAdapter(cmd)
                            Dim dt As DataTable = New DataTable()
                            da.Fill(dt)
                            da.Dispose()
                            source1.DataSource = dt
                            Me.bunifuDataGridView1.DataSource = source1
                      dt.Columns("Total").Expression = "[CIU]*[QTY]"          Me.bunifuDataGridView1.Refresh()
                        End Using
                    End Using
                End Using
            Catch ex As Exception
            End Try
        End Sub
  Private Sub PopulateComboBox()
            Dim query As String = "SELECT DISTINCT PNM FROM RPD "
            Try
                Using con As OleDbConnection = New OleDbConnection(cn)
                    Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
                        'Fill the DataTable with records from Table.
                        Dim dt As DataTable = New DataTable()
                        sda.Fill(dt)

                        'Insert the Default Item to DataTable.
                        Dim row As DataRow = dt.NewRow()

                        row(0) = ""

                        dt.Rows.InsertAt(row, 0)

                        'Assign DataTable as DataSource.
                        ComboBox1.DataSource = dt
                        ComboBox1.DisplayMember = "PNM"
                        ComboBox1.ValueMember = "PNM"
                    End Using
                End Using
            Catch myerror As OleDbException
                MessageBox.Show("Error: " & myerror.Message)
            Finally

            End Try
        End Sub


问:
Transfer last images in file to another
I'm trying to find python code to transfer the last 10 or so images to another file.

```<code>import os
import shutil
import fnmatch

source = 'the folder name'
destination = 'folder name'

def get_latest_image(source, y=('jpg')):
    valid_files = [os.path.join(source, destination) for destination in os.listdir(source)]
    valid_files = [f for f in valid_files if '.' in f and \
    f.rsplit('.',1)[-1] in y and os.path.isfile(f)]
    for f in files:
        if fnmatch.fnmatch(f,y)==True:
            shutil.move(source + f, y + f)
</code>```

...
This is the code I tried using if you could possibly help me figuring out the code it would really help

Title: Transfer last images in file to another

Body:
I'm trying to find python code to transfer the last 10 or so images to another file.

import os
import shutil
import fnmatch

source = 'the folder name'
destination = 'folder name'

def get_latest_image(source, y=('jpg')):
    valid_files = [os.path.join(source, destination) for destination in os.listdir(source)]
    valid_files = [f for f in valid_files if '.' in f and \
    f.rsplit('.',1)[-1] in y and os.path.isfile(f)]
    for f in files:
        if fnmatch.fnmatch(f,y)==True:
            shutil.move(source + f, y + f)

...
This is the code I tried using if you could possibly help me figuring out the code it would really help


问:
using a ssl enabled node.js sveltekit app alongside tomcat server which is currently hosting apps in https
I am currently having a server with tomcat web server hosting few apps in https. Now we built a sveltekit app that is not static. I am trying to add this app be exposed as a https site.

I found many articles that point out using apache as a reverse proxy and pointing to the node.js app. However in my case, there are already 2 apps on tomcat running in https.

I this case, kindly confirm if i need to move all the ssl logic to the apache and setup tomcat to run in http and allow apache to receive https and forward to tomcat as http and return the response back. I am also starting to experiment with this, but wanted to know if this is a production ready approach.


问:
how to stop scanf() from skipping to the newline in c?
```<code>#include<stdio.h>
int main(){
  int num;
  for(int i=0;i<5;i++){
    printf("Enter the number: ");
    scanf("%d",&num);
  }

}
</code>```

So this is the code and it is working perfectly fine. But I want all the printf statements to be printed in same line. like Enter the number:5 Enter the number: 4 Enter the number:6 .......
basically i want scanf to stop skipping to the next line after i enter the value . I want the next printf statement to be on the same line following the value i entered for scanf(). is it possible ?

Body:
#include<stdio.h>
int main(){
  int num;
  for(int i=0;i<5;i++){
    printf("Enter the number: ");
    scanf("%d",&num);
  }

}

So this is the code and it is working perfectly fine. But I want all the printf statements to be printed in same line. like Enter the number:5 Enter the number: 4 Enter the number:6 .......
basically i want scanf to stop skipping to the next line after i enter the value . I want the next printf statement to be on the same line following the value i entered for scanf(). is it possible ?


问:
Problem posting model to action with data from viewcomponent. Among other things
Login controller

```<code>try
            {
                if (currentPage == null)
                {
                    currentPage = _pageRouteHelper.Page as LoginPage;
                    if (currentPage == null) return View(vm);
                }
                var baseUrl = _uriHelper.GetFriendlyUrl(currentPage);
                var tabSelected = this.Request.Query["tabName"];
                Enum.TryParse(tabSelected, out LoginPageViewModel.LoginTypes activeTab);
                GetTabs(currentPage, vm, baseUrl, ref activeTab);

                vm ??= new LoginPageViewModel();
                vm.ActiveTab = activeTab;
                vm.TextArea = GetTextArea(vm.Tabs);
                vm.Links = GetLinks(vm.Tabs);

                switch (activeTab)
                {
                    case LoginPageViewModel.LoginTypes.Sbid:
                        vm.BankidModel = new BankidLoginViewModel();
                        break;
                    case LoginPageViewModel.LoginTypes.Forms:
                        vm.PasswordModel = new PasswordLoginViewModel();
                        break;
                    default:
                        vm.BankidModel = new BankidLoginViewModel();
                        break;
                }
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message, typeof(LoginController));
            }
            return View(vm);
</code>```

PArt of the loginAction in controller

```<code>[HttpPost]
        public async Task<IActionResult> LoginAction(LoginPageViewModel? viewModel)
        {
            if (!ModelState.IsValid)
                return ViewComponent("BankidLogin");
</code>```

CSHTML the login-cshtml

```<code>@using EPiServer.Shell.Web.Mvc.Html
@using Garantum.Optimizely.Core.ViewModels.Pages
@using Garantum.Optimizely.Core.ContentModels.Pages
@using Microsoft.AspNetCore.Mvc.TagHelpers
@model Garantum.Optimizely.Core.ViewModels.Pages.LoginPageViewModel
@{
    Layout = "MasterPages/SiteMaster";
    ViewData["Title"] = "Login";
}
<div id="LoginPage">
    <div id="LoginArea">
        <h1>@Model.Heading</h1>
        <p></p>
        @*<p>@Model.PageTextArea</p>*@
        <div class="tabsContainer">
            <table>
                <tbody>
                    <tr>
                        <td class="marginTab">
                            <div class="leftMarginTabs"></div>
                        </td>
                        @foreach (var tabItem in Model.Tabs)
                        {
                            <td role="presentation" class="@tabItem.Css">
                                <div>
                                    <a href="@tabItem.Url">@tabItem.TabName</a>
                                </div>
                            </td>
                        }
                    </tr>
                </tbody>
            </table>
        </div>
        @Html.DisplayFor(model => model.TextArea, new {@class = "textArea"})
        <div class="loginAreaContent">
                @switch (Model.ActiveTab)
                {
                    case LoginPageViewModel.LoginTypes.Sbid:
                        @*<cache expires-after="@TimeSpan.FromMinutes(5)">*@
                        @await Component.InvokeAsync("BankidLogin")
                        @*</cache>*@
                        break;
                    case LoginPageViewModel.LoginTypes.Forms:
                        @*<cache expires-after="@TimeSpan.FromMinutes(5)">*@
                    @await Component.InvokeAsync("PasswordLogin")
                        @*</cache>*@
                        break;
                    default:
                        break;
                }
            @using (Html.BeginForm("LoginAction", "Login", FormMethod.Post))
                {
                <div class="row">
                    @Html.HiddenFor(m => m.BankidModel)
                    <input class="btn btn-grey" type="submit" value="@Html.Translate("/LoginPage/Login/Header")" />
                    <div class="clear"></div>
                </div>
                }
        </div>
        <ul id="LoginLinks">
            @foreach (var link in Model.Links)
            {
                <li>
                    <a target="@link.Target" href="@link.Href">@link.Text</a>
                </li>
            }
        </ul>
    </div>
</div>

</code>```

because I want to use (if possible) viewcomonets to frame data for each tab.
So if we start by BankIdLogin that have a model

```<code>using Garantum.Optimizely.Core.Helpers;
using System.ComponentModel.DataAnnotations;
using System.Runtime.InteropServices;

namespace Garantum.Optimizely.Core.ViewModels.Components.Login
{
    public class BankidLoginViewModel
    {
        [SocSecNumberMask("sv")]
        public string? PersonalNumber { get; set; }

    }
}

</code>```

Component

```<code>public async Task<IViewComponentResult> InvokeAsync(BankidLoginViewModel model)
    {
        if (model == null)
        {
            var viewModel = new BankidLoginViewModel()
            {

            };
        }
        return View(model);
    }
}
</code>```
```<code>@using EPiServer.Shell.Web.Mvc.Html
@using Microsoft.AspNetCore.Routing;
@model Garantum.Optimizely.Core.ViewModels.Components.Login.BankidLoginViewModel
@Html.AntiForgeryToken()
<div class="row">
    <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
    @Html.TextBoxFor(model => model.PersonalNumber, new {@class = "input-text", @placeholder = @Html.Translate("/Format/Input/SocSecNumber"), @tabindex = "1"})
    @Html.ValidationMessageFor(model => model.PersonalNumber,"", new { @class = "error" })
    <div class="clear"></div>
</div>
</code>```

Also a validationattribute

```<code>using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Garantum.Optimizely.Core.Helpers;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class SocSecNumberMaskAttribute : ValidationAttribute
{
    private readonly string _mask;
    private readonly string _inputMask;
    private readonly string _errorMessage;
    public string InputMask
    {
        get { return _inputMask; }
    }
    public SocSecNumberMaskAttribute(string? lang)
    {
        lang = lang ?? "sv";
        _mask = CultureHelper.Translate("/Format/Regexp/SocSecNumber", lang);
        _inputMask = CultureHelper.Translate("/Format/Input/SocSecNumber", lang);
        _errorMessage = CultureHelper.Translate("/Login/Message/SocSecNumberFormatError", lang);
        _errorMessage.Replace("{1}", _inputMask);
    }

    private string GetErrorMessage(string value) => _errorMessage.Replace("{0}", value);
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        var socSecNumber = value as string;
        if (socSecNumber == null || !MatchesMask(_mask, socSecNumber))
        {
            return new ValidationResult(GetErrorMessage(socSecNumber??string.Empty));
        }
        return ValidationResult.Success;
    }
    // Checks if the entered socsecnumber matches the mask.
    internal bool MatchesMask(string mask, string socSecNumber)
    {
        Regex pattern = new Regex(_mask);
        //var regex = new RegularExpressionAttribute(mask);
        return pattern.IsMatch(socSecNumber);
    }
}
</code>```

OK
I want to simply achive that When on Bankidtab is postng an illelgal personal number servervalidation result is presented beside the textbox, otherwise continue with post code.
I first tried hvaing the submitbutton on the viewcomonent-section - with no sussess
I then like now have variables for viewmodels in my loginmodel, set to new when tab is clicked

Q1:
In login Action a new empoty Loginmodel is posted It shold have all prperties set , I dont understand why!
Q2
How do I set the personalnumber fieid in LoginViewModel.BankidLogin to the one used in the view component?

WELL
So the tabs and invocing of VC seems to work all problems occusrs during post

Body:
Login controller

try
            {
                if (currentPage == null)
                {
                    currentPage = _pageRouteHelper.Page as LoginPage;
                    if (currentPage == null) return View(vm);
                }
                var baseUrl = _uriHelper.GetFriendlyUrl(currentPage);
                var tabSelected = this.Request.Query["tabName"];
                Enum.TryParse(tabSelected, out LoginPageViewModel.LoginTypes activeTab);
                GetTabs(currentPage, vm, baseUrl, ref activeTab);

                vm ??= new LoginPageViewModel();
                vm.ActiveTab = activeTab;
                vm.TextArea = GetTextArea(vm.Tabs);
                vm.Links = GetLinks(vm.Tabs);

                switch (activeTab)
                {
                    case LoginPageViewModel.LoginTypes.Sbid:
                        vm.BankidModel = new BankidLoginViewModel();
                        break;
                    case LoginPageViewModel.LoginTypes.Forms:
                        vm.PasswordModel = new PasswordLoginViewModel();
                        break;
                    default:
                        vm.BankidModel = new BankidLoginViewModel();
                        break;
                }
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message, typeof(LoginController));
            }
            return View(vm);

PArt of the loginAction in controller

[HttpPost]
        public async Task<IActionResult> LoginAction(LoginPageViewModel? viewModel)
        {
            if (!ModelState.IsValid)
                return ViewComponent("BankidLogin");

CSHTML the login-cshtml

@using EPiServer.Shell.Web.Mvc.Html
@using Garantum.Optimizely.Core.ViewModels.Pages
@using Garantum.Optimizely.Core.ContentModels.Pages
@using Microsoft.AspNetCore.Mvc.TagHelpers
@model Garantum.Optimizely.Core.ViewModels.Pages.LoginPageViewModel
@{
    Layout = "MasterPages/SiteMaster";
    ViewData["Title"] = "Login";
}

@Model.Heading

        @*
@Model.PageTextArea
*@

                        @foreach (var tabItem in Model.Tabs)
                        {

                                    @tabItem.TabName

                        }

        @Html.DisplayFor(model => model.TextArea, new {@class = "textArea"})

                @switch (Model.ActiveTab)
                {
                    case LoginPageViewModel.LoginTypes.Sbid:
                        @*<cache expires-after="@TimeSpan.FromMinutes(5)">*@
                        @await Component.InvokeAsync("BankidLogin")
                        @*</cache>*@
                        break;
                    case LoginPageViewModel.LoginTypes.Forms:
                        @*<cache expires-after="@TimeSpan.FromMinutes(5)">*@
                    @await Component.InvokeAsync("PasswordLogin")
                        @*</cache>*@
                        break;
                    default:
                        break;
                }
            @using (Html.BeginForm("LoginAction", "Login", FormMethod.Post))
                {

                    @Html.HiddenFor(m => m.BankidModel)
                    <input class="btn btn-grey" type="submit" value="@Html.Translate("/LoginPage/Login/Header")" />

                }

            @foreach (var link in Model.Links)
            {

                    @link.Text

            }

because I want to use (if possible) viewcomonets to frame data for each tab.
So if we start by BankIdLogin that have a model

using Garantum.Optimizely.Core.Helpers;
using System.ComponentModel.DataAnnotations;
using System.Runtime.InteropServices;

namespace Garantum.Optimizely.Core.ViewModels.Components.Login
{
    public class BankidLoginViewModel
    {
        [SocSecNumberMask("sv")]
        public string? PersonalNumber { get; set; }

    }
}

Component

public async Task<IViewComponentResult> InvokeAsync(BankidLoginViewModel model)
    {
        if (model == null)
        {
            var viewModel = new BankidLoginViewModel()
            {

            };
        }
        return View(model);
    }
}

@using EPiServer.Shell.Web.Mvc.Html
@using Microsoft.AspNetCore.Routing;
@model Garantum.Optimizely.Core.ViewModels.Components.Login.BankidLoginViewModel
@Html.AntiForgeryToken()

    @Html.TextBoxFor(model => model.PersonalNumber, new {@class = "input-text", @placeholder = @Html.Translate("/Format/Input/SocSecNumber"), @tabindex = "1"})
    @Html.ValidationMessageFor(model => model.PersonalNumber,"", new { @class = "error" })

Also a validationattribute

using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Garantum.Optimizely.Core.Helpers;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class SocSecNumberMaskAttribute : ValidationAttribute
{
    private readonly string _mask;
    private readonly string _inputMask;
    private readonly string _errorMessage;
    public string InputMask
    {
        get { return _inputMask; }
    }
    public SocSecNumberMaskAttribute(string? lang)
    {
        lang = lang ?? "sv";
        _mask = CultureHelper.Translate("/Format/Regexp/SocSecNumber", lang);
        _inputMask = CultureHelper.Translate("/Format/Input/SocSecNumber", lang);
        _errorMessage = CultureHelper.Translate("/Login/Message/SocSecNumberFormatError", lang);
        _errorMessage.Replace("{1}", _inputMask);
    }

    private string GetErrorMessage(string value) => _errorMessage.Replace("{0}", value);
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        var socSecNumber = value as string;
        if (socSecNumber == null || !MatchesMask(_mask, socSecNumber))
        {
            return new ValidationResult(GetErrorMessage(socSecNumber??string.Empty));
        }
        return ValidationResult.Success;
    }
    // Checks if the entered socsecnumber matches the mask.
    internal bool MatchesMask(string mask, string socSecNumber)
    {
        Regex pattern = new Regex(_mask);
        //var regex = new RegularExpressionAttribute(mask);
        return pattern.IsMatch(socSecNumber);
    }
}

OK
I want to simply achive that When on Bankidtab is postng an illelgal personal number servervalidation result is presented beside the textbox, otherwise continue with post code.
I first tried hvaing the submitbutton on the viewcomonent-section - with no sussess
I then like now have variables for viewmodels in my loginmodel, set to new when tab is clicked

Q1:
In login Action a new empoty Loginmodel is posted It shold have all prperties set , I dont understand why!
Q2
How do I set the personalnumber fieid in LoginViewModel.BankidLogin to the one used in the view component?

WELL
So the tabs and invocing of VC seems to work all problems occusrs during post


问:
Is there a way to make a counter that doesn't restart every time i refresh the website page
So I've created a counter that adds 40 every specific time (e.g. every second).
I want to keep it as it is right now but find a way to not make it restart every time I refresh the page.

The code is:

```<code> <div class="baseNum" id="baseNum"> base number = 1000</div>
   <div class="resultContainer" id="resultContainer">
    after every sec + 40 = <span class="result" id="result"></span>
  </div>

    var resultDisplay = document.getElementById("result");

    var baseNum = 1000;
    var add = 40;
    var time = 24 * 3600000; // change the 24 to any hours you want

    resultDisplay.innerHTML = baseNum;

    function add40() {

        setTimeout(() => {
            resultDisplay.innerHTML = baseNum;

            if (baseNum !== 0) {
                baseNum += 40;
            } add40()
        }, time);
    } add40();
</code>```

I'm using Wordpress for a client with Elementor, if you guys maybe know an alternative in this environment.
Thank you!

Body:
So I've created a counter that adds 40 every specific time (e.g. every second).
I want to keep it as it is right now but find a way to not make it restart every time I refresh the page.

The code is:

 base number = 1000

    after every sec + 40 =

    var resultDisplay = document.getElementById("result");

    var baseNum = 1000;
    var add = 40;
    var time = 24 * 3600000; // change the 24 to any hours you want

    resultDisplay.innerHTML = baseNum;

    function add40() {

        setTimeout(() => {
            resultDisplay.innerHTML = baseNum;

            if (baseNum !== 0) {
                baseNum += 40;
            } add40()
        }, time);
    } add40();

I'm using Wordpress for a client with Elementor, if you guys maybe know an alternative in this environment.
Thank you!


问:
Navigation Drawer (or some similar side menu) from inside a fragment
I am creating a book app. The app displays the pages of a book, and by swiping left and right you can move the pages of the book forward and backwards. The setup includes an activity as limited code as possible, and a fragment

I am trying to include a side menu, which will display the book's pages, and allow the user to jump to the selected page

The problem I am facing is, by using a Navigation Drawer, I have to initialize it in the main activity. This does not allow me to pass the list to the drawer (which makes sense, since it is for jumping from one fragment to another)

Is there any other way to create the described side menu, without having to put my code inside an activity?


问:
Weird console.log when I try to pass data between pages/files
Trying to pass data from parent to child, but I get this whole message, and the passed props don't show up in the child.

I go into parent component. Console logs {"parentToChild": ""}. I click the add to cart button, it prints in the parent page, and console logs {"parentToChild": "Bluey Footy Ball"}. When I click the cart logo to enter the cart page, the console logs this:

{"navigation": {"addListener": [Function addListener], "canGoBack": [Function canGoBack], "dispatch": [Function dispatch], "getId": [Function getId], "getParent": [Function getParent], "getState": [Function anonymous], "goBack": [Function anonymous], "isFocused": [Function isFocused], "navigate": [Function anonymous], "pop": [Function anonymous], "popToTop": [Function anonymous], "push": [Function anonymous], "removeListener": [Function removeListener], "replace": [Function anonymous], "reset": [Function anonymous], "setOptions": [Function setOptions], "setParams": [Function anonymous]}, "route": {"key": "Cart-5_cc7df7GhCLvLrLn31mO", "name": "Cart", "params": undefined, "path": undefined}}

Parent (ToyDetails.js):

```<code>const ToyDetails = () => {
  const [data, setData] = useState('');

  const parentToChild = () => {
    setData(name)
  }

  return (
    <View>
      <Cart parentToChild={data}
      <TouchableOpacity onPress={()=>parentToChild()}
        <Text>{buttonText}</Text>
      </TouchableOpacity>
    </View>
  )
}
</code>```

Child (Cart.js):

```<code>const Cart = (props) => {
  console.log(props)
  return (
    <View>
      <Text>Test Print</Text>
      <Text>{props.parentToChild}</Text>
    </View>
  )
}

export default Cart
</code>```

Body:
Trying to pass data from parent to child, but I get this whole message, and the passed props don't show up in the child.

I go into parent component. Console logs {"parentToChild": ""}. I click the add to cart button, it prints in the parent page, and console logs {"parentToChild": "Bluey Footy Ball"}. When I click the cart logo to enter the cart page, the console logs this:

{"navigation": {"addListener": [Function addListener], "canGoBack": [Function canGoBack], "dispatch": [Function dispatch], "getId": [Function getId], "getParent": [Function getParent], "getState": [Function anonymous], "goBack": [Function anonymous], "isFocused": [Function isFocused], "navigate": [Function anonymous], "pop": [Function anonymous], "popToTop": [Function anonymous], "push": [Function anonymous], "removeListener": [Function removeListener], "replace": [Function anonymous], "reset": [Function anonymous], "setOptions": [Function setOptions], "setParams": [Function anonymous]}, "route": {"key": "Cart-5_cc7df7GhCLvLrLn31mO", "name": "Cart", "params": undefined, "path": undefined}}

Parent (ToyDetails.js):

const ToyDetails = () => {
  const [data, setData] = useState('');

  const parentToChild = () => {
    setData(name)
  }

  return (
    <View>
      <Cart parentToChild={data}
      <TouchableOpacity onPress={()=>parentToChild()}
        <Text>{buttonText}</Text>
      </TouchableOpacity>
    </View>
  )
}

Child (Cart.js):

const Cart = (props) => {
  console.log(props)
  return (
    <View>
      <Text>Test Print</Text>
      <Text>{props.parentToChild}</Text>
    </View>
  )
}

export default Cart


问:
error in appending dictionary in for loop. Solution
I am new to leet code, i was trying to run the code it was working fine in my colab notebook.
But in leet window why it is showing [0,0] output.

my concern is what is the difference in writing the seen[v] = i line 4 or 8
if i write in line 4 it shows error

```<code>def twoSum(nums, target):
        seen = {}
        for i, v in enumerate(nums):
            seen[v] = i #??
            remaining = target - v
            if remaining in seen:
                return [seen[remaining], i]
            # seen[v] = i # ??

        return []

nums = [2,7,11,15]
target = 9
twoSum(nums, target)
</code>```

Body:
I am new to leet code, i was trying to run the code it was working fine in my colab notebook.
But in leet window why it is showing [0,0] output.

my concern is what is the difference in writing the seen[v] = i line 4 or 8
if i write in line 4 it shows error

def twoSum(nums, target):
        seen = {}
        for i, v in enumerate(nums):
            seen[v] = i #??
            remaining = target - v
            if remaining in seen:
                return [seen[remaining], i]
            # seen[v] = i # ??

        return []

nums = [2,7,11,15]
target = 9
twoSum(nums, target)


问:
Jetpack Glance Widget: update called on app exit
I implemented a Glance Widget using

Glance 1.0.0-alpha05

GlanceAppWidgetHost 0.2.2

Using the following provider spec. Notice the updatePeriodMillis = 0

```<code><?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:description="@string/loyalty_card_title"
    android:minWidth="110dp"
    android:minHeight="50dp"
    android:resizeMode="horizontal|vertical"
    android:targetCellWidth="2"
    android:targetCellHeight="2"
    android:widgetCategory="home_screen|keyguard"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/loyalty_card_widget_initial"
    android:previewImage="@drawable/splash_logo"
    tools:targetApi="s" /> <!-- targetCellWidth and -height will be ignored by api < s, which is fine -->
</code>```

Now, every time I close(and perhaps open, too) I see the widget update, which manifests in the initialLayout being shown very briefly, giving a glitch appearance. Nothing regarding the widget data changed. How to prevent this?

Issue looks closely related to In Android, Glance widgets are "flickering" during every update (even if there is no content change)
and associated bug report https://issuetracker.google.com/issues/241076154

However, I am unsure if it is reelevant since I do not use WorkManager anywhere in my project.

Body:
I implemented a Glance Widget using

Glance 1.0.0-alpha05

GlanceAppWidgetHost 0.2.2

Using the following provider spec. Notice the updatePeriodMillis = 0

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:description="@string/loyalty_card_title"
    android:minWidth="110dp"
    android:minHeight="50dp"
    android:resizeMode="horizontal|vertical"
    android:targetCellWidth="2"
    android:targetCellHeight="2"
    android:widgetCategory="home_screen|keyguard"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/loyalty_card_widget_initial"
    android:previewImage="@drawable/splash_logo"
    tools:targetApi="s" />

Now, every time I close(and perhaps open, too) I see the widget update, which manifests in the initialLayout being shown very briefly, giving a glitch appearance. Nothing regarding the widget data changed. How to prevent this?

Issue looks closely related to In Android, Glance widgets are "flickering" during every update (even if there is no content change)
and associated bug report https://issuetracker.google.com/issues/241076154

However, I am unsure if it is reelevant since I do not use WorkManager anywhere in my project.


问:
Can’t insert text after inserting image in edit mode draft.js
I first upload the image to s3 through my draft.js editor.
The image is saved and everything working well. But when I open draft.js to edit the content, I can’t add some text.

It seems that the part of adding text is despair if there is only image in the first render.

I try to restart the editor in first rendering with empty content and then adding the content, but it’s not working.
So currently I’m starting the draft JS editor with content (image)

```<code>const insertImage = (base64) => {
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
  'image',
  'IMMUTABLE',
  { src: base64 }
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set(editorState, {
  currentContent: contentStateWithEntity,
});
return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ');
</code>```

};

```<code><Editor
          blockStyleFn={getBlockStyle}
          customStyleMap={colorStyleMap}
          editorState={editorState}
          onChange={handleEditorChange}
          onBlur={handleBlur}
          placeholder={placeholder}
          readOnly={readOnly}
          plugins={plugins}
          handlePastedFiles={handleFilesAttach}
          ref={(element) => {
            editorRef = element;
          }}
        />
</code>```

Body:
I first upload the image to s3 through my draft.js editor.
The image is saved and everything working well. But when I open draft.js to edit the content, I can’t add some text.

It seems that the part of adding text is despair if there is only image in the first render.

I try to restart the editor in first rendering with empty content and then adding the content, but it’s not working.
So currently I’m starting the draft JS editor with content (image)

const insertImage = (base64) => {
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
  'image',
  'IMMUTABLE',
  { src: base64 }
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set(editorState, {
  currentContent: contentStateWithEntity,
});
return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ');

};

<Editor
          blockStyleFn={getBlockStyle}
          customStyleMap={colorStyleMap}
          editorState={editorState}
          onChange={handleEditorChange}
          onBlur={handleBlur}
          placeholder={placeholder}
          readOnly={readOnly}
          plugins={plugins}
          handlePastedFiles={handleFilesAttach}
          ref={(element) => {
            editorRef = element;
          }}
        />


问:
Quartz stops running scheduled job at the time of production deployments
We have a Spring Boot based microservice which is used to run a scheduled job every 15 seconds using Quartz Scheduler. However, whenever we try to release a new version of this microservice on production, the scheduler stops running the job for about 4-5 minutes before starting to work as normal again. The deployment procedure involves spawning up new server instances and until they are detected as healthy, the old instances are not brought down.

During deployments of this microservice, the scheduled job is not triggered by Quartz. Instead, we receive the following logs in our service -

o.s.s.quartz.LocalDataSourceJobStore - ClusterManager: Scanning for instance "<instance-id>"'s failed in-progress jobs.

o.s.s.quartz.LocalDataSourceJobStore - ClusterManager: detected 2 failed or restarted instances.

We are using MySQL database to store the Quartz related data and have defined the following properties in quartz.properties file -

```<code>#-------- quartz.properties -------#

#============================================================================
# Configure Main Scheduler Properties
#============================================================================

org.quartz.scheduler.instanceName = MyScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.skipUpdateCheck = true

#============================================================================
# Configure ThreadPool
#============================================================================

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 25
org.quartz.threadPool.threadPriority = 5

#============================================================================
# Configure JobStore
#============================================================================

org.quartz.jobStore.misfireThreshold = 60000

org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties = false
org.quartz.jobStore.dataSource = jobDs
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = true
org.quartz.jobStore.clusterCheckinInterval = 20000

org.quartz.jobStore.acquireTriggersWithinLock=true
org.quartz.dataSource.jobDs.URL = jdbc:mysql://localhost\:3306/my_database?zeroDateTimeBehavior=convertToNull
org.quartz.dataSource.jobDs.user = root
org.quartz.dataSource.jobDs.password = root
org.quartz.dataSource.jobDs.maxConnections = 50
org.quartz.dataSource.jobDs.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.jobDs.validationQuery=select 0 from dual
</code>```

We have a hunch that this problem might be either because -

The clusterCheckinInterval is set to 20000 ms (20s) whereas the scheduled job runs every 15s. It might be the case that the instance on which the scheduled job is to be run has gone unhealthy but not yet been detected as unhealthy by Quartz's health-check thread because of this time difference.

Instances are registering themselves to Quartz on application start-up but application start-up is taking longer than 15s leading the Quartz to run job on such instances and failing.

If anyone has faced similar issues in the past, can you help us shed some light on what the actual issue might be here?

Body:
We have a Spring Boot based microservice which is used to run a scheduled job every 15 seconds using Quartz Scheduler. However, whenever we try to release a new version of this microservice on production, the scheduler stops running the job for about 4-5 minutes before starting to work as normal again. The deployment procedure involves spawning up new server instances and until they are detected as healthy, the old instances are not brought down.

During deployments of this microservice, the scheduled job is not triggered by Quartz. Instead, we receive the following logs in our service -

o.s.s.quartz.LocalDataSourceJobStore - ClusterManager: Scanning for instance "<instance-id>"'s failed in-progress jobs.

o.s.s.quartz.LocalDataSourceJobStore - ClusterManager: detected 2 failed or restarted instances.

We are using MySQL database to store the Quartz related data and have defined the following properties in quartz.properties file -

#-------- quartz.properties -------#

#============================================================================
# Configure Main Scheduler Properties
#============================================================================

org.quartz.scheduler.instanceName = MyScheduler
org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.skipUpdateCheck = true

#============================================================================
# Configure ThreadPool
#============================================================================

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 25
org.quartz.threadPool.threadPriority = 5

#============================================================================
# Configure JobStore
#============================================================================

org.quartz.jobStore.misfireThreshold = 60000

org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties = false
org.quartz.jobStore.dataSource = jobDs
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.isClustered = true
org.quartz.jobStore.clusterCheckinInterval = 20000

org.quartz.jobStore.acquireTriggersWithinLock=true
org.quartz.dataSource.jobDs.URL = jdbc:mysql://localhost\:3306/my_database?zeroDateTimeBehavior=convertToNull
org.quartz.dataSource.jobDs.user = root
org.quartz.dataSource.jobDs.password = root
org.quartz.dataSource.jobDs.maxConnections = 50
org.quartz.dataSource.jobDs.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.jobDs.validationQuery=select 0 from dual

We have a hunch that this problem might be either because -

The clusterCheckinInterval is set to 20000 ms (20s) whereas the scheduled job runs every 15s. It might be the case that the instance on which the scheduled job is to be run has gone unhealthy but not yet been detected as unhealthy by Quartz's health-check thread because of this time difference.

Instances are registering themselves to Quartz on application start-up but application start-up is taking longer than 15s leading the Quartz to run job on such instances and failing.

If anyone has faced similar issues in the past, can you help us shed some light on what the actual issue might be here?


问:
System.NullReferenceException C sharp code
enter image description here

```<code> private void button3_Click(object sender, EventArgs e)
        {

            if (dataGridView1.Rows.Count > 0)
            {
                Microsoft.Office.Interop.Excel.Application xcelApp = new              Microsoft.Office.Interop.Excel.Application();
                xcelApp.Application.Workbooks.Add(Type.Missing);
                for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
                {
                    xcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
                }

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        xcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                    xcelApp.Columns.AutoFit();
                    xcelApp.Visible = true;
                }
            }
        }
</code>```

I hae system nullreference exception. Could help me someone please?

Guys, where is my problem please?

Body:
enter image description here

 private void button3_Click(object sender, EventArgs e)
        {

            if (dataGridView1.Rows.Count > 0)
            {
                Microsoft.Office.Interop.Excel.Application xcelApp = new              Microsoft.Office.Interop.Excel.Application();
                xcelApp.Application.Workbooks.Add(Type.Missing);
                for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
                {
                    xcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
                }

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        xcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                    xcelApp.Columns.AutoFit();
                    xcelApp.Visible = true;
                }
            }
        }

I hae system nullreference exception. Could help me someone please?

Guys, where is my problem please?


问:
Extracting mathematical equation from a deep neural network in MATLAB?
I have built a deep neural network consist of two hidden layers (6 neurons in the first layer and 4 in the second layer), (11 inputs), and (1 output). Below is the code:

```<code>net=newff(Norm_inputs,Norm_Outputs,[6 4],{'tansig' 'tansig' 'tansig'}); %% Neural Network with 12 inputs and four Neurons in the Hidden layers
net.divideParam.trainRatio=80;     %% 70% of the data are used for training
net.divideParam.testRatio=20;      %% 15% of the data are used for testing
net.divideParam.valRatio=0;       %% 15% of the data are used for the validation
net.trainParam.lr=0.01;             %% Learning rate
net.trainParam.min_grad=1e-20;
net.trainParam.goal=1e-30;
net.trainParam.epochs=1000;
net = train(net,Norm_inputs,Norm_Outputs);
</code>```

where Norm_inputs are the normalized inputs and Norm_Outputs are the normalized outputs:

Below is the output of my network:

enter image description here

To test the accuracy of network I am using the following:

```<code>A = net([0.613497 1 1 0.660657 0.675336 0.150442 0.343584 0.162069 0.655799 0.574284 9.83E-05 ]')
</code>```

I am comparing the output of A with my raw data to check the performance..

I tried to extract the mathematical form so I can avoid opening matlab everytime to see the results..

I did the following in the command window to exctract the weights and biases:

```<code>b1 = net.b{1};
b2 = net.b{2};
W = net.IW{1,1};
LW = net.LW{2,1};
x = [0.613497 1 1 0.660657 0.675336 0.150442 0.343584 0.162069 0.655799 0.574284 9.83E-05 ] %Inputs
</code>```

Then I used the following equation to see the output:

In the command window, I did the following:

```<code>b1 = net.b{1}; b2 = net.b{2}; b3 = net.b{3};
W_ITH = net.IW{1,1}; W_H1TH2 = net.LW{2,1}; W_H2TO = net.LW{3,2};
</code>```
```<code>>> h1 = tansig(b1+W_ITH*x)
>> h2 = tansig(b2+W_H1TH2*h1)
>> h3 = tansig(b3+W_H2TO*h2)
>> Output = tansig(h3)
</code>```

x: input vector as a column;
W_ITH: weights between the input layer and the first hidden layer;
b1: The biases between the input layer and the first hidden layer

h1: output from the first hidden layer;
W_H1TH2: weights between the first hidden layer and the second hidden layer; b2: The biases between the first hidden layer and second hidden layer

h3 here is a scalar and I did the following: Output = tansig(h3)..

However, the output is different when I compared it with x=net(input)
Any help!

I am expecting to have an equation at the end that can calculate the output based on the weights and biases!

Body:
I have built a deep neural network consist of two hidden layers (6 neurons in the first layer and 4 in the second layer), (11 inputs), and (1 output). Below is the code:

net=newff(Norm_inputs,Norm_Outputs,[6 4],{'tansig' 'tansig' 'tansig'}); %% Neural Network with 12 inputs and four Neurons in the Hidden layers
net.divideParam.trainRatio=80;     %% 70% of the data are used for training
net.divideParam.testRatio=20;      %% 15% of the data are used for testing
net.divideParam.valRatio=0;       %% 15% of the data are used for the validation
net.trainParam.lr=0.01;             %% Learning rate
net.trainParam.min_grad=1e-20;
net.trainParam.goal=1e-30;
net.trainParam.epochs=1000;
net = train(net,Norm_inputs,Norm_Outputs);

where Norm_inputs are the normalized inputs and Norm_Outputs are the normalized outputs:

Below is the output of my network:

enter image description here

To test the accuracy of network I am using the following:

A = net([0.613497 1 1 0.660657 0.675336 0.150442 0.343584 0.162069 0.655799 0.574284 9.83E-05 ]')

I am comparing the output of A with my raw data to check the performance..

I tried to extract the mathematical form so I can avoid opening matlab everytime to see the results..

I did the following in the command window to exctract the weights and biases:

b1 = net.b{1};
b2 = net.b{2};
W = net.IW{1,1};
LW = net.LW{2,1};
x = [0.613497 1 1 0.660657 0.675336 0.150442 0.343584 0.162069 0.655799 0.574284 9.83E-05 ] %Inputs

Then I used the following equation to see the output:

In the command window, I did the following:

b1 = net.b{1}; b2 = net.b{2}; b3 = net.b{3};
W_ITH = net.IW{1,1}; W_H1TH2 = net.LW{2,1}; W_H2TO = net.LW{3,2};

>> h1 = tansig(b1+W_ITH*x)
>> h2 = tansig(b2+W_H1TH2*h1)
>> h3 = tansig(b3+W_H2TO*h2)
>> Output = tansig(h3)

x: input vector as a column;
W_ITH: weights between the input layer and the first hidden layer;
b1: The biases between the input layer and the first hidden layer

h1: output from the first hidden layer;
W_H1TH2: weights between the first hidden layer and the second hidden layer; b2: The biases between the first hidden layer and second hidden layer

h3 here is a scalar and I did the following: Output = tansig(h3)..

However, the output is different when I compared it with x=net(input)
Any help!

I am expecting to have an equation at the end that can calculate the output based on the weights and biases!


问:
Is it okay for a field-resolver to write to the database in typegraphql
I have a property which, every time that it is queried should return a new value. I need to keep track of this value so I need to save this to the database. This would lead to queries which request this field now modifying the database...

 @FieldResolver(() => String)
  async signatureToken(
    @Root() address: Address,
    @Ctx() { em }: WithRequiredOnly<Context, "em"> //entity manager of the database (typeorm)
  ): Promise<string> {
    // ! Is it okay for a fieldresolver to modify the database?
    const newSignatureToken = uuidv4();
    address.signatureToken = newSignatureToken;
    address.signatureTokenCreated = new Date();
    await em.save(address) // Save the new address with signatureToken to the database

    return newSignatureToken;
  }
```


问:
DxUpload: How to change color of upload icon and loading bar?
I have been learning abour DevExpress and used DxUpload tag in my code. Everything seems to work smoothly, but I am not sure how to change the default blue color of the icon and loading bar that appears after user uploads file?

I have looked into css classes my code uses, but have found nothing that would be linked to this specific object.

Thanks in advance.