问:
How to right align a CMFCLinkCtrl?
I have just added a CMFCLinkCtrl to my dialog:

CONTROL         "od 9:42-44",IDC_MFCLINK_OD_REFERENCE,"MfcLink",WS_TABSTOP,289,143,42,11

Looks like :

At the moment it is not mapped to any variable because I have set the URL and Text within the IDE. But I would like this tooltip to be right aligned. It doesn't change size but to be sure I do not want it to flow to the right any further. Is this possible?

I have reviewed the available properties in the IDE and there are no text alignment controls:

答:
In the end I had to use the CHyperlink control. It is derived from CMFCLinkCtrl.

In the comments to my question the suggestion was made to make use of the m_nAlignStyle property. This seemed logical because the link control is derived from CMFCButton. But that does not work.

The CHyperlink control does use the aforementioned property but has a bespoke OnDraw handler:

```<code>// ----------------------------------------------------------------------------------------------------
// Set the alignment for the hyperlink.
// ----------------------------------------------------------------------------------------------------
BOOL CHyperlink::SetTextAlignment(HyperlinkAlignment enumValue)
    {
    if (enumValue == Left)
        {
        m_nAlignStyle = ALIGN_LEFT;
        //SizeToContent(TRUE, FALSE);
        Invalidate();
        }
    else if (enumValue == Right)
        {
        m_nAlignStyle = ALIGN_RIGHT;
        //SizeToContent(TRUE, FALSE);
        Invalidate();
        }
    else if (enumValue == Center)
        {
        m_nAlignStyle = ALIGN_CENTER;
        //SizeToContent(TRUE, TRUE);
        Invalidate();
        }
    else
        {
        return FALSE;
        }

    return TRUE;
    }
</code>```

Notice that I commented out the SizeToContent calls since it did not make sense to do that. If you size the control to the content then what is the point of supporting alignment (apart from vertically)?

In my case, by:

Using CHyperlink.

Adjusting the SetTextAlignment method.

It would work. Example:

```<code>void CChristianLifeMinistryUtils::InitODLink(CHyperlink& rLinkCtrl)
{
    const LanguageMSA eForeignLang = theApp.GetForeignLanguageGroupLanguageID();
    const CString strODLink = GENERALLABEL3(eForeignLang, IDS_STR_OD_WOL_LINK);
    const CString strODTooltip = GENERALLABEL3(eForeignLang, IDS_STR_OD_WOL_TITLE);

    if (eForeignLang == LanguageMSA::Arabic)
    {
        rLinkCtrl.SetWindowText(_T("ش م 9:42-44"));
    }

    rLinkCtrl.SetURL(strODLink);
    rLinkCtrl.SetTooltip(strODTooltip);
    rLinkCtrl.SetTextAlignment(CHyperlink::Right);
}
</code>```

Title: How to right align a CMFCLinkCtrl?

Body:
In the end I had to use the CHyperlink control. It is derived from CMFCLinkCtrl.

In the comments to my question the suggestion was made to make use of the m_nAlignStyle property. This seemed logical because the link control is derived from CMFCButton. But that does not work.

The CHyperlink control does use the aforementioned property but has a bespoke OnDraw handler:

// ----------------------------------------------------------------------------------------------------
// Set the alignment for the hyperlink.
// ----------------------------------------------------------------------------------------------------
BOOL CHyperlink::SetTextAlignment(HyperlinkAlignment enumValue)
    {
    if (enumValue == Left)
        {
        m_nAlignStyle = ALIGN_LEFT;
        //SizeToContent(TRUE, FALSE);
        Invalidate();
        }
    else if (enumValue == Right)
        {
        m_nAlignStyle = ALIGN_RIGHT;
        //SizeToContent(TRUE, FALSE);
        Invalidate();
        }
    else if (enumValue == Center)
        {
        m_nAlignStyle = ALIGN_CENTER;
        //SizeToContent(TRUE, TRUE);
        Invalidate();
        }
    else
        {
        return FALSE;
        }

    return TRUE;
    }

Notice that I commented out the SizeToContent calls since it did not make sense to do that. If you size the control to the content then what is the point of supporting alignment (apart from vertically)?

In my case, by:

Using CHyperlink.

Adjusting the SetTextAlignment method.

It would work. Example:

void CChristianLifeMinistryUtils::InitODLink(CHyperlink& rLinkCtrl)
{
    const LanguageMSA eForeignLang = theApp.GetForeignLanguageGroupLanguageID();
    const CString strODLink = GENERALLABEL3(eForeignLang, IDS_STR_OD_WOL_LINK);
    const CString strODTooltip = GENERALLABEL3(eForeignLang, IDS_STR_OD_WOL_TITLE);

    if (eForeignLang == LanguageMSA::Arabic)
    {
        rLinkCtrl.SetWindowText(_T("ش م 9:42-44"));
    }

    rLinkCtrl.SetURL(strODLink);
    rLinkCtrl.SetTooltip(strODTooltip);
    rLinkCtrl.SetTextAlignment(CHyperlink::Right);
}


来源: stackexchange

问:
SharedPreferences behaviour on Update/Uninstall
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

```<code>public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
</code>```

答:
There is no hook that you can use to erase the shared preferences in the case of an update.

Nikolay is right you can save the version number of your app. And compare it with the current version number.

To obtain the current version number call:

```<code>this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode
</code>```

For more info on what information is available in the package info read the Documentation on the PackageInfo and the PackageManager.

ContentLicense: CC BY-SA 3.0

Body:
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}

Body:
There is no hook that you can use to erase the shared preferences in the case of an update.

Nikolay is right you can save the version number of your app. And compare it with the current version number.

To obtain the current version number call:

this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode

For more info on what information is available in the package info read the Documentation on the PackageInfo and the PackageManager.


问:
Editing .mat file in Python
I am trying to import a .mat (not human readable) file in python
I imported it using a package called AT.

```<code>import at
from at.plot import plot_beta
import time
import matplotlib.pyplot as plt

r = at.load_mat('FCCee_z_512_nosol_10.mat', key='RING')
</code>```

Now, I want to access the data inside this .mat file and also to add some values to it using python and to save the updated file in .py format.

The result of printing the r is :

```<code>Lattice(<11470 elements>, name='l000015', energy=45600000000.0, particle=Particle('electron'), `periodicity=1, harmonic_number=121657, mat_key='RING', mat_file='N:\\musa\\1\\1\\General-`quistions\\MAD-X_Python\\fccV8_AT\\FCCee_z_512_nosol_10.mat', key='ring')`
</code>```

Ho can i edit the valus of this file and save in in python format ?

答:
You can use scipy loadmat method to read .mat files.

https://docs.scipy.org/doc/scipy-1.8.0/html-scipyorg/reference/generated/scipy.io.loadmat.html?highlight=loadmat#scipy.io.loadmat

import scipy.io
r = scipy.io.loadmat('FCCee_z_512_nosol_10.mat')
r['data'] # you want to access
```

ContentLicense: CC BY-SA 4.0

Title: Editing .mat file in Python

Body:
I am trying to import a .mat (not human readable) file in python
I imported it using a package called AT.

import at
from at.plot import plot_beta
import time
import matplotlib.pyplot as plt

r = at.load_mat('FCCee_z_512_nosol_10.mat', key='RING')

Now, I want to access the data inside this .mat file and also to add some values to it using python and to save the updated file in .py format.

The result of printing the r is :

Lattice(<11470 elements>, name='l000015', energy=45600000000.0, particle=Particle('electron'), `periodicity=1, harmonic_number=121657, mat_key='RING', mat_file='N:\\musa\\1\\1\\General-`quistions\\MAD-X_Python\\fccV8_AT\\FCCee_z_512_nosol_10.mat', key='ring')`

Ho can i edit the valus of this file and save in in python format ?


问:
Sequelize setting association owner id "number | { [CreationAttributeBranch: true; }" is not assignable to number
When copying the TypeScript manual, using Project.create() when manually setting the ownerId, it errors out.
In clarification, the following code:

```<code>const ab = Project.create({ name: 'abc', ownerId: newUser.get('id') })
</code>```

Errors outType 'number | { [CreationAttributeBrand]: true; }' is not assignable to type 'number'. Type '{ [CreationAttributeBrand]: true; }' is not assignable to type 'number'.
Using the built in user.createProject works, but manually attempting create a standalone doesn't work correctly. I understand why it's happening, but I need a workaround because the actual model I have has multiple associations to create.

You can get the same code by copying https://sequelize.org/master/manual/typescript.html example and adding the above code.

答: This was a bug in Sequelize v6.13. It was fixed later on. Updating versions fixed it. (The return value was number | { [CreationAttributeBrand]...} When it was supposed to be number & )

Body:
When copying the TypeScript manual, using Project.create() when manually setting the ownerId, it errors out.
In clarification, the following code:

const ab = Project.create({ name: 'abc', ownerId: newUser.get('id') })

Errors outType 'number | { [CreationAttributeBrand]: true; }' is not assignable to type 'number'. Type '{ [CreationAttributeBrand]: true; }' is not assignable to type 'number'.
Using the built in user.createProject works, but manually attempting create a standalone doesn't work correctly. I understand why it's happening, but I need a workaround because the actual model I have has multiple associations to create.

You can get the same code by copying https://sequelize.org/master/manual/typescript.html example and adding the above code.


问:
Why AOP is not working in my Spring Boot project? It never execute the @Around annoted method
I was trying to follow this video tutorial to add AOP to my Spring Boot project in order to perform log operation: https://www.youtube.com/watch?v=RVvKPP5HyaA

But it is not working, it is not logging anything.

So this is my pom.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.easydefi</groupId>
    <artifactId>GET-USER-WS</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GET-USER-WS</name>
    <description>Microservice that retrieves users from DB</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <!-- Validation -->
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <!-- Security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- JWT -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>nl.martijndwars</groupId>
            <artifactId>web-push</artifactId>
            <version>5.1.1</version>
        </dependency>

        <dependency>
          <groupId>org.bouncycastle</groupId>
          <artifactId>bcprov-jdk15on</artifactId>
          <version>1.68</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

As you can see I added this dependency to it:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.6.3</version>
</dependency>
</code>```

Then I created this LoggingAOP class in order to configure AOP behavior:

```<code>package com.easydefi.aop.logging;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.java.Log;

@Aspect
@Component
@Log
public class LoggingAOP {

    @Pointcut(value = "execution(* com.easydefi.users.*.*.*(..))")
    public void myPointcut() {

    }

    @Around("myPointcut()")
    public Object applicationLogger(ProceedingJoinPoint pjp) throws Throwable {

        ObjectMapper mapper = new ObjectMapper();

        String methodName = pjp.getSignature().getName();
        String className = pjp.getTarget().getClass().toString();

        Object[] argsArray = pjp.getArgs();

        log.info("Method invoked " + className + ":" + methodName + "() arguments: " + mapper.writeValueAsString(argsArray));

        Object response = pjp.proceed();

        log.info(className + ":" + methodName + "() Response: " + mapper.writeValueAsString(response));

        return response;

    }

}
</code>```

In theory the used @Pointcut expression:

```<code>@Pointcut(value = "execution(* com.easydefi.users.*.*.*(..))")
</code>```

should define the execution o all method into all class of all package defined into the project root that is com.easydefi.users but it is logging nothing.

Running my application and calling a controller method or a service method I expected that he would enter into the applicationLogger() method. But it is not working (I also tried in debug mode and it never enter into this method).

This is my project structure:

So what is wrong? What am I missing? How can I try to fix it?

答:
Your pointcut

execution(* com.easydefi.users.*.*.*(..))
```
<p>looks a bit unflexible, but it works perfectly for intercepting methods like</p>
<pre class="lang-none prettyprint-override"><code>public void com.easydefi.users.service.CoinService.doSomething()
public boolean com.easydefi.users.specification.MySpec.fooBar(int, String)
</code>```

It works not for

public String com.easydefi.users.specification.criteria.MyCriteria.zot()
public void com.easydefi.users.aa.bb.cc.SomeService.zot()
```
<p>for reasons <em><strong>M. Deinum</strong></em> has mentioned already. His suggestion to use the <code>..*</code> notation, which means "any method in any class in the package preceded by <code>..*</code>", is exactly right:</p>
<pre class="lang-none prettyprint-override"><code>execution(* com.easydefi.users..*(..))
</code>```

I also want to stress that the credit for this answer should be his, and if he likes to simply copy my answer and post it under his own name instead of just a comment, I shall remove this one gladly instead. But I do think questions deserve comprehensive answers.

Body:
I was trying to follow this video tutorial to add AOP to my Spring Boot project in order to perform log operation: https://www.youtube.com/watch?v=RVvKPP5HyaA

But it is not working, it is not logging anything.

So this is my pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/>
    </parent>
    <groupId>com.easydefi</groupId>
    <artifactId>GET-USER-WS</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GET-USER-WS</name>
    <description>Microservice that retrieves users from DB</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>nl.martijndwars</groupId>
            <artifactId>web-push</artifactId>
            <version>5.1.1</version>
        </dependency>

        <dependency>
          <groupId>org.bouncycastle</groupId>
          <artifactId>bcprov-jdk15on</artifactId>
          <version>1.68</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>2.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

As you can see I added this dependency to it:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.6.3</version>
</dependency>

Then I created this LoggingAOP class in order to configure AOP behavior:

package com.easydefi.aop.logging;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.java.Log;

@Aspect
@Component
@Log
public class LoggingAOP {

    @Pointcut(value = "execution(* com.easydefi.users.*.*.*(..))")
    public void myPointcut() {

    }

    @Around("myPointcut()")
    public Object applicationLogger(ProceedingJoinPoint pjp) throws Throwable {

        ObjectMapper mapper = new ObjectMapper();

        String methodName = pjp.getSignature().getName();
        String className = pjp.getTarget().getClass().toString();

        Object[] argsArray = pjp.getArgs();

        log.info("Method invoked " + className + ":" + methodName + "() arguments: " + mapper.writeValueAsString(argsArray));

        Object response = pjp.proceed();

        log.info(className + ":" + methodName + "() Response: " + mapper.writeValueAsString(response));

        return response;

    }

}

In theory the used @Pointcut expression:

@Pointcut(value = "execution(* com.easydefi.users.*.*.*(..))")

should define the execution o all method into all class of all package defined into the project root that is com.easydefi.users but it is logging nothing.

Running my application and calling a controller method or a service method I expected that he would enter into the applicationLogger() method. But it is not working (I also tried in debug mode and it never enter into this method).

This is my project structure:

So what is wrong? What am I missing? How can I try to fix it?

Body:
Your pointcut

execution(* com.easydefi.users.*.*.*(..))

looks a bit unflexible, but it works perfectly for intercepting methods like

public void com.easydefi.users.service.CoinService.doSomething()
public boolean com.easydefi.users.specification.MySpec.fooBar(int, String)

It works not for

public String com.easydefi.users.specification.criteria.MyCriteria.zot()
public void com.easydefi.users.aa.bb.cc.SomeService.zot()

for reasons M. Deinum has mentioned already. His suggestion to use the ..* notation, which means "any method in any class in the package preceded by ..*", is exactly right:

execution(* com.easydefi.users..*(..))

I also want to stress that the credit for this answer should be his, and if he likes to simply copy my answer and post it under his own name instead of just a comment, I shall remove this one gladly instead. But I do think questions deserve comprehensive answers.


问:
Snowflake connectivity with GIT
Is there any way we can connect snowflake with GIT for version control. With the help of that, we can maintain version of our merge statement and any other sql script in GIT.</p>

答: DBeaver has git integration and is the best solution my team has found for version control with Snowflake. It's not perfect but it allows you to run your scripts against Snowflake and then push your SQL code to a git repository through the app UI or command line.

Title: Snowflake connectivity with GIT


问:
Serverless Framework - Cannot generate IAM policy statement for Task state
I'm trying to use serverless framework to deploy a step function that calls a couple of lambdas. Here's my serverless.yml:

    org: bizrob
    app: flexipod-2-queue
    service: flexipod-2-queue

    frameworkVersion: "2 || 3"

    custom:
      region: eu-west-1

    provider:
      name: aws
      runtime: nodejs14.x

    plugins:
      - serverless-step-functions

    functions:
      pullSqlSvr:
        handler: flexipod-2-queue/pullSqlSvrData.pullSqlSvr
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"
          SQS_QUEUE_URL: !Ref "MyQueue"
      sendToDataLake:
        handler: queue-2-datalake/sendToDataLake.sendBatchToQueue
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"

    stepFunctions:
      stateMachines:
        flexipodFlow:
          name: flexipodFlow
          definition:
            StartAt: pullSqlSvr
            States:
              pullSqlSvr:
                Type: Task
                Resource:
                  Fn::GetAtt:[pullSqlSvr, Arn]
                Next: sendToDataLake
              sendToDataLake:
                Type: Task
                Resource:
                  Fn::GetAtt:[sendToDataLake, Arn]
                End: true

    resources:
      Resources:
        MyQueue:
          Type: "AWS::SQS::Queue"
          Properties:
            QueueName: "flexipod"
```

When I run serverless deploy I see the following error:

Deploying flexipod-2-queue to stage dev (us-east-1,
"serverless-admin-2" provider) Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[pullSqlSvr,
Arn]', Next: 'sendToDataLake' } Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[sendToDataLake,
Arn]', End: true }

× Stack flexipod-2-queue-dev failed to deploy (72s) Environment:
win32, node 16.1.0, framework 3.0.0, plugin 6.0.0, SDK 4.3.0
Credentials: Serverless Dashboard, "serverless-admin-2" provider
(https://app.serverless.com/bizrob/apps/flexipod-2-queue/flexipod-2-queue/dev/us-east-1/providers)
Docs:        docs.serverless.com Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error: CREATE_FAILED: FlexipodFlow (AWS::StepFunctions::StateMachine)
Resource handler returned message: "Invalid State Machine Definition:
'SCHEMA_VALIDATION_FAILED: Value is not a valid resource ARN at
/States/pullSqlSvr/Resource, SCHEMA_VALIDATION_FAILED: Value is not a
valid resource ARN at /States/sendToDataLake/Resource' (Service:
AWSStepFunctions; Status Code: 400; Error Code: InvalidDefinition

Any advice on how to solve please?

答:
In my experience serverless-step-functions fails to deploy properly if any keys in the Steps block begin with a lowercase letter. Changing it to the seemingly case-sensitive equivalents, like the following, and redeploying may do the trick:

```<code>States:
  PullSqlSvr:
    Type: Task
    Resource:
      Fn::GetAtt:[pullSqlSvr, Arn]
    Next: sendToDataLake
  SendToDataLake:
    Type: Task
    Resource:
      Fn::GetAtt:[sendToDataLake, Arn]
    End: true
</code>```

(I just converted the pullSqlSvr and sendToDataLake to their PascalCase equivalents PullSqlSvr and SendToDataLake.)

Body:
I'm trying to use serverless framework to deploy a step function that calls a couple of lambdas. Here's my serverless.yml:

    org: bizrob
    app: flexipod-2-queue
    service: flexipod-2-queue

    frameworkVersion: "2 || 3"

    custom:
      region: eu-west-1

    provider:
      name: aws
      runtime: nodejs14.x

    plugins:
      - serverless-step-functions

    functions:
      pullSqlSvr:
        handler: flexipod-2-queue/pullSqlSvrData.pullSqlSvr
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"
          SQS_QUEUE_URL: !Ref "MyQueue"
      sendToDataLake:
        handler: queue-2-datalake/sendToDataLake.sendBatchToQueue
        environment:
          REGION: ${self:custom.region}
          API_VERSION_S3: "2006-03-01"
          API_VERSION_SQS: "2012-11-05"

    stepFunctions:
      stateMachines:
        flexipodFlow:
          name: flexipodFlow
          definition:
            StartAt: pullSqlSvr
            States:
              pullSqlSvr:
                Type: Task
                Resource:
                  Fn::GetAtt:[pullSqlSvr, Arn]
                Next: sendToDataLake
              sendToDataLake:
                Type: Task
                Resource:
                  Fn::GetAtt:[sendToDataLake, Arn]
                End: true

    resources:
      Resources:
        MyQueue:
          Type: "AWS::SQS::Queue"
          Properties:
            QueueName: "flexipod"

When I run serverless deploy I see the following error:

Deploying flexipod-2-queue to stage dev (us-east-1,
"serverless-admin-2" provider) Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[pullSqlSvr,
Arn]', Next: 'sendToDataLake' } Cannot generate IAM policy statement
for Task state { Type: 'Task', Resource: 'Fn::GetAtt:[sendToDataLake,
Arn]', End: true }

× Stack flexipod-2-queue-dev failed to deploy (72s) Environment:
win32, node 16.1.0, framework 3.0.0, plugin 6.0.0, SDK 4.3.0
Credentials: Serverless Dashboard, "serverless-admin-2" provider
(https://app.serverless.com/bizrob/apps/flexipod-2-queue/flexipod-2-queue/dev/us-east-1/providers)
Docs:        docs.serverless.com Support:     forum.serverless.com
Bugs:        github.com/serverless/serverless/issues

Error: CREATE_FAILED: FlexipodFlow (AWS::StepFunctions::StateMachine)
Resource handler returned message: "Invalid State Machine Definition:
'SCHEMA_VALIDATION_FAILED: Value is not a valid resource ARN at
/States/pullSqlSvr/Resource, SCHEMA_VALIDATION_FAILED: Value is not a
valid resource ARN at /States/sendToDataLake/Resource' (Service:
AWSStepFunctions; Status Code: 400; Error Code: InvalidDefinition

Any advice on how to solve please?

Body:
In my experience serverless-step-functions fails to deploy properly if any keys in the Steps block begin with a lowercase letter. Changing it to the seemingly case-sensitive equivalents, like the following, and redeploying may do the trick:

States:
  PullSqlSvr:
    Type: Task
    Resource:
      Fn::GetAtt:[pullSqlSvr, Arn]
    Next: sendToDataLake
  SendToDataLake:
    Type: Task
    Resource:
      Fn::GetAtt:[sendToDataLake, Arn]
    End: true

(I just converted the pullSqlSvr and sendToDataLake to their PascalCase equivalents PullSqlSvr and SendToDataLake.)


问:
Android ImageView with PixelArt
I want to dispaly pixelart in an ImageView but it keeps getting blurry.
I tried it like explained in this post (and some others) and I tried it with the function createScaledBitmap like you can see in the code. But it still gets blurry.
What else can I do to show my PixelArt correctly?

```<code>        var bitmap = Bitmap.createScaledBitmap(fu, 120, 120, false)
        var drawable = BitmapDrawable(context.resources, bitmap)
        drawable.setAntiAlias(false)
        drawable.setFilterBitmap(false)
        myImageView.setImageDrawable(drawable )
</code>```

(The Imageview is inside a RecyclerView but I don't think that that is important for my problem.)

答:
You're scaling the image up before disabling the filtering, so it still looks filtered. It also wastes memory to enlarge a small sprite into a large bitmap.

You don't need to mess with manual scaling like that. You can set the drawable on you ImageView (either assign it in your XML layout or call setImageResource on it). Then set isFilterBitmap to false on its drawable.

```<code>myImageView.setImageResource(R.drawable.mySprite) // if not already set in XML
myImageView.drawable?.isFilterBitmap = false
</code>```

Title: Android ImageView with PixelArt

Body:
I want to dispaly pixelart in an ImageView but it keeps getting blurry.
I tried it like explained in this post (and some others) and I tried it with the function createScaledBitmap like you can see in the code. But it still gets blurry.
What else can I do to show my PixelArt correctly?

        var bitmap = Bitmap.createScaledBitmap(fu, 120, 120, false)
        var drawable = BitmapDrawable(context.resources, bitmap)
        drawable.setAntiAlias(false)
        drawable.setFilterBitmap(false)
        myImageView.setImageDrawable(drawable )

(The Imageview is inside a RecyclerView but I don't think that that is important for my problem.)

Body:
You're scaling the image up before disabling the filtering, so it still looks filtered. It also wastes memory to enlarge a small sprite into a large bitmap.

You don't need to mess with manual scaling like that. You can set the drawable on you ImageView (either assign it in your XML layout or call setImageResource on it). Then set isFilterBitmap to false on its drawable.

myImageView.setImageResource(R.drawable.mySprite) // if not already set in XML
myImageView.drawable?.isFilterBitmap = false


问:
How can I write a loop/function to calculate the % difference between different rows/factors?
I'm looking to do something that's out of my coding league. I have included 2 snippets of real data below.

Basically I want to mutate/add a column (or even create a new dataframe if that is easier) that calculates the % difference of a measurement "median.fsc" that corresponds to the same "strain" but different "starvation state" but within the same experiment "run".

So for example

I want the % difference of median.fsc of 381-starved / 381-enriched for run 1

I presume i would be using dplyr but have no clue where to start!

Some further manipulation that I also want to do - but guessing I can adapt whatever code I do end up using.

Strain-comparison (median.fsc) expressed as % ie 381.dwecA (enriched) / 381 (enriched)  in run 1

```<code>structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
        8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
        "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
        "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
            starvation = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
            2L), .Label = c("starved", "enriched"), class = "factor"),
            live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
            ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(9283.6,
            8012.8, 8030.1, 9464.1, 8286, 7903.6, 10600.7, 8539.2, 8935.1
            ), mean.fsc = c(11002.9, 9551.4, 9606.6, 10747.4, 9824, 9277,
            11874.9, 9645.4, 10537.6), median.fsc = c(10581.7, 8420.3,
            8393.4, 10050.1, 8771.6, 7979.3, 11526, 8371.3, 9701.5),
            std.dv = c(5808.4, 5482.6, 5533, 5264, 5481.1, 5250, 5202.3,
            4816.8, 5654.1), run = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
            1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
        -9L), class = c("tbl_df", "tbl", "data.frame"))
</code>```
```<code>    structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
    8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
    "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
    "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
        starvation = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
        1L), .Label = c("starved", "enriched"), class = "factor"),
        live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
        ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(2123.8,
        2426.4, 2056.6, 2556.5, 2452, 2703.3, 2065, 3875, 2362.6),
        mean.fsc = c(2482.7, 2867, 2321, 2757.6, 2651.4, 3107.2,
        2368.9, 4308.2, 2571.1), median.fsc = c(1924.9, 2177, 1896,
        2512.2, 2378.8, 2442.8, 1883.6, 3882.8, 2263.4), std.dv = c(NA_real_,
        NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
        NA_real_, NA_real_), run = structure(c(1L, 1L, 1L, 1L, 1L,
        1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
    -9L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
Would you consider joining the two tables on matching columns and then deploying calculations within the obtained structure?

```<code>library("tidyverse")
full_join(
    mutate(df_A, strain = as.character(strain), run = as.integer(run)),
    mutate(df_B, strain = as.character(strain), run = as.integer(run)),
    by = c("strain" = "strain", "run" = "run"),
    suffix = c ("_dtaA", "_dtaB")
) %>%
    glimpse() %>%
    # Ensure that looking at unmatched starvation rates
    filter(starvation_dtaA != starvation_dtaB) %>%
    mutate(any_calcs = median.fsc_dtaA - median.fsc_dtaB) %>%
    select(starts_with("strain"), starts_with("run"), contains("any_calcs"),
           starts_with("starvation")) %>%
    glimpse()
</code>```

Results

```<code># Rows: 9
# Columns: 5
# $ strain          <chr> "381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE", "381.dwecE.cwecE", "381.dwaa…
# $ run             <int> 1, 1, 1, 1, 1, 1, 1, 1, 1
# $ any_calcs       <dbl> 8656.8, 6243.3, 6497.4, 7537.9, 6392.8, 5536.5, 9642.4, 4488.5, 7438.1
# $ starvation_dtaA <fct> enriched, enriched, enriched, enriched, enriched, enriched, enriched, enriched, …
# $ starvation_dtaB <fct> starved, starved, starved, starved, starved, starved, starved, starved, starved
</code>```

Body:
I'm looking to do something that's out of my coding league. I have included 2 snippets of real data below.

Basically I want to mutate/add a column (or even create a new dataframe if that is easier) that calculates the % difference of a measurement "median.fsc" that corresponds to the same "strain" but different "starvation state" but within the same experiment "run".

So for example

I want the % difference of median.fsc of 381-starved / 381-enriched for run 1

I presume i would be using dplyr but have no clue where to start!

Some further manipulation that I also want to do - but guessing I can adapt whatever code I do end up using.

Strain-comparison (median.fsc) expressed as % ie 381.dwecA (enriched) / 381 (enriched)  in run 1

structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
        8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
        "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
        "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
            starvation = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
            2L), .Label = c("starved", "enriched"), class = "factor"),
            live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
            ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(9283.6,
            8012.8, 8030.1, 9464.1, 8286, 7903.6, 10600.7, 8539.2, 8935.1
            ), mean.fsc = c(11002.9, 9551.4, 9606.6, 10747.4, 9824, 9277,
            11874.9, 9645.4, 10537.6), median.fsc = c(10581.7, 8420.3,
            8393.4, 10050.1, 8771.6, 7979.3, 11526, 8371.3, 9701.5),
            std.dv = c(5808.4, 5482.6, 5533, 5264, 5481.1, 5250, 5202.3,
            4816.8, 5654.1), run = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
            1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
        -9L), class = c("tbl_df", "tbl", "data.frame"))

    structure(list(strain = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
    8L, 10L), .Label = c("381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE",
    "381.dwecE.cwecE", "381.dwaaG", "381.dwaaG.cwaaG", "381.dE.dG",
    "381.dE.dG.cE.cG.c1", "381.dE.dG.cE.cG.c2"), class = "factor"),
        starvation = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
        1L), .Label = c("starved", "enriched"), class = "factor"),
        live.dead = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
        ), .Label = c("live", "mixed"), class = "factor"), geomean.fsc = c(2123.8,
        2426.4, 2056.6, 2556.5, 2452, 2703.3, 2065, 3875, 2362.6),
        mean.fsc = c(2482.7, 2867, 2321, 2757.6, 2651.4, 3107.2,
        2368.9, 4308.2, 2571.1), median.fsc = c(1924.9, 2177, 1896,
        2512.2, 2378.8, 2442.8, 1883.6, 3882.8, 2263.4), std.dv = c(NA_real_,
        NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
        NA_real_, NA_real_), run = structure(c(1L, 1L, 1L, 1L, 1L,
        1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor")), row.names = c(NA,
    -9L), class = c("tbl_df", "tbl", "data.frame"))

Body:
Would you consider joining the two tables on matching columns and then deploying calculations within the obtained structure?

library("tidyverse")
full_join(
    mutate(df_A, strain = as.character(strain), run = as.integer(run)),
    mutate(df_B, strain = as.character(strain), run = as.integer(run)),
    by = c("strain" = "strain", "run" = "run"),
    suffix = c ("_dtaA", "_dtaB")
) %>%
    glimpse() %>%
    # Ensure that looking at unmatched starvation rates
    filter(starvation_dtaA != starvation_dtaB) %>%
    mutate(any_calcs = median.fsc_dtaA - median.fsc_dtaB) %>%
    select(starts_with("strain"), starts_with("run"), contains("any_calcs"),
           starts_with("starvation")) %>%
    glimpse()

Results

# Rows: 9
# Columns: 5
# $ strain          <chr> "381", "381.dwecA", "381.dwecA.cwecA", "381.dwecE", "381.dwecE.cwecE", "381.dwaa…
# $ run             <int> 1, 1, 1, 1, 1, 1, 1, 1, 1
# $ any_calcs       <dbl> 8656.8, 6243.3, 6497.4, 7537.9, 6392.8, 5536.5, 9642.4, 4488.5, 7438.1
# $ starvation_dtaA <fct> enriched, enriched, enriched, enriched, enriched, enriched, enriched, enriched, …
# $ starvation_dtaB <fct> starved, starved, starved, starved, starved, starved, starved, starved, starved


问:
Vue element-ui <el-table-column> formatter – how to display html?
How to return html formatted cell value?

I want to get custom formatted value (with html or other components) with <el-table-column> formatter.

<el-table :data="data">
  <el-table-column v-for="(column, index) in columns"
                   :key="index" :label="column.label"
                   :formatter="column.formatter">
  </el-table-column>
</el-table>
```

<pre class="lang-js prettyprint-override"><code>data() {
  return {
    columns: [
      {
        label: 'Created at',
        formatter: (row, col, value, index) => {
          return `<span class="date">${value}</span>`
        }
      },
      // edit:
      {
        label: 'Address',
        formatter: (row, col, value, index) => {
          return `<mini-map :data="${row}"></mini-map>`
        }
      }
      // other dynamic columns...
    ]
  }
}
</code>```

But cell content is displayed as escaped html string. Is there any possibility to force html?

EPIC EDIT: I added an answer with a solution.

答:
I feel headache, but it worked for me</p>
```<code><el-table :data="tableData" style="width: 100%">
              <el-table-column label="shortName" width="180">
                <template v-slot="scope">
                  <span v-html="scope ? scope.row.shortName : ''"></span>
                </template>
              </el-table-column>
...
</code>```

Body:
How to return html formatted cell value?

I want to get custom formatted value (with html or other components) with <el-table-column> formatter.

<el-table :data="data">
  <el-table-column v-for="(column, index) in columns"
                   :key="index" :label="column.label"
                   :formatter="column.formatter">
  </el-table-column>
</el-table>

data() {
  return {
    columns: [
      {
        label: 'Created at',
        formatter: (row, col, value, index) => {
          return `<span class="date">${value}</span>`
        }
      },
      // edit:
      {
        label: 'Address',
        formatter: (row, col, value, index) => {
          return `<mini-map :data="${row}"></mini-map>`
        }
      }
      // other dynamic columns...
    ]
  }
}

But cell content is displayed as escaped html string. Is there any possibility to force html?

EPIC EDIT: I added an answer with a solution.

Body:
I feel headache, but it worked for me

<el-table :data="tableData" style="width: 100%">
              <el-table-column label="shortName" width="180">
                <template v-slot="scope">
                  <span v-html="scope ? scope.row.shortName : ''"></span>
                </template>
              </el-table-column>
...


问:
Get Index of Object in TouchesEnded
i have a UIViewController with many UIImageViews. I need in touchEnded event get a index of this UIimage.

How do Make?

Thank's

答: Instead of UIImageViews, why don't you use UIButtons? You can set the image with setImage:forState:, and the target action and object with addTarget:action:forControlEvents. When your target action gets called, the button will be sent as the sender argument.

Title: Get Index of Object in TouchesEnded


问:
How can I fix "kex_exchange_identification: read: Connection reset by peer"?
I want to copy data with scp in a GitLab pipeline using PRIVATE_KEY.

The error is:

kex_exchange_identification: read: Connection reset by peer
Connection reset by x.x.x.x port 22
lost connection
```
<p>Pipeline log:</p>
<pre class="lang-none prettyprint-override"><code>$ mkdir -p ~/.ssh

$ echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa

$ chmod 600 ~/.ssh/id_rsa

$ eval "$(ssh-agent -s)"
Agent pid 22

$ ssh-add ~/.ssh/id_rsa
Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)

$ ssh-keyscan -H $IP >> ~/.ssh/known_hosts
# x.x.x.x:22 SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.10
# x.x.x.x:22 SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.10

$ scp -rv api.yml root@$IP:/home/services/test/

Executing: program /usr/bin/ssh host x.x.x.x, user root, command scp -v -r -t /home/services/test/

OpenSSH_8.6p1, OpenSSL 1.1.1l  24 Aug 2021
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling
debug1: Connecting to x.x.x.x [x.x.x.x] port 22.
debug1: Connection established.
debug1: identity file /root/.ssh/id_rsa type -1
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa_sk type -1
debug1: identity file /root/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: identity file /root/.ssh/id_ed25519_sk type -1
debug1: identity file /root/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /root/.ssh/id_xmss type -1
debug1: identity file /root/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.6
kex_exchange_identification: read: Connection reset by peer
Connection reset by x.x.x.x port 22
lost connection
</code>```

答:
The same issue with me:

I have fixed the issue by doing the below steps.

edit file etc/hosts.allow. Command to do so sudo nano /etc/hosts.allow.

At the end, update the value of ALL keys to ALL like ALL : ALL. Save the file and try again.

Basically, ALL might be set to something else therefore while establishing ssh connection to the host, it is expecting that the request should come from the IP address starting from 10...* if ALL set to ALL : 10.. Therefore by replacing 10. with ALL, you are allowing connection from everywhere.

Body:
I want to copy data with scp in a GitLab pipeline using PRIVATE_KEY.

The error is:

kex_exchange_identification: read: Connection reset by peer
Connection reset by x.x.x.x port 22
lost connection

Pipeline log:

$ mkdir -p ~/.ssh

$ echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa

$ chmod 600 ~/.ssh/id_rsa

$ eval "$(ssh-agent -s)"
Agent pid 22

$ ssh-add ~/.ssh/id_rsa
Identity added: /root/.ssh/id_rsa (/root/.ssh/id_rsa)

$ ssh-keyscan -H $IP >> ~/.ssh/known_hosts
# x.x.x.x:22 SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.10
# x.x.x.x:22 SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.10

$ scp -rv api.yml root@$IP:/home/services/test/

Executing: program /usr/bin/ssh host x.x.x.x, user root, command scp -v -r -t /home/services/test/

OpenSSH_8.6p1, OpenSSL 1.1.1l  24 Aug 2021
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Authenticator provider $SSH_SK_PROVIDER did not resolve; disabling
debug1: Connecting to x.x.x.x [x.x.x.x] port 22.
debug1: Connection established.
debug1: identity file /root/.ssh/id_rsa type -1
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: identity file /root/.ssh/id_dsa type -1
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: identity file /root/.ssh/id_ecdsa_sk type -1
debug1: identity file /root/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: identity file /root/.ssh/id_ed25519_sk type -1
debug1: identity file /root/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /root/.ssh/id_xmss type -1
debug1: identity file /root/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.6
kex_exchange_identification: read: Connection reset by peer
Connection reset by x.x.x.x port 22
lost connection


问:
In an Angular.js controller's scope function code doesn't run below a $timeout statement inside
I have a button for which I have set ng-click="refresh()". The console logs before the timeout function logs correctly but the console log inside the $timeout block and after the block doesn't seem to log. If I remove the $timeout block every console log works. I even checked with $interval instead of $timeout but same behaviour.

I wanted to do something like this here

I'm using Angular.js 1.4.0

This is my implementation inside the controller

      $scope.refreshing ={state: false};
      $scope.refresh = function(){
        console.log($scope);
        $scope.refreshing.state = true;
        $scope.search(); //sends an http request and loads results.
        console.log('this logs');
        // $scope.refreshing.state = false;
        $timeout(function(){
           console.log('this doesnt log')
           $scope.refreshing.state = false;
         },2000);
        console.log('this doesnt log')

      }
```

答:
You'll want to make sure your dependency injection is wired up properly. For example:

angular
    .module("MyApp")
    .controller("MyController", ["$scope", "$timeout", MyController]);

function MyController($scope, $timeout) {
    // controller code
}
```

See John Papa's AngularJS style guide for some best practices relating to controllers.

Body:
You'll want to make sure your dependency injection is wired up properly. For example:

angular
    .module("MyApp")
    .controller("MyController", ["$scope", "$timeout", MyController]);

function MyController($scope, $timeout) {
    // controller code
}

See John Papa's AngularJS style guide for some best practices relating to controllers.


问:
How to filter some urls from python list?
I wrote this code for extract images urls from a web page as I given. And it shows all images urls. But I need to filter "https://images.unsplash.com/profile" urls and print them.

```<code>from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

print(images)
</code>```

I tried;

```<code>from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

if "https://images.unsplash.com/profile" in images:
    print(images)
</code>```

And didn't worked!

答:
You can make your selection more specific with css selectors:

```<code>soup.select('img[src*="https://images.unsplash.com/profile"]')
</code>```

Example

```<code>from bs4 import BeautifulSoup
import urllib.request

url= "https://unsplash.com/t/nature"
html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)

images = [img['src'] for img in soup.select('img[src*="https://images.unsplash.com/profile"]')]

print(images)
</code>```

Output

```<code>['https://images.unsplash.com/profile-1544707963613-16baf868f301?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff', 'https://images.unsplash.com/profile-1604758536753-68fd6f23aaf7image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff', 'https://images.unsplash.com/profile-1516997253075-2a25da8007e7?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff', 'https://images.unsplash.com/profile-1628142977790-d9f66dcbc498image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff']
</code>```

EDIT

Just printing the urls line by line:

```<code>for img in soup.select('img[src*="https://images.unsplash.com/profile"]'):
    print(img['src'])
</code>```

Body:
I wrote this code for extract images urls from a web page as I given. And it shows all images urls. But I need to filter "https://images.unsplash.com/profile" urls and print them.

from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

print(images)

I tried;

from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

if "https://images.unsplash.com/profile" in images:
    print(images)

And didn't worked!

Body:
You can make your selection more specific with css selectors:

soup.select('img[src*="https://images.unsplash.com/profile"]')

Example

from bs4 import BeautifulSoup
import urllib.request

url= "https://unsplash.com/t/nature"
html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)

images = [img['src'] for img in soup.select('img[src*="https://images.unsplash.com/profile"]')]

print(images)

Output

['https://images.unsplash.com/profile-1544707963613-16baf868f301?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff', 'https://images.unsplash.com/profile-1604758536753-68fd6f23aaf7image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff', 'https://images.unsplash.com/profile-1516997253075-2a25da8007e7?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff', 'https://images.unsplash.com/profile-1628142977790-d9f66dcbc498image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff']

EDIT

Just printing the urls line by line:

for img in soup.select('img[src*="https://images.unsplash.com/profile"]'):
    print(img['src'])


问:
forward log messages from syslog to custom log in Linux server
I'm going to send my logs from syslog to a custom log in ubuntu server, you guys know what should I do ? how can I config my rsyslog.conf? is there any direct way to send my logs from spring boot app to a custom log not syslog server?</p>

答:
Spring Boot uses Logback by default. Logback contains a syslog appender, see here: https://logback.qos.ch/manual/appenders.html#SyslogAppender:

<configuration>

  <appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
    <syslogHost>remote_home</syslogHost>
    <facility>AUTH</facility>
    <suffixPattern>[%thread] %logger %msg</suffixPattern>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="SYSLOG" />
  </root>
</configuration>
```

To get fine-grained control over Spring Boot logging, see here: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.logging.custom-log-configuration

You could add the snippet above in the logback-spring.xml. Citing from the documentation:

When possible, we recommend that you use the -spring variants for your logging configuration (for example, logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.

Body:
Spring Boot uses Logback by default. Logback contains a syslog appender, see here: https://logback.qos.ch/manual/appenders.html#SyslogAppender:

<configuration>

  <appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
    <syslogHost>remote_home</syslogHost>
    <facility>AUTH</facility>
    <suffixPattern>[%thread] %logger %msg</suffixPattern>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="SYSLOG" />
  </root>
</configuration>

To get fine-grained control over Spring Boot logging, see here: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.logging.custom-log-configuration

You could add the snippet above in the logback-spring.xml. Citing from the documentation:

When possible, we recommend that you use the -spring variants for your logging configuration (for example, logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.


问:
How to import JQuery into a Typescript file?

Update

No import was required.  Instead, I needed to add a reference to the top of the file.  So the first line of my WebAPI.js should have been /// <reference path ="../typings/jquery/jquery.d.ts"/> instead of import { $ } from '../jquery-3.1.1';

I am trying to import jQuery to use in a Typescript file, but I am receiving a variety of errors with everything I try.  I followed the solutions here and here, but without any luck.

tsconfig.json

```<code>{
    "compilerOptions": {
        "removeComments": true,
        "preserveConstEnums": true,
    "out": "Scripts/CCSEQ.Library.js",
    "module": "amd",
        "sourceMap": true,
    "target": "es5",
    "allowJs": true
}
</code>```

WebAPI.js

```<code>import { $ } from '../jquery-3.1.1';

export class ExpenseTransaction extends APIBase {

    constructor() {
        super();
    }

    Get(): void {
        let expenses: Array<Model.ExpenseTransaction>;
        let self = this;
        $.ajax({
            url: this.Connection,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            success: function (data: any): void {
                expenses = self.ConvertToEntity(data.value);
            },
            error: function (data: any): void { console.log(data.status); }
        });
    };
}
</code>```

I have also tried import * as $ from '../jquery.3.1.1'

Errors

Module jquery-3.1.1 has no exported member $

Property ajax does not exist on type (selector: any, context: any) => any

答:
es5

Importing is as simple as:

```<code>import * as $ from 'jquery';
</code>```

But only if we install related .d.ts files:

npm install @types/jquery --save-dev
```
<h2>es6</h2>
<p>Same as above, but if you want to be able to use "<code>$</code>" as function, to listen for document-ready event (like "<code>$(function () { ... })</code>"), then continue reading.</p>
<p>First, in <code>tsconfig.json</code> file, do something like:</p>
<pre class="lang-json prettyprint-override"><code>{
    "compilerOptions": {
        "esModuleInterop": true
    }
}
</code>```

Then import without "* as " part, like:

```<code>import $ from 'jquery';
</code>```

See also stackoverflow.com/Understanding-esModuleInterop

Body:
Update

No import was required.  Instead, I needed to add a reference to the top of the file.  So the first line of my WebAPI.js should have been /// <reference path ="../typings/jquery/jquery.d.ts"/> instead of import { $ } from '../jquery-3.1.1';

I am trying to import jQuery to use in a Typescript file, but I am receiving a variety of errors with everything I try.  I followed the solutions here and here, but without any luck.

tsconfig.json

{
    "compilerOptions": {
        "removeComments": true,
        "preserveConstEnums": true,
    "out": "Scripts/CCSEQ.Library.js",
    "module": "amd",
        "sourceMap": true,
    "target": "es5",
    "allowJs": true
}

WebAPI.js

import { $ } from '../jquery-3.1.1';

export class ExpenseTransaction extends APIBase {

    constructor() {
        super();
    }

    Get(): void {
        let expenses: Array<Model.ExpenseTransaction>;
        let self = this;
        $.ajax({
            url: this.Connection,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            success: function (data: any): void {
                expenses = self.ConvertToEntity(data.value);
            },
            error: function (data: any): void { console.log(data.status); }
        });
    };
}

I have also tried import * as $ from '../jquery.3.1.1'

Errors

Module jquery-3.1.1 has no exported member $

Property ajax does not exist on type (selector: any, context: any) => any

Body:
es5

Importing is as simple as:

import * as $ from 'jquery';

But only if we install related .d.ts files:

npm install @types/jquery --save-dev

es6

Same as above, but if you want to be able to use "$" as function, to listen for document-ready event (like "$(function () { ... })"), then continue reading.

First, in tsconfig.json file, do something like:

{
    "compilerOptions": {
        "esModuleInterop": true
    }
}

Then import without "* as " part, like:

import $ from 'jquery';

See also stackoverflow.com/Understanding-esModuleInterop


问:
sorting in Angular4 based on header clicked
I am trying to implement sorting on Angular4 , when a header is clicked . I want the whole result set to be sorted on the field clicked. I was able to use something like this in Angular1

```<code> ng-click="sortType = 'empId'; sortReverse = !sortReverse;"
</code>```

And my ng-repeat was something like this

```<code> ng-repeat="employees in searchresponse|orderBy:sortType:sortReverse"
</code>```

How can i implement something like this or something different which allows me to sort fields in ascending/descending order when clicked . This is what i have started with Angular4 and stuck currently

```<code><table class="table table-bordered table-fixed  table-striped text-center">
    <tr style=" background-color: #bccbd4 ">
        <td class="tabH1" align="center">
            <a>
                <u>EmpId</u>
            </a>
        </td>
        <td class="tabH1" align="center">
            <a>
                <u>Name</u>
            </a>
        </td>
        <td class="tabH1" align="center">
            <a>
                <u>Mobile-Num</u>
            </a>
        </td>
    </tr>
    <tr *ngFor="let emp of empList">
        <td align="center">{{emp.id}}</td>
        <td align="center">{{emp.name}}</td>
        <td align="center">{{emp.mobile}}</td>
    </tr>
</table>
</code>```

My sample JSON

```<code>this.empList = [
    {
        id: '1',
        name: 'test',
        mobile: '1234567890'
    },
    {
        id: '2',
        name: 'kumar',
        mobile: '9786543210'
    }
];
</code>```

When id is clicked, i want the whole JSON to be sorted based on the empId .should i create my own Pipe or should i create a function to sort the resultset . Any example on how to proceed is greatly appreciated .

答:
Angular material have a solution for this using matSort, it also comes with an arrow for asc and desc sort, see this link,
although you still need to write the sort logic yourself (they show you how to do it), here is the example they provide:</p>
```<code>import {Component} from '@angular/core';
import {Sort} from '@angular/material/sort';

export interface Dessert {
  calories: number;
  carbs: number;
  fat: number;
  name: string;
  protein: number;
}

/**
 * @title Sorting overview
 */
@Component({
  selector: 'sort-overview-example',
  template: `
    <table matSort (matSortChange)="sortData($event)">
      <tr>
        <th mat-sort-header="name">Dessert (100g)</th>
        <th mat-sort-header="calories">Calories</th>
        <th mat-sort-header="fat">Fat (g)</th>
        <th mat-sort-header="carbs">Carbs (g)</th>
        <th mat-sort-header="protein">Protein (g)</th>
      </tr>

      <tr *ngFor="let dessert of sortedData">
        <td>{{dessert.name}}</td>
        <td>{{dessert.calories}}</td>
        <td>{{dessert.fat}}</td>
        <td>{{dessert.carbs}}</td>
        <td>{{dessert.protein}}</td>
      </tr>
    </table>`,
})
export class SortOverviewExample {
  desserts: Dessert[] = [
    {name: 'Frozen yogurt', calories: 159, fat: 6, carbs: 24, protein: 4},
    {name: 'Ice cream sandwich', calories: 237, fat: 9, carbs: 37, protein: 4},
    {name: 'Eclair', calories: 262, fat: 16, carbs: 24, protein: 6},
    {name: 'Cupcake', calories: 305, fat: 4, carbs: 67, protein: 4},
    {name: 'Gingerbread', calories: 356, fat: 16, carbs: 49, protein: 4},
  ];

  sortedData: Dessert[];

  constructor() {
    this.sortedData = this.desserts.slice();
  }

  sortData(sort: Sort) {
    const data = this.desserts.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name':
          return compare(a.name, b.name, isAsc);
        case 'calories':
          return compare(a.calories, b.calories, isAsc);
        case 'fat':
          return compare(a.fat, b.fat, isAsc);
        case 'carbs':
          return compare(a.carbs, b.carbs, isAsc);
        case 'protein':
          return compare(a.protein, b.protein, isAsc);
        default:
          return 0;
      }
    });
  }
}

function compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
</code>```

Body:
I am trying to implement sorting on Angular4 , when a header is clicked . I want the whole result set to be sorted on the field clicked. I was able to use something like this in Angular1

 ng-click="sortType = 'empId'; sortReverse = !sortReverse;"

And my ng-repeat was something like this

 ng-repeat="employees in searchresponse|orderBy:sortType:sortReverse"

How can i implement something like this or something different which allows me to sort fields in ascending/descending order when clicked . This is what i have started with Angular4 and stuck currently

                EmpId

                Name

                Mobile-Num

        {{emp.id}}
        {{emp.name}}
        {{emp.mobile}}

My sample JSON

this.empList = [
    {
        id: '1',
        name: 'test',
        mobile: '1234567890'
    },
    {
        id: '2',
        name: 'kumar',
        mobile: '9786543210'
    }
];

When id is clicked, i want the whole JSON to be sorted based on the empId .should i create my own Pipe or should i create a function to sort the resultset . Any example on how to proceed is greatly appreciated .

Body:
Angular material have a solution for this using matSort, it also comes with an arrow for asc and desc sort, see this link,
although you still need to write the sort logic yourself (they show you how to do it), here is the example they provide:

import {Component} from '@angular/core';
import {Sort} from '@angular/material/sort';

export interface Dessert {
  calories: number;
  carbs: number;
  fat: number;
  name: string;
  protein: number;
}

/**
 * @title Sorting overview
 */
@Component({
  selector: 'sort-overview-example',
  template: `
    <table matSort (matSortChange)="sortData($event)">
      <tr>
        <th mat-sort-header="name">Dessert (100g)</th>
        <th mat-sort-header="calories">Calories</th>
        <th mat-sort-header="fat">Fat (g)</th>
        <th mat-sort-header="carbs">Carbs (g)</th>
        <th mat-sort-header="protein">Protein (g)</th>
      </tr>

      <tr *ngFor="let dessert of sortedData">
        <td>{{dessert.name}}</td>
        <td>{{dessert.calories}}</td>
        <td>{{dessert.fat}}</td>
        <td>{{dessert.carbs}}</td>
        <td>{{dessert.protein}}</td>
      </tr>
    </table>`,
})
export class SortOverviewExample {
  desserts: Dessert[] = [
    {name: 'Frozen yogurt', calories: 159, fat: 6, carbs: 24, protein: 4},
    {name: 'Ice cream sandwich', calories: 237, fat: 9, carbs: 37, protein: 4},
    {name: 'Eclair', calories: 262, fat: 16, carbs: 24, protein: 6},
    {name: 'Cupcake', calories: 305, fat: 4, carbs: 67, protein: 4},
    {name: 'Gingerbread', calories: 356, fat: 16, carbs: 49, protein: 4},
  ];

  sortedData: Dessert[];

  constructor() {
    this.sortedData = this.desserts.slice();
  }

  sortData(sort: Sort) {
    const data = this.desserts.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }

    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name':
          return compare(a.name, b.name, isAsc);
        case 'calories':
          return compare(a.calories, b.calories, isAsc);
        case 'fat':
          return compare(a.fat, b.fat, isAsc);
        case 'carbs':
          return compare(a.carbs, b.carbs, isAsc);
        case 'protein':
          return compare(a.protein, b.protein, isAsc);
        default:
          return 0;
      }
    });
  }
}

function compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}


问:
How to hide swagger models at bottom with gin-swagger?
I am using gin-swagger for generating API document.

It shows Models at the bottom of the page list by default.

How to hide it?

答:
You juste have to add this line

```<code>ginSwagger.DefaultModelsExpandDepth(-1))
</code>```

like that

```<code>ginSwagger.WrapHandler(swaggerFiles.Handler,
        ginSwagger.DefaultModelsExpandDepth(-1))
</code>```

Body:
You juste have to add this line

ginSwagger.DefaultModelsExpandDepth(-1))

like that

ginSwagger.WrapHandler(swaggerFiles.Handler,
        ginSwagger.DefaultModelsExpandDepth(-1))


问:
show checked checkbox values on textarea javascript
I am trying to get all the checkbox checked values on the input field provided. I am using javascript to get the values but it only shows one checked value. When I check another checkbox it displays the second one only.
Here is what i did so far:

```<code><html>
<head>
<script type="text/javascript">
function checkbox(val){
document.getElementById("show").value = val;
}
</script>
</head>
<body>
    <form>
        <input type="checkbox" id="bk" name="vehicle" onClick="checkbox(this.value);" value="Bike">I have a bike<br></br>
        <input type="checkbox" id="cr" name="vehicle" onClick="checkbox(this.value);" value="Car">I have a car<br></br>
        <input type="text" id="show" name="vehicle"><br>
        <input type="submit" value="Showe">
    </form>
</body>
</html>
</code>```

As I said, this one only shows a single checked value, but I want to show all the checked values on the input field specified!
Thanks!

答:
var txt = document.getElementById( 'droptxt' ),
            content = document.getElementById( 'content' ),
            list = document.querySelectorAll( '.content input[type="checkbox"]' ),
            quantity = document.querySelectorAll( '.quantity' );
        txt.addEventListener( 'click', function() {
            content.classList.toggle( 'show' )
        } )

        window.onclick = function( e ) {
            if ( !e.target.matches( '.list' ) ) {
                if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
            }
        }

        list.forEach( function( item, index ) {
            item.addEventListener( 'click', function() {
                calc()
            } )
        } )

        function calc() {
            for ( var i = 0, arr = []; i < list.length; i++ ) {
            let spanArray = [];
            document.querySelectorAll('span').forEach(element => {
                spanArray.push(element.innerHTML);
            });

                if ( list[ i ].checked ) arr.push( list[ i ].value + " "+ spanArray)
            }
            txt.value = arr.join(', ')
        }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    h1 {
            color: #0000ff;
        }
        #droptxt {
            padding: 8px;
            width: 300px;
            cursor: pointer;
            box-sizing: border-box
        }
        .dropdown {
            position: relative;
            display: inline-block
        }
        .content {
            display: none;
            position: absolute;
            background-color: #f1f1f1;
            min-width: 200px;
            overflow: auto;
            box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
            z-index: 1
        }
        .content div {
            padding: 10px 15px
        }
        .content div:hover {
            background-color: #ddd
        }
        .show {
            display: block
        }</code>```

KIAAT

    Adding/Removing Checkbox Values into TextArea

    <input type="text" id="droptxt" class="list" placeholder="Select the values" readonly>

            <input type="checkbox" id="market" class="list"  value="Bike" /> I have a bike

            <input type="checkbox" id="banana" class="list" value="Car" /> I have a car

```

Body:
I am trying to get all the checkbox checked values on the input field provided. I am using javascript to get the values but it only shows one checked value. When I check another checkbox it displays the second one only.
Here is what i did so far:

    <form>
        <input type="checkbox" id="bk" name="vehicle" onClick="checkbox(this.value);" value="Bike">I have a bike

        <input type="checkbox" id="cr" name="vehicle" onClick="checkbox(this.value);" value="Car">I have a car

        <input type="text" id="show" name="vehicle">

        <input type="submit" value="Showe">
    </form>

As I said, this one only shows a single checked value, but I want to show all the checked values on the input field specified!
Thanks!

Body:
var txt = document.getElementById( 'droptxt' ),
            content = document.getElementById( 'content' ),
            list = document.querySelectorAll( '.content input[type="checkbox"]' ),
            quantity = document.querySelectorAll( '.quantity' );
        txt.addEventListener( 'click', function() {
            content.classList.toggle( 'show' )
        } )

        window.onclick = function( e ) {
            if ( !e.target.matches( '.list' ) ) {
                if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
            }
        }

        list.forEach( function( item, index ) {
            item.addEventListener( 'click', function() {
                calc()
            } )
        } )

        function calc() {
            for ( var i = 0, arr = []; i < list.length; i++ ) {
            let spanArray = [];
            document.querySelectorAll('span').forEach(element => {
                spanArray.push(element.innerHTML);
            });

                if ( list[ i ].checked ) arr.push( list[ i ].value + " "+ spanArray)
            }
            txt.value = arr.join(', ')
        }

    h1 {
            color: #0000ff;
        }
        #droptxt {
            padding: 8px;
            width: 300px;
            cursor: pointer;
            box-sizing: border-box
        }
        .dropdown {
            position: relative;
            display: inline-block
        }
        .content {
            display: none;
            position: absolute;
            background-color: #f1f1f1;
            min-width: 200px;
            overflow: auto;
            box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
            z-index: 1
        }
        .content div {
            padding: 10px 15px
        }
        .content div:hover {
            background-color: #ddd
        }
        .show {
            display: block
        }

<h1>KIAAT</h1>
    <b>Adding/Removing Checkbox Values into TextArea</b>
    <br><br>
    <input type="text" id="droptxt" class="list" placeholder="Select the values" readonly>
        <div id="content" class="content">
            <div id="market" class="list">
            <label><input type="checkbox" id="market" class="list"  value="Bike" /> I have a bike</label>
            </div>

            <div class="list">
            <label><input type="checkbox" id="banana" class="list" value="Car" /> I have a car</label>
            </div>
        </div>


问:
In Mongodb , how do I check if all the documents are unique for a value?
Let's say I have 4 documents in the database:

```<code>{ name: 'alex' }
{ name: 'jen' }
{ name: 'alex' }
{ name: 'john'}
</code>```

In MongoDB Shell, I want to know if 2 or more documents share the same 'name'.

Basically, if all the names are different, return true.
If 2 or people have the same name, return false.

答:
Try this, uses a quick map-reduce query to find the number of documents that have the same name, and returns true if they're all different:</p>

```<code>function allDifferent() {
    var m = function() { emit(this.name, 1); }
    var r = function(key, emits) {
        var n = 0; emits.forEach(function(v) { n += v; }); return n;
    }
    var result = db.mycol.mapReduce(m, r, { out: "namecounts" });
    var allDifferent= (db.namecounts.count( { value: { $gt: 1 } } ) == 0)
    db.namecounts.drop();
    return allDifferent;
}
</code>```

Body:
Let's say I have 4 documents in the database:

{ name: 'alex' }
{ name: 'jen' }
{ name: 'alex' }
{ name: 'john'}

In MongoDB Shell, I want to know if 2 or more documents share the same 'name'.

Basically, if all the names are different, return true.
If 2 or people have the same name, return false.

Body:
Try this, uses a quick map-reduce query to find the number of documents that have the same name, and returns true if they're all different:

function allDifferent() {
    var m = function() { emit(this.name, 1); }
    var r = function(key, emits) {
        var n = 0; emits.forEach(function(v) { n += v; }); return n;
    }
    var result = db.mycol.mapReduce(m, r, { out: "namecounts" });
    var allDifferent= (db.namecounts.count( { value: { $gt: 1 } } ) == 0)
    db.namecounts.drop();
    return allDifferent;
}


问:
custom error type handling after receiving data from internet
I have RestManager class which is used to fetch data from Internet

```<code>class RestManager {

func fetchData<T: Decodable>(url: URL) -> AnyPublisher<T, ErrorType> {

     URLSession.shared
        .dataTaskPublisher(for: url)
        .map { $0.data }
        .decode(type: T.self, decoder: JSONDecoder())
        .mapError({ error in
            if let error = error as? URLError {
                switch error.code {
                case .notConnectedToInternet, .timedOut, .networkConnectionLost:
                    return .noInternetConnection
                case .cannotDecodeRawData, .cannotDecodeContentData:
                    return .empty
                default:
                    return .general
                }
            }
            return .general
        })
        .eraseToAnyPublisher()
}
}
</code>```

In Repository class there is function getCountriesList which, using RestManager is returning AnyPublisher<[Country], ErrorType> where ErrorType represents enum with custom cases for error handling (.noInternetConnection, .general, .empty)

```<code>class Covid19RepositoryImpl: Covid19Repository {

func getCountriesList() -> AnyPublisher<[Country], ErrorType> {
    let url = RestEndpoints.countriesList.endpoint()
    return RestManager().fetchData(url: url)
}
}
</code>```

In viewModel class, in function getAllCountries, pipeline is created for fetching and saving data in countries variable, and in .sink in completion I tried to save ErrorType (if there is any error) in specific variable called error

I tried to use like this

```<code>class CountriesViewModelImpl: CountriesViewModel {

var repository: Covid19Repository

@Published var countries: [Country] = []
@Published var error: ErrorType?
@Published var loader: Bool = true

private var cancellables: Set<AnyCancellable> = .init()

init(repository: Covid19Repository){
    self.repository = repository
    getAllCountries()
}

func getAllCountries() {

   repository
        .getCountriesList()
        .receive(on: RunLoop.main)
        .sink { error in
            self.error = error
            }
        } receiveValue: { [unowned self] newCountries in
            self.countries = newCountries
            self.error = nil
            self.loader = false
        }
        .store(in: &cancellables)
}
}
</code>```

But it returns Cannot assign value of type 'Subscribers.Completion' to type 'ErrorType'

Is there any other way I can handle error?

答:
sink returns an enum in the receiveCompletion closure with finished and failure cases

```<code>.sink { completion in
    switch completion {
        case .finished: print("finished")
        case .failure(let error): self.error = error
    }
} receiveValue: ...
</code>```

Body:
I have RestManager class which is used to fetch data from Internet

class RestManager {

func fetchData<T: Decodable>(url: URL) -> AnyPublisher<T, ErrorType> {

     URLSession.shared
        .dataTaskPublisher(for: url)
        .map { $0.data }
        .decode(type: T.self, decoder: JSONDecoder())
        .mapError({ error in
            if let error = error as? URLError {
                switch error.code {
                case .notConnectedToInternet, .timedOut, .networkConnectionLost:
                    return .noInternetConnection
                case .cannotDecodeRawData, .cannotDecodeContentData:
                    return .empty
                default:
                    return .general
                }
            }
            return .general
        })
        .eraseToAnyPublisher()
}
}

In Repository class there is function getCountriesList which, using RestManager is returning AnyPublisher<[Country], ErrorType> where ErrorType represents enum with custom cases for error handling (.noInternetConnection, .general, .empty)

class Covid19RepositoryImpl: Covid19Repository {

func getCountriesList() -> AnyPublisher<[Country], ErrorType> {
    let url = RestEndpoints.countriesList.endpoint()
    return RestManager().fetchData(url: url)
}
}

In viewModel class, in function getAllCountries, pipeline is created for fetching and saving data in countries variable, and in .sink in completion I tried to save ErrorType (if there is any error) in specific variable called error

I tried to use like this

class CountriesViewModelImpl: CountriesViewModel {

var repository: Covid19Repository

@Published var countries: [Country] = []
@Published var error: ErrorType?
@Published var loader: Bool = true

private var cancellables: Set<AnyCancellable> = .init()

init(repository: Covid19Repository){
    self.repository = repository
    getAllCountries()
}

func getAllCountries() {

   repository
        .getCountriesList()
        .receive(on: RunLoop.main)
        .sink { error in
            self.error = error
            }
        } receiveValue: { [unowned self] newCountries in
            self.countries = newCountries
            self.error = nil
            self.loader = false
        }
        .store(in: &cancellables)
}
}

But it returns Cannot assign value of type 'Subscribers.Completion' to type 'ErrorType'

Is there any other way I can handle error?

Body:
sink returns an enum in the receiveCompletion closure with finished and failure cases

.sink { completion in
    switch completion {
        case .finished: print("finished")
        case .failure(let error): self.error = error
    }
} receiveValue: ...


问:
SharedPreferences behaviour on Update/Uninstall
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

```<code>public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
</code>```

答:
try to listen this Intents:

```ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_DATA_CLEARED
ACTION_PACKAGE_FIRST_LAUNCH
ACTION_PACKAGE_INSTALL
ACTION_PACKAGE_REMOVED
ACTION_PACKAGE_REPLACED
ACTION_PACKAGE_RESTARTED```

more on: http://developer.android.com/reference/android/content/Intent.html#ACTION_PACKAGE_ADDED

Body:
I am using shared preferences to store the number of times my application has been launched. Only on the first launch i display an Welcome message telling the user about the new features and changes in that version.

But as i absorbed on reinstalling the app or upgrading the application i am not able to remove the previous shared preferences. i would like to get the dialog when i reinstall the software or upgrade it too.

AppLauncher

public class AppLauncher {
    static long launch_count = 0;
    private static boolean isLaunch = false;

    public static void app_launched(Context mContext) {
        System.out.println("I m in AppLauncher");
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) {
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter

        launch_count = prefs.getLong("launch_count", 0);
        editor.putLong("launch_count", launch_count);

        System.out.println("launch_count=" + launch_count);
        if (launch_count == 0 || launch_count == 1) {
            // showLaunchDialog(mContext);
            isLaunch = true;
        }
        if (isLaunch == true) {
            showLaunchDialog(mContext);
            isLaunch = false;
        }
        editor.commit();
    }

    public static void showLaunchDialog(Context mcontext) {
        final Dialog dialog = new Dialog(mcontext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.whatsnew);

        Button dismisButton = (Button) dialog.findViewById(R.id.dismisButtom);
        System.out.println("inside dialog_started");
        dismisButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}

Body:
try to listen this Intents:

ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_DATA_CLEARED
ACTION_PACKAGE_FIRST_LAUNCH
ACTION_PACKAGE_INSTALL
ACTION_PACKAGE_REMOVED
ACTION_PACKAGE_REPLACED
ACTION_PACKAGE_RESTARTED

more on: http://developer.android.com/reference/android/content/Intent.html#ACTION_PACKAGE_ADDED


问:
How to use natsort in different language?
I'm trying to sort an array using natsort/natcasesort. But I'm having trouble with non-English (In Turkish) characters. This is the only option that works for me at the moment. How can I overcome this problem?
For example, the array looks like this:

```<code>   $texts= array("A","Ü","Ç","Ş","Ğ");
    natcasesort($texts);
    echo '```'; print_r($files); echo '```';
</code>```

Output:

```<code>Array
(
    [0] => A
    [2] => Ç
    [1] => Ü
    [4] => Ğ
    [3] => Ş
)

$all_characters = [ "ğ", "Ğ", "ç", "Ç", "ş", "Ş", "ü", "Ü", "ö", "Ö", "ı", "İ" ];

$alphabet_all = "AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz";
$small_letters = array("İ","I","Ş","Ğ","Ö","Ü","Ç");
$capital_letters = array("i","ı","ş","ğ","ö","ü","ç");
</code>```

How should it be ?

A, Ç, Ğ, Ş, Ü

答:
Natsort is not suitable for language-specific sorting. That's what the Collator class is for.</p>
```<code>$all_characters = [ "ğ", "Ğ", "ç", "Ç", "ş", "Ş", "ü", "Ü", "ö", "Ö", "ı", "İ" ];

$collator = new Collator('tr_TR');

//The following line is only required if natsort is desired
$collator->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);

$collator->sort($all_characters);

echo implode(', ',$all_characters);
//ç, Ç, ğ, Ğ, ı, İ, ö, Ö, ş, Ş, ü, Ü
</code>```

Body:
I'm trying to sort an array using natsort/natcasesort. But I'm having trouble with non-English (In Turkish) characters. This is the only option that works for me at the moment. How can I overcome this problem?
For example, the array looks like this:

   $texts= array("A","Ü","Ç","Ş","Ğ");
    natcasesort($texts);
    echo '
'; print_r($files); echo '
';

Output:

Array
(
    [0] => A
    [2] => Ç
    [1] => Ü
    [4] => Ğ
    [3] => Ş
)

$all_characters = [ "ğ", "Ğ", "ç", "Ç", "ş", "Ş", "ü", "Ü", "ö", "Ö", "ı", "İ" ];

$alphabet_all = "AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz";
$small_letters = array("İ","I","Ş","Ğ","Ö","Ü","Ç");
$capital_letters = array("i","ı","ş","ğ","ö","ü","ç");

How should it be ?

A, Ç, Ğ, Ş, Ü

Body:
Natsort is not suitable for language-specific sorting. That's what the Collator class is for.

$all_characters = [ "ğ", "Ğ", "ç", "Ç", "ş", "Ş", "ü", "Ü", "ö", "Ö", "ı", "İ" ];

$collator = new Collator('tr_TR');

//The following line is only required if natsort is desired
$collator->setAttribute(Collator::NUMERIC_COLLATION, Collator::ON);

$collator->sort($all_characters);

echo implode(', ',$all_characters);
//ç, Ç, ğ, Ğ, ı, İ, ö, Ö, ş, Ş, ü, Ü