问:
Add custome text after price in woocommerce product page
I am working on salient theme for my E-commerce website. I want to show "B" after price in woocommerce product page.
The page displays like "$99,99"

I want to make it displays like this: "$99,99 TEXT"

I have the code for it :

```<code>function change_product_price( $price ) {
    $price .= ' TEXT';
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
</code>```

Now I want to know where to add the code in woo-commerce directory. Any help would be appreciated.

thanks

答:
Add this code inside functions.php of your theme:

```<code>function cw_change_product_price_display( $price ) {
    $price .= ' TEXT';
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );
</code>```

Body:
I am working on salient theme for my E-commerce website. I want to show "B" after price in woocommerce product page.
The page displays like "$99,99"

I want to make it displays like this: "$99,99 TEXT"

I have the code for it :

function change_product_price( $price ) {
    $price .= ' TEXT';
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );

Now I want to know where to add the code in woo-commerce directory. Any help would be appreciated.

thanks

Body:
Add this code inside functions.php of your theme:

function cw_change_product_price_display( $price ) {
    $price .= ' TEXT';
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );


来源: stackexchange

问:
How to disable HTTPS or change to HTTP in dev and prod version on symfony?
My problem is like in the title.

 In my project i tried to add HTTPS to /login and /admin routes. Both routes are imported from third party bundles: login from FOSUserBundle and admin from EasyAdminBundle. To achieve that I added requires_channel: https to the security.yml file, like it was described in this thread https://symfony.com/doc/current/security/force_https.html.

 My access_control section looked like:

```<code>access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: https }
</code>```

 I started the site through built-in server to check if it will force https connection and it was. Obviously there was an error because symfony built-in server doesn't support ssl connections but in the address bar there was https://. I uploaded this version to the server and I wanted to continue working on the next functionality, so I deleted the requires_channel entry but when I launch the page by typing php bin/console server:start 0.0.0.0:80 and typing in the browser address bar localhost/admin symphony still forces https. My next guess was to change requires_channel: https to requires_channel: http but that did not work either.

 The same happens on the production server, ie HTTPS is still enforced when requires_channel is removed or set to HTTP, but there i can live with that because in the end i will have to generate certificate and launch ssl connection in apache config files, but I can't work on dev version.

 I looked for similar issues but mostly if threads was about symfony and HTTP or HTTPS, people asks how to force HTTPS but this I already did. I can't find similar problem to mine so please if someone have any idea what goes wrong feel free to response or if anyone already solved my problem or very similar one please paste links.

Full content of security.yml file:

```<code>security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: "%router.request_context.scheme%" }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: "%router.request_context.scheme%" }
</code>```

答:
Finally I managed to find solution for my problem.

 As I suspected there was some data in system and browser cache, although I was clearing symfony cache, there still was some forcing https:// on login and admin routes.

 What I done is clearing all possible cache using BleachBit, and now it works as it should.

 Thank you all, for your time.

ContentLicense: CC BY-SA 3.0

Body:
My problem is like in the title.

 In my project i tried to add HTTPS to /login and /admin routes. Both routes are imported from third party bundles: login from FOSUserBundle and admin from EasyAdminBundle. To achieve that I added requires_channel: https to the security.yml file, like it was described in this thread https://symfony.com/doc/current/security/force_https.html.

 My access_control section looked like:

access_control:
    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: https }

 I started the site through built-in server to check if it will force https connection and it was. Obviously there was an error because symfony built-in server doesn't support ssl connections but in the address bar there was https://. I uploaded this version to the server and I wanted to continue working on the next functionality, so I deleted the requires_channel entry but when I launch the page by typing php bin/console server:start 0.0.0.0:80 and typing in the browser address bar localhost/admin symphony still forces https. My next guess was to change requires_channel: https to requires_channel: http but that did not work either.

 The same happens on the production server, ie HTTPS is still enforced when requires_channel is removed or set to HTTP, but there i can live with that because in the end i will have to generate certificate and launch ssl connection in apache config files, but I can't work on dev version.

 I looked for similar issues but mostly if threads was about symfony and HTTP or HTTPS, people asks how to force HTTPS but this I already did. I can't find similar problem to mine so please if someone have any idea what goes wrong feel free to response or if anyone already solved my problem or very similar one please paste links.

Full content of security.yml file:

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: "%router.request_context.scheme%" }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN, requires_channel: "%router.request_context.scheme%" }


问:
regroup rows by value in a table and return a counter of the line collapsed
i'm stuck with this little problem:

df sample

i want to collapse the column UnstableDependenciesPackage and i know i can do it with the function group_by

```<code>UD %>% group_by(UnstableDependenciesPackage, version, project, Type)
</code>```

the problem is that i want to summarize those occurences in the NumBadDep column, so i'll get for example:

```<code>org.apache.tools.ant.util - 1

org.apache.tools.ant.taskdefs - 3

org.apache.tools.ant.types - 2
</code>```

and so on. But i miss the second step of my instruction

答:
To get a count of occurrences for each unique combination of UnstableDependenciesPackage, version, project, Type you could use summarize and the n() function.

UD %>% group_by(UnstableDependenciesPackage, version, project, Type) %>% summarize(count = n())

Body:
i'm stuck with this little problem:

df sample

i want to collapse the column UnstableDependenciesPackage and i know i can do it with the function group_by

UD %>% group_by(UnstableDependenciesPackage, version, project, Type)

the problem is that i want to summarize those occurences in the NumBadDep column, so i'll get for example:

org.apache.tools.ant.util - 1

org.apache.tools.ant.taskdefs - 3

org.apache.tools.ant.types - 2

and so on. But i miss the second step of my instruction


问:
Hibernate Envers: Better way to add multiple Projections
I want to add projections on selected fields as I can not pass whole result list.
I am doing this to achieve the same.

```<code>List resultList = reader.createQuery()
            .forRevisionsOfEntity(MyAsset.class, false, true)
            .add(AuditEntity.id().eq(assetId))
            .add(AuditEntity.property("quantity").hasChanged())
            .addOrder(AuditEntity.revisionNumber().asc())
            .addProjection(AuditEntity.property("updatedAt", "updatedAt"))
            .addProjection(AuditEntity.property("updatedBy", "updatedBy"))
            .addProjection(AuditEntity.property("quantity", "quantity"))
            .getResultList();
</code>```

Is there any better way to do the same? Something like Custom Projections.

Thanks in advance.

答:
There is no alternative other than what you've shown for adding projections.

If you have an idea on how to improve this, you're welcomed to open a RFE here and supply your ideas on how you'd like to see it enhanced.  If you have the time, you're also welcomed to submit a workable solution via  PR and we can review it and offer some input.

Body:
I want to add projections on selected fields as I can not pass whole result list.
I am doing this to achieve the same.

List resultList = reader.createQuery()
            .forRevisionsOfEntity(MyAsset.class, false, true)
            .add(AuditEntity.id().eq(assetId))
            .add(AuditEntity.property("quantity").hasChanged())
            .addOrder(AuditEntity.revisionNumber().asc())
            .addProjection(AuditEntity.property("updatedAt", "updatedAt"))
            .addProjection(AuditEntity.property("updatedBy", "updatedBy"))
            .addProjection(AuditEntity.property("quantity", "quantity"))
            .getResultList();

Is there any better way to do the same? Something like Custom Projections.

Thanks in advance.


问:
Is there a way to manually control the pagename in WordPress?
I'm working on a bilingual website for a client, offering both English and French. I'm using the qTranslate plugin for the content, which is working great. However the client is requesting the the URLs need to be translated into French as well.

http://englishdomain.com/users

http://frenchdomain.com/utilisateurs

In the example URLs above, 'utilisateurs' needs to use the same page in the admin as 'users'. I already have support for englishdomain.com and frenchdomain.com working. I just need to find a way to tell WordPress to use the 'users' page when the pagename is 'utilisateurs'.

There are a lot of sections in this site, so I was thinking about setting up an array of all the English => French matches and then validating from there.

答:
It's tricky. You can look at a plugin like WPML, but I don't think any of them will do what you want.

One possibility to explore is to use Urban Giraffe's Redirection plugin:

http://urbangiraffe.com/plugins/redirection/

There is a "pass through" action that can be used to do what you want. You would have to define redirection rules for each page, but it should do the trick.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Using a custom BottomSheetDialog class means I can't touchOutside to cancel
So I made a custom class that does basically nothing except boilerplate code plus customizing the callback. For whatever reason, I can't seem to make it cancel when I touch outside the bounds of the bottom sheet.

```<code>public class CustomBottomSheetDialog extends AppCompatDialog {

public CustomBottomSheetDialog(Context context) {
    super(context, R.style.Theme_Design_Light_BottomSheetDialog);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

@Override
public void setContentView(View view) {
    final CoordinatorLayout coordinator = (CoordinatorLayout) View.inflate(getContext(),
            R.layout.design_bottom_sheet_dialog, null);
    FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);
    BottomSheetBehavior.from(bottomSheet).setBottomSheetCallback(mBottomSheetCallback);
    bottomSheet.addView(view);
    super.setContentView(coordinator);
}

private BottomSheetBehavior.BottomSheetCallback mBottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_HIDDEN) {
            cancel(); // The only not boilerplate code here, woo
        }
    }

    @Override
    public void onSlide(View bottomSheet, float slideOffset) { }
};
</code>```

Things I've tried:

bottomSheetDialog.setCancelable(true);

bottomSheetDialog.setCanceledOnTouchOutside(true);

Overriding dispatchTouchEvent, but I can't get the rectangle to equal anything besides the size of the entire screen.

If I don't use the custom class (ie simply change my CustomBottomSheetDialog call to just BottomSheetDialog), I get the cancel on touch outside, but then I don't get a cancel when I drag to hide the dialog, which I am required to have.

答:
Finally got it. In the onCreate, I added a single line of code to find the touch_outside view and add a click listener to cancel the dialog. The touch_outside view is generated by default. I did not need to add it in my bottom sheet's XML.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    findViewById(R.id.touch_outside).setOnClickListener(v -> cancel()); // <--- this guy
    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
</code>```

Thanks goes to this tutorial.

Body:
So I made a custom class that does basically nothing except boilerplate code plus customizing the callback. For whatever reason, I can't seem to make it cancel when I touch outside the bounds of the bottom sheet.

public class CustomBottomSheetDialog extends AppCompatDialog {

public CustomBottomSheetDialog(Context context) {
    super(context, R.style.Theme_Design_Light_BottomSheetDialog);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

@Override
public void setContentView(View view) {
    final CoordinatorLayout coordinator = (CoordinatorLayout) View.inflate(getContext(),
            R.layout.design_bottom_sheet_dialog, null);
    FrameLayout bottomSheet = (FrameLayout) coordinator.findViewById(R.id.design_bottom_sheet);
    BottomSheetBehavior.from(bottomSheet).setBottomSheetCallback(mBottomSheetCallback);
    bottomSheet.addView(view);
    super.setContentView(coordinator);
}

private BottomSheetBehavior.BottomSheetCallback mBottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(View bottomSheet, int newState) {
        if (newState == BottomSheetBehavior.STATE_HIDDEN) {
            cancel(); // The only not boilerplate code here, woo
        }
    }

    @Override
    public void onSlide(View bottomSheet, float slideOffset) { }
};

Things I've tried:

bottomSheetDialog.setCancelable(true);

bottomSheetDialog.setCanceledOnTouchOutside(true);

Overriding dispatchTouchEvent, but I can't get the rectangle to equal anything besides the size of the entire screen.

If I don't use the custom class (ie simply change my CustomBottomSheetDialog call to just BottomSheetDialog), I get the cancel on touch outside, but then I don't get a cancel when I drag to hide the dialog, which I am required to have.

Body:
Finally got it. In the onCreate, I added a single line of code to find the touch_outside view and add a click listener to cancel the dialog. The touch_outside view is generated by default. I did not need to add it in my bottom sheet's XML.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    findViewById(R.id.touch_outside).setOnClickListener(v -> cancel()); // <--- this guy
    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

Thanks goes to this tutorial.


问:
QML TextArea scroll events
Is there a way to know when TextArea scroll has reached the top or bottom? I want to implement dynamic text loading in a chat client: when the user scrolls to the top, more text is added to the document. Something like this (pseudo-code):

```<code>import QtQuick 2.4
import QtQuick.Controls 1.2

TextArea {
      id: chat
      onScrolledToTop: text = loadMoreText() + text
}
</code>```

答:
```<code>ScrollView {
        width: root.width - ((root.width/10) * 2) - (root.width/15)*2
        x:  (root.width/10) + root.width/15
        height: root.height - (root.height/5)
        clip: true

        TextArea {
            id: textArea
            clip: true
            width: root.width - ((root.width/10) * 2) - (root.width/15)*2
            height: root.height - (root.height/5)
            wrapMode: "WrapAtWordBoundaryOrAnywhere"
            placeholderText: "inter description"
        }
    }
</code>```

Title: QML TextArea scroll events

Body:
Is there a way to know when TextArea scroll has reached the top or bottom? I want to implement dynamic text loading in a chat client: when the user scrolls to the top, more text is added to the document. Something like this (pseudo-code):

import QtQuick 2.4
import QtQuick.Controls 1.2

TextArea {
      id: chat
      onScrolledToTop: text = loadMoreText() + text
}


问:
VSTS Test Assemblies - No test assemblies found
I'm attempting to run some selenium tests in my solution that are in a project called SA.SEPA.Web.UI.Selenium as part of a build definition in VSTS, but it is failing to run the Visual Studio Test task with the error...

No test assemblies found matching the pattern: **\*Selenium*.dll.

Search folder is set to - $(System.DefaultWorkingDirectory)

Preceding tasks are a nuget restore and build solution

Can anyone help?

答:
You are specifying $(System.DefaultWorkingDirectory) as the search folder. By default (unless overridden), this points to the Source folder on the Agent.
If you are instructing MSBuild (using the OutDir parameter) to output your assemblies in a specific location then you should use that location.

Edit: If this is an On-premises Agent, it should also be running in interactive mode (not service) if you want to execute any UI tests


问:
How can I declare a function or variable in a file and use it always in Swift
Currently I am working on a project and I have to use an alert message almost in every view controller. Particularly this one:

```<code>func showMessage(myMessage: String) {
    let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}
</code>```

Using the same code over an over again makes my code verbose. This scenario goes with some other functions and some variables also. How can I declare this function somewhere in a different file and use it whenever necessary? Shall I use a singleton pattern like:

```<code>static let sharedInstance = viewController()
</code>```

If so, please show me an example.

答:
The best way to do this is using an extension such as:

```<code>extension UIViewController {
    func showMessage(myMessage: String) {
        let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
        myAlert.addAction(okAction)
        self.present(myAlert, animated: true, completion: nil)
    }
}
</code>```

This way you can use it in any class subclassed from UIViewController.  You could also just drop the function into a swift file as a "global function" but that's not very clean.

Body:
Currently I am working on a project and I have to use an alert message almost in every view controller. Particularly this one:

func showMessage(myMessage: String) {
    let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}

Using the same code over an over again makes my code verbose. This scenario goes with some other functions and some variables also. How can I declare this function somewhere in a different file and use it whenever necessary? Shall I use a singleton pattern like:

static let sharedInstance = viewController()

If so, please show me an example.

Body:
The best way to do this is using an extension such as:

extension UIViewController {
    func showMessage(myMessage: String) {
        let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
        myAlert.addAction(okAction)
        self.present(myAlert, animated: true, completion: nil)
    }
}

This way you can use it in any class subclassed from UIViewController.  You could also just drop the function into a swift file as a "global function" but that's not very clean.


问:
How to handle exception the right way in c# console app
I have a small console app which will be scheduled on different intervals of the day, this console app will download files from ftp.
I have a class called BatchProcessor, which is downloading the files from the ftp, unzipping them based on the vendor type putting them into the different vendors folder and later reading and storing into SQL Server database.

I need some advice that what I am doing is right or wrong because I need to catch exception almost at any stage....

Here is the code skeleton.
Program.cs

```<code> class Program
    {
        static void Main(string[] args)
        {
var batchProcessor = new BatchProcessor();
            batchProcessor.Start();
        }
    }
</code>```

This is the BatchProcessor class

```<code>public class BatchProcessor
{
    public bool Start()
    {
        try
        {
            var result = Connect();
            if (!result) return false;

            result = SearchLatestFiles();
            if (!result) return false;

            result = DownloadFiles();
            if (!result) return false;
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool Connect()
    {
        try
        {
            // 1. Connect to FTP
        }
        catch (Exception)
        {
            throw;
        }

    }

    public bool SearchLatestFiles()
    {
        try
        {
            // 1. Look for the latest fils
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool DownloadFiles()
    {
        try
        {
            // 1. Latest files found so download them.
        }
        catch (Exception)
        {

            throw;
        }

    }
}
</code>```

答:
Since the application will be running unattended, your best way to diagnose errors is to deploy some kind of logging. I would recommend to use log4net available as a Nuget package. It is easy to install and configure and before throwing an error you should log error message and stack.
Good practice to review these logs daily.
One more thing: You are throwing cough errors in your class, but main  does not handle these errors - it will lead to app crash and abnormal termination.

Good luck

Body:
I have a small console app which will be scheduled on different intervals of the day, this console app will download files from ftp.
I have a class called BatchProcessor, which is downloading the files from the ftp, unzipping them based on the vendor type putting them into the different vendors folder and later reading and storing into SQL Server database.

I need some advice that what I am doing is right or wrong because I need to catch exception almost at any stage....

Here is the code skeleton.
Program.cs

 class Program
    {
        static void Main(string[] args)
        {
var batchProcessor = new BatchProcessor();
            batchProcessor.Start();
        }
    }

This is the BatchProcessor class

public class BatchProcessor
{
    public bool Start()
    {
        try
        {
            var result = Connect();
            if (!result) return false;

            result = SearchLatestFiles();
            if (!result) return false;

            result = DownloadFiles();
            if (!result) return false;
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool Connect()
    {
        try
        {
            // 1. Connect to FTP
        }
        catch (Exception)
        {
            throw;
        }

    }

    public bool SearchLatestFiles()
    {
        try
        {
            // 1. Look for the latest fils
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool DownloadFiles()
    {
        try
        {
            // 1. Latest files found so download them.
        }
        catch (Exception)
        {

            throw;
        }

    }
}


问:
Pivot in pandas creates issues with indexing
Pivoting a dataframe in pandas creates an annoying index over the column. reset_index() does not seem to get rid of the issue. Could someone help me proceed. The codebase and what I see currently are listed below

```<code>import pandas as pd

products = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'],
                    'store': ['Walmart', 'Dia', 'Walmart', 'Fnac', 'Dia','Walmart'],
                    'price':[11.42, 23.50, 19.99, 15.95, 55.75, 111.55],
                    'testscore': [4, 3, 5, 7, 5, 8]})

pivot_products = products.pivot(index='category', columns='store', values='price')

print(pivot_products)
</code>```

Running this code block provides the output as

```<code>store            Dia   Fnac  Walmart
category
Cleaning       23.50    NaN    11.42
Entertainment    NaN  15.95    19.99
Tech           55.75    NaN   111.55
</code>```

when I reset index on pivot_products, it provides

```<code>store       category    Dia   Fnac  Walmart
 0           Cleaning  23.50    NaN    11.42
 1      Entertainment    NaN  15.95    19.99
 2               Tech  55.75    NaN   111.55
</code>```

I really don't want the store column which shows up here - it does not capture any relevant data and ends up holding garbage values. Any ideas?

答:
store isn't a column.  It's the name of the columns object.  Use pd.DataFrame.rename_axis

```<code>pivot_products.rename_axis(None, 1)

                 Dia   Fnac  Walmart
category
Cleaning       23.50    NaN    11.42
Entertainment    NaN  15.95    19.99
Tech           55.75    NaN   111.55
</code>```

Body:
Pivoting a dataframe in pandas creates an annoying index over the column. reset_index() does not seem to get rid of the issue. Could someone help me proceed. The codebase and what I see currently are listed below

import pandas as pd

products = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'],
                    'store': ['Walmart', 'Dia', 'Walmart', 'Fnac', 'Dia','Walmart'],
                    'price':[11.42, 23.50, 19.99, 15.95, 55.75, 111.55],
                    'testscore': [4, 3, 5, 7, 5, 8]})

pivot_products = products.pivot(index='category', columns='store', values='price')

print(pivot_products)

Running this code block provides the output as

store            Dia   Fnac  Walmart
category
Cleaning       23.50    NaN    11.42
Entertainment    NaN  15.95    19.99
Tech           55.75    NaN   111.55

when I reset index on pivot_products, it provides

store       category    Dia   Fnac  Walmart
 0           Cleaning  23.50    NaN    11.42
 1      Entertainment    NaN  15.95    19.99
 2               Tech  55.75    NaN   111.55

I really don't want the store column which shows up here - it does not capture any relevant data and ends up holding garbage values. Any ideas?

Body:
store isn't a column.  It's the name of the columns object.  Use pd.DataFrame.rename_axis

pivot_products.rename_axis(None, 1)

                 Dia   Fnac  Walmart
category
Cleaning       23.50    NaN    11.42
Entertainment    NaN  15.95    19.99
Tech           55.75    NaN   111.55


问:
Selenium internal server error cause by captureNetworkTraffic()?
Essentially, I'm spawning a multitude of selenium client instances which all connect to one selenium server.

Running about 20 at one time works perfectly fine on my box.

I then added a feature that uses the captureNetworkTraffic() method to read the network traffic as JSON so that I can log the stats to each instance's respective run log.

And now, suddenly, if I run anymore than maybe 3 or 4 at one time, they nearly all fail with a lovely "Internal Selenium Server Error"!

I have done several different tries (with different browsers) both with and without the network stats info being logged, and they all point to the same conclusion: I can't run more than 3 or 4 with this feature.

Does anyone perhaps know why this is? I know for sure this is the cause of the failures too for I've isolated the failure to just this single line of code.

Thank you

答:
I've found the culprit: java.util.ConcurrentModificationException

According to this support post, the internal ArrayList handling the network traffic statistics isn't syncronized, and is sometimes trying to be concurrently modified, i.e. when you're attempting to run 40 different clients at one time!


问:
Pick out specific, optional key from metavalues object in JSON and store into my class
I'm struggling to make this conversion happen, and not sure it's entirely feasible.  My JSON from a third party could look like this:

```<code>{
"equipments": [
    {
        "serialNumber": "11-17-053",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1508856453875,
        "fieldOffice_id": "594af5425fbfca00111a0c20",
        "clients_id": [],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33121
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            }
        },
        "schedules": [],
        "id": "59ef52854d40a9009c787596"
    },
    {
        "serialNumber": "11-17-054",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1508856453875,
        "fieldOffice_id": "594af5425fbfca00111a0c20",
        "clients_id": [],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33121
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            }
        },
        "schedules": [],
        "id": "59ef52854d40a9009c787597"
    },
    {
        "serialNumber": "8-17-022",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1505326964589,
        "fieldOffice_id": "594af5425fbfca00111a0c20",
        "clients_id": [],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33121
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            }
        },
        "schedules": [],
        "id": "59b9777480e426009d01d48d"
    },
    {
        "serialNumber": "22A-17-001",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1504908025733,
        "fieldOffice_id": "58b74b080c206710004ff726",
        "clients_id": [
            "59bbfdf5725cd00012fb15d8"
        ],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33122
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            },
            "g99idmcqyuo2na9e6l": "YARD",
            "709pm94prt2tpjt90y": 5,
            "bgen1h4i5b6f8xa1kh": "9/8/2017 7:18:24 PM",
            "yvtvsl8dedudqjtdud": "0.00000, 0.00000",
            "aj3h2b5fdbic9s72m3": "Parex",
            "8wt1re82xidjiv8rzi": "YARD"
        },
        "schedules": [],
        "id": "59b312f93256d5009c4a73fb"
    },....
</code>```

This is obviously not a complete example, but should help get my question across.

Is there a way to create a C# class that pulls in certain fields only if they exist from the "metavalues" array?

My current class is as follows which works to get the data, but not exactly how I want.

```<code>public class Equipment
{
    [JsonProperty("serialNumber")]
    public string SerialNumber { get; set; }
    public string equipmentType_id { get; set; }
    public bool isInService { get; set; }
    public List<string> clients_Id { get; set; }
    public string fieldOffice_id { get; set; }
    [JsonProperty("id")]
    public string EquipmentId { get; set; }
    [JsonProperty("metavalues")]
    public Dictionary<string, object> metavalues { get; set; }
}
</code>```

What I'm after, is taking the key of "g99idmcqyuo2na9e6l" which is optional in the metavalues, and store it in a property called "LeaseName".

I tried the following to no avail.

```<code>    public class Equipment
    {
        [JsonProperty("serialNumber")]
        public string SerialNumber { get; set; }
        public string equipmentType_id { get; set; }
        public bool isInService { get; set; }
        public List<string> clients_Id { get; set; }
        public string fieldOffice_id { get; set; }
        [JsonProperty("id")]
        public string EquipmentId { get; set; }
        [JsonProperty("g99idmcqyuo2na9e6l")]
        public string LeaseName { get; set; }
    }
</code>```

If I try to make a class for the metavalues section, I get an exception indicating that JSON.NET can't convert it to my object, hence why I used the Dictionary<string, object> option.

EDIT # 1:  The accepted answer works for me, but for those who stumble upon this and truly need a property name from a nested array you could try the following.

```<code>[OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            if (metavalues != null)
            {
                if (metavalues.ContainsKey("g99idmcqyuo2na9e6l"))
                {
                    string _LeaseName = (string)metavalues["g99idmcqyuo2na9e6l"];
                    LeaseName = _LeaseName;
                }
            }
        }
</code>```

I think my edit approach is a bit overkill but just throwing this out there.

答:
Yes, this is possible, but since the lease value is still one level down in the JSON you need an intermediate class to hold it (to replace the dictionary).

```<code>public class Equipment
{
    ...
    [JsonProperty("metavalues")]
    public MetaValues MetaValues { get; set; }
}

public class MetaValues
{
    [JsonProperty("g99idmcqyuo2na9e6l")]
    public string LeaseName { get; set; }
}
</code>```

Fiddle: https://dotnetfiddle.net/Ddqzc7

Body:
I'm struggling to make this conversion happen, and not sure it's entirely feasible.  My JSON from a third party could look like this:

{
"equipments": [
    {
        "serialNumber": "11-17-053",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1508856453875,
        "fieldOffice_id": "594af5425fbfca00111a0c20",
        "clients_id": [],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33121
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            }
        },
        "schedules": [],
        "id": "59ef52854d40a9009c787596"
    },
    {
        "serialNumber": "11-17-054",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1508856453875,
        "fieldOffice_id": "594af5425fbfca00111a0c20",
        "clients_id": [],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33121
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            }
        },
        "schedules": [],
        "id": "59ef52854d40a9009c787597"
    },
    {
        "serialNumber": "8-17-022",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1505326964589,
        "fieldOffice_id": "594af5425fbfca00111a0c20",
        "clients_id": [],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33121
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            }
        },
        "schedules": [],
        "id": "59b9777480e426009d01d48d"
    },
    {
        "serialNumber": "22A-17-001",
        "equipmentType_id": "589dda4952172110008870c7",
        "created": 1504908025733,
        "fieldOffice_id": "58b74b080c206710004ff726",
        "clients_id": [
            "59bbfdf5725cd00012fb15d8"
        ],
        "notes": "",
        "isInService": true,
        "metavalues": {
            "0t78nzhp9w265avlvt": {
                "item_ids": [
                    33122
                ]
            },
            "7ogz4kehqh8h3cwip8": {
                "item_ids": [
                    33128
                ]
            },
            "g99idmcqyuo2na9e6l": "YARD",
            "709pm94prt2tpjt90y": 5,
            "bgen1h4i5b6f8xa1kh": "9/8/2017 7:18:24 PM",
            "yvtvsl8dedudqjtdud": "0.00000, 0.00000",
            "aj3h2b5fdbic9s72m3": "Parex",
            "8wt1re82xidjiv8rzi": "YARD"
        },
        "schedules": [],
        "id": "59b312f93256d5009c4a73fb"
    },....

This is obviously not a complete example, but should help get my question across.

Is there a way to create a C# class that pulls in certain fields only if they exist from the "metavalues" array?

My current class is as follows which works to get the data, but not exactly how I want.

public class Equipment
{
    [JsonProperty("serialNumber")]
    public string SerialNumber { get; set; }
    public string equipmentType_id { get; set; }
    public bool isInService { get; set; }
    public List<string> clients_Id { get; set; }
    public string fieldOffice_id { get; set; }
    [JsonProperty("id")]
    public string EquipmentId { get; set; }
    [JsonProperty("metavalues")]
    public Dictionary<string, object> metavalues { get; set; }
}

What I'm after, is taking the key of "g99idmcqyuo2na9e6l" which is optional in the metavalues, and store it in a property called "LeaseName".

I tried the following to no avail.

    public class Equipment
    {
        [JsonProperty("serialNumber")]
        public string SerialNumber { get; set; }
        public string equipmentType_id { get; set; }
        public bool isInService { get; set; }
        public List<string> clients_Id { get; set; }
        public string fieldOffice_id { get; set; }
        [JsonProperty("id")]
        public string EquipmentId { get; set; }
        [JsonProperty("g99idmcqyuo2na9e6l")]
        public string LeaseName { get; set; }
    }

If I try to make a class for the metavalues section, I get an exception indicating that JSON.NET can't convert it to my object, hence why I used the Dictionary<string, object> option.

EDIT # 1:  The accepted answer works for me, but for those who stumble upon this and truly need a property name from a nested array you could try the following.

[OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            if (metavalues != null)
            {
                if (metavalues.ContainsKey("g99idmcqyuo2na9e6l"))
                {
                    string _LeaseName = (string)metavalues["g99idmcqyuo2na9e6l"];
                    LeaseName = _LeaseName;
                }
            }
        }

I think my edit approach is a bit overkill but just throwing this out there.

Body:
Yes, this is possible, but since the lease value is still one level down in the JSON you need an intermediate class to hold it (to replace the dictionary).

public class Equipment
{
    ...
    [JsonProperty("metavalues")]
    public MetaValues MetaValues { get; set; }
}

public class MetaValues
{
    [JsonProperty("g99idmcqyuo2na9e6l")]
    public string LeaseName { get; set; }
}

Fiddle: https://dotnetfiddle.net/Ddqzc7


问:
Wrong text encoding returned when query from PostgreSQL database using RPostgreSQL
I used R and DBI to query data from a PostgreSQL but got corrupted results with weird characters. I check both server encoding and client encoding, and they are all UTF-8. Here's what I did

Connect to the db

library(DBI)

conn <- dbConnect(
    drv = RPostgreSQL::PostgreSQL(),
    host = *,
    dbname = ,
    user = ,
    password = *
)

Fetch the result

result_df <- dbGetQuery(
        conn,
        "select description
        from some_table
        where user_id = 1234"
    )

Result
What I got is ã¯ã˜ã‚ã¾ã—ã¦1008(ã¨ãƒ¼ã‚„orã¨ã…ãƒ¼ã‚„)ã¨ã„ã„ã¾ã™ã€‚ è¡¨ç¾ã™ã‚‹ã®ãŒå¤§å¥½ããªåã§ã™!! æ„Ÿæ€§ãŒäººã¨ã‚ºãƒ¬ã¦ã¾ã™(ç¬‘) ãŠæŒã‚’ã‚‚ã£ã¨ã†ã¾ããªã‚ŠãŸã„ã§ã™ã€‚
while the actual text is はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。

I test again by reading the text and then print it back

```<code>x <- 'はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。'
print(x)
>> はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。
</code>```

There's nothing wrong with the encoding in this case, so I think the problem happened when the data is returned from the database into R, but I don't know how to fix it.

答:
RPostgreSQL does not set string encodings properly, see this issue.

So in the meantime you have to declare the encoding yourself. With
dplyr, you can do it like this:

suppressPackageStartupMessages({
  library(dplyr)
  library(RPostgreSQL)
})

my_con <-
  dbConnect(
    PostgreSQL(),
    user = my_username,
    password = my_password,
    host = my_host,
    dbname = my_dbname
  )

my_table <- tribble(
  ~user_id,    ~description,
  "1234",     "はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。"
)

copy_to(my_con, my_table)

result_df <- dbGetQuery(my_con, "SELECT description FROM my_table WHERE user_id = '1234'" )

declare_utf8 <- function(x) {
  Encoding(x) <- "UTF-8"
  x
}

result_df %>% mutate_if(is.character, declare_utf8) %>% pull()
#> [1] "はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。"

dbDisconnect(my_con)
#> [1] TRUE
```

pull() is not necessary here. I just use it because your description
would not print right as a data.frame() on my machine due to
another character encoding
bug,
so I am pulling it out as a vector.

Body:
I used R and DBI to query data from a PostgreSQL but got corrupted results with weird characters. I check both server encoding and client encoding, and they are all UTF-8. Here's what I did

Connect to the db

library(DBI)

conn <- dbConnect(
    drv = RPostgreSQL::PostgreSQL(),
    host = *,
    dbname = ,
    user = ,
    password = *
)

Fetch the result

result_df <- dbGetQuery(
        conn,
        "select description
        from some_table
        where user_id = 1234"
    )

Result
What I got is ã¯ã˜ã‚ã¾ã—ã¦1008(ã¨ãƒ¼ã‚„orã¨ã…ãƒ¼ã‚„)ã¨ã„ã„ã¾ã™ã€‚ è¡¨ç¾ã™ã‚‹ã®ãŒå¤§å¥½ããªåã§ã™!! æ„Ÿæ€§ãŒäººã¨ã‚ºãƒ¬ã¦ã¾ã™(ç¬‘) ãŠæŒã‚’ã‚‚ã£ã¨ã†ã¾ããªã‚ŠãŸã„ã§ã™ã€‚
while the actual text is はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。

I test again by reading the text and then print it back

x <- 'はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。'
print(x)
>> はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。

There's nothing wrong with the encoding in this case, so I think the problem happened when the data is returned from the database into R, but I don't know how to fix it.

Body:
RPostgreSQL does not set string encodings properly, see this issue.

So in the meantime you have to declare the encoding yourself. With
dplyr, you can do it like this:

suppressPackageStartupMessages({
  library(dplyr)
  library(RPostgreSQL)
})

my_con <-
  dbConnect(
    PostgreSQL(),
    user = my_username,
    password = my_password,
    host = my_host,
    dbname = my_dbname
  )

my_table <- tribble(
  ~user_id,    ~description,
  "1234",     "はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。"
)

copy_to(my_con, my_table)

result_df <- dbGetQuery(my_con, "SELECT description FROM my_table WHERE user_id = '1234'" )

declare_utf8 <- function(x) {
  Encoding(x) <- "UTF-8"
  x
}

result_df %>% mutate_if(is.character, declare_utf8) %>% pull()
#> [1] "はじめまして1008(とーやorとぅーや)といいます。 表現するのが大好きな子です!! 感性が人とズレてます(笑) お歌をもっとうまくなりたいです。"

dbDisconnect(my_con)
#> [1] TRUE

pull() is not necessary here. I just use it because your description
would not print right as a data.frame() on my machine due to
another character encoding
bug,
so I am pulling it out as a vector.


问:
Integrate AOS library with Angular4 application
I am working on Angular 4.4.6 application and I want to implement some animations on scroll using the awesome plugin AOS

my code:

app.component.ts

```<code>import * as AOS from 'aos';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.scss'],
 encapsulation:ViewEncapsulation.None
})
export class AppComponent implements OnInit {
 ngOnInit(){
  AOS.init();
 }
}
</code>```

app.component.html

```<code><div class="box" data-aos="slide-left">
      <img src="assets/imgs/seo.png" alt="">
</div>
</code>```

angulr.cli.json

```<code>"styles": [
    "../node_modules/aos/dist/aos.css",
    "../node_modules/animate.css/animate.min.css",
    "styles.scss"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/aos/dist/aos.js"
  ],
</code>```

I've tried the answer here with no hope
https://stackoverflow.com/a/44808496/4183947

Note: I've no errors in my console.

答:
I'm trying to get the same thing working for a site I'm migrating to Angular 4.2.4. Since you included the path to the AOS stylesheet in your angular.cli.json you probably already installed AOS via:

```<code>npm install aos --save
</code>```

I got it running with the following:

```<code>// angular.cli.json
...
"styles": [
  "../node_modules/aos/dist/aos.css",
  "styles.scss"
],
"scripts": [],
...
</code>```

and:

```<code>// app.component.ts
import { Component, OnInit } from '@angular/core';

import * as AOS from 'aos';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'app';

  ngOnInit() {
    AOS.init();
  }
}
</code>```

and in my case I have markup in a HomeComponent:

```<code>// home.component.html
...
<div data-aos="fade-up" data-aos-once="true">
  the content
</div>
...
</code>```

I might explore using AOS via the Angular Dependency Injection system in the future, as described in animate into view when scrolled to angular2 but simply importing AOS in app.component.ts is working so far.

Body:
I am working on Angular 4.4.6 application and I want to implement some animations on scroll using the awesome plugin AOS

my code:

app.component.ts

import * as AOS from 'aos';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.scss'],
 encapsulation:ViewEncapsulation.None
})
export class AppComponent implements OnInit {
 ngOnInit(){
  AOS.init();
 }
}

app.component.html

angulr.cli.json

"styles": [
    "../node_modules/aos/dist/aos.css",
    "../node_modules/animate.css/animate.min.css",
    "styles.scss"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/aos/dist/aos.js"
  ],

I've tried the answer here with no hope
https://stackoverflow.com/a/44808496/4183947

Note: I've no errors in my console.

Body:
I'm trying to get the same thing working for a site I'm migrating to Angular 4.2.4. Since you included the path to the AOS stylesheet in your angular.cli.json you probably already installed AOS via:

npm install aos --save

I got it running with the following:

// angular.cli.json
...
"styles": [
  "../node_modules/aos/dist/aos.css",
  "styles.scss"
],
"scripts": [],
...

and:

// app.component.ts
import { Component, OnInit } from '@angular/core';

import * as AOS from 'aos';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'app';

  ngOnInit() {
    AOS.init();
  }
}

and in my case I have markup in a HomeComponent:

// home.component.html
...
<div data-aos="fade-up" data-aos-once="true">
  the content
</div>
...

I might explore using AOS via the Angular Dependency Injection system in the future, as described in animate into view when scrolled to angular2 but simply importing AOS in app.component.ts is working so far.


问:
Swapping arguments inside a list of liss of tuples
I have a list of lists of tuples in the following form:

```<code>a = [[( 0,  1),
      ( 2,  3),
      ( 4,  5)],

     [( 6,  7),
      ( 8,  9),
      (10, 11)],

     [(12, 13),
      (14, 15),
      (16, 17)]]
</code>```

What I want to do, is to swap the two arguments inside the tuples.

I have tried the two following options, but without succes, the argumets keep their positions:

```<code>for i in range(0, len(a)-1):
    for j in range(0, len(a)/2):

        a[i][j] = a[i][j][1], a[i][j][0]

        a[i][j] = tuple(reversed(a[i][j]))
</code>```

Every help would be very much appreciated

答:
Consider changing your loops to:

```<code>for i in range(0, len(a)):
    for j in range(0, len(a[i])):
        a[i][j] = tuple(reversed(a[i][j]))
</code>```

In order to iterate over a list of lists (of tuples, in this case), you need to make sure you're specifying the lengths of each part correctly. In len(a)-1 in the outer loop, you don't need the -1, as range(x,y) takes you from x to y-1 already. In the inner loop, you need to specify the length of the inner list.

@Moses has a good answer on why creating a new tuple is the correct approach.

Body:
I have a list of lists of tuples in the following form:

a = [[( 0,  1),
      ( 2,  3),
      ( 4,  5)],

     [( 6,  7),
      ( 8,  9),
      (10, 11)],

     [(12, 13),
      (14, 15),
      (16, 17)]]

What I want to do, is to swap the two arguments inside the tuples.

I have tried the two following options, but without succes, the argumets keep their positions:

for i in range(0, len(a)-1):
    for j in range(0, len(a)/2):

        a[i][j] = a[i][j][1], a[i][j][0]

        a[i][j] = tuple(reversed(a[i][j]))

Every help would be very much appreciated

Body:
Consider changing your loops to:

for i in range(0, len(a)):
    for j in range(0, len(a[i])):
        a[i][j] = tuple(reversed(a[i][j]))

In order to iterate over a list of lists (of tuples, in this case), you need to make sure you're specifying the lengths of each part correctly. In len(a)-1 in the outer loop, you don't need the -1, as range(x,y) takes you from x to y-1 already. In the inner loop, you need to specify the length of the inner list.

@Moses has a good answer on why creating a new tuple is the correct approach.


问:
Importing csv rows to powershell, with date specified as greater than
I have two csv files. One with a report from AD, containing accounts created during last month, second is manually kept database, that should theoretically contain the same information, but from all history of our company, with some additional data needed for accounting. I imported the AD report to powershell, now I need to import specific rows of the database. The rows I need are defined by a value in column "Date added". I need to import only rows, where the date exceeds specific value. I have this code:

```<code>$Report = Read-Host "File name" #AD report, last ten chars are date of report creation, in format yyyy-MM-dd
$Date_text = $Report.Substring($Report.get_Length()-10)
$Date = Get-Date -Date $Date_text
$Date_limit = (($Date).AddDays(-$Date.Day)).Date
$Date_start = $Date_limit.AddMonths(-1)
$CSVlicence = Import-Csv $Database -Encoding UTF8 |
where {(Where-Object {![string]::IsNullOrWhiteSpace($_.'Date added')} |
ForEach-Object{$_.'Date added' = $_.'datum Pridani' -as [datetime] $_}) -gt $Date_start}
</code>```

When run like this, nothing is imported. Without the condition the database is imported successfully, but it's extremely large and the rest of the script takes for ever. So I need to work only with relevant data. I don't care, that when Date_limit is 30th Sep, the Date_start would be 30th Aug instead of 31st Aug. That's just few more rows, but all those 10 years or so really takes for ever, if everything is imported.

答:
So based on your current logic, it filters the PSCustomObject based on your constraints, which is the wrong way to handle it since any item in the object will cause it to be filtered out.  You want to filter the source.

```<code>$Report = Read-Host -Prompt 'Filename'
## Grabs the datestamp at the end
$Date = Get-Date -Date $Report.Substring($Report.Length - 10)
## Grabs last day of previous month
$Limit = $Date.AddDays(-$Date.Day)
## Grabs last day of two months ago, inaccuracy of one day
$Start = $Limit.AddMonths(-1)

Get-Content -Path $Database -TotalCount 1 | Set-Content -Path 'tempfile'
Get-Content -Path $Database -Encoding 'UTF8' |
    ## Checks that the entry has a valid date entry within limits
    ForEach-Object {
      ## For m/d/yy or d/m/yy variants, try
      ## '\d{1,2}\/\d{1,2}\/\d{2,4}'
      If ($_ -match '\d{4}-\d{2}-\d{2}')
      {
        [DateTime]$Date = $Matches[0]
        If ($Date -gt $Start -and $Date -lt $Limit) { $_ }
      }
    } |
    Add-Content -Path 'tempfile'

$CSV = Import-Csv -Path 'tempfile' -Encoding 'UTF8'
</code>```

Body:
I have two csv files. One with a report from AD, containing accounts created during last month, second is manually kept database, that should theoretically contain the same information, but from all history of our company, with some additional data needed for accounting. I imported the AD report to powershell, now I need to import specific rows of the database. The rows I need are defined by a value in column "Date added". I need to import only rows, where the date exceeds specific value. I have this code:

$Report = Read-Host "File name" #AD report, last ten chars are date of report creation, in format yyyy-MM-dd
$Date_text = $Report.Substring($Report.get_Length()-10)
$Date = Get-Date -Date $Date_text
$Date_limit = (($Date).AddDays(-$Date.Day)).Date
$Date_start = $Date_limit.AddMonths(-1)
$CSVlicence = Import-Csv $Database -Encoding UTF8 |
where {(Where-Object {![string]::IsNullOrWhiteSpace($_.'Date added')} |
ForEach-Object{$_.'Date added' = $_.'datum Pridani' -as [datetime] $_}) -gt $Date_start}

When run like this, nothing is imported. Without the condition the database is imported successfully, but it's extremely large and the rest of the script takes for ever. So I need to work only with relevant data. I don't care, that when Date_limit is 30th Sep, the Date_start would be 30th Aug instead of 31st Aug. That's just few more rows, but all those 10 years or so really takes for ever, if everything is imported.

Body:
So based on your current logic, it filters the PSCustomObject based on your constraints, which is the wrong way to handle it since any item in the object will cause it to be filtered out.  You want to filter the source.

$Report = Read-Host -Prompt 'Filename'
## Grabs the datestamp at the end
$Date = Get-Date -Date $Report.Substring($Report.Length - 10)
## Grabs last day of previous month
$Limit = $Date.AddDays(-$Date.Day)
## Grabs last day of two months ago, inaccuracy of one day
$Start = $Limit.AddMonths(-1)

Get-Content -Path $Database -TotalCount 1 | Set-Content -Path 'tempfile'
Get-Content -Path $Database -Encoding 'UTF8' |
    ## Checks that the entry has a valid date entry within limits
    ForEach-Object {
      ## For m/d/yy or d/m/yy variants, try
      ## '\d{1,2}\/\d{1,2}\/\d{2,4}'
      If ($_ -match '\d{4}-\d{2}-\d{2}')
      {
        [DateTime]$Date = $Matches[0]
        If ($Date -gt $Start -and $Date -lt $Limit) { $_ }
      }
    } |
    Add-Content -Path 'tempfile'

$CSV = Import-Csv -Path 'tempfile' -Encoding 'UTF8'


问:
memcpy vs for loop - What's the proper way to copy an array from a pointer?
I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums).  Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo.  I understand the following is invalid:

```<code>void foo (int[] nums)
{
    myGlobalArray = *nums
}
</code>```

What is the proper way to copy the array?  Should I use memcpy like so:

```<code>void foo (int[] nums)
{
    memcpy(&myGlobalArray, nums, 10);
}
</code>```

or should I use a for loop?

```<code>void foo(int[] nums)
{
    for(int i =0; i < 10; i++)
    {
        myGlobalArray[i] = nums[i];
    }
}
</code>```

Is there a third option that I'm missing?

答:
For performance, use memcpy (or equivalents). It's highly optimised platform-specific code for shunting lots of data around fast.

For maintainability, consider what you're doing - the for loop may be more readable and easier to understand. (Getting a memcpy wrong is a fast route to a crash or worse)

Body:
I have a function foo(int[] nums) which I understand is essentially equivalent to foo(int* nums).  Inside foo I need to copy the contents of the array pointed to by numsinto some int[10] declared within the scope of foo.  I understand the following is invalid:

void foo (int[] nums)
{
    myGlobalArray = *nums
}

What is the proper way to copy the array?  Should I use memcpy like so:

void foo (int[] nums)
{
    memcpy(&myGlobalArray, nums, 10);
}

or should I use a for loop?

void foo(int[] nums)
{
    for(int i =0; i < 10; i++)
    {
        myGlobalArray[i] = nums[i];
    }
}

Is there a third option that I'm missing?


问:
How to reset Android Studio
I want to reset Android Studio 0.2.13 to the default state. That means reset all settings, remove all projects, all gradle files so that it would act like a fresh installation. What steps do I have to follow to achieve this?

答:
Build - Clean project.
Basically, this is a problem with studio 3.0.
https://developer.android.com/studio/build/gradle-plugin-3-0-0.html (authorized link).</p>

Title: How to reset Android Studio


问:
Delayed entry survival model: R vs Stata differences
I have some code in Stata that I'm trying to redo in R. I'm working on a delayed entry survival model and I want to limit the follow-up to 5 years. In Stata this is very easy and can be done as follows for example:

```<code>stset end, fail(failure) id(ID) origin(start) enter(entry) exit(time 5)
stcox var1
</code>```

However, I'm having trouble recreating this in R. I've made a toy example limiting follow-up to 1000 days - here is the setup:

```<code>library(survival); library(foreign); library(rstpm2)

data(brcancer)
brcancer$start <- 0
# Make delayed entry time
brcancer$entry <- brcancer$rectime / 2
# Write to dta file for Stata
write.dta(brcancer, "brcancer.dta")
</code>```

Ok so now we've set up an identical dataset for use in both R and Stata. Here is the Stata bit code and model result:

```<code>use "brcancer.dta", clear
stset rectime, fail(censrec) origin(start) enter(entry) exit(time 1000)
stcox hormon
</code>```

And here is the R code and results:

```<code># Limit follow-up to 1000 days
brcancer$limit <- ifelse(brcancer$rectime <1000, brcancer$rectime, 1000)
# Cox model
mod1 <- coxph(Surv(time=entry, time2= limit, event = censrec) ~ hormon, data=brcancer, ties = "breslow")
summary(mod1)
</code>```

As you can see the R estimates and Stata estimates differ slightly, and I cannot figure out why. Have I set up the R model incorrectly to match Stata, or is there another reason the results differ?

答:
Since the methods match on an avaialble dataset after recoding the deaths that occur after to termination date, I'm posting the relevant sections of my comment as an answer.

I also think that you should have changed any of the deaths at time greater than 1000 to be considered censored. (Notice that the numbers of events is quite different in the two sets of results.

Body:
I have some code in Stata that I'm trying to redo in R. I'm working on a delayed entry survival model and I want to limit the follow-up to 5 years. In Stata this is very easy and can be done as follows for example:

stset end, fail(failure) id(ID) origin(start) enter(entry) exit(time 5)
stcox var1

However, I'm having trouble recreating this in R. I've made a toy example limiting follow-up to 1000 days - here is the setup:

library(survival); library(foreign); library(rstpm2)

data(brcancer)
brcancer$start <- 0
# Make delayed entry time
brcancer$entry <- brcancer$rectime / 2
# Write to dta file for Stata
write.dta(brcancer, "brcancer.dta")

Ok so now we've set up an identical dataset for use in both R and Stata. Here is the Stata bit code and model result:

use "brcancer.dta", clear
stset rectime, fail(censrec) origin(start) enter(entry) exit(time 1000)
stcox hormon

And here is the R code and results:

# Limit follow-up to 1000 days
brcancer$limit <- ifelse(brcancer$rectime <1000, brcancer$rectime, 1000)
# Cox model
mod1 <- coxph(Surv(time=entry, time2= limit, event = censrec) ~ hormon, data=brcancer, ties = "breslow")
summary(mod1)

As you can see the R estimates and Stata estimates differ slightly, and I cannot figure out why. Have I set up the R model incorrectly to match Stata, or is there another reason the results differ?


问:
How do I get the contents of the response body of a GET request before the POST request fires? Can this be done with promise?
So I'm receiving a JSON object from the front-end and sending it to my backend to the endpoint /getData. Here, I use a GET request to obtain data from an API and I need to send both the JSON object and the GET response body in the final POST request. But when I send the request, the body of the GET response comes in too late and "formInfo" is undefined.

How do I fix this so the POST request sends once the GET is fulfilled?

```<code> app.post('/getData', function(req, res) {
    debugger;
    var data = req.body;
    console.log(data);
    toSend = data;
    res.send({msg: "Success"});
    var findID = {};
    var endPoint = 'https://secure.p01.eloqua.com/API/REST/2.0/assets/form/' + toSend["formID"].toString();
    var options = {
        method: "GET",
        headers: {'Authorization': authenticationHeader, 'Content-Type': 'application/json'}
    };
    request.get(endPoint, options, function (error, response, body) {
        console.log(body);
        findID = body["elements"];
            request({
                    method: "POST",
                    headers: {'content-type': 'application/json', 'authorization': authenticationHeader},
                    url: 'http://localhost:3000/handleData',
                    json: {
                        "tuples": toSend,
                        "formInfo": body['elements']
                    }},
                function (error, response, body) {
                    console.log(response);
                });
    });
});
</code>```

答:
Have you considered using the fetch API?

It's widely supported in modern browsers - and you can transpile it worst case - and NodeJS.

With it you'd be able to chain requests, e.g.

```<code>fetch(`first.url.com`)
  .then(response =>
    fetch(`second.url.com`, {body: response.body})
  )
</code>```

Body:
So I'm receiving a JSON object from the front-end and sending it to my backend to the endpoint /getData. Here, I use a GET request to obtain data from an API and I need to send both the JSON object and the GET response body in the final POST request. But when I send the request, the body of the GET response comes in too late and "formInfo" is undefined.

How do I fix this so the POST request sends once the GET is fulfilled?

 app.post('/getData', function(req, res) {
    debugger;
    var data = req.body;
    console.log(data);
    toSend = data;
    res.send({msg: "Success"});
    var findID = {};
    var endPoint = 'https://secure.p01.eloqua.com/API/REST/2.0/assets/form/' + toSend["formID"].toString();
    var options = {
        method: "GET",
        headers: {'Authorization': authenticationHeader, 'Content-Type': 'application/json'}
    };
    request.get(endPoint, options, function (error, response, body) {
        console.log(body);
        findID = body["elements"];
            request({
                    method: "POST",
                    headers: {'content-type': 'application/json', 'authorization': authenticationHeader},
                    url: 'http://localhost:3000/handleData',
                    json: {
                        "tuples": toSend,
                        "formInfo": body['elements']
                    }},
                function (error, response, body) {
                    console.log(response);
                });
    });
});

Body:
Have you considered using the fetch API?

It's widely supported in modern browsers - and you can transpile it worst case - and NodeJS.

With it you'd be able to chain requests, e.g.

fetch(`first.url.com`)
  .then(response =>
    fetch(`second.url.com`, {body: response.body})
  )


问:
Are there disadvantages in putting code into Userforms instead of modules?
Are there disadvantages in putting code into a VBA Userform instead of into a "normal" module?

This might be a simple question but I have not found a conclusive answer to it while searching the web and stackoverflow.

Background: I am developing a Front-End Application of a database in Excel-VBA. To select different filters I have different userforms. I ask what general program design is better: (1) putting the control structure into a separate module OR (2) putting the code for the next userform or action in the userform.

Lets make an example. I have a Active-X Button which triggers my filters and my forms.

Variant1: Modules

In the CommandButton:

```<code>Private Sub CommandButton1_Click()
  call UserInterfaceControlModule
End Sub
</code>```

In the Module:

```<code>Sub UserInterfaceControllModule()
Dim decisionInput1 As Boolean
Dim decisionInput2 As Boolean

UserForm1.Show
decisionInput1 = UserForm1.decision

If decisionInput1 Then
  UserForm2.Show
Else
  UserForm3.Show
End If

End Sub
</code>```

In Variant 1 the control structure is in a normal module. And decisions about which userform to show next are separated from the userform. Any information needed to decide about which userform to show next has to be pulled from the userform.

Variant2: Userform

In the CommadButton:

```<code>Private Sub CommandButton1_Click()
  UserForm1.Show
End Sub
</code>```

In Userform1:

```<code>Private Sub ToUserform2_Click()
  UserForm2.Show
  UserForm1.Hide
End Sub

Private Sub UserForm_Click()
  UserForm2.Show
  UserForm1.Hide
End Sub
</code>```

In Variant 2 the control structure is directly in the userforms and each userform has the instructions about what comes after it.

I have started development using method 2. If this was a mistake and there are some serious drawbacks to this method I want to know it rather sooner than later.

答:
Disclaimer I wrote the article Victor K linked to. I own that blog, and manage the open-source VBIDE add-in project it's for.

Neither of your alternatives are ideal. Back to basics.

To select different filters I have differnt (sic) userforms.

Your specifications demand that the user needs to be able to select different filters, and you chose to implement a UI for it using a UserForm. So far, so good... and it's all downhill from there.

Making the form responsible for anything other than presentation concerns is a common mistake, and it has a name: it's the Smart UI [anti-]pattern, and the problem with it is that it doesn't scale. It's great for prototyping (i.e. make a quick thing that "works" - note the scare quotes), not so much for anything that needs to be maintained over years.

You've probably seen these forms, with 160 controls, 217 event handlers, and 3 private procedures closing in on 2000 lines of code each: that's how badly Smart UI scales, and it's the only possible outcome down that road.

You see, a UserForm is a class module: it defines the blueprint of an object. Objects usually want to be instantiated, but then someone had the genius idea of granting all instances of MSForms.UserForm a predeclared ID, which in COM terms means you basically get a global object for free.

Great! No? No.

```<code>UserForm1.Show
decisionInput1 = UserForm1.decision

If decisionInput1 Then
  UserForm2.Show
Else
  UserForm3.Show
End If
</code>```

What happens if UserForm1 is "X'd-out"? Or if UserForm1 is Unloaded? If the form isn't handling its QueryClose event, the object is destroyed - but because that's the default instance, VBA automatically/silently creates a new one for you, just before your code reads UserForm1.decision - as a result you get whatever the initial global state is for UserForm1.decision.

If it wasn't a default instance, and QueryClose wasn't handled, then accessing the .decision member of a destroyed object would give you the classic run-time error 91 for accessing a null object reference.

UserForm2.Show and UserForm3.Show both do the same thing: fire-and-forget - whatever happens happens, and to find out exactly what that consists of, you need to dig it up in the forms' respective code-behind.

In other words, the forms are running the show. They're responsible for collecting the data, presenting that data, collecting user input, and doing whatever work needs to be done with it. That's why it's called "Smart UI": the UI knows everything.

There's a better way. MSForms is the COM ancestor of .NET's WinForms UI framework, and what the ancestor has in common with its .NET successor, is that it works particularly well with the famous Model-View-Presenter (MVP) pattern.

The Model

That's your data. Essentially, it's what your application logic need to know out of the form.

UserForm1.decision let's go with that.

Add a new class, call it, say, FilterModel. Should be a very simple class:

```<code>Option Explicit

Private Type TModel
    SelectedFilter As String
End Type
Private this As TModel

Public Property Get SelectedFilter() As String
    SelectedFilter = this.SelectedFilter
End Property

Public Property Let SelectedFilter(ByVal value As String)
    this.SelectedFilter = value
End Property

Public Function IsValid() As Boolean
    IsValid = this.SelectedFilter <> vbNullString
End Function
</code>```

That's really all we need: a class to encapsulate the form's data. The class can be responsible for some validation logic, or whatever - but it doesn't collect the data, it doesn't present it to the user, and it doesn't consume it either. It is the data.

Here there's only 1 property, but you could have many more: think one field on the form => one property.

The model is also what the form needs to know from the application logic. For example if the form needs a drop-down that displays a number of possible selections, the model would be the object exposing them.

The View

That's your form. It's responsible for knowing about controls, writing to and reading from the model, and... that's all. We're looking at a dialog here: we bring it up, user fills it up, closes it, and the program acts upon it - the form itself doesn't do anything with the data it collects. The model might validate it, the form might decide to disable its Ok button until the model says its data is valid and good to go, but under no circumstances a UserForm reads or writes from a worksheet, a database, a file, a URL, or anything.

The form's code-behind is dead simple: it wires up the UI with the model instance, and enables/disables its buttons as needed.

The important things to remember:

Hide, don't Unload: the view is an object, and objects don't self-destruct.

NEVER refer to the form's default instance.

Always handle QueryClose, again, to avoid a self-destructing object ("X-ing out" of the form would otherwise destroy the instance).

In this case the code-behind might look like this:

```<code>Option Explicit
Private Type TView
    Model As FilterModel
    IsCancelled As Boolean
End Type
Private this As TView

Public Property Get Model() As FilterModel
    Set Model = this.Model
End Property

Public Property Set Model(ByVal value As FilterModel)
    Set this.Model = value
    Validate
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = this.IsCancelled
End Property

Private Sub TextBox1_Change()
    this.Model.SelectedFilter = TextBox1.Text
    Validate
End Sub

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub Validate()
    OkButton.Enabled = this.Model.IsValid
End Sub

Private Sub CancelButton_Click()
    OnCancel
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = True
        OnCancel
    End If
End Sub

Private Sub OnCancel()
    this.IsCancelled = True
    Me.Hide
End Sub
</code>```

That's literally all the form does. It isn't responsible for knowing where the data comes from or what to do with it.

The Presenter

That's the "glue" object that connects the dots.

```<code>Option Explicit

Public Sub DoSomething()
    Dim m As FilterModel
    Set m = New FilterModel
    With New FilterForm
        Set .Model = m 'set the model
        .Show 'display the dialog
        If Not .IsCancelled Then 'how was it closed?
            'consume the data
            Debug.Print m.SelectedFilter
        End If
    End With
End Sub
</code>```

If the data in the model needed to come from a database, or some worksheet, it uses a class instance (yes, another object!) that's responsible for doing just that.

The calling code could be your ActiveX button's click handler, New-ing up the presenter and calling its DoSomething method.

This isn't everything there is to know about OOP in VBA (I didn't even mention interfaces, polymorphism, test stubs and unit testing), but if you want objectively scalable code, you'll want to go down the MVP rabbit hole and explore the possibilities truly object-oriented code bring to VBA.

TL;DR:

Code ("business logic") simply doesn't belong in forms' code-behind, in any code base that means to scale and be maintained across several years.

In "variant 1" the code is hard to follow because you're jumping between modules and the presentation concerns are mixed with the application logic: it's not the form's job to know what other form to show given button A or button B was pressed. Instead it should let the presenter know what the user means to do, and act accordingly.

In "variant 2" the code is hard to follow because everything is hidden in userforms' code-behind: we don't know what the application logic is unless we dig into that code, which now purposely mixes presentation and business logic concerns. That is exactly what the "Smart UI" anti-pattern does.

In other words variant 1 is slightly better than variant 2, because at least the logic isn't in the code-behind, but it's still a "Smart UI" because it's running the show instead of telling its caller what's happening.

In both cases, coding against the forms' default instances is harmful, because it puts state in global scope (anyone can access the default instances and do anything to its state, from anywhere in the code).

Treat forms like the objects they are: instantiate them!

In both cases, because the form's code is tightly coupled with the application logic and intertwined with presentation concerns, it's completely impossible to write a single unit test that covers even one single aspect of what's going on. With the MVP pattern, you can completely decouple the components, abstract them behind interfaces, isolate responsibilities, and write dozens of automated unit tests that cover every single piece of functionality and document exactly what the specifications are - without writing a single bit of documentation: the code becomes its own documentation.

Body:
Are there disadvantages in putting code into a VBA Userform instead of into a "normal" module?

This might be a simple question but I have not found a conclusive answer to it while searching the web and stackoverflow.

Background: I am developing a Front-End Application of a database in Excel-VBA. To select different filters I have different userforms. I ask what general program design is better: (1) putting the control structure into a separate module OR (2) putting the code for the next userform or action in the userform.

Lets make an example. I have a Active-X Button which triggers my filters and my forms.

Variant1: Modules

In the CommandButton:

Private Sub CommandButton1_Click()
  call UserInterfaceControlModule
End Sub

In the Module:

Sub UserInterfaceControllModule()
Dim decisionInput1 As Boolean
Dim decisionInput2 As Boolean

UserForm1.Show
decisionInput1 = UserForm1.decision

If decisionInput1 Then
  UserForm2.Show
Else
  UserForm3.Show
End If

End Sub

In Variant 1 the control structure is in a normal module. And decisions about which userform to show next are separated from the userform. Any information needed to decide about which userform to show next has to be pulled from the userform.

Variant2: Userform

In the CommadButton:

Private Sub CommandButton1_Click()
  UserForm1.Show
End Sub

In Userform1:

Private Sub ToUserform2_Click()
  UserForm2.Show
  UserForm1.Hide
End Sub

Private Sub UserForm_Click()
  UserForm2.Show
  UserForm1.Hide
End Sub

In Variant 2 the control structure is directly in the userforms and each userform has the instructions about what comes after it.

I have started development using method 2. If this was a mistake and there are some serious drawbacks to this method I want to know it rather sooner than later.

Body:
Disclaimer I wrote the article Victor K linked to. I own that blog, and manage the open-source VBIDE add-in project it's for.

Neither of your alternatives are ideal. Back to basics.

To select different filters I have differnt (sic) userforms.

Your specifications demand that the user needs to be able to select different filters, and you chose to implement a UI for it using a UserForm. So far, so good... and it's all downhill from there.

Making the form responsible for anything other than presentation concerns is a common mistake, and it has a name: it's the Smart UI [anti-]pattern, and the problem with it is that it doesn't scale. It's great for prototyping (i.e. make a quick thing that "works" - note the scare quotes), not so much for anything that needs to be maintained over years.

You've probably seen these forms, with 160 controls, 217 event handlers, and 3 private procedures closing in on 2000 lines of code each: that's how badly Smart UI scales, and it's the only possible outcome down that road.

You see, a UserForm is a class module: it defines the blueprint of an object. Objects usually want to be instantiated, but then someone had the genius idea of granting all instances of MSForms.UserForm a predeclared ID, which in COM terms means you basically get a global object for free.

Great! No? No.

UserForm1.Show
decisionInput1 = UserForm1.decision

If decisionInput1 Then
  UserForm2.Show
Else
  UserForm3.Show
End If

What happens if UserForm1 is "X'd-out"? Or if UserForm1 is Unloaded? If the form isn't handling its QueryClose event, the object is destroyed - but because that's the default instance, VBA automatically/silently creates a new one for you, just before your code reads UserForm1.decision - as a result you get whatever the initial global state is for UserForm1.decision.

If it wasn't a default instance, and QueryClose wasn't handled, then accessing the .decision member of a destroyed object would give you the classic run-time error 91 for accessing a null object reference.

UserForm2.Show and UserForm3.Show both do the same thing: fire-and-forget - whatever happens happens, and to find out exactly what that consists of, you need to dig it up in the forms' respective code-behind.

In other words, the forms are running the show. They're responsible for collecting the data, presenting that data, collecting user input, and doing whatever work needs to be done with it. That's why it's called "Smart UI": the UI knows everything.

There's a better way. MSForms is the COM ancestor of .NET's WinForms UI framework, and what the ancestor has in common with its .NET successor, is that it works particularly well with the famous Model-View-Presenter (MVP) pattern.

The Model

That's your data. Essentially, it's what your application logic need to know out of the form.

UserForm1.decision let's go with that.

Add a new class, call it, say, FilterModel. Should be a very simple class:

Option Explicit

Private Type TModel
    SelectedFilter As String
End Type
Private this As TModel

Public Property Get SelectedFilter() As String
    SelectedFilter = this.SelectedFilter
End Property

Public Property Let SelectedFilter(ByVal value As String)
    this.SelectedFilter = value
End Property

Public Function IsValid() As Boolean
    IsValid = this.SelectedFilter <> vbNullString
End Function

That's really all we need: a class to encapsulate the form's data. The class can be responsible for some validation logic, or whatever - but it doesn't collect the data, it doesn't present it to the user, and it doesn't consume it either. It is the data.

Here there's only 1 property, but you could have many more: think one field on the form => one property.

The model is also what the form needs to know from the application logic. For example if the form needs a drop-down that displays a number of possible selections, the model would be the object exposing them.

The View

That's your form. It's responsible for knowing about controls, writing to and reading from the model, and... that's all. We're looking at a dialog here: we bring it up, user fills it up, closes it, and the program acts upon it - the form itself doesn't do anything with the data it collects. The model might validate it, the form might decide to disable its Ok button until the model says its data is valid and good to go, but under no circumstances a UserForm reads or writes from a worksheet, a database, a file, a URL, or anything.

The form's code-behind is dead simple: it wires up the UI with the model instance, and enables/disables its buttons as needed.

The important things to remember:

Hide, don't Unload: the view is an object, and objects don't self-destruct.

NEVER refer to the form's default instance.

Always handle QueryClose, again, to avoid a self-destructing object ("X-ing out" of the form would otherwise destroy the instance).

In this case the code-behind might look like this:

Option Explicit
Private Type TView
    Model As FilterModel
    IsCancelled As Boolean
End Type
Private this As TView

Public Property Get Model() As FilterModel
    Set Model = this.Model
End Property

Public Property Set Model(ByVal value As FilterModel)
    Set this.Model = value
    Validate
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = this.IsCancelled
End Property

Private Sub TextBox1_Change()
    this.Model.SelectedFilter = TextBox1.Text
    Validate
End Sub

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub Validate()
    OkButton.Enabled = this.Model.IsValid
End Sub

Private Sub CancelButton_Click()
    OnCancel
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = True
        OnCancel
    End If
End Sub

Private Sub OnCancel()
    this.IsCancelled = True
    Me.Hide
End Sub

That's literally all the form does. It isn't responsible for knowing where the data comes from or what to do with it.

The Presenter

That's the "glue" object that connects the dots.

Option Explicit

Public Sub DoSomething()
    Dim m As FilterModel
    Set m = New FilterModel
    With New FilterForm
        Set .Model = m 'set the model
        .Show 'display the dialog
        If Not .IsCancelled Then 'how was it closed?
            'consume the data
            Debug.Print m.SelectedFilter
        End If
    End With
End Sub

If the data in the model needed to come from a database, or some worksheet, it uses a class instance (yes, another object!) that's responsible for doing just that.

The calling code could be your ActiveX button's click handler, New-ing up the presenter and calling its DoSomething method.

This isn't everything there is to know about OOP in VBA (I didn't even mention interfaces, polymorphism, test stubs and unit testing), but if you want objectively scalable code, you'll want to go down the MVP rabbit hole and explore the possibilities truly object-oriented code bring to VBA.

TL;DR:

Code ("business logic") simply doesn't belong in forms' code-behind, in any code base that means to scale and be maintained across several years.

In "variant 1" the code is hard to follow because you're jumping between modules and the presentation concerns are mixed with the application logic: it's not the form's job to know what other form to show given button A or button B was pressed. Instead it should let the presenter know what the user means to do, and act accordingly.

In "variant 2" the code is hard to follow because everything is hidden in userforms' code-behind: we don't know what the application logic is unless we dig into that code, which now purposely mixes presentation and business logic concerns. That is exactly what the "Smart UI" anti-pattern does.

In other words variant 1 is slightly better than variant 2, because at least the logic isn't in the code-behind, but it's still a "Smart UI" because it's running the show instead of telling its caller what's happening.

In both cases, coding against the forms' default instances is harmful, because it puts state in global scope (anyone can access the default instances and do anything to its state, from anywhere in the code).

Treat forms like the objects they are: instantiate them!

In both cases, because the form's code is tightly coupled with the application logic and intertwined with presentation concerns, it's completely impossible to write a single unit test that covers even one single aspect of what's going on. With the MVP pattern, you can completely decouple the components, abstract them behind interfaces, isolate responsibilities, and write dozens of automated unit tests that cover every single piece of functionality and document exactly what the specifications are - without writing a single bit of documentation: the code becomes its own documentation.


问:
Getting an undefined "this" when using Classes/Async Await
I've just started to experiment with classes and async await. I'm using Node version 8.9.0 (LTS). When I console.log(this), I get undefined instead of the reference to the object.

subhandler.js

```<code>class Handler {
  constructor(props) {
    this.defaultRes = {
      data: successMessage,
      statusCode: 200
    };
  }

  async respond(handler, reply, response = this.defaultRes) {
    console.log(this); // why is `this` undefined????
    try {
      await handler;
      return reply(response.data).code(response.statusCode)
    } catch(error) {
      return reply(error);
    }
  }
}

class SubHandler extends Handler {
  constructor(props) {
    super(props);
    this.something = 'else';
  }

  makeRequest(request, reply) {
    console.log(this); // why is `this` undefined!!
    // in this case, doSomeAsyncRequest is a promise
    const handler = doSomeAsyncRequest.make(request.params);
    super.respond(handler, reply, response);
  }
}

module.exports = new SubHandler;
</code>```

Inside Hapi route

```<code>const SubHandler = require('./subhandler');

server.route({
    method: 'GET',
    path: '/',
    handler: SubHandler.makeRequest,
    // handler: function (request, reply) {
    //  reply('Hello!'); //leaving here to show example
    //}
});
</code>```

Prototype example

```<code>function Example() {
  this.a = 'a';
  this.b = 'b';
}

Example.prototype.fn = function() {
  console.log(this); // this works here
}

const ex = new Example();
ex.fn();
</code>```

答:
If you want this to always point to the instance in makeRequest, bind its context in the constructor:

```<code>class SubHandler extends Handler {
  constructor(props) {
    super(props);

    this.makeRequest = this.makeRequest.bind(this)

    this.something = 'else';
  }

  makeRequest(request, reply) {
    console.log(this);
    const handler = doSomeAsyncRequest.make(request.params);
    super.respond(handler, reply, response);
  }
}
</code>```

Body:
I've just started to experiment with classes and async await. I'm using Node version 8.9.0 (LTS). When I console.log(this), I get undefined instead of the reference to the object.

subhandler.js

class Handler {
  constructor(props) {
    this.defaultRes = {
      data: successMessage,
      statusCode: 200
    };
  }

  async respond(handler, reply, response = this.defaultRes) {
    console.log(this); // why is `this` undefined????
    try {
      await handler;
      return reply(response.data).code(response.statusCode)
    } catch(error) {
      return reply(error);
    }
  }
}

class SubHandler extends Handler {
  constructor(props) {
    super(props);
    this.something = 'else';
  }

  makeRequest(request, reply) {
    console.log(this); // why is `this` undefined!!
    // in this case, doSomeAsyncRequest is a promise
    const handler = doSomeAsyncRequest.make(request.params);
    super.respond(handler, reply, response);
  }
}

module.exports = new SubHandler;

Inside Hapi route

const SubHandler = require('./subhandler');

server.route({
    method: 'GET',
    path: '/',
    handler: SubHandler.makeRequest,
    // handler: function (request, reply) {
    //  reply('Hello!'); //leaving here to show example
    //}
});

Prototype example

function Example() {
  this.a = 'a';
  this.b = 'b';
}

Example.prototype.fn = function() {
  console.log(this); // this works here
}

const ex = new Example();
ex.fn();

Body:
If you want this to always point to the instance in makeRequest, bind its context in the constructor:

class SubHandler extends Handler {
  constructor(props) {
    super(props);

    this.makeRequest = this.makeRequest.bind(this)

    this.something = 'else';
  }

  makeRequest(request, reply) {
    console.log(this);
    const handler = doSomeAsyncRequest.make(request.params);
    super.respond(handler, reply, response);
  }
}


问:
Could not create unique index - claims to have duplicate values but it doesn't
I'm trying to create a unique index on code field:

```<code>$ CREATE UNIQUE INDEX "one_code_per_person" on "core_person"("code") WHERE "code" IS NOT NULL;
ERROR:  could not create unique index "one_code_per_person"
DETAIL:  Table contains duplicated values.
</code>```

It says there are duplicate values but:

```<code>$ select code, count(*) from core_person group by code having count(*)>2;
code | count
-----------+-------
(0 rows)
</code>```

which proves there are not.

WTF?

答:
This:

```<code>HAVING COUNT(*) > 2
</code>```

...means there needs to be 3+ duplicates.  You want to use:

```<code>HAVING COUNT(*) > 1
</code>```

...to find records with 2+ duplicates.

Body:
I'm trying to create a unique index on code field:

$ CREATE UNIQUE INDEX "one_code_per_person" on "core_person"("code") WHERE "code" IS NOT NULL;
ERROR:  could not create unique index "one_code_per_person"
DETAIL:  Table contains duplicated values.

It says there are duplicate values but:

$ select code, count(*) from core_person group by code having count(*)>2;
code | count
-----------+-------
(0 rows)

which proves there are not.

WTF?

Body:
This:

HAVING COUNT(*) > 2

...means there needs to be 3+ duplicates.  You want to use:

HAVING COUNT(*) > 1

...to find records with 2+ duplicates.