问:
Exception when creating datasource with PostgreSQL driver in Spring Boot
I'm trying to create a non-web application using Spring Boot following a MKyong's example, but I got the following error:

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.5.RELEASE)

(...) Several not relevant INFO log lines

2018-12-12 11:45:29.420 ERROR 30866 --- [ main] com.zaxxer.hikari.HikariConfig           : Failed to load driver class org.postgresql.Driver from HikariConfig class classloader sun.misc.Launcher$AppClassLoader@18b4aac2
2018-12-12 11:45:29.423  WARN 30866 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'ldConfiguration': Could not bind properties to 'LdConfiguration' : prefix=datasources.ld, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'datasources.ld' to es.ortoplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64
2018-12-12 11:45:29.435  INFO 30866 --- [ main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-12 11:45:29.440 ERROR 30866 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'datasources.ld' to es.oplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64:

    Property: datasources.ld.driverclassname
    Value: org.postgresql.Driver
    Origin: class path resource [application.yml]:3:22
    Reason: Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader

Action:

Update your application's configuration
</code>```

My conf file (application.yml) is

```<code>datasources:
  ld:
    driverClassName: org.postgresql.Driver
    jdbc-url: jdbc:postgresql://localhost:5432/oplus
    username: user123
    password: 123456
    connection-test-query: SELECT 1
</code>```

And in my Maven pom.xml file I added:

```<code><dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <!--<version> (managed by Spring Boot)42.2.5 </version> -->
</dependency>
</code>```

My entry point class:

```<code>@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired private UsuarioRepository usuarioRep;
    @Override
    public void run(String... args) throws Exception {
        App app = new App();
        System.out.printf("Users: %1d", app.usuarioRep.count());

    }

    public static void main(String[] args) throws ClassNotFoundException {
        //Class.forName("org.postgresql.Driver");
        SpringApplication.run(App.class, args);

    }

}
</code>```

As you can see, I've tried to check if the class is already in the classpath. If I uncomment that line I got a ClassNotFoundException, so it seems the error is caused because Maven is not including the dependency. I've tried to set the scope as runtime, but it fails anyway.

Anyway, here is my Configuration class:

```<code>@Configuration
@ConfigurationProperties(prefix = "datasources.ld")
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "postgreEntityManagerFactory", transactionManagerRef = "postgreTransactionManager",
        basePackages = "es.plus.l.dao")
public class LdConfiguration extends HikariConfig {

    @Bean(name = "postgreDataSource")
    @Primary
    public DataSource dataSource() {
        return new HikariDataSource(this);
    }

    @Bean(name = "postgreEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean postgreEntityManagerFactory(
            final EntityManagerFactoryBuilder builder,
            @Qualifier("postgreDataSource") final DataSource dataSource) {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setJpaVendorAdapter(this.vendorAdaptor());
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPersistenceUnitName("postgre");
        entityManagerFactoryBean.setPackagesToScan("es.oplus.ld.model");
        entityManagerFactoryBean.setJpaProperties(this.jpaHibernateProperties());
        entityManagerFactoryBean.afterPropertiesSet();
        return entityManagerFactoryBean;
    }

    @Bean(name = "postgreTransactionManager")
    @Primary
    public PlatformTransactionManager postgreTransactionManager(
          @Qualifier("postgreEntityManagerFactory") final EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

    private HibernateJpaVendorAdapter vendorAdaptor() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        // put all the adapter properties here, such as show sql
        return vendorAdapter;
    }

    private Properties jpaHibernateProperties() {
        final Properties properties = new Properties();
        // put all required jpa propeties here
        return properties;
    }

}
</code>```

答:
Make sure you have both JDBC driver and PostgreSQL dependencies in pom.xml as follows:</p>
```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
</code>```

Body:
I'm trying to create a non-web application using Spring Boot following a MKyong's example, but I got the following error:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.5.RELEASE)

(...) Several not relevant INFO log lines

2018-12-12 11:45:29.420 ERROR 30866 --- [ main] com.zaxxer.hikari.HikariConfig           : Failed to load driver class org.postgresql.Driver from HikariConfig class classloader sun.misc.Launcher$AppClassLoader@18b4aac2
2018-12-12 11:45:29.423  WARN 30866 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'ldConfiguration': Could not bind properties to 'LdConfiguration' : prefix=datasources.ld, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'datasources.ld' to es.ortoplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64
2018-12-12 11:45:29.435  INFO 30866 --- [ main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-12 11:45:29.440 ERROR 30866 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'datasources.ld' to es.oplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64:

    Property: datasources.ld.driverclassname
    Value: org.postgresql.Driver
    Origin: class path resource [application.yml]:3:22
    Reason: Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader

Action:

Update your application's configuration

My conf file (application.yml) is

datasources:
  ld:
    driverClassName: org.postgresql.Driver
    jdbc-url: jdbc:postgresql://localhost:5432/oplus
    username: user123
    password: 123456
    connection-test-query: SELECT 1

And in my Maven pom.xml file I added:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>

</dependency>

My entry point class:

@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired private UsuarioRepository usuarioRep;
    @Override
    public void run(String... args) throws Exception {
        App app = new App();
        System.out.printf("Users: %1d", app.usuarioRep.count());

    }

    public static void main(String[] args) throws ClassNotFoundException {
        //Class.forName("org.postgresql.Driver");
        SpringApplication.run(App.class, args);

    }

}

As you can see, I've tried to check if the class is already in the classpath. If I uncomment that line I got a ClassNotFoundException, so it seems the error is caused because Maven is not including the dependency. I've tried to set the scope as runtime, but it fails anyway.

Anyway, here is my Configuration class:

@Configuration
@ConfigurationProperties(prefix = "datasources.ld")
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "postgreEntityManagerFactory", transactionManagerRef = "postgreTransactionManager",
        basePackages = "es.plus.l.dao")
public class LdConfiguration extends HikariConfig {

    @Bean(name = "postgreDataSource")
    @Primary
    public DataSource dataSource() {
        return new HikariDataSource(this);
    }

    @Bean(name = "postgreEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean postgreEntityManagerFactory(
            final EntityManagerFactoryBuilder builder,
            @Qualifier("postgreDataSource") final DataSource dataSource) {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setJpaVendorAdapter(this.vendorAdaptor());
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPersistenceUnitName("postgre");
        entityManagerFactoryBean.setPackagesToScan("es.oplus.ld.model");
        entityManagerFactoryBean.setJpaProperties(this.jpaHibernateProperties());
        entityManagerFactoryBean.afterPropertiesSet();
        return entityManagerFactoryBean;
    }

    @Bean(name = "postgreTransactionManager")
    @Primary
    public PlatformTransactionManager postgreTransactionManager(
          @Qualifier("postgreEntityManagerFactory") final EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

    private HibernateJpaVendorAdapter vendorAdaptor() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        // put all the adapter properties here, such as show sql
        return vendorAdapter;
    }

    private Properties jpaHibernateProperties() {
        final Properties properties = new Properties();
        // put all required jpa propeties here
        return properties;
    }

}

Body:
Make sure you have both JDBC driver and PostgreSQL dependencies in pom.xml as follows:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>


来源: stackexchange

问:
Logical reasoning at Klarna interview
I get this reasoning question in Klarna pre test. Please help me to solve this. Question is in image</p>

答:
The correct Answer is B

Its because the middle column black squares remain constant while the two right columns move left. When they merge they become white. At separation restore to black.

ContentLicense: CC BY-SA 4.0

Title: Logical reasoning at Klarna interview


问:
AttributeError: Can't get attribute 'starfield_solve' on <module '__main__' (built-in)>
I have seen similar posts with the same problem. I tried to implement other suggested solutions that worked, but somehow it does not work for me. This is shorted example of my code that I am running in jupyter notebook:

```<code>def starfield_solve(file,verify):
    do_something

def apply_async_callback(src_path, verify):
    with Pool(processes=PROCESSES) as pool:
        multiple_results = [pool.apply_async(
            starfield_solve, args=(file, verify)) for file in files]

if __name__ == "__main__" :
    apply_async_callback(src_path, verify)
</code>```

EDIT:
I am putting down below the minimal reproducible example.
Further note, this exact code works on linux, but it doesn/t work on MacOS Monterey 12.1

```<code>import multiprocessing as mp
def starfield_solve(num):
    print(num)
    return num

def apply_async_callback():
    temp_dir = [1,2,3]
    PROCESSES = mp.cpu_count() - 1
    with mp.Pool(processes=PROCESSES) as pool:
        multiple_results = [pool.apply_async(starfield_solve, args=(num,)) for num in temp_dir]
        output = [res.get() for res in multiple_results if res.get()]

if __name__ == "__main__" :
    apply_async_callback()
</code>```

And this is the full error:

```<code>Process SpawnPoolWorker-20:
Traceback (most recent call last):
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/pool.py", line 114, in worker
    task = get()
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/queues.py", line 368, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'starfield_solve' on <module '__main__' (built-in)>
</code>```

答:
This seems to be a limitation on IPython (read as Jupyter Notebook) not fully supporting multiprocessing (relevant GitHub issue on IPython's repository). Use this solution, based on this GitHub issue:

Put your target function (starfield_solve) in a *.py file

Import the function from the file

Use that function to apply_async_callback

So, step 1:

```<code># your_module.py
def starfield_solve(file,verify):
    do_something
</code>```

Then, in your Jupyter Notebook, apply steps 2 and 3:

```<code>from your_module import starfield_solve

def apply_async_callback(src_path, verify):
    with Pool(processes=PROCESSES) as pool:
        multiple_results = [pool.apply_async(
            starfield_solve, args=(file, verify)) for file in files]
</code>```

Body:
I have seen similar posts with the same problem. I tried to implement other suggested solutions that worked, but somehow it does not work for me. This is shorted example of my code that I am running in jupyter notebook:

def starfield_solve(file,verify):
    do_something

def apply_async_callback(src_path, verify):
    with Pool(processes=PROCESSES) as pool:
        multiple_results = [pool.apply_async(
            starfield_solve, args=(file, verify)) for file in files]

if __name__ == "__main__" :
    apply_async_callback(src_path, verify)

EDIT:
I am putting down below the minimal reproducible example.
Further note, this exact code works on linux, but it doesn/t work on MacOS Monterey 12.1

import multiprocessing as mp
def starfield_solve(num):
    print(num)
    return num

def apply_async_callback():
    temp_dir = [1,2,3]
    PROCESSES = mp.cpu_count() - 1
    with mp.Pool(processes=PROCESSES) as pool:
        multiple_results = [pool.apply_async(starfield_solve, args=(num,)) for num in temp_dir]
        output = [res.get() for res in multiple_results if res.get()]

if __name__ == "__main__" :
    apply_async_callback()

And this is the full error:

Process SpawnPoolWorker-20:
Traceback (most recent call last):
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/pool.py", line 114, in worker
    task = get()
  File "/opt/miniconda3/envs/astrometry/lib/python3.9/multiprocessing/queues.py", line 368, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'starfield_solve' on <module '__main__' (built-in)>

Body:
This seems to be a limitation on IPython (read as Jupyter Notebook) not fully supporting multiprocessing (relevant GitHub issue on IPython's repository). Use this solution, based on this GitHub issue:

Put your target function (starfield_solve) in a *.py file

Import the function from the file

Use that function to apply_async_callback

So, step 1:

# your_module.py
def starfield_solve(file,verify):
    do_something

Then, in your Jupyter Notebook, apply steps 2 and 3:

from your_module import starfield_solve

def apply_async_callback(src_path, verify):
    with Pool(processes=PROCESSES) as pool:
        multiple_results = [pool.apply_async(
            starfield_solve, args=(file, verify)) for file in files]


问:
Are there any compression and encryption libraries in C#?
I want to compress some files (into the ZIP format) and encrypt them if possible using C#. Is there some way to do this?

Can encryption be done as a part of the compression itself?

答: For compression, look at the System.IO.Compression namespace and for encryption look at System.Security.Cryptography.

OwnerDisplayName: Niyaz

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Skizz

ContentLicense: CC BY-SA 3.0


问:
Unresolved plugin: 'org.apache.maven.plugins:maven-compiler-plugin:3.8.0'
I tried to set up Maven projects under my IntelliJ IDE. However, when I try to update the pom.xml file, I am getting this error. I tried deleting the .m2 repository under Users, made the changes under Build Tools for Maven. Still, the issue doesn't seem to get resolved.

答:
You can try
File -> Invalidate Caches -> Invalidate and Restart
so IntelliJ will try index again to the resources.</p>


问:
AdMob not loading ads after update
I have an android published app working and serving ads with the app-ads.txt setup correctly. I tried to upgrade the ads library to the latest 'com.google.android.gms:play-services-ads:20.5.0' and now I am getting the error code 3 'No add config' every time I try to load an ad.

Long story short, after much investigation I downloaded the Google ads sample which works okay. If I change the applicationId on the project build.gradle to anything ads loads. If I change it to the id of my app I get the error.

Why the new ad library refuse to serve my app while the published app works okay?

答: I found the issue not clear on the docs. When you use the admob mediation you need to define the test devices. Mediation will not work with the new test ids.</p>

Title: AdMob not loading ads after update


问:
Would like to return different classes from a single generic method call without using object
I have three classes--very simple example:

```<code>    public class MyTableLayoutPanelBase : TableLayoutPanel
    {
    }

    public class MyTableLayoutPanelExt : MyTableLayoutPanelBase
    {
    }

    public class MyTableLayoutPanelUltraExt : MyTableLayoutPanelExt
    {
    }
</code>```

The Base subclass subclasses the Microsoft WinForms TableLayoutPanel control. I then have an Ext version that further subclasses my Base class and an UltraExt that subclasses the Ext class. In my real-world use, the Base, Ext, and UltraExt subclasses add some properties beyond what was inherited. For the sake of this discussion, all of these classes have the same implementation...

What I'd like is a factory that returns one of these subclassed objects. The approach I took was to do this:

```<code>    public static object CreateMyTableLayoutPanelControl<T>()
    {
        if (typeof(T) == typeof(MyTableLayoutPanelControlBase))
        {
            return new MyTableLayoutPanelControlBase();
        }
        if (typeof(T) == typeof(MyTableLayoutPanelControlExt))
        {
            return new MyTableLayoutPanelControlExt();
        }
        if (typeof(T) == typeof(MyTableLayoutPanelControlUltraExt))
        {
            return new MyTableLayoutPanelControlUltraExt();
        }
    }
</code>```

This lets me do something like this:

```<code>var myTableLayoutPanelControlExt = (MyTableLayoutPanelExt)CreateMyTableLayoutPanelControl<MyTableLayoutPanelExt>();
</code>```

The problem is that I need to cast the object returned to the subclass type I need--I know the cast will succeed as long as I cast to one of the three types I know CreateMyTableLayoutPanelControl will return. But that's kludgy, and expensive. I'd much rather just receive from the factory the actual object in the correct type I need.

Is there a way I can leverage the generics and the fact that my classes don't implement an interface to return not object but the actual class instance requested in the CreateMyTableLayoutControl generics call? Ideally, I'd like this code to work without casts:

```<code>MyTableLayoutPanelExt myTableLayoutPanelControlExt = CreateMyTableLayoutPanelControl<MyTableLayoutPanelExt>();
</code>```

答:
You could do this in two steps:

First, create a non-generic method using a Type parameter doing the heavy lifting:

```<code>public static MyTableLayoutPanelBase CreateMyTableLayoutPanelControl(Type t)
{
    if (t == typeof(MyTableLayoutPanelBase))
    {
        return new MyTableLayoutPanelBase();
    }
    if (t == typeof(MyTableLayoutPanelExt))
    {
        return new MyTableLayoutPanelExt();
    }
    if (t == typeof(MyTableLayoutPanelUltraExt))
    {
        return new MyTableLayoutPanelUltraExt();
    }
    return null;
}
</code>```

Then, you can easily provide a generic version doing the cast for you:

```<code>public static T CreateMyTableLayoutPanelControl<T>() where T : MyTableLayoutPanelBase
{
    return (T)CreateMyTableLayoutPanelControl(typeof(T));
}
</code>```

Body:
I have three classes--very simple example:

    public class MyTableLayoutPanelBase : TableLayoutPanel
    {
    }

    public class MyTableLayoutPanelExt : MyTableLayoutPanelBase
    {
    }

    public class MyTableLayoutPanelUltraExt : MyTableLayoutPanelExt
    {
    }

The Base subclass subclasses the Microsoft WinForms TableLayoutPanel control. I then have an Ext version that further subclasses my Base class and an UltraExt that subclasses the Ext class. In my real-world use, the Base, Ext, and UltraExt subclasses add some properties beyond what was inherited. For the sake of this discussion, all of these classes have the same implementation...

What I'd like is a factory that returns one of these subclassed objects. The approach I took was to do this:

    public static object CreateMyTableLayoutPanelControl<T>()
    {
        if (typeof(T) == typeof(MyTableLayoutPanelControlBase))
        {
            return new MyTableLayoutPanelControlBase();
        }
        if (typeof(T) == typeof(MyTableLayoutPanelControlExt))
        {
            return new MyTableLayoutPanelControlExt();
        }
        if (typeof(T) == typeof(MyTableLayoutPanelControlUltraExt))
        {
            return new MyTableLayoutPanelControlUltraExt();
        }
    }

This lets me do something like this:

var myTableLayoutPanelControlExt = (MyTableLayoutPanelExt)CreateMyTableLayoutPanelControl<MyTableLayoutPanelExt>();

The problem is that I need to cast the object returned to the subclass type I need--I know the cast will succeed as long as I cast to one of the three types I know CreateMyTableLayoutPanelControl will return. But that's kludgy, and expensive. I'd much rather just receive from the factory the actual object in the correct type I need.

Is there a way I can leverage the generics and the fact that my classes don't implement an interface to return not object but the actual class instance requested in the CreateMyTableLayoutControl generics call? Ideally, I'd like this code to work without casts:

MyTableLayoutPanelExt myTableLayoutPanelControlExt = CreateMyTableLayoutPanelControl<MyTableLayoutPanelExt>();

Body:
You could do this in two steps:

First, create a non-generic method using a Type parameter doing the heavy lifting:

public static MyTableLayoutPanelBase CreateMyTableLayoutPanelControl(Type t)
{
    if (t == typeof(MyTableLayoutPanelBase))
    {
        return new MyTableLayoutPanelBase();
    }
    if (t == typeof(MyTableLayoutPanelExt))
    {
        return new MyTableLayoutPanelExt();
    }
    if (t == typeof(MyTableLayoutPanelUltraExt))
    {
        return new MyTableLayoutPanelUltraExt();
    }
    return null;
}

Then, you can easily provide a generic version doing the cast for you:

public static T CreateMyTableLayoutPanelControl<T>() where T : MyTableLayoutPanelBase
{
    return (T)CreateMyTableLayoutPanelControl(typeof(T));
}


问:
Adopting Bamboo or TeamCity as native Windows C++ build automation/CI server?
At the moment, we are running our automated (not CI as such) builds via FinalBuilder via a very simple homegrown Apache interface that just launches the FB scripts on our server. (I like FinalBuilder, and will keep it, but it's CI server, FinalBuilder Server just doesn't cut it IMHO -- especially it doesn't support any "agent" concept at the moment to distribute builds across machines.)

We are doing native C++ development on Windows with a bit .NET mixed in where it's needed and makes sense.

Our current FinalBuilder scripts do everything quite well, from creating nightly builds to full releases (build / automated translation / build / unit test / create setup / put created artifacts on a network share / ...), but our webinterface, queuing abilities, user traceability and reporting is pretty limited.

I have looked around and it seems that TeamCity and Bamboo tick similar boxes, but most descriptions I can find cover only Java and/or .NET simple builds.

So my specific question is, given

several (20-30) complicated FinalBuilder Scripts that work to my satisfaction and that I will have to integrate into ("call" from) the new automation/"CI" server

Native Windows C++ and .NET projects

The actual build (= compiler invocation(s)) is done via a few Visual Studio solution files at the moment

Currently one build server machine, wishing to scale to 2-3 atm.

Using JIRA as issue tracker

using AccuRev as SCM

which tool is better suited, and why: TeamCity (currently 6.5) or Bamboo (currently 3.1).

(Note that I also hope to get some highly subjective answers on the TeamCity and Bamboo forums.)

答: For completeness' sake: I ended up using Jenkins + Finalbuilder. :-)</p>


问:
Location of @classmethod
Where is the source code for the decorator classmethod located in the python source code.  Specifically I am having trouble finding the exact file it's defined in version 2.7.2</p>

答:
I found this in ms-python.vscode-pylance-2022.1.3...\stdlib\builtins.pyi:</p>
```<code>class staticmethod(Generic[_R]):
__func__: Callable[..., _R]
__isabstractmethod__: bool
def __init__(self: staticmethod[_R], __f: Callable[..., _R]) -> None: ...
def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R]: ...
if sys.version_info >= (3, 10):
    __name__: str
    __qualname__: str
    __wrapped__: Callable[..., _R]
    def __call__(self, *args: Any, **kwargs: Any) -> _R: ...

class classmethod(Generic[_R]):
__func__: Callable[..., _R]
__isabstractmethod__: bool
def __init__(self: classmethod[_R], __f: Callable[..., _R]) -> None: ...
def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R]: ...
if sys.version_info >= (3, 10):
    __name__: str
    __qualname__: str
    __wrapped__: Callable[..., _R]
</code>```

Title: Location of @classmethod

Body:
I found this in ms-python.vscode-pylance-2022.1.3...\stdlib\builtins.pyi:

class staticmethod(Generic[_R]):
__func__: Callable[..., _R]
__isabstractmethod__: bool
def __init__(self: staticmethod[_R], __f: Callable[..., _R]) -> None: ...
def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R]: ...
if sys.version_info >= (3, 10):
    __name__: str
    __qualname__: str
    __wrapped__: Callable[..., _R]
    def __call__(self, *args: Any, **kwargs: Any) -> _R: ...

class classmethod(Generic[_R]):
__func__: Callable[..., _R]
__isabstractmethod__: bool
def __init__(self: classmethod[_R], __f: Callable[..., _R]) -> None: ...
def __get__(self, __obj: _T, __type: type[_T] | None = ...) -> Callable[..., _R]: ...
if sys.version_info >= (3, 10):
    __name__: str
    __qualname__: str
    __wrapped__: Callable[..., _R]


答:
You can try to use Activator.CreateInstance function with generics, then let generics type make constract with TableLayoutPanel your base Type TableLayoutPanel

```<code>public static T CreateMyTableLayoutPanelControl<T>()
    where T : TableLayoutPanel
{
    return Activator.CreateInstance<T>();
}
</code>```

I would not return object type from the method unless necessary, because it will cause some problems.

c# fiddle

Title: Would like to return different classes from a single generic method call without using object

Body:
You can try to use Activator.CreateInstance function with generics, then let generics type make constract with TableLayoutPanel your base Type TableLayoutPanel

public static T CreateMyTableLayoutPanelControl<T>()
    where T : TableLayoutPanel
{
    return Activator.CreateInstance<T>();
}

I would not return object type from the method unless necessary, because it will cause some problems.

c# fiddle


问:
Pyserial only works with opencv when readline() is used
So, I am creating a program that calculate some degrees based on opencv and then sends them to an Arduino using pyserial for a servo to rotate. The problem is this only works when ser.readline() is used which slows down opencv a lot. I've tried using ser.flush() or even ser.read() but they don't seem to work. I've also tried adjusting timeout in the pyserial initialization which still doesn't make any difference.
This is the python code

# For webcam input:
cap = cv2.VideoCapture(0)
with mp_pose.Pose(
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as pose:

  while cap.isOpened():
    success, image = cap.read()
    if not success:
      print("Ignoring empty camera frame.")
      # If loading a video, use 'break' instead of 'continue'.
      continue
    # To improve performance, optionally mark the image as not writeable to
    # pass by reference.
    image.flags.writeable = False
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    results = pose.process(image)

    if not results.pose_landmarks:
      continue
    image_height, image_width, _ = image.shape

    try:
      angle = calculate_degrees(results)
      ser.write(str(angle).encode())    # Draw the pose annotation on the image.
      # Said readline
      ser.readline()
    except:
      pass
    image.flags.writeable = True
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    mp_drawing.draw_landmarks(
        image,
        results.pose_landmarks,
        mp_pose.POSE_CONNECTIONS,
        landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style())
    # Flip the image horizontally for a selfie-view display.
    cv2.imshow('MediaPipe Pose', cv2.flip(image, 1))
    if cv2.waitKey(5) and 0xFF == 27:
      break
cap.release()
ser.close()
```
<p>and here is the arduino code</p>
<pre class="lang-cpp prettyprint-override"><code>#include <Arduino.h>
#include <Servo.h>

Servo servo;

void setup() {
  // put your setup code here, to run once:
  servo.attach(7);
  servo.write(0);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    if (Serial.available()){
      String angle_string = Serial.readString();
      Serial.print("Recieved Value: ");
      Serial.println(angle_string);
      int angle = angle_string.toInt();
      servo.write(angle);
    }
}
</code>```

答:
I'm not sure about the OpenCV part,but by changing the baud rate of Arduino can speed up data receiving and transmitting.

Change

```<code>Serial.begin(9600);
</code>```

to

```<code>Serial.begin(115200);
</code>```

If this doesn't help.I suggest you to use a Raspberry Pi to do this project.By using the GPIO of RPi,you can interact with your servo directly and with no delay.

Update:
You need to add a delay of 15~20ms after servo.write(angle);to let the servo move to its position.

Here is a simple program that I wrote to test my servo.

```<code>#include <Servo.h>

Servo myservo;

String inString="";
int val;

void setup() {
  Serial.begin(9600);
  myservo.attach(22);
}

void loop() {
  if(Serial.available() > 0){
  inString = Serial.readStringUntil('\n');
  val = inString.toInt();
  Serial.println(val);
  myservo.write(val);
  delay(15);
  }
}
</code>```

Body:
So, I am creating a program that calculate some degrees based on opencv and then sends them to an Arduino using pyserial for a servo to rotate. The problem is this only works when ser.readline() is used which slows down opencv a lot. I've tried using ser.flush() or even ser.read() but they don't seem to work. I've also tried adjusting timeout in the pyserial initialization which still doesn't make any difference.
This is the python code

# For webcam input:
cap = cv2.VideoCapture(0)
with mp_pose.Pose(
    min_detection_confidence=0.5,
    min_tracking_confidence=0.5) as pose:

  while cap.isOpened():
    success, image = cap.read()
    if not success:
      print("Ignoring empty camera frame.")
      # If loading a video, use 'break' instead of 'continue'.
      continue
    # To improve performance, optionally mark the image as not writeable to
    # pass by reference.
    image.flags.writeable = False
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    results = pose.process(image)

    if not results.pose_landmarks:
      continue
    image_height, image_width, _ = image.shape

    try:
      angle = calculate_degrees(results)
      ser.write(str(angle).encode())    # Draw the pose annotation on the image.
      # Said readline
      ser.readline()
    except:
      pass
    image.flags.writeable = True
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    mp_drawing.draw_landmarks(
        image,
        results.pose_landmarks,
        mp_pose.POSE_CONNECTIONS,
        landmark_drawing_spec=mp_drawing_styles.get_default_pose_landmarks_style())
    # Flip the image horizontally for a selfie-view display.
    cv2.imshow('MediaPipe Pose', cv2.flip(image, 1))
    if cv2.waitKey(5) and 0xFF == 27:
      break
cap.release()
ser.close()

and here is the arduino code

#include <Arduino.h>
#include <Servo.h>

Servo servo;

void setup() {
  // put your setup code here, to run once:
  servo.attach(7);
  servo.write(0);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
    if (Serial.available()){
      String angle_string = Serial.readString();
      Serial.print("Recieved Value: ");
      Serial.println(angle_string);
      int angle = angle_string.toInt();
      servo.write(angle);
    }
}

Body:
I'm not sure about the OpenCV part,but by changing the baud rate of Arduino can speed up data receiving and transmitting.

Change

Serial.begin(9600);

to

Serial.begin(115200);

If this doesn't help.I suggest you to use a Raspberry Pi to do this project.By using the GPIO of RPi,you can interact with your servo directly and with no delay.

Update:
You need to add a delay of 15~20ms after servo.write(angle);to let the servo move to its position.

Here is a simple program that I wrote to test my servo.

#include <Servo.h>

Servo myservo;

String inString="";
int val;

void setup() {
  Serial.begin(9600);
  myservo.attach(22);
}

void loop() {
  if(Serial.available() > 0){
  inString = Serial.readStringUntil('\n');
  val = inString.toInt();
  Serial.println(val);
  myservo.write(val);
  delay(15);
  }
}


问:
Import dll into Unity "file inaccessible" or "not valid assembly"
I am trying to import a dll into my Unity project. I have the dll copied into the Assets folder. When I try to "Add Reference" in Visual Studio, I keep getting this error.

Can anyone point to what issue may be causing this error? The dll in question is from the Native SDK for the Varjo headset. I am trying to import it so I can use the Native API from within my Unity project (requires functionality the Unity plugin does not provide).

答:
Don't add the .dll to the references in visual project. Just drop it into your assets folder (better yet some subfolder).

To be able to use the relevant APIs from C# you will need to write a wrapper class similar to the one shown in this example:

https://docs.unity3d.com/Manual/NativePlugins.html

If you want you can give me a few examples of methods you want to call and I can show you how to expose them to c#.


问:
Date Unit test passed locally but failed in Gitlab CD/CI pipeline
For date validation, I used luxon for my app. For each function I have made unit test. My unit test passed locally but when I deployed my code in gitlab, Most of my test failed. The expected result is so different than received. I don't understand what's the wrong. This my CD/CI pipeline images. Image-1, image-2, Image-3 and there are more. Basically all my test failed

My all test passed in code-sandbox

These are my all functions:

import {
  DateTime
} from 'luxon'

export const DEFAULT_DATE_FORMAT = 'd.M.yyyy'
export const SHORT_TIME_FORMAT = 'HH:mm'
export const ISO_DATE_FORMAT = 'yyyy-MM-dd'
export const DATE_TIME_FORMAT = 'd.M.yyyy HH:mm'
export const DATE_MONTH_FORMAT = 'd.M'

export const WEEKDAYS = [
  'SUNDAY',
  'MONDAY',
  'TUESDAY',
  'WEDNESDAY',
  'THURSDAY',
  'FRIDAY',
  'SATURDAY',
]

export const dateToStrings = (date: string | number | Date): DateTime =>
  DateTime.fromISO(new Date(date).toISOString())

export const formatDateTime = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(DATE_TIME_FORMAT)
export const formatDateMonthYear = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(DEFAULT_DATE_FORMAT)

export const formatTime = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(SHORT_TIME_FORMAT)

export const NextDayFormatYearMonthDate = (date: string | number | Date): string =>
  dateToStrings(date).plus({
    days: 1
  }).toFormat(ISO_DATE_FORMAT)

export const PreviousDayFormatYearMonthDate = (date: string | number | Date): string =>
  dateToStrings(date).plus({
    days: -1
  }).toFormat(ISO_DATE_FORMAT)

export const dateDifference = (date: string | number | Date): number => {
  const diff = dateToStrings(date).diff(DateTime.now(), 'days').toObject()

  return Math.abs(Math.ceil(diff.days as number))
}

export const formatYearMonthDate = (date: Date | string | undefined): string => {
  if (!date) {
    //  if date is undefined, return empty string
    return ''
  } else {
    return dateToStrings(date).toFormat(ISO_DATE_FORMAT)
  }
}
export const weekNumber = (date: string | Date): number =>
  dateToStrings(date).startOf('week').weekNumber

export const nextWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').plus({
    days: 7
  }).toFormat(ISO_DATE_FORMAT)

export const previousWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').plus({
    days: -7
  }).toFormat(ISO_DATE_FORMAT)
export const firstDateOfWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').toFormat(ISO_DATE_FORMAT)

export const lastDateOfWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').plus({
    days: 6
  }).toFormat(ISO_DATE_FORMAT)

export const firstMondayOfTheWeekWithGMT = (date: Date): Date =>
  dateToStrings(date).startOf('week').toJSDate()

export const formatDateMonth = (date: string | Date): string =>
  dateToStrings(date).toFormat(DATE_MONTH_FORMAT)

export const shortDateString = (date: Date): string => {
  const shortForm = dateToStrings(date).setLocale('fi').toFormat('EEE')
  return shortForm.length > 1 ? `${shortForm.charAt(0).toUpperCase()}${shortForm.slice(1)}` : ''
}

export const hasSameDay = (date1: Date, date2: Date): boolean =>
  dateToStrings(date1).hasSame(dateToStrings(date2), 'day')

export const isToday = (date: string | number | Date): boolean => {
  return dateToStrings(date).toISODate() === DateTime.local().toISODate()
}

export const compareDays = (
  date1: Date | string | number,
  date2: Date | string | number,
): number => {
  const compareWithDay = dateToStrings(date1).diff(dateToStrings(date2), ['days']).toObject()

  return Math.abs(Math.ceil(compareWithDay.days as number))
}```
</div>
</div>
</p>
<p><strong>This is my all tests</strong></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>import {
  formatDateTime,
  formatDateMonthYear,
  formatTime,
  NextDayFormatYearMonthDate,
  PreviousDayFormatYearMonthDate,
  dateDifference,
  formatYearMonthDate,
  weekNumber,
  nextWeek,
  previousWeek,
  firstDateOfWeek,
  lastDateOfWeek,
  formatDateMonth,
  shortDateString,
  compareDays,
  DATE_MONTH_FORMAT,
  DEFAULT_DATE_FORMAT,
  SHORT_TIME_FORMAT,
  ISO_DATE_FORMAT,
  DATE_TIME_FORMAT,
} from 'utils/date'
import { DateTime } from 'luxon'

const toDateString = 'Mon Feb 07 2022 00:00:00 GMT+0200 (Eastern European Standard Time)'
const toISOString = '2018-05-01T13:44:48.708709Z'
const today = new Date()
const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)

describe('formatDateTime', () => {
  it('Should return format date time when date is string', () => {
    expect(formatDateTime('2022-02-11T06:44:57+00:00')).toBe('7.2.2022 00:00')
  })

  it('Should return format date time when date is toISOString', () => {
    expect(formatDateTime(toISOString)).toBe('1.5.2018 16:44')
  })
  it('Should return format date time when date is today', () => {
    expect(formatDateTime(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(DATE_TIME_FORMAT),
    )
  })
})

describe('formatDateMonthYear', () => {
  it('Should return format date when date is string', () => {
    expect(formatDateMonthYear(toDateString)).toBe('7.2.2022')
  })

  it('Should return format date when date is ISO String', () => {
    expect(formatDateMonthYear(toISOString)).toBe('1.5.2018')
  })

  it('Should return format date when date is today', () => {
    expect(formatDateMonthYear(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(DEFAULT_DATE_FORMAT),
    )
  })
})

describe('formatTime', () => {
  it('Should return 00:00 when there is no time', () => {
    expect(formatTime(toDateString)).toBe('00:00')
  })

  it('Should return format time', () => {
    expect(formatTime(toISOString)).toBe('16:44')
  })

  it('Should return format time when date is today', () => {
    expect(formatTime(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(SHORT_TIME_FORMAT),
    )
  })
})

describe('NextDayFormatYearMonthDate ', () => {
  it('Should return next day format year when date is string', () => {
    expect(NextDayFormatYearMonthDate(toDateString)).toBe('2022-02-08')
  })

  it('Should return next day format year when date is ISOString', () => {
    expect(NextDayFormatYearMonthDate(toISOString)).toBe('2018-05-02')
  })
  it('Should return next day format year when date is today', () => {
    expect(NextDayFormatYearMonthDate(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).plus({ days: 1 }).toFormat(ISO_DATE_FORMAT),
    )
  })
})

describe('PreviousDayFormatYearMonthDate', () => {
  it('Should return next day format year when date is string', () => {
    expect(PreviousDayFormatYearMonthDate(toDateString)).toBe('2022-02-06')
  })

  it('Should return next day format year when date is ISOString', () => {
    expect(PreviousDayFormatYearMonthDate(toISOString)).toBe('2018-04-30')
  })
  it('Should return next day format year when date is today', () => {
    expect(PreviousDayFormatYearMonthDate(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).plus({ days: -1 }).toFormat(ISO_DATE_FORMAT),
    )
  })
})

describe('dateDifference', () => {
  it('Should return 0 when date is today', () => {
    expect(dateDifference(today)).toBe(0)
  })

  it('Should return 1 when date is not today', () => {
    expect(dateDifference(tomorrow)).toBe(1)
  })

  it('Should return 1 when date is not today', () => {
    expect(dateDifference(yesterday)).toBe(1)
  })
})

describe('formatYearMonthDate', () => {
  it('Should return format date when date is string', () => {
    expect(formatYearMonthDate(toDateString)).toBe('2022-02-07')
  })

  it('Should return format date when date is ISO String', () => {
    expect(formatYearMonthDate(toISOString)).toBe('2018-05-01')
  })

  it('Should return format date when date is today', () => {
    expect(formatYearMonthDate(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(ISO_DATE_FORMAT),
    )
  })

  it('Should return empty string when date is undefined', () => {
    expect(formatYearMonthDate(undefined)).toBe('')
  })
})

describe('weekNumber', () => {
  it('Should return week number when date is string', () => {
    expect(weekNumber(toDateString)).toBe(6)
  })

  it('Should return week number when date is ISO String', () => {
    expect(weekNumber(toISOString)).toBe(18)
  })

  it('Should return week number when date is today', () => {
    expect(weekNumber(today)).toBe(DateTime.fromISO(new Date().toISOString()).weekNumber)
  })
})

describe('nextWeek', () => {
  it('Should return next week date when date is string', () => {
    expect(nextWeek(toDateString)).toBe('2022-02-14')
  })

  it('Should return next week date when date is ISO String', () => {
    expect(nextWeek(toISOString)).toBe('2018-05-07')
  })
})

describe('previousWeek', () => {
  it('Should return previous week date when date is string', () => {
    expect(previousWeek(toDateString)).toBe('2022-01-31')
  })

  it('Should return previous week date when date is ISO String', () => {
    expect(previousWeek(toISOString)).toBe('2018-04-23')
  })
})

describe('firstDateOfWeek', () => {
  it('Should return first date of the week when date is string', () => {
    expect(firstDateOfWeek(toDateString)).toBe('2022-02-07')
  })

  it('Should return first date of the week when date is ISO String', () => {
    expect(firstDateOfWeek(toISOString)).toBe('2018-04-30')
  })
})

describe('lastDateOfWeek', () => {
  it('Should return first date of the week when date is string', () => {
    expect(lastDateOfWeek(toDateString)).toBe('2022-02-13')
  })

  it('Should return first date of the week when date is ISO String', () => {
    expect(lastDateOfWeek(toISOString)).toBe('2018-05-06')
  })
})

describe('formatDateMonth', () => {
  it('Should return format date month when date is string', () => {
    expect(formatDateMonth(toDateString)).toBe('7.2')
  })

  it('Should return format date month when date is ISO String', () => {
    expect(formatDateMonth(toISOString)).toBe('1.5')
  })

  it('Should return format date month when date is today', () => {
    expect(formatDateMonth(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(DATE_MONTH_FORMAT),
    )
  })
})

describe('shortDateString', () => {
  it('Should return first two letters Finnish weekdays when date is string', () => {
    expect(shortDateString(new Date(toDateString))).toBe('Ma')
  })

  it('Should return first two letters Finnish weekdays when date is ISO String', () => {
    expect(shortDateString(new Date(toISOString))).toBe('Ti')
  })
})

describe('compareDays', () => {
  it('Should return 0 if the dates are same', () => {
    expect(compareDays(new Date(toDateString), new Date(toDateString))).toBe(0)
  })

  it('Should return 0 if the dates are same', () => {
    expect(compareDays(new Date(toDateString), new Date(toISOString))).toBe(1378)
  })

  it('Should return 0 if the dates are string', () => {
    expect(compareDays(toDateString, toISOString)).toBe(1378)
  })
})</code>```

答:
The difference has to do with the timezone of your local computer and the timezone of the GitLab runner. The GitLab runners use UTC timezone.

Take this case for example:

const toDateString = 'Mon Feb 07 2022 00:00:00 GMT+0200 (Eastern European Standard Time)'
// ...
describe('formatTime', () => {
  it('Should return 00:00 when there is no time', () => {
    expect(formatTime(toDateString)).toBe('00:00')
  })
```
<p>In your unit test results:</p>
```Expected: "00:00"
Received: "22:00"
```

This would pass if your local timezone is UTC+2, but would fail if your timezone is UTC. Mon Feb 07 2022 00:00:00 GMT+0200 is Sun Feb 06 2022 22:00:00 in UTC time.

From the luxon docs: (emphasis added)

A DateTime comprises of:

[...]

A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).

[...]

You'll probably want to normalize your tests to use a particular timezone. See this question for hints on how to change the timezone of the datetime objects.

Body:
For date validation, I used luxon for my app. For each function I have made unit test. My unit test passed locally but when I deployed my code in gitlab, Most of my test failed. The expected result is so different than received. I don't understand what's the wrong. This my CD/CI pipeline images. Image-1, image-2, Image-3 and there are more. Basically all my test failed

My all test passed in code-sandbox

These are my all functions:

import {
  DateTime
} from 'luxon'

export const DEFAULT_DATE_FORMAT = 'd.M.yyyy'
export const SHORT_TIME_FORMAT = 'HH:mm'
export const ISO_DATE_FORMAT = 'yyyy-MM-dd'
export const DATE_TIME_FORMAT = 'd.M.yyyy HH:mm'
export const DATE_MONTH_FORMAT = 'd.M'

export const WEEKDAYS = [
  'SUNDAY',
  'MONDAY',
  'TUESDAY',
  'WEDNESDAY',
  'THURSDAY',
  'FRIDAY',
  'SATURDAY',
]

export const dateToStrings = (date: string | number | Date): DateTime =>
  DateTime.fromISO(new Date(date).toISOString())

export const formatDateTime = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(DATE_TIME_FORMAT)
export const formatDateMonthYear = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(DEFAULT_DATE_FORMAT)

export const formatTime = (date: string | number | Date): string =>
  dateToStrings(date).toFormat(SHORT_TIME_FORMAT)

export const NextDayFormatYearMonthDate = (date: string | number | Date): string =>
  dateToStrings(date).plus({
    days: 1
  }).toFormat(ISO_DATE_FORMAT)

export const PreviousDayFormatYearMonthDate = (date: string | number | Date): string =>
  dateToStrings(date).plus({
    days: -1
  }).toFormat(ISO_DATE_FORMAT)

export const dateDifference = (date: string | number | Date): number => {
  const diff = dateToStrings(date).diff(DateTime.now(), 'days').toObject()

  return Math.abs(Math.ceil(diff.days as number))
}

export const formatYearMonthDate = (date: Date | string | undefined): string => {
  if (!date) {
    //  if date is undefined, return empty string
    return ''
  } else {
    return dateToStrings(date).toFormat(ISO_DATE_FORMAT)
  }
}
export const weekNumber = (date: string | Date): number =>
  dateToStrings(date).startOf('week').weekNumber

export const nextWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').plus({
    days: 7
  }).toFormat(ISO_DATE_FORMAT)

export const previousWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').plus({
    days: -7
  }).toFormat(ISO_DATE_FORMAT)
export const firstDateOfWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').toFormat(ISO_DATE_FORMAT)

export const lastDateOfWeek = (date: string | Date): string =>
  dateToStrings(date).startOf('week').plus({
    days: 6
  }).toFormat(ISO_DATE_FORMAT)

export const firstMondayOfTheWeekWithGMT = (date: Date): Date =>
  dateToStrings(date).startOf('week').toJSDate()

export const formatDateMonth = (date: string | Date): string =>
  dateToStrings(date).toFormat(DATE_MONTH_FORMAT)

export const shortDateString = (date: Date): string => {
  const shortForm = dateToStrings(date).setLocale('fi').toFormat('EEE')
  return shortForm.length > 1 ? `${shortForm.charAt(0).toUpperCase()}${shortForm.slice(1)}` : ''
}

export const hasSameDay = (date1: Date, date2: Date): boolean =>
  dateToStrings(date1).hasSame(dateToStrings(date2), 'day')

export const isToday = (date: string | number | Date): boolean => {
  return dateToStrings(date).toISODate() === DateTime.local().toISODate()
}

export const compareDays = (
  date1: Date | string | number,
  date2: Date | string | number,
): number => {
  const compareWithDay = dateToStrings(date1).diff(dateToStrings(date2), ['days']).toObject()

  return Math.abs(Math.ceil(compareWithDay.days as number))
}

This is my all tests

import {
  formatDateTime,
  formatDateMonthYear,
  formatTime,
  NextDayFormatYearMonthDate,
  PreviousDayFormatYearMonthDate,
  dateDifference,
  formatYearMonthDate,
  weekNumber,
  nextWeek,
  previousWeek,
  firstDateOfWeek,
  lastDateOfWeek,
  formatDateMonth,
  shortDateString,
  compareDays,
  DATE_MONTH_FORMAT,
  DEFAULT_DATE_FORMAT,
  SHORT_TIME_FORMAT,
  ISO_DATE_FORMAT,
  DATE_TIME_FORMAT,
} from 'utils/date'
import { DateTime } from 'luxon'

const toDateString = 'Mon Feb 07 2022 00:00:00 GMT+0200 (Eastern European Standard Time)'
const toISOString = '2018-05-01T13:44:48.708709Z'
const today = new Date()
const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)

describe('formatDateTime', () => {
  it('Should return format date time when date is string', () => {
    expect(formatDateTime('2022-02-11T06:44:57+00:00')).toBe('7.2.2022 00:00')
  })

  it('Should return format date time when date is toISOString', () => {
    expect(formatDateTime(toISOString)).toBe('1.5.2018 16:44')
  })
  it('Should return format date time when date is today', () => {
    expect(formatDateTime(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(DATE_TIME_FORMAT),
    )
  })
})

describe('formatDateMonthYear', () => {
  it('Should return format date when date is string', () => {
    expect(formatDateMonthYear(toDateString)).toBe('7.2.2022')
  })

  it('Should return format date when date is ISO String', () => {
    expect(formatDateMonthYear(toISOString)).toBe('1.5.2018')
  })

  it('Should return format date when date is today', () => {
    expect(formatDateMonthYear(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(DEFAULT_DATE_FORMAT),
    )
  })
})

describe('formatTime', () => {
  it('Should return 00:00 when there is no time', () => {
    expect(formatTime(toDateString)).toBe('00:00')
  })

  it('Should return format time', () => {
    expect(formatTime(toISOString)).toBe('16:44')
  })

  it('Should return format time when date is today', () => {
    expect(formatTime(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(SHORT_TIME_FORMAT),
    )
  })
})

describe('NextDayFormatYearMonthDate ', () => {
  it('Should return next day format year when date is string', () => {
    expect(NextDayFormatYearMonthDate(toDateString)).toBe('2022-02-08')
  })

  it('Should return next day format year when date is ISOString', () => {
    expect(NextDayFormatYearMonthDate(toISOString)).toBe('2018-05-02')
  })
  it('Should return next day format year when date is today', () => {
    expect(NextDayFormatYearMonthDate(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).plus({ days: 1 }).toFormat(ISO_DATE_FORMAT),
    )
  })
})

describe('PreviousDayFormatYearMonthDate', () => {
  it('Should return next day format year when date is string', () => {
    expect(PreviousDayFormatYearMonthDate(toDateString)).toBe('2022-02-06')
  })

  it('Should return next day format year when date is ISOString', () => {
    expect(PreviousDayFormatYearMonthDate(toISOString)).toBe('2018-04-30')
  })
  it('Should return next day format year when date is today', () => {
    expect(PreviousDayFormatYearMonthDate(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).plus({ days: -1 }).toFormat(ISO_DATE_FORMAT),
    )
  })
})

describe('dateDifference', () => {
  it('Should return 0 when date is today', () => {
    expect(dateDifference(today)).toBe(0)
  })

  it('Should return 1 when date is not today', () => {
    expect(dateDifference(tomorrow)).toBe(1)
  })

  it('Should return 1 when date is not today', () => {
    expect(dateDifference(yesterday)).toBe(1)
  })
})

describe('formatYearMonthDate', () => {
  it('Should return format date when date is string', () => {
    expect(formatYearMonthDate(toDateString)).toBe('2022-02-07')
  })

  it('Should return format date when date is ISO String', () => {
    expect(formatYearMonthDate(toISOString)).toBe('2018-05-01')
  })

  it('Should return format date when date is today', () => {
    expect(formatYearMonthDate(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(ISO_DATE_FORMAT),
    )
  })

  it('Should return empty string when date is undefined', () => {
    expect(formatYearMonthDate(undefined)).toBe('')
  })
})

describe('weekNumber', () => {
  it('Should return week number when date is string', () => {
    expect(weekNumber(toDateString)).toBe(6)
  })

  it('Should return week number when date is ISO String', () => {
    expect(weekNumber(toISOString)).toBe(18)
  })

  it('Should return week number when date is today', () => {
    expect(weekNumber(today)).toBe(DateTime.fromISO(new Date().toISOString()).weekNumber)
  })
})

describe('nextWeek', () => {
  it('Should return next week date when date is string', () => {
    expect(nextWeek(toDateString)).toBe('2022-02-14')
  })

  it('Should return next week date when date is ISO String', () => {
    expect(nextWeek(toISOString)).toBe('2018-05-07')
  })
})

describe('previousWeek', () => {
  it('Should return previous week date when date is string', () => {
    expect(previousWeek(toDateString)).toBe('2022-01-31')
  })

  it('Should return previous week date when date is ISO String', () => {
    expect(previousWeek(toISOString)).toBe('2018-04-23')
  })
})

describe('firstDateOfWeek', () => {
  it('Should return first date of the week when date is string', () => {
    expect(firstDateOfWeek(toDateString)).toBe('2022-02-07')
  })

  it('Should return first date of the week when date is ISO String', () => {
    expect(firstDateOfWeek(toISOString)).toBe('2018-04-30')
  })
})

describe('lastDateOfWeek', () => {
  it('Should return first date of the week when date is string', () => {
    expect(lastDateOfWeek(toDateString)).toBe('2022-02-13')
  })

  it('Should return first date of the week when date is ISO String', () => {
    expect(lastDateOfWeek(toISOString)).toBe('2018-05-06')
  })
})

describe('formatDateMonth', () => {
  it('Should return format date month when date is string', () => {
    expect(formatDateMonth(toDateString)).toBe('7.2')
  })

  it('Should return format date month when date is ISO String', () => {
    expect(formatDateMonth(toISOString)).toBe('1.5')
  })

  it('Should return format date month when date is today', () => {
    expect(formatDateMonth(today)).toBe(
      DateTime.fromISO(new Date().toISOString()).toFormat(DATE_MONTH_FORMAT),
    )
  })
})

describe('shortDateString', () => {
  it('Should return first two letters Finnish weekdays when date is string', () => {
    expect(shortDateString(new Date(toDateString))).toBe('Ma')
  })

  it('Should return first two letters Finnish weekdays when date is ISO String', () => {
    expect(shortDateString(new Date(toISOString))).toBe('Ti')
  })
})

describe('compareDays', () => {
  it('Should return 0 if the dates are same', () => {
    expect(compareDays(new Date(toDateString), new Date(toDateString))).toBe(0)
  })

  it('Should return 0 if the dates are same', () => {
    expect(compareDays(new Date(toDateString), new Date(toISOString))).toBe(1378)
  })

  it('Should return 0 if the dates are string', () => {
    expect(compareDays(toDateString, toISOString)).toBe(1378)
  })
})

Body:
The difference has to do with the timezone of your local computer and the timezone of the GitLab runner. The GitLab runners use UTC timezone.

Take this case for example:

const toDateString = 'Mon Feb 07 2022 00:00:00 GMT+0200 (Eastern European Standard Time)'
// ...
describe('formatTime', () => {
  it('Should return 00:00 when there is no time', () => {
    expect(formatTime(toDateString)).toBe('00:00')
  })

In your unit test results:

Expected: "00:00"
Received: "22:00"

This would pass if your local timezone is UTC+2, but would fail if your timezone is UTC. Mon Feb 07 2022 00:00:00 GMT+0200 is Sun Feb 06 2022 22:00:00 in UTC time.

From the luxon docs: (emphasis added)

A DateTime comprises of:

[...]

A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).

[...]

You'll probably want to normalize your tests to use a particular timezone. See this question for hints on how to change the timezone of the datetime objects.


问:
Ascending order of fetched data

I am fetching count. My target is to display it in ASCENDING ORDER. i have tried to sort it using sort($match); but i have still failed to achieve my goal. Thank you. Any help will be appreciated

Controller:

```<code>function asdasdas(){
            $entry= $this->repo->entryfetch();

            $data='<table>
    <thead><tr><th>NO. </th></tr></thead>';

            foreach($entry as $entry){

                $match= $this->repo->matchfetch($entry->handlerID);

                $data.='<thead><tr><th><hr>'.$entry->handlerID.' '.$entry->entryName.'</th> ';

                foreach($match as $match){

                    $diff = $match->weightM - $match->weightW;

                    if($match->handlerIDM === $entry->handlerID){
                        $name=$match->handlertestW;
                        $count=$match->countM;
                    }else{

                        $name=$match->handlerM;
                        $count=$match->countW;
                    }

                    $data.='<tbody><tr><td>'.$count.'</td>';

                    $data.='<td></td></tr></tbody>';
    //
                }

            }

            $data .='<table>';

            echo $data;

</code>```

sort($match); // i have tried to sort it using this but it is not working.
}

答:
You can loop the array from the last index to 0</p>
```<code>function asdasdas()
{
    $entry = $this->repo->entryfetch();
    $data = '<table>
    <thead><tr><th>NO. </th></tr></thead>';

    for ($j = count($entry) - 1; $j >= 0; $j--) {
        $match = $this->repo->matchfetch($entry[$j]->handlerID);
        $data .= '<thead><tr><th><hr>' . $entry[$j]->handlerID . ' ' . $entry[$j]->entryName . '</th> ';

        for ($i = count($match) - 1; $i >= 0; $i--) {
            $diff = $match[$i]->weightM - $match[$i]->weightW;
            if ($match[$i]->handlerIDM === $entry[$j]->handlerID) {
                $name = $match[$i]->handlertestW;
                $count = $match[$i]->countM;
            } else {
                $name = $match[$i]->handlerM;
                $count = $match[$i]->countW;
            }
            $data .= '<tbody><tr><td>' . $count . '</td>';
            $data .= '<td></td></tr></tbody>';
        }
    }
    $data .= '<table>';
    echo $data;
}
</code>```

Title: Ascending order of fetched data

Body:
I am fetching count. My target is to display it in ASCENDING ORDER. i have tried to sort it using sort($match); but i have still failed to achieve my goal. Thank you. Any help will be appreciated

Controller:

function asdasdas(){
            $entry= $this->repo->entryfetch();

            $data='

NO.

';

            foreach($entry as $entry){

                $match= $this->repo->matchfetch($entry->handlerID);

                $data.='

'.$entry->handlerID.' '.$entry->entryName.'	 ';

                foreach($match as $match){

                    $diff = $match->weightM - $match->weightW;

                    if($match->handlerIDM === $entry->handlerID){
                        $name=$match->handlertestW;
                        $count=$match->countM;
                    }else{

                        $name=$match->handlerM;
                        $count=$match->countW;
                    }

                    $data.='

'.$count.'	';

                    $data.='

';
    //
                }

            }

            $data .='
';

            echo $data;

sort($match); // i have tried to sort it using this but it is not working.
}

Body:
You can loop the array from the last index to 0

function asdasdas()
{
    $entry = $this->repo->entryfetch();
    $data = '<table>
    <thead><tr><th>NO. </th></tr></thead>';

    for ($j = count($entry) - 1; $j >= 0; $j--) {
        $match = $this->repo->matchfetch($entry[$j]->handlerID);
        $data .= '<thead><tr><th><hr>' . $entry[$j]->handlerID . '&nbsp;' . $entry[$j]->entryName . '</th> ';

        for ($i = count($match) - 1; $i >= 0; $i--) {
            $diff = $match[$i]->weightM - $match[$i]->weightW;
            if ($match[$i]->handlerIDM === $entry[$j]->handlerID) {
                $name = $match[$i]->handlertestW;
                $count = $match[$i]->countM;
            } else {
                $name = $match[$i]->handlerM;
                $count = $match[$i]->countW;
            }
            $data .= '<tbody><tr><td>' . $count . '</td>';
            $data .= '<td></td></tr></tbody>';
        }
    }
    $data .= '<table>';
    echo $data;
}


问:
Execute multiline bash command from Python and get its output
I am under Python 3.8.10 in Ubuntu 20.04 trying to execute a multiline bash command and get its output. For this I am trying to combine this and this. My bash command is this:

/home/foo/.drsosc/drs-5.0.6/drscl << ASD
info
exit
ASD
```
<p>and it works as I want. Now in Python I have this:</p>
<pre class="lang-py prettyprint-override"><code>from pathlib import Path
import subprocess

PATH_TO_drscl = Path.home()/Path('.drsosc/drs-5.0.6/drscl')

def send_command(cmd: str):
    execute_this = f'''{PATH_TO_drscl} << ASD
{cmd}
exit
ASD'''
    return subprocess.run([execute_this], stdout=subprocess.PIPE)

print(send_command('info'))
</code>```

but I get

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.drsosc/drs-5.0.6/drscl << ASD\ninfo\nexit\nASD'
</code>```

It seems that the problem is with the '\n' not being properly interpreted?

答:
I found that this works as I want:

result = subprocess.run(
    str(PATH_TO_drscl),
    input = f'{cmd}\nexit',
    text = True,
    stdout = subprocess.PIPE
)
```

Body:
I am under Python 3.8.10 in Ubuntu 20.04 trying to execute a multiline bash command and get its output. For this I am trying to combine this and this. My bash command is this:

/home/foo/.drsosc/drs-5.0.6/drscl << ASD
info
exit
ASD

and it works as I want. Now in Python I have this:

from pathlib import Path
import subprocess

PATH_TO_drscl = Path.home()/Path('.drsosc/drs-5.0.6/drscl')

def send_command(cmd: str):
    execute_this = f'''{PATH_TO_drscl} << ASD
{cmd}
exit
ASD'''
    return subprocess.run([execute_this], stdout=subprocess.PIPE)

print(send_command('info'))

but I get

FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.drsosc/drs-5.0.6/drscl << ASD\ninfo\nexit\nASD'

It seems that the problem is with the '\n' not being properly interpreted?


问:
How to clear the screen with \x1b[2j?
How do we implement clrscr()? Googling it I found that \x1b[2j can be used to clear the screen but how do we use it?

答:
<pre class="lang-c prettyprint-override"><code>#include <unistd.h>
write(STDOUT_FILENO, "\x1b[2J", 4);
</code>```

Title: How to clear the screen with \x1b[2j?


问:
Unity2D OverlapCollider detects an collider when its not overlapping at all
```<code>ContactFilter2D _contactFilter = new ContactFilter2D();
_contactFilter.SetLayerMask(LayerMask.GetMask("Box"));

List<Collider2D> _overlapColliders = new List<Collider2D>();

int _collidersCount = hitboxCollider.OverlapCollider(_contactFilter, _overlapColliders);
if (_collidersCount)
{
    Debug.Log("I detected an collider when its not true at all!");
}
</code>```

Here a screenshot of my case -> Sample

As the title said, I can't find a solution at all, maybe I'm missing something.
Thx, and sorry for my bad question.

答:
I found out that "Default Contact Offset" is the cause.
Here link related to this: https://stackoverflow.com/a/53101873/13162558</p>

Body:
ContactFilter2D _contactFilter = new ContactFilter2D();
_contactFilter.SetLayerMask(LayerMask.GetMask("Box"));

List<Collider2D> _overlapColliders = new List<Collider2D>();

int _collidersCount = hitboxCollider.OverlapCollider(_contactFilter, _overlapColliders);
if (_collidersCount)
{
    Debug.Log("I detected an collider when its not true at all!");
}

Here a screenshot of my case -> Sample

As the title said, I can't find a solution at all, maybe I'm missing something.
Thx, and sorry for my bad question.


问:
Can't Run adb On M1 zsh: segmentation fault adb
I try to run my React Native project on MacBook Pro M1 but when I run adb it's gives error : zsh: segmentation fault adb.

I tried run adb from both ~/Library/Android/sdk/platform-tools & ~/usr/local/bin/adb.

Tried reinstall platform-tools in android studio.

Tried install and reinstall platform-tools from brew.

Tried reinstall android studio itself.

Device: MacBook Pro M1 2020, SSD: 512, RAM: 8

OS: macOS Monterey

Android Studio: android-studio-2021.1.1.21-mac_arm

答: adb gives error but adb command works

Body: adb gives error but adb command works


问:
Gradle project in Android Studio not importing libraries
So I downloaded a template from http://www.androidbootstrap.com/ and I was  able to compile and deploy it after changing a few things. However, there are errors in every java and layout file. All of the libraries are showing up with red underlines in the imports section and all of their functions are doing the same. It's not able to find the functions when I'm editing, but when building it seems to be fine. What can I do to fix this?</p>

答: I had a similar problem. In my case the solution was that I had to add maven { url 'https://jitpack.io' } in settings.gradle.


问:
Add Percentage Sign in Table in R
How do I add percentage sign to this table?
table(sample.1$Department)/50*100

I want to add the percentage sign to the numbers here. E.g. 28%, 46%, 8%, etc.

答:
You might want to use proportions(table(.)) instead of calculating the percentages manually which is prone to mistakes. Try one of those:

```<code>with(sample.1, as.data.frame.table(proportions(table(Department))*100)) |>
  transform(Freq=paste0(Freq, '%'))
#   Department Freq
# 1   Facility  10%
# 2       Fire  28%
# 3     Police  46%
# 4     Public   8%
# 5    Special   8%

with(sample.1, proportions(table(Department))*100) |>
  {\(.) setNames(paste0(., '%'), unlist(attr(., 'dimnames')))}()
# Facility     Fire   Police   Public  Special
#    "10%"    "28%"    "46%"     "8%"     "8%"
</code>```

Note: R >= 4.1 used.

Data:

```<code>sample.1 <- data.frame(Department=unlist(Map(rep, c('Fire', 'Police','Public',  'Facility', 'Special'),
                                  c(14, 23, 4, 5,  4))))
</code>```

Title: Add Percentage Sign in Table in R

Body:
You might want to use proportions(table(.)) instead of calculating the percentages manually which is prone to mistakes. Try one of those:

with(sample.1, as.data.frame.table(proportions(table(Department))*100)) |>
  transform(Freq=paste0(Freq, '%'))
#   Department Freq
# 1   Facility  10%
# 2       Fire  28%
# 3     Police  46%
# 4     Public   8%
# 5    Special   8%

with(sample.1, proportions(table(Department))*100) |>
  {\(.) setNames(paste0(., '%'), unlist(attr(., 'dimnames')))}()
# Facility     Fire   Police   Public  Special
#    "10%"    "28%"    "46%"     "8%"     "8%"

Note: R >= 4.1 used.

Data:

sample.1 <- data.frame(Department=unlist(Map(rep, c('Fire', 'Police','Public',  'Facility', 'Special'),
                                  c(14, 23, 4, 5,  4))))


问:
IE9 Document Mode Toggle fixes SharePoint CSS issues?
I'm working on my first SharePoint project doing some UX support.  My client's page uses some custom css including a horizontal main-menu with dropdown sub-menus.  When the page is loaded in IE9, none of the sub-menus work correctly.  The dropdowns appear when you hover over the top-level item but when you drop your cursor down to the sub-menu, the hover doesn't register and the menu disappears.

These links work fine in latest versions of Chrome and Firefox, so I'm pretty sure this is an IE quirk.  In IE9, if I open the developer tools and toggle the document mode from IE9 to IE7 and then back to IE9, the menus work correctly for the remainder of the browser tab's lifetime (e.g. when I use the sub-menus to navigate to other pages, the dropdowns continue to function properly).  Unfortunately, since this is SharePoint, I don't have a lot of control over the structure of the html here.

Anyone know what might be going on?  Does anyone know the impact of toggling the browser modes to IE7 and back and why that might fix the problem?  Thanks!

答:
Try this:

```<code><meta http-equiv="X-UA-Compatible" content="IE=7">
</code>```

It will force IE8, IE9 etc to render as if they were IE7.

Body:
Try this:

<meta http-equiv="X-UA-Compatible" content="IE=7">

It will force IE8, IE9 etc to render as if they were IE7.


问:
Error in R: mutate( ) must be size 4 or 1, not 0
My data:

```<code>data_control <-  structure(list(group = c("control", "control", "control", "control" ), cycle = c(0, 1, 2, 3), non_obese_prob = c(1, -0.0133333333333334, 0.00017777777777778, -0.00000237037037037042), obese_prob = c(0, 1.01333333333333, 0.999822222222222, 1.00000237037037)), row.names = c(NA, -4L), class = "data.frame")

data_qaly <- structure(list(cycle = c(0, 1, 2, 3, 0, 1, 2, 3), qaly = c(0.879173868649325, 0.876535027508255, 0.876535027508255, 0.876535027508255, 0.729214080532041, 0.73572153807131, 0.73572153807131, 0.73572153807131), state = c("non_obese", "non_obese", "non_obese", "non_obese", "obese", "obese", "obese", "obese")), row.names = c(NA, -8L), class = "data.frame")

</code>```
```<code>data_control <- data_control %>%
                mutate(qaly_non_obese = data_qaly$qaly[data_qaly$state == "non-obese"]) %>%
                mutate(qaly_obese = data_qaly$qaly[data_qaly$state == "obese"])
</code>```

Error: Problem with mutate() column qaly_non_obese.
ℹ qaly_non_obese = data_qaly$qaly[data_qaly$state == "non-obese"].
ℹ qaly_non_obese must be size 4 or 1, not 0.

Body:
My data:

data_control <-  structure(list(group = c("control", "control", "control", "control" ), cycle = c(0, 1, 2, 3), non_obese_prob = c(1, -0.0133333333333334, 0.00017777777777778, -0.00000237037037037042), obese_prob = c(0, 1.01333333333333, 0.999822222222222, 1.00000237037037)), row.names = c(NA, -4L), class = "data.frame")

data_qaly <- structure(list(cycle = c(0, 1, 2, 3, 0, 1, 2, 3), qaly = c(0.879173868649325, 0.876535027508255, 0.876535027508255, 0.876535027508255, 0.729214080532041, 0.73572153807131, 0.73572153807131, 0.73572153807131), state = c("non_obese", "non_obese", "non_obese", "non_obese", "obese", "obese", "obese", "obese")), row.names = c(NA, -8L), class = "data.frame")

data_control <- data_control %>%
                mutate(qaly_non_obese = data_qaly$qaly[data_qaly$state == "non-obese"]) %>%
                mutate(qaly_obese = data_qaly$qaly[data_qaly$state == "obese"])

Error: Problem with mutate() column qaly_non_obese.
ℹ qaly_non_obese = data_qaly$qaly[data_qaly$state == "non-obese"].
ℹ qaly_non_obese must be size 4 or 1, not 0.

Body:
Maybe you need a left_join

library(dplyr)

left_join(data_control, data_qaly, by="cycle")

    group cycle non_obese_prob obese_prob      qaly     state
1 control     0   1.000000e+00  0.0000000 0.8791739 non_obese
2 control     0   1.000000e+00  0.0000000 0.7292141     obese
3 control     1  -1.333333e-02  1.0133333 0.8765350 non_obese
4 control     1  -1.333333e-02  1.0133333 0.7357215     obese
5 control     2   1.777778e-04  0.9998222 0.8765350 non_obese
6 control     2   1.777778e-04  0.9998222 0.7357215     obese
7 control     3  -2.370370e-06  1.0000024 0.8765350 non_obese
8 control     3  -2.370370e-06  1.0000024 0.7357215     obese


问:
Count duplicate values in array php
Firstly thanks in advance :)

I write a code like this way:

```<code>$data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,5];

$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}else{
  echo 'No Duplicate';
}
</code>```

This code works perfectly but when I get data from the server-side like :

```<code>$getValue = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,5';
$data = [$getValue];

$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}else{
  echo 'No Duplicate';
}
</code>```

code not working, anyone please help me here to sort out.

答:
Try this,</p>
```<code>$getValue = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,5';
$data = [$getValue];
$data = explode(',', $data[0]);
$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}else{
  echo 'No Duplicate';
}
</code>```

Title: Count duplicate values in array php

Body:
Firstly thanks in advance :)

I write a code like this way:

$data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,5];

$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}else{
  echo 'No Duplicate';
}

This code works perfectly but when I get data from the server-side like :

$getValue = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,5';
$data = [$getValue];

$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}else{
  echo 'No Duplicate';
}

code not working, anyone please help me here to sort out.

Body:
Try this,

$getValue = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,5';
$data = [$getValue];
$data = explode(',', $data[0]);
$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}else{
  echo 'No Duplicate';
}


问:
Python socket - Couldn't read HTTP POST request body
I'm trying to real a whole HTTP 1.1 POST request through a socket based HTTP proxy, and couldn't read the body of the request right after reading the headers.

The main code of handling the POST request handling is:

```<code>import socket
...
# request_buffer is initialized with the request's first line (with the method, uri and status).
request_buffer = http_status_line
socket_file = client_socket.makefile()
raw_headers = recv_headers(socket_file)
socket_file.close()
request_buffer += raw_headers
headers = dict_headers(raw_headers)
body_len = int(headers['Content-Length'][0])
print(repr(request_buffer))
raw_request = recv_body(client_socket, body_len)
request_buffer += raw_request
print(repr(raw_request))
server_socket.send(request_buffer)
</code>```

While the auxiliary functions' source code is:

```<code>def recv_headers(socket_file):
    raw_headers = ''
    while True:
        header = socket_file.readline()
        raw_headers += header
        if len(header) == 2:     # if header == '\r\n'
            break
    return raw_headers

def recv_body(conn_socket, body_len):
    request_body = ''
    bytes_read = 0
    body_chunk = conn_socket.recv(body_len - bytes_read)
    while len(body_chunk) > 0:
        request_body += body_chunk
        bytes_read += len(body_chunk)
        body_chunk = conn_socket.recv(body_len - bytes_read)
    return request_body
</code>```

Note: I've omitted the source code of dict_headers() because it's working well, and I wanted to minimize the amount of code for your convenience.
In addition, I already made sure that body_len has the right value (the value in the Content-Length header).

Printed result:

As you can see raw_request (the request body) is not being printed at all.

The original POST request which being forwarded through the proxy:

The original request indeed has a body which is: log=test&pwd=test.

Any help will be more than appreciated

答:
```<code>socket_file = client_socket.makefile()
raw_headers = recv_headers(socket_file)
...
raw_request = recv_body(client_socket, body_len)
</code>```

With makefile you are using buffered I/O inside recv_headers. The later recv inside recv_body instead works with the original socket object and thus unbuffered I/O. Mixing buffered and unbuffered I/O is a receipt for trouble.

The problem is that the initial buffered I/O might internally retrieve more data from the underlying socket than actually needed for reading the headers. These extra data are kept in the internal buffer of socket_file and are available for socket_file.read. They are not available for client_socket.recv anymore though since they are already retrieved from the underlying socket.

Thus, never mix buffered and unbuffered I/O. Once you've switched to buffered I/O stay with it.

Body:
I'm trying to real a whole HTTP 1.1 POST request through a socket based HTTP proxy, and couldn't read the body of the request right after reading the headers.

The main code of handling the POST request handling is:

import socket
...
# request_buffer is initialized with the request's first line (with the method, uri and status).
request_buffer = http_status_line
socket_file = client_socket.makefile()
raw_headers = recv_headers(socket_file)
socket_file.close()
request_buffer += raw_headers
headers = dict_headers(raw_headers)
body_len = int(headers['Content-Length'][0])
print(repr(request_buffer))
raw_request = recv_body(client_socket, body_len)
request_buffer += raw_request
print(repr(raw_request))
server_socket.send(request_buffer)

While the auxiliary functions' source code is:

def recv_headers(socket_file):
    raw_headers = ''
    while True:
        header = socket_file.readline()
        raw_headers += header
        if len(header) == 2:     # if header == '\r\n'
            break
    return raw_headers

def recv_body(conn_socket, body_len):
    request_body = ''
    bytes_read = 0
    body_chunk = conn_socket.recv(body_len - bytes_read)
    while len(body_chunk) > 0:
        request_body += body_chunk
        bytes_read += len(body_chunk)
        body_chunk = conn_socket.recv(body_len - bytes_read)
    return request_body

Note: I've omitted the source code of dict_headers() because it's working well, and I wanted to minimize the amount of code for your convenience.
In addition, I already made sure that body_len has the right value (the value in the Content-Length header).

Printed result:

As you can see raw_request (the request body) is not being printed at all.

The original POST request which being forwarded through the proxy:

The original request indeed has a body which is: log=test&pwd=test.

Any help will be more than appreciated

Body:
socket_file = client_socket.makefile()
raw_headers = recv_headers(socket_file)
...
raw_request = recv_body(client_socket, body_len)

With makefile you are using buffered I/O inside recv_headers. The later recv inside recv_body instead works with the original socket object and thus unbuffered I/O. Mixing buffered and unbuffered I/O is a receipt for trouble.

The problem is that the initial buffered I/O might internally retrieve more data from the underlying socket than actually needed for reading the headers. These extra data are kept in the internal buffer of socket_file and are available for socket_file.read. They are not available for client_socket.recv anymore though since they are already retrieved from the underlying socket.

Thus, never mix buffered and unbuffered I/O. Once you've switched to buffered I/O stay with it.


问:
Does transform/opacity property invoke paint step in the browser conveyor
Investigating how browser's render works I've noticed that in chrome dev tools with enabled flag paint flashing triggers paint step on changing transform/opacity property.

Look at these screenshots with code:

Example 1 (transform/opacity property)

let elem = document.querySelector(".newLayer");
let count = 0;
function anim(){
  elem.style.transform = `translate(${count}px,0)`;
  /// interchangeable
  /// elem.style.opacity = `${count/500}`;
  if(count++ < 500)
    requestAnimationFrame(anim);
  }
anim();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.newLayer{
  position:relative;
  width:150px;
  height:150px;
  background-color: red;
}</code>```

I am a new Layer
```
</div>
</div>

<img src="https://i.stack.imgur.com/JfNPD.jpg" alt="enter image description here" /></p>
<p><strong>Example 2 (<code>transform/opacity</code> property with <code>will-change</code>)</strong>
<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>let elem = document.querySelector(".newLayer");
let count = 0;
function anim(){
  elem.style.transform = `translate(${count}px,0)`;
  /// interchangeable
  /// elem.style.opacity = `${count/500}`;
  if(count++ < 500)
    requestAnimationFrame(anim);
  }
anim();</code>```

.newLayer{
  will-change: transform;
  position:relative;
  width:150px;
  height:150px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newLayer">I am a new Layer</div></code>```

It confuses me, because I've seen this one and this one sources, they say when you're using transform/opacity, paint stage is ommited. So what is it? Why do we see paint in the first example, and don't in second? Which one is lying?

Interesting one example with 2 paint operations:

let elem = document.querySelector(".newLayer");
let count = 0;
function anim(){
  elem.style.left = `${count}px`;
  if(count++ < 500)
    requestAnimationFrame(anim);
  }
anim();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.newLayer{
  position:relative;
  width:150px;
  height:150px;
  background-color: red;
}</code>```

I am a new Layer
```

Yes, there is used property of positioning, but look at the paint operations, one big stripe and one small such as in example without will-change. What does it mean (I am speaking about paint with tiny stripe length)?

Is the tiny paint block related with raster threads, what about big one?

答:
Neither example is lying.

The browser minimises the number of layers it needs to composite together. It only creates a layer if it's given a reason to believe there'll be a benefit.

If you animate transform or opacity using CSS transitions, CSS animations, or web animations, the browser knows ahead of time that the element is animating in a way that might be optimised by creating a layer, so Chrome creates one for the duration of the animation.

If you animate using rAF, the browser doesn't have this foresight. will-change exists as a way to hint to the browser that it should create a layer for this element, depending on the changing property.

These are hints, and the browser isn't guaranteed to create a layer. There are other cases where some browsers create a layer, such as when another element needs to paint on top of a layer, and in the case of some other CSS like transform: translateZ(…).

Body:
Investigating how browser's render works I've noticed that in chrome dev tools with enabled flag paint flashing triggers paint step on changing transform/opacity property.

Look at these screenshots with code:

Example 1 (transform/opacity property)

let elem = document.querySelector(".newLayer");
let count = 0;
function anim(){
  elem.style.transform = `translate(${count}px,0)`;
  /// interchangeable
  /// elem.style.opacity = `${count/500}`;
  if(count++ < 500)
    requestAnimationFrame(anim);
  }
anim();

.newLayer{
  position:relative;
  width:150px;
  height:150px;
  background-color: red;
}

I am a new Layer

Example 2 (transform/opacity property with will-change)

let elem = document.querySelector(".newLayer");
let count = 0;
function anim(){
  elem.style.transform = `translate(${count}px,0)`;
  /// interchangeable
  /// elem.style.opacity = `${count/500}`;
  if(count++ < 500)
    requestAnimationFrame(anim);
  }
anim();

.newLayer{
  will-change: transform;
  position:relative;
  width:150px;
  height:150px;
  background-color: red;
}

I am a new Layer

It confuses me, because I've seen this one and this one sources, they say when you're using transform/opacity, paint stage is ommited. So what is it? Why do we see paint in the first example, and don't in second? Which one is lying?

Interesting one example with 2 paint operations:

let elem = document.querySelector(".newLayer");
let count = 0;
function anim(){
  elem.style.left = `${count}px`;
  if(count++ < 500)
    requestAnimationFrame(anim);
  }
anim();

.newLayer{
  position:relative;
  width:150px;
  height:150px;
  background-color: red;
}

I am a new Layer

Yes, there is used property of positioning, but look at the paint operations, one big stripe and one small such as in example without will-change. What does it mean (I am speaking about paint with tiny stripe length)?

Is the tiny paint block related with raster threads, what about big one?


问:
How to use `Environ("USERPROFILE")` to open workbook on desktop , while desktop location changed to another drive (D)?
On my work PC, I have no write on system drive (c).

So, I have used properties of desktop folder and changed location of it to another drive (d).

From windows 10,  I am using my desktop from that drive (d) similarly as it was on drive (c).

Problem: I tried this vba code to open workbook on my desktop

```<code>Dim wb1 As Workbook: Set wb1 = Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Query1.xls")
</code>```

,but I got this error

Run-time error 1004:Sorry, we couldn't find C:\Users\Waleed\Desktop\Query1.xls. Is it possible it was moved, renamed or deleted?

I am asking this question, as I use excel files on my work pc and my laptop (no restriction) interchangeably

And it is hard to change my vba codes every time I change my machine.

As always , thanks for any help.

答:
Desktop on Different Drives

Get it in a sub

Sub DirDesktop()
    Dim DeskTopPath As String: DeskTopPath = Environ("USERPROFILE") & "\Desktop\"
    If Len(Dir(DeskTopPath, vbDirectory)) = 0 Then
        DeskTopPath = Replace(DeskTopPath, "C", "D", , 1)
    End If
    Debug.Print DeskTopPath & "Query1.xls"
End Sub
```
<p><strong>Get it using a function</strong></p>
<pre class="lang-vb prettyprint-override"><code>Sub GetDeskTopTEST()
    Dim DeskTopPath As String: DeskTopPath = GetDeskTop
    Debug.Print DeskTopPath & "Query1.xls"
End Sub

Function GetDeskTop() As String
    GesktopPath = Environ("USERPROFILE") & "\Desktop\"
    If Len(Dir(GetDeskTop, vbDirectory)) = 0 Then
        GetDeskTop = Replace(GetDeskTop, "C", "D", , 1)
    End If
End Function
</code>```

Here's another idea

You can set your own Environ variables.
Go to Windows Settings > About > scroll down to Advanced Settings and at the bottom click on Environment Variables. Click the upper New box and in the Variable Name box use e.g. DeskTop and in the Variable value box use the path. If you do this on both computers, you can on both of them access the folder with Environ("DeskTop"). You have to restart Excel for this to take effect.

Body:
On my work PC, I have no write on system drive (c).

So, I have used properties of desktop folder and changed location of it to another drive (d).

From windows 10,  I am using my desktop from that drive (d) similarly as it was on drive (c).

Problem: I tried this vba code to open workbook on my desktop

Dim wb1 As Workbook: Set wb1 = Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Query1.xls")

,but I got this error

Run-time error 1004:Sorry, we couldn't find C:\Users\Waleed\Desktop\Query1.xls. Is it possible it was moved, renamed or deleted?

I am asking this question, as I use excel files on my work pc and my laptop (no restriction) interchangeably

And it is hard to change my vba codes every time I change my machine.

As always , thanks for any help.

Body:
Desktop on Different Drives

Get it in a sub

Sub DirDesktop()
    Dim DeskTopPath As String: DeskTopPath = Environ("USERPROFILE") & "\Desktop\"
    If Len(Dir(DeskTopPath, vbDirectory)) = 0 Then
        DeskTopPath = Replace(DeskTopPath, "C", "D", , 1)
    End If
    Debug.Print DeskTopPath & "Query1.xls"
End Sub

Get it using a function

Sub GetDeskTopTEST()
    Dim DeskTopPath As String: DeskTopPath = GetDeskTop
    Debug.Print DeskTopPath & "Query1.xls"
End Sub

Function GetDeskTop() As String
    GesktopPath = Environ("USERPROFILE") & "\Desktop\"
    If Len(Dir(GetDeskTop, vbDirectory)) = 0 Then
        GetDeskTop = Replace(GetDeskTop, "C", "D", , 1)
    End If
End Function

Here's another idea

You can set your own Environ variables.
Go to Windows Settings > About > scroll down to Advanced Settings and at the bottom click on Environment Variables. Click the upper New box and in the Variable Name box use e.g. DeskTop and in the Variable value box use the path. If you do this on both computers, you can on both of them access the folder with Environ("DeskTop"). You have to restart Excel for this to take effect.


问:
jQuery each function, skip a specific element
I'm trying to use the jQuery each function: http://api.jquery.com/each/

I have a list of things, and I want to perform different javascript for different list elements.

Here's  the  html code:

```<code><ul id="list-with-stuff">
    <li class='non-stuff'>foo</li>
    <li>bar</li>
</ul>
</code>```

And here's the javascript:

```<code>jQuery.fn.stuffplaylist = function() {

    return this.each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};

$(document).ready(function() {
    $("#list-with-stuff").stuffplaylist();
});
</code>```

Check it out on jsfiddle here: http://jsfiddle.net/73gB9/

The problem I am having is not being able to work out how to determine what list element is selected, and thus run different javascript. For example I want to run the "TRUE" alert for the first element in the list, however it only runs the "FALSE" alert in it's current state.

I know it must be possible, however I'm inexperienced with Javascript & jQuery and haven't been able to work out from searching the internet.

With the above code if you make ul have the class 'non-stuff' then it does output the "TRUE" alert message, otherwise the "FALSE" alert pops up.

So if you know the best practice way of doing it then I am keen to hear your answer. Particularly if it helps me along with learning Javascript :-)

Thank you.

答:
Looks like you're mixing up your
 and
s. You're close.

If you want the plugin to operate on
, make this modification:

```<code>jQuery.fn.stuffplaylist = function() {

    return this.children('li').each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};
</code>```

And you can refine this further by cutting the elements you don't need out of the selection.

```<code>   jQuery.fn.stuffplaylist = function() {
        return this.children('li.non-stuff').each(function() {
                //$(this).text() -> 'foo'
                alert("TRUE. Has non-stuff class");
                return true;
        });
    };
</code>```

Body:
I'm trying to use the jQuery each function: http://api.jquery.com/each/

I have a list of things, and I want to perform different javascript for different list elements.

Here's  the  html code:

foo

bar

And here's the javascript:

jQuery.fn.stuffplaylist = function() {

    return this.each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};

$(document).ready(function() {
    $("#list-with-stuff").stuffplaylist();
});

Check it out on jsfiddle here: http://jsfiddle.net/73gB9/

The problem I am having is not being able to work out how to determine what list element is selected, and thus run different javascript. For example I want to run the "TRUE" alert for the first element in the list, however it only runs the "FALSE" alert in it's current state.

I know it must be possible, however I'm inexperienced with Javascript & jQuery and haven't been able to work out from searching the internet.

With the above code if you make ul have the class 'non-stuff' then it does output the "TRUE" alert message, otherwise the "FALSE" alert pops up.

So if you know the best practice way of doing it then I am keen to hear your answer. Particularly if it helps me along with learning Javascript :-)

Thank you.

Body:
Looks like you're mixing up your <ul> and <li>s. You're close.

If you want the plugin to operate on <ul>, make this modification:

jQuery.fn.stuffplaylist = function() {

    return this.children('li').each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};

And you can refine this further by cutting the elements you don't need out of the selection.

   jQuery.fn.stuffplaylist = function() {
        return this.children('li.non-stuff').each(function() {
                //$(this).text() -> 'foo'
                alert("TRUE. Has non-stuff class");
                return true;
        });
    };