问:
Android Studio: Transparent checkout using Mercado Pago
I am trying to implement for the first time the Mercado Pago's transparent checkout in Android.

I've already downloaded the newest version of the SDK provided in https://github.com/mercadopago/px-android and executed it normally in the Emulator.

In the GitHub page mentioned above, we have an explanation of how to implement Mercado Pago's checkout with just one line of code:

```<code>new MercadoPagoCheckout.Builder("public_key", "checkout_preference_id")
    .build()
    .startPayment(activityOrContext, requestCode);
</code>```

Where public_key we can get in the credentials webpage. But the String checkout_preference_id I have no idea of how to create it, even though they showed how to create it at the end of the GitHub webpage.

Create your preference id

```<code>curl -X POST \
     'https://api.mercadopago.com/checkout/preferences?access_token=ACCESS_TOKEN' \
     -H 'Content-Type: application/json' \
     -d '{
           "items": [
               {
               "title": "Dummy Item",
               "description": "Multicolor Item",
               "quantity": 1,
               "currency_id": "ARS",
               "unit_price": 10.0
               }
           ],
           "payer": {
               "email": "payer@email.com"
           }
     }'
</code>```

I tried to put a random String in checkout_preference_id, but it did not work. Only the String in the example app of Mercado Pago worked.

```<code>private static final String DUMMY_PREFERENCE_ID = "243962506-0bb62e22-5c7b-425e-a0a6-c22d0f4758a9";
</code>```

All the other ways of implementing it presented in the example app of Mercado Pago require a fake confirmation of payment.

I appreciate if anyone could show some code of how to create and pass the variable checkout_preference_id into the main command of Mercado Pago payment.

EDIT

I also appreciate if anyone could give us an example of a Not fake confirmation of payment with some code.

I guess checkout_preference_id can be accessed via a Marketplace website or maybe creating a curl using Android's webservice. Then, it is still a mystery to me.

Concerning to the alternitive way of paying with MercadoPago, we have this other arguments to pass:

```<code>new MercadoPagoCheckout.Builder("public_key", checkoutPreference, paymentConfiguration)
                .build()
                .startPayment(activityOrContext, requestCode);
</code>```

Where checkoutPreference allows you to create a custom item to sell.

```<code>final Item item = new Item.Builder("Product Title", 1, new BigDecimal(12.3)).setDescription("Product Description").build();
CheckoutPreference checkoutPreference = new CheckoutPreference.Builder(Sites.BRASIL, "a@a.a", Collections.singletonList(item)).setDefaultInstallments(1).build();
</code>```

paymentConfiguration is implemented the fake confirmation of payment.

```<code>PaymentConfiguration paymentConfiguration = new PaymentConfiguration.Builder(new MyPaymentProcessor()).build();
</code>```

Where the class MyPaymentProcessor() and the other classes in which it depends on can be found in the GitHub example.

答:
Álysson Alexandre helped to understand how to generate the String checkout_preference_id.

Below you will see the minimum code needed to receive a payment with MercadoPago.

Firstly, you have to add the dependencies in the build.gradle (Module: app)

```<code>// Dealing with HTTP internet connection
implementation 'com.android.volley:volley:1.1.1'

//Dealing with MercadoPago SDK and dependencies
implementation 'com.mercadopago.android.px:checkout:4.0.+'
</code>```

Some people recommend to add internet permission in the Manifest

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Next, you need to create a JSONObject and there are different ways of doing that.

This way:

```<code>    StringBuilder strjsonobj = new StringBuilder();
    String strJson = "{\n" +
            "           \"items\": [\n" +
            "               {\n" +
            "               \"title\": \"Item\",\n" +
            "               \"description\": \"Multicolor Item\",\n" +
            "               \"quantity\": 1,\n" +
            "               \"currency_id\": \"BRL\",\n" +
            "               \"unit_price\": 35.0\n" +
            "               }\n" +
            "           ],\n" +
            "           \"payer\": {\n" +
            "\t\t    \"name\": \"Núbia\",\n" +
            "\t\t    \"surname\": \"Macedo\",\n" +
            "\t\t    \"email\": \"leann@gmail.com\",\n" +
            "\t\t    \"date_created\": \"2015-06-02T12:58:41.425-04:00\",\n" +
            "\t\t    \"phone\": {\n" +
            "\t\t      \"area_code\": \"\",\n" +
            "\t\t      \"number\": \"880.402.7555\"\n" +
            "\t\t    },\n" +
            "\t\t    \"identification\": {\n" +
            "\t\t      \"type\": \"DNI\",\n" +
            "\t\t      \"number\": \"123456789\"\n" +
            "\t\t    },\n" +
            "\t\t    \"address\": {\n" +
            "\t\t      \"street_name\": \"Núbia Viela\",\n" +
            "\t\t      \"street_number\": 25598,\n" +
            "\t\t      \"zip_code\": \"8972\"\n" +
            "\t\t    }\n" +
            "\t\t  }\n" +
            "     }";

    strjsonobj.append(strJson);
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(strjsonobj.toString());
        Log.i("debinf MainAct", "object is : "+jsonObject);
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Or this way:

```<code>    JSONObject jsonObject = new JSONObject();
    final JSONObject itemJSON = new JSONObject();
    final JSONObject payerJSON = new JSONObject();
    JSONArray itemJsonArray = new JSONArray();
    try {

        itemJSON.put("title", "Dummy Item");
        itemJSON.put("description", "Multicolor Item");
        itemJSON.put("quantity", 1);
        itemJSON.put("currency_id", "BRL");
        itemJSON.put("unit_price", 2.10);

        itemJsonArray.put(itemJSON);

        JSONObject phoneJSON = new JSONObject();
        phoneJSON.put("area_code", "");
        phoneJSON.put("number", "880.402.7555");
        JSONObject idJSON = new JSONObject();
        idJSON.put("type", "DNI");
        idJSON.put("number", "123456789");
        JSONObject addressJSON = new JSONObject();
        addressJSON.put("street_name", "Núbia Viela");
        addressJSON.put("street_number", 25598);
        addressJSON.put("zip_code", "8972");

        payerJSON.put("name", "Núbia");
        payerJSON.put("surname", "Macedo");
        payerJSON.put("email", "leann@gmail.com");
        payerJSON.put("date_created", "2015-06-02T12:58:41.425-04:00");
        payerJSON.put("phone", phoneJSON);
        payerJSON.put("identification", idJSON);
        payerJSON.put("address", addressJSON);

        jsonObject.put("items", itemJsonArray);
        jsonObject.put("payer", payerJSON);
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

MercadoPago suggests to send as much information as you can about the payer in order to increase the rate of payment conversion. But you can send as little as shown in the question.

Besides that, you can personalize other things in the JSONObject such as shown here

Now, let's create the variable String checkout_preference_id. For that, I used the method volley. When the MercadoPago server sends back our variable, we will automatically start the payment.

```<code>    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    final String url = "https://api.mercadopago.com/checkout/preferences?access_token="+ACCESS_TOKEN_SANDBOX;
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                Log.i("debinf MainAct", "response JSONObject: "+response);
                String checkoutPreferenceId = response.getString("id");
                new MercadoPagoCheckout.Builder(PUBLIC_KEY_SANDBOX, checkoutPreferenceId).build().startPayment(MainActivity.this,REQUEST_CODE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("debinf MainAct", "response ERROR: "+error.networkResponse.allHeaders);
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };
    requestQueue.add(jsonObjectRequest);
</code>```

Use REQUEST_CODE sent by startPayment to obtain the checkout result in onActivityResult.

```<code>@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (requestCode == REQUEST_CODE) {
        if (resultCode == MercadoPagoCheckout.PAYMENT_RESULT_CODE) {
            final Payment payment = (Payment) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_PAYMENT_RESULT);
            ((TextView) findViewById(R.id.mp_results)).setText("Resultado del pago: " + payment.getStatus());
            //Done!
        } else if (resultCode == RESULT_CANCELED) {
            if (data != null && data.getExtras() != null
                && data.getExtras().containsKey(MercadoPagoCheckout.EXTRA_ERROR)) {
                final MercadoPagoError mercadoPagoError =
                    (MercadoPagoError) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_ERROR);
                ((TextView) findViewById(R.id.mp_results)).setText("Error: " +  mercadoPagoError.getMessage());
                //Resolve error in checkout
            } else {
                //Resolve canceled checkout
            }
        }
    }
}
</code>```

That's it! Please, be free to improve the above code. Mainly, regarding to the security issues.

Body:
I am trying to implement for the first time the Mercado Pago's transparent checkout in Android.

I've already downloaded the newest version of the SDK provided in https://github.com/mercadopago/px-android and executed it normally in the Emulator.

In the GitHub page mentioned above, we have an explanation of how to implement Mercado Pago's checkout with just one line of code:

new MercadoPagoCheckout.Builder("public_key", "checkout_preference_id")
    .build()
    .startPayment(activityOrContext, requestCode);

Where public_key we can get in the credentials webpage. But the String checkout_preference_id I have no idea of how to create it, even though they showed how to create it at the end of the GitHub webpage.

Create your preference id

curl -X POST \
     'https://api.mercadopago.com/checkout/preferences?access_token=ACCESS_TOKEN' \
     -H 'Content-Type: application/json' \
     -d '{
           "items": [
               {
               "title": "Dummy Item",
               "description": "Multicolor Item",
               "quantity": 1,
               "currency_id": "ARS",
               "unit_price": 10.0
               }
           ],
           "payer": {
               "email": "payer@email.com"
           }
     }'

I tried to put a random String in checkout_preference_id, but it did not work. Only the String in the example app of Mercado Pago worked.

private static final String DUMMY_PREFERENCE_ID = "243962506-0bb62e22-5c7b-425e-a0a6-c22d0f4758a9";

All the other ways of implementing it presented in the example app of Mercado Pago require a fake confirmation of payment.

I appreciate if anyone could show some code of how to create and pass the variable checkout_preference_id into the main command of Mercado Pago payment.

EDIT

I also appreciate if anyone could give us an example of a Not fake confirmation of payment with some code.

I guess checkout_preference_id can be accessed via a Marketplace website or maybe creating a curl using Android's webservice. Then, it is still a mystery to me.

Concerning to the alternitive way of paying with MercadoPago, we have this other arguments to pass:

new MercadoPagoCheckout.Builder("public_key", checkoutPreference, paymentConfiguration)
                .build()
                .startPayment(activityOrContext, requestCode);

Where checkoutPreference allows you to create a custom item to sell.

final Item item = new Item.Builder("Product Title", 1, new BigDecimal(12.3)).setDescription("Product Description").build();
CheckoutPreference checkoutPreference = new CheckoutPreference.Builder(Sites.BRASIL, "a@a.a", Collections.singletonList(item)).setDefaultInstallments(1).build();

paymentConfiguration is implemented the fake confirmation of payment.

PaymentConfiguration paymentConfiguration = new PaymentConfiguration.Builder(new MyPaymentProcessor()).build();

Where the class MyPaymentProcessor() and the other classes in which it depends on can be found in the GitHub example.

Body:
Álysson Alexandre helped to understand how to generate the String checkout_preference_id.

Below you will see the minimum code needed to receive a payment with MercadoPago.

Firstly, you have to add the dependencies in the build.gradle (Module: app)

// Dealing with HTTP internet connection
implementation 'com.android.volley:volley:1.1.1'

//Dealing with MercadoPago SDK and dependencies
implementation 'com.mercadopago.android.px:checkout:4.0.+'

Some people recommend to add internet permission in the Manifest

<uses-permission android:name="android.permission.INTERNET" />

Next, you need to create a JSONObject and there are different ways of doing that.

This way:

    StringBuilder strjsonobj = new StringBuilder();
    String strJson = "{\n" +
            "           \"items\": [\n" +
            "               {\n" +
            "               \"title\": \"Item\",\n" +
            "               \"description\": \"Multicolor Item\",\n" +
            "               \"quantity\": 1,\n" +
            "               \"currency_id\": \"BRL\",\n" +
            "               \"unit_price\": 35.0\n" +
            "               }\n" +
            "           ],\n" +
            "           \"payer\": {\n" +
            "\t\t    \"name\": \"Núbia\",\n" +
            "\t\t    \"surname\": \"Macedo\",\n" +
            "\t\t    \"email\": \"leann@gmail.com\",\n" +
            "\t\t    \"date_created\": \"2015-06-02T12:58:41.425-04:00\",\n" +
            "\t\t    \"phone\": {\n" +
            "\t\t      \"area_code\": \"\",\n" +
            "\t\t      \"number\": \"880.402.7555\"\n" +
            "\t\t    },\n" +
            "\t\t    \"identification\": {\n" +
            "\t\t      \"type\": \"DNI\",\n" +
            "\t\t      \"number\": \"123456789\"\n" +
            "\t\t    },\n" +
            "\t\t    \"address\": {\n" +
            "\t\t      \"street_name\": \"Núbia Viela\",\n" +
            "\t\t      \"street_number\": 25598,\n" +
            "\t\t      \"zip_code\": \"8972\"\n" +
            "\t\t    }\n" +
            "\t\t  }\n" +
            "     }";

    strjsonobj.append(strJson);
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(strjsonobj.toString());
        Log.i("debinf MainAct", "object is : "+jsonObject);
    } catch (JSONException e) {
        e.printStackTrace();
    }

Or this way:

    JSONObject jsonObject = new JSONObject();
    final JSONObject itemJSON = new JSONObject();
    final JSONObject payerJSON = new JSONObject();
    JSONArray itemJsonArray = new JSONArray();
    try {

        itemJSON.put("title", "Dummy Item");
        itemJSON.put("description", "Multicolor Item");
        itemJSON.put("quantity", 1);
        itemJSON.put("currency_id", "BRL");
        itemJSON.put("unit_price", 2.10);

        itemJsonArray.put(itemJSON);

        JSONObject phoneJSON = new JSONObject();
        phoneJSON.put("area_code", "");
        phoneJSON.put("number", "880.402.7555");
        JSONObject idJSON = new JSONObject();
        idJSON.put("type", "DNI");
        idJSON.put("number", "123456789");
        JSONObject addressJSON = new JSONObject();
        addressJSON.put("street_name", "Núbia Viela");
        addressJSON.put("street_number", 25598);
        addressJSON.put("zip_code", "8972");

        payerJSON.put("name", "Núbia");
        payerJSON.put("surname", "Macedo");
        payerJSON.put("email", "leann@gmail.com");
        payerJSON.put("date_created", "2015-06-02T12:58:41.425-04:00");
        payerJSON.put("phone", phoneJSON);
        payerJSON.put("identification", idJSON);
        payerJSON.put("address", addressJSON);

        jsonObject.put("items", itemJsonArray);
        jsonObject.put("payer", payerJSON);
    } catch (JSONException e) {
        e.printStackTrace();
    }

MercadoPago suggests to send as much information as you can about the payer in order to increase the rate of payment conversion. But you can send as little as shown in the question.

Besides that, you can personalize other things in the JSONObject such as shown here

Now, let's create the variable String checkout_preference_id. For that, I used the method volley. When the MercadoPago server sends back our variable, we will automatically start the payment.

    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    final String url = "https://api.mercadopago.com/checkout/preferences?access_token="+ACCESS_TOKEN_SANDBOX;
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                Log.i("debinf MainAct", "response JSONObject: "+response);
                String checkoutPreferenceId = response.getString("id");
                new MercadoPagoCheckout.Builder(PUBLIC_KEY_SANDBOX, checkoutPreferenceId).build().startPayment(MainActivity.this,REQUEST_CODE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.i("debinf MainAct", "response ERROR: "+error.networkResponse.allHeaders);
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            return headers;
        }
    };
    requestQueue.add(jsonObjectRequest);

Use REQUEST_CODE sent by startPayment to obtain the checkout result in onActivityResult.

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (requestCode == REQUEST_CODE) {
        if (resultCode == MercadoPagoCheckout.PAYMENT_RESULT_CODE) {
            final Payment payment = (Payment) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_PAYMENT_RESULT);
            ((TextView) findViewById(R.id.mp_results)).setText("Resultado del pago: " + payment.getStatus());
            //Done!
        } else if (resultCode == RESULT_CANCELED) {
            if (data != null && data.getExtras() != null
                && data.getExtras().containsKey(MercadoPagoCheckout.EXTRA_ERROR)) {
                final MercadoPagoError mercadoPagoError =
                    (MercadoPagoError) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_ERROR);
                ((TextView) findViewById(R.id.mp_results)).setText("Error: " +  mercadoPagoError.getMessage());
                //Resolve error in checkout
            } else {
                //Resolve canceled checkout
            }
        }
    }
}

That's it! Please, be free to improve the above code. Mainly, regarding to the security issues.


来源: stackexchange

问:
static website hosted in s3: pages return 404 after refresh
With this bucket policy:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::mypage.com/*"
        }
    ]
}
</code>```

I am deploying a website that is build by reactJS v16+ (react-router-dom v5), and when I open the url, it works perfectly, e.g. from mypage.com, the  that goes to /list works fine. Url is loaded as mypage.com/list and the page content is displayed.

However on any child page that is not homepage, for example mypage.com/list, once I refresh the page with browser, it returns S3's 404:

```<code>404 Not Found

    Code: NoSuchKey
    Message: The specified key does not exist.
    Key: list
</code>```

I don't even know how to debug this... any idea?

答:
As @Panther mentioned in the comment, the right way to go is to add an error fallback to index.html in the S3 bucket's static web hosting configuration.

The reason of this is when a URL is hit (either by manual input in the browser or a refresh), it sends a request to /list to the S3's root server (the one managed by AWS) before it hits our bucket. That S3 server have no idea if this is a reactjs app or not, so it goes into the bucket to look for the /list in the root of my bucket, which doesn't exist, so it returns the 404 error.

However by adding the error fallback, now when it gets 404, it redirects the request to index.html, where the react app defined and loaded into. In this case, the /list will go through the normal flow to reach the right router that handles page rendering, problem solved.

ContentLicense: CC BY-SA 4.0

Body:
With this bucket policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::mypage.com/*"
        }
    ]
}

I am deploying a website that is build by reactJS v16+ (react-router-dom v5), and when I open the url, it works perfectly, e.g. from mypage.com, the  that goes to /list works fine. Url is loaded as mypage.com/list and the page content is displayed.

However on any child page that is not homepage, for example mypage.com/list, once I refresh the page with browser, it returns S3's 404:

404 Not Found

    Code: NoSuchKey
    Message: The specified key does not exist.
    Key: list

I don't even know how to debug this... any idea?


问:
Swift How to wrap long text of label in collection cell and set margin in text label
For now, I am using custom collection view layout to implement this.

Each cell contains a label with different length of text. I return the width of cell by using the function below:

```<code>func collectionView(collectionView: UICollectionView, widthForSubsectionAtIndexPath indexPath: NSIndexPath, height: CGFloat) -> CGFloat {
    let text = subsections[indexPath.row]
    let font = UIFont(name: "Helvetica neue", size: 24)
    dLog("height ==> \(height)")
    let rect = NSString(string: text).boundingRectWithSize(CGSize(width: CGFloat(MAXFLOAT), height: height), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font!], context: nil)
    dLog("rect ==> \(rect)")
    return rect.width
}
</code>```

This can wrap text just as shown in picture. But I also want to make the distance between text is the same. The red circles above are not in same size. I guess it depends on the length of text.

Here is the constrain that I am using:

How can I set margin distance between text and cell same and at same time wrap words correctly?

BTW, When I output the height and rect information in console, I find the height information is different. The height of grey bar is actually 50. Here is the output:

[SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 63.192, 27.96)
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 60.432, 27.96)
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 241.8, 27.96)
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 98.232, 27.96)
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 56.88, 27.96)

答:
Inside your custom collectionView cell object, set your label's numberOfLines property to zero.

```<code>label.numberOfLines = 0
</code>```

then in your constraints, pin your label on the leading and trailing edges of the custom collectionView cells.

```<code>yourLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
yourLabel.trailingAnchor.constraint(equalTo: trailingAnchor)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For now, I am using custom collection view layout to implement this.

Each cell contains a label with different length of text. I return the width of cell by using the function below:

func collectionView(collectionView: UICollectionView, widthForSubsectionAtIndexPath indexPath: NSIndexPath, height: CGFloat) -> CGFloat {
    let text = subsections[indexPath.row]
    let font = UIFont(name: "Helvetica neue", size: 24)
    dLog("height ==> \(height)")
    let rect = NSString(string: text).boundingRectWithSize(CGSize(width: CGFloat(MAXFLOAT), height: height), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font!], context: nil)
    dLog("rect ==> \(rect)")
    return rect.width
}

This can wrap text just as shown in picture. But I also want to make the distance between text is the same. The red circles above are not in same size. I guess it depends on the length of text.

Here is the constrain that I am using:

How can I set margin distance between text and cell same and at same time wrap words correctly?

BTW, When I output the height and rect information in console, I find the height information is different. The height of grey bar is actually 50. Here is the output:

[SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 63.192, 27.96)
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 60.432, 27.96)
  2016-06-24 12:13:50.507 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 241.8, 27.96)
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 98.232, 27.96)
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:91] collectionView(:widthForSubsectionAtIndexPath:height:) - height ==> 50.0
  2016-06-24 12:13:50.508 Atlas[12714:496386] [SubsectionHeaderCollectionViewController.swift:93] collectionView(:widthForSubsectionAtIndexPath:height:) - rect ==> (0.0, 0.0, 56.88, 27.96)

Body:
Inside your custom collectionView cell object, set your label's numberOfLines property to zero.

label.numberOfLines = 0

then in your constraints, pin your label on the leading and trailing edges of the custom collectionView cells.

yourLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
yourLabel.trailingAnchor.constraint(equalTo: trailingAnchor)


问:
How to send QMap over socket?
I have a QMap object:

```<code>QMap<QString, int> map;
</code>```

and I would like to send it over TCP socket. Do I have to convert it to JSON and then send it or?

答:
Try to use this approach:

On Server side use this to send a map:

```<code>// to send Map
qint64 SendMap(QMap<String, int> map){
    QByteArray block;
    QDataStream sendStream(&block, QIODevice::ReadWrite);

    sendStream << quint64(0) // for size of data
               << map;       // your map

    sendStream.device()->seek(0); // return back to set data size

    sendStream << (quint64)(block.size() - sizeof(quint64)); // set data size

    return socket->write(block);    // send data
}
</code>```

On Client side, when you expect a map, use this to read a map:

```<code>// to receive Map
QMap<QString, int> ReceiveMap(QTcpSocket *socket){
    QDataStream readStream(socket);
    quint64 dataBlockSize = 0;

    while(true) {
        if (!dataBlockSize) {
            if (socket->bytesAvailable() < sizeof(quint64)) { // waiting data size
                break;                                        // to be available
            }
            readStream >> dataBlockSize;
        }

        if (socket->bytesAvailable() < dataBlockSize) { // waiting full data
            break;
        }

        QMap<QString, int> map;
        readStream >> map;

        return map;
    }
}
</code>```

Title: How to send QMap over socket?

Body:
I have a QMap object:

QMap<QString, int> map;

and I would like to send it over TCP socket. Do I have to convert it to JSON and then send it or?

Body:
Try to use this approach:

On Server side use this to send a map:

// to send Map
qint64 SendMap(QMap<String, int> map){
    QByteArray block;
    QDataStream sendStream(&block, QIODevice::ReadWrite);

    sendStream << quint64(0) // for size of data
               << map;       // your map

    sendStream.device()->seek(0); // return back to set data size

    sendStream << (quint64)(block.size() - sizeof(quint64)); // set data size

    return socket->write(block);    // send data
}

On Client side, when you expect a map, use this to read a map:

// to receive Map
QMap<QString, int> ReceiveMap(QTcpSocket *socket){
    QDataStream readStream(socket);
    quint64 dataBlockSize = 0;

    while(true) {
        if (!dataBlockSize) {
            if (socket->bytesAvailable() < sizeof(quint64)) { // waiting data size
                break;                                        // to be available
            }
            readStream >> dataBlockSize;
        }

        if (socket->bytesAvailable() < dataBlockSize) { // waiting full data
            break;
        }

        QMap<QString, int> map;
        readStream >> map;

        return map;
    }
}


问:
Reference array keys without knowing their names?
If I have an array like this:

```<code>$array = array('something'=>array('more'=>array('id'=> 34)));
</code>```

Then print_r($array['something']['more']['id'] works fine.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.

答:
You can use a foreach statement. Use a recursive function to handle nested arrays (untested):

```<code>public function iterateNestedArray($array) {
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            print_r(iterateNestedArray($value));
        }
    }
    else {
        return $array;
    }
}
</code>```

You might consider implementing this function with a second argument to pass a callback function, rather than just print_ring every value.

Body:
If I have an array like this:

$array = array('something'=>array('more'=>array('id'=> 34)));

Then print_r($array['something']['more']['id'] works fine.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.

Body:
You can use a foreach statement. Use a recursive function to handle nested arrays (untested):

public function iterateNestedArray($array) {
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            print_r(iterateNestedArray($value));
        }
    }
    else {
        return $array;
    }
}

You might consider implementing this function with a second argument to pass a callback function, rather than just print_ring every value.


问:
Convert Uint8List to String with Dart
cipher.process returns an Uint8List which is a list of unsigned integers (0-255). I need to convert this Uint8List to a string that I can easily convert back to the same Uint8List.

    var cipherText = cipher.process( inputAsUint8List );
    return ASCII.decode(cipherText);
```

ASCII.decode throws an error since some of the integers are > 127.

答:
Dart uses UTF-16 to store Strings. For now in Dart there is no simple way of converting it easly to bytes and backwards. Therefore, you can use raw calculations to convert String to Uint8List and backwards.

Dart code:

import 'dart:typed_data';

void main() {
  // Source
  String source = 'Hello! Cześć! 你好! ご挨拶！Привет! ℌ! !';
  print(source.length.toString() + ': "' + source + '" (' + source.runes.length.toString() + ')');

  // String (Dart uses UTF-16) to bytes
  var list = new List<int>();
  source.runes.forEach((rune) {
    if (rune >= 0x10000) {
      rune -= 0x10000;
      int firstWord = (rune >> 10) + 0xD800;
      list.add(firstWord >> 8);
      list.add(firstWord & 0xFF);
      int secondWord = (rune & 0x3FF) + 0xDC00;
      list.add(secondWord >> 8);
      list.add(secondWord & 0xFF);
    }
    else {
        list.add(rune >> 8);
        list.add(rune & 0xFF);
    }
  });
  Uint8List bytes = Uint8List.fromList(list);

  // Here you have `Uint8List` available

  // Bytes to UTF-16 string
  StringBuffer buffer = new StringBuffer();
  for (int i = 0; i < bytes.length;) {
    int firstWord = (bytes[i] << 8) + bytes[i + 1];
    if (0xD800 <= firstWord && firstWord <= 0xDBFF) {
      int secondWord = (bytes[i + 2] << 8) + bytes[i + 3];
      buffer.writeCharCode(((firstWord - 0xD800) << 10) + (secondWord - 0xDC00) + 0x10000);
      i += 4;
    }
    else {
        buffer.writeCharCode(firstWord);
      i += 2;
    }
  }

  // Outcome
  String outcome = buffer.toString();
  print(outcome.length.toString() + ': "' + outcome + '" (' + outcome.runes.length.toString() + ')');
}
```

<p>Result:</p>

```52: "Hello! Cześć! 你好! ご挨拶！Привет! ℌ! !" (43)
52: "Hello! Cześć! 你好! ご挨拶！Привет! ℌ! !" (43)
```

Run it online

Title: Convert Uint8List to String with Dart

Body:
cipher.process returns an Uint8List which is a list of unsigned integers (0-255). I need to convert this Uint8List to a string that I can easily convert back to the same Uint8List.

    var cipherText = cipher.process( inputAsUint8List );
    return ASCII.decode(cipherText);

ASCII.decode throws an error since some of the integers are > 127.

Body:
Dart uses UTF-16 to store Strings. For now in Dart there is no simple way of converting it easly to bytes and backwards. Therefore, you can use raw calculations to convert String to Uint8List and backwards.

Dart code:

import 'dart:typed_data';

void main() {
  // Source
  String source = 'Hello! Cześć! 你好! ご挨拶！Привет! ℌ! !';
  print(source.length.toString() + ': "' + source + '" (' + source.runes.length.toString() + ')');

  // String (Dart uses UTF-16) to bytes
  var list = new List<int>();
  source.runes.forEach((rune) {
    if (rune >= 0x10000) {
      rune -= 0x10000;
      int firstWord = (rune >> 10) + 0xD800;
      list.add(firstWord >> 8);
      list.add(firstWord & 0xFF);
      int secondWord = (rune & 0x3FF) + 0xDC00;
      list.add(secondWord >> 8);
      list.add(secondWord & 0xFF);
    }
    else {
        list.add(rune >> 8);
        list.add(rune & 0xFF);
    }
  });
  Uint8List bytes = Uint8List.fromList(list);

  // Here you have `Uint8List` available

  // Bytes to UTF-16 string
  StringBuffer buffer = new StringBuffer();
  for (int i = 0; i < bytes.length;) {
    int firstWord = (bytes[i] << 8) + bytes[i + 1];
    if (0xD800 <= firstWord && firstWord <= 0xDBFF) {
      int secondWord = (bytes[i + 2] << 8) + bytes[i + 3];
      buffer.writeCharCode(((firstWord - 0xD800) << 10) + (secondWord - 0xDC00) + 0x10000);
      i += 4;
    }
    else {
        buffer.writeCharCode(firstWord);
      i += 2;
    }
  }

  // Outcome
  String outcome = buffer.toString();
  print(outcome.length.toString() + ': "' + outcome + '" (' + outcome.runes.length.toString() + ')');
}

Result:

52: "Hello! Cześć! 你好! ご挨拶！Привет! ℌ! !" (43)
52: "Hello! Cześć! 你好! ご挨拶！Привет! ℌ! !" (43)

Run it online


问:
is it possible to get another view's width in flutter?
I want to make this design , can we get another widget's width ?

As per shown in image I want to make underline below the Text widget and width of Text is wrap so underline width is also change according to Text name.

答:
Did you try this approach?</p>

```<code> Text(
      "Some Text With Underline",
      softWrap: true,
      textAlign: TextAlign.center,
      style: TextStyle(
        decoration: textdecoration,
      ),
    );
</code>```

Body:
Did you try this approach?

 Text(
      "Some Text With Underline",
      softWrap: true,
      textAlign: TextAlign.center,
      style: TextStyle(
        decoration: textdecoration,
      ),
    );


问:
Vba Excel Code does not read a third worksheet
I'm working with two workbooks, both with different sheets. The code is writen for the Workbook called "Rober.xslm" and in the following macro I open another workbook ("Formato permisos.xlsm") and read values in some sheets to work with them in my original workbook. Firstly I managed to read the values from the sheet "Requisitos contenedor + ATI" in the workbook "Formato permisos.xlsm" and work with then in my sheet "Seleccion_ECs" from "Rober.xlsm".

The problem comes when I select, or activate, or open the sheet "ECs full" from the workbook "Rober.xlsm". I don't understand why this statement:
Set shECF=wbDest.Worksheets("ECs full")
returns Nothing if I also have this one:
Set shrelacion=wbDest.Worksheets("Relación ciclo y fechas")
and it works with it! The name ECs full is well written. It's a normal sheet, not a chartsheet.

```<code>Set wbSource = Workbooks.Open(sFileName)

Debug.Print (wbSource.Name) '"Formato permisos.xlsm"

If Err.Number <> 0 Then Debug.Print ("Error number en Libro gráficas: " & Err.Number)

If Err.Number = 0 Then Debug.Print ("No ha habido error en libro gráficas")

Set Requisitos = wbSource.Worksheets("Requisitos Contenedor + ATI")

Set QvsE = Workbooks.Open(sFileName) 'wbSource.Charts("Curva - QvsE")

Set wbDest = ThisWorkbook 'Workbooks("Rober.xlsm")

Debug.Print (wbDest.Name) '"Rober.xlsm"

If Err.Number <> 0 Then Debug.Print ("Error number en Libro Rober: " & Err.Number)

Set shEC = wbDest.Worksheets("Seleccion_ECs")

If Err.Number <> 0 Then Debug.Print ("Error number en hoja Seleccion_ECs: " & Err.Number)

im fechaActual As Variant, fechaEOC As Date

Dim shECF As Worksheets, rangoECF As Range

Dim nFilasECF As Double, nColumECF As Double, años As Double

Set shECF = wbDest.Worksheets("ECs full")

'wbDest.Sheets("ECs_full").Activate --These are some thigs I tried

'wbDest.Sheets("ECs_full").Select

If Err.Number <> 0 Then Debug.Print ("Error al seleccionar hoja ECs full: " & Err.Number)

MsgBox ThisWorkbook.Path & vbNewLine & ThisWorkbook.Name 'Archivo Rober

Set rangoECF = Sheets("ECs full").UsedRange

    nFilasECF = rangoECF.Rows.Count

    nColumECF = rangoECF.Columns.Count

Set shrelacion = wbDest.Worksheets("Relación ciclo y fechas")

For g = 1 To nColumECF

    If shECF.Cells(1, g) = "último ciclo de operación" Then

        C = shECF.Cells(1, g).Column 'Don't manage to get this value since I can't read the sheet "ECs full"

    End If

Next g
</code>```

答:
It took me a while to see this

```<code>Dim shECF As Worksheet
</code>```

(Not Worksheets)

Body:
I'm working with two workbooks, both with different sheets. The code is writen for the Workbook called "Rober.xslm" and in the following macro I open another workbook ("Formato permisos.xlsm") and read values in some sheets to work with them in my original workbook. Firstly I managed to read the values from the sheet "Requisitos contenedor + ATI" in the workbook "Formato permisos.xlsm" and work with then in my sheet "Seleccion_ECs" from "Rober.xlsm".

The problem comes when I select, or activate, or open the sheet "ECs full" from the workbook "Rober.xlsm". I don't understand why this statement:
Set shECF=wbDest.Worksheets("ECs full")
returns Nothing if I also have this one:
Set shrelacion=wbDest.Worksheets("Relación ciclo y fechas")
and it works with it! The name ECs full is well written. It's a normal sheet, not a chartsheet.

Set wbSource = Workbooks.Open(sFileName)

Debug.Print (wbSource.Name) '"Formato permisos.xlsm"

If Err.Number <> 0 Then Debug.Print ("Error number en Libro gráficas: " & Err.Number)

If Err.Number = 0 Then Debug.Print ("No ha habido error en libro gráficas")

Set Requisitos = wbSource.Worksheets("Requisitos Contenedor + ATI")

Set QvsE = Workbooks.Open(sFileName) 'wbSource.Charts("Curva - QvsE")

Set wbDest = ThisWorkbook 'Workbooks("Rober.xlsm")

Debug.Print (wbDest.Name) '"Rober.xlsm"

If Err.Number <> 0 Then Debug.Print ("Error number en Libro Rober: " & Err.Number)

Set shEC = wbDest.Worksheets("Seleccion_ECs")

If Err.Number <> 0 Then Debug.Print ("Error number en hoja Seleccion_ECs: " & Err.Number)

im fechaActual As Variant, fechaEOC As Date

Dim shECF As Worksheets, rangoECF As Range

Dim nFilasECF As Double, nColumECF As Double, años As Double

Set shECF = wbDest.Worksheets("ECs full")

'wbDest.Sheets("ECs_full").Activate --These are some thigs I tried

'wbDest.Sheets("ECs_full").Select

If Err.Number <> 0 Then Debug.Print ("Error al seleccionar hoja ECs full: " & Err.Number)

MsgBox ThisWorkbook.Path & vbNewLine & ThisWorkbook.Name 'Archivo Rober

Set rangoECF = Sheets("ECs full").UsedRange

    nFilasECF = rangoECF.Rows.Count

    nColumECF = rangoECF.Columns.Count

Set shrelacion = wbDest.Worksheets("Relación ciclo y fechas")

For g = 1 To nColumECF

    If shECF.Cells(1, g) = "último ciclo de operación" Then

        C = shECF.Cells(1, g).Column 'Don't manage to get this value since I can't read the sheet "ECs full"

    End If

Next g

Body:
It took me a while to see this

Dim shECF As Worksheet

(Not Worksheets)


问:
adding single marker on map, Android, Google API
On my application i receive coordinates from a remote server and i want to mark the location on the coordinates on a map, this happens on demand inside onClick method. The problem is that when i update the location i end up with multiple markers on the map instead of just one, the current location. is there any way to remove the previous marker before adding the next one?

I followed the steps in this tutorial : http://developer.android.com/resources/tutorials/views/hello-mapview.html

And my code goes like this :

```<code>public class AppTwoAndroid extends MapActivity {
private Button refreshButton;
double lat, lon;
ConnectionHandler conhandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    Log.i("AppTwo", "making connectionhandler object");
    conhandler = new ConnectionHandler();
    conhandler.execute();

    Log.i("AppTwo", "making button");
    this.refreshButton = (Button)this.findViewById(R.id.close);

    final List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
    final AppTwoAndroidItemizedOverlay itemizedoverlay = new AppTwoAndroidItemizedOverlay(drawable);

    refreshButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i("AppTwo", "inside onclick");
            if (mapOverlays.contains(itemizedoverlay) == true) {
                mapOverlays.remove(itemizedoverlay);
            }
            conhandler.write();
            lat = conhandler.retLat();
            lon = conhandler.retLon();
            lat = lat * 1e6;
            lon = lon * 1e6;
            int ilat = (int) lat;
            int ilon = (int) lon;
            GeoPoint point = new GeoPoint(ilat ,ilon);
            OverlayItem overlayitem = new OverlayItem(point, null, "AppOne");
            itemizedoverlay.addOverlay(overlayitem);
            mapOverlays.add(itemizedoverlay);

            Toast.makeText(getBaseContext(), "lat is: " + lat + " lon is: " + lon
                    ,  Toast.LENGTH_SHORT).show();

            }
    });
}
@Override
     protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}
</code>```

and my AppTwoAndroidItemizedOverlay class is :

```<code>public class AppTwoAndroidItemizedOverlay extends ItemizedOverlay {

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;

public AppTwoAndroidItemizedOverlay(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));
    // TODO Auto-generated constructor stub
}

@Override
protected boolean onTap(int index) {
  OverlayItem item = mOverlays.get(index);
  AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
  dialog.setTitle(item.getTitle());
  dialog.setMessage(item.getSnippet());
  dialog.show();
  return true;
}

public AppTwoAndroidItemizedOverlay(Drawable defaultMarker, Context context) {
      super(defaultMarker);
      mContext = context;
}

public void addOverlay(OverlayItem overlay) {
    mOverlays.add(overlay);
    populate();
}

@Override
protected OverlayItem createItem(int i) {
  return mOverlays.get(i);
}

@Override
public int size() {
  return mOverlays.size();
}

}
</code>```

答:
In the onClick method just give

mapOverlays.clear();

this should clear any existing markers.

Hope this works :)

Body:
On my application i receive coordinates from a remote server and i want to mark the location on the coordinates on a map, this happens on demand inside onClick method. The problem is that when i update the location i end up with multiple markers on the map instead of just one, the current location. is there any way to remove the previous marker before adding the next one?

I followed the steps in this tutorial : http://developer.android.com/resources/tutorials/views/hello-mapview.html

And my code goes like this :

public class AppTwoAndroid extends MapActivity {
private Button refreshButton;
double lat, lon;
ConnectionHandler conhandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    MapView mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    Log.i("AppTwo", "making connectionhandler object");
    conhandler = new ConnectionHandler();
    conhandler.execute();

    Log.i("AppTwo", "making button");
    this.refreshButton = (Button)this.findViewById(R.id.close);

    final List<Overlay> mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
    final AppTwoAndroidItemizedOverlay itemizedoverlay = new AppTwoAndroidItemizedOverlay(drawable);

    refreshButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.i("AppTwo", "inside onclick");
            if (mapOverlays.contains(itemizedoverlay) == true) {
                mapOverlays.remove(itemizedoverlay);
            }
            conhandler.write();
            lat = conhandler.retLat();
            lon = conhandler.retLon();
            lat = lat * 1e6;
            lon = lon * 1e6;
            int ilat = (int) lat;
            int ilon = (int) lon;
            GeoPoint point = new GeoPoint(ilat ,ilon);
            OverlayItem overlayitem = new OverlayItem(point, null, "AppOne");
            itemizedoverlay.addOverlay(overlayitem);
            mapOverlays.add(itemizedoverlay);

            Toast.makeText(getBaseContext(), "lat is: " + lat + " lon is: " + lon
                    ,  Toast.LENGTH_SHORT).show();

            }
    });
}
@Override
     protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

and my AppTwoAndroidItemizedOverlay class is :

public class AppTwoAndroidItemizedOverlay extends ItemizedOverlay {

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;

public AppTwoAndroidItemizedOverlay(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));
    // TODO Auto-generated constructor stub
}

@Override
protected boolean onTap(int index) {
  OverlayItem item = mOverlays.get(index);
  AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
  dialog.setTitle(item.getTitle());
  dialog.setMessage(item.getSnippet());
  dialog.show();
  return true;
}

public AppTwoAndroidItemizedOverlay(Drawable defaultMarker, Context context) {
      super(defaultMarker);
      mContext = context;
}

public void addOverlay(OverlayItem overlay) {
    mOverlays.add(overlay);
    populate();
}

@Override
protected OverlayItem createItem(int i) {
  return mOverlays.get(i);
}

@Override
public int size() {
  return mOverlays.size();
}

}


问:
when using the llvm pass on a program, error: unable to execute command: Segmentation fault (core dumped)
A simple LLVM pass example, for LLVM-7.0.0.
I get this error when trying to run:

clang -I~/clang_llvm2/include -Xclang -load -Xclang build/skeleton/libSkeletonPass.* test/a.cpp

I saw a function called main!

...

clang-7: error: unable to execute command: Segmentation fault (core dumped)
clang-7: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 7.0.0 (tags/RELEASE_700/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
clang-7: note: diagnostic msg: PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash backtrace, preprocessed source, and associated run script.
clang-7: error: unable to execute command: Segmentation fault (core dumped)
clang-7: note: diagnostic msg: Error generating preprocessed source(s).

The simple LLVM pass for LLVM-7.0.0

```<code>#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace llvm;

namespace {
  struct SkeletonPass : public FunctionPass {
    static char ID;
    SkeletonPass() : FunctionPass(ID) {}

    bool runOnFunction(Function &F) {
      errs() << "I saw a function called " << F.getName() << "!\n";
      return false;
    }
  };
}

char SkeletonPass::ID = 0;

// Automatically enable the pass.
// http://adriansampson.net/blog/clangpass.html
static void registerSkeletonPass(const PassManagerBuilder &,
                         legacy::PassManagerBase &PM) {
  PM.add(new SkeletonPass());
}
static RegisterStandardPasses
  RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible,
                 registerSkeletonPass);
</code>```

a.cpp program is a simple hello world program.
LLVM_HOME is properly set.
Using prebuilt llvm files.

答:
You're not alone with this error (https://bugs.llvm.org/show_bug.cgi?id=34573), LLVM seems to crash at the end of the program when RegisterStandardPasses is used since LLVM 5.

According to this answer: https://github.com/sampsyo/llvm-pass-skeleton/issues/7#issuecomment-401834287 a solution is to add -Wl,-znodelete to the compiler flags when you link your program. It worked for me.

Body:
A simple LLVM pass example, for LLVM-7.0.0.
I get this error when trying to run:

clang -I~/clang_llvm2/include -Xclang -load -Xclang build/skeleton/libSkeletonPass.* test/a.cpp

I saw a function called main!

...

clang-7: error: unable to execute command: Segmentation fault (core dumped)
clang-7: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 7.0.0 (tags/RELEASE_700/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
clang-7: note: diagnostic msg: PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash backtrace, preprocessed source, and associated run script.
clang-7: error: unable to execute command: Segmentation fault (core dumped)
clang-7: note: diagnostic msg: Error generating preprocessed source(s).

The simple LLVM pass for LLVM-7.0.0

#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
using namespace llvm;

namespace {
  struct SkeletonPass : public FunctionPass {
    static char ID;
    SkeletonPass() : FunctionPass(ID) {}

    bool runOnFunction(Function &F) {
      errs() << "I saw a function called " << F.getName() << "!\n";
      return false;
    }
  };
}

char SkeletonPass::ID = 0;

// Automatically enable the pass.
// http://adriansampson.net/blog/clangpass.html
static void registerSkeletonPass(const PassManagerBuilder &,
                         legacy::PassManagerBase &PM) {
  PM.add(new SkeletonPass());
}
static RegisterStandardPasses
  RegisterMyPass(PassManagerBuilder::EP_EarlyAsPossible,
                 registerSkeletonPass);

a.cpp program is a simple hello world program.
LLVM_HOME is properly set.
Using prebuilt llvm files.


问:
Unable to display the current status of a process in VB.Net
I have written below piece of code to achieve my task of exporting printers details on the machine. Below code works without any issues.

Generally, it takes a few seconds or more to generate the printer details file, hence I would like to display the status of this process on a label or text box (like "File is being generated. Please wait..", "File is generated.." etc.)

I'm unable to get the right status on the label with below code. It directly shows the "File is generated" status. But if put messagebox before and after while loop then it works fine.

Any assistance is greatly helpful. Thank you.

```<code>Label1.Text = "Status: File is being generated. Please wait.."

Dim pPrintBrm As New ProcessStartInfo
pPrintBrm.FileName = "C:\Windows\System32\spool\tools\PrintBrm.exe"
pPrintBrm.Arguments = " " & "-B" & " " & "-F" & " " &
My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport"
pPrintBrm.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(pPrintBrm)

Dim exists As Boolean = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")

MessageBox.Show("before while " & exists)

While (exists = "False")

exists = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")

End While

MessageBox.Show("after while " & exists)

If File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport") Then

Label1.Text = "Status: File is generated"
Else
Label1.Text = "Status: Failed"
End If
</code>```

答:
You can use Async/Await to keep your app responsive while it is in the loop:

```<code>Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Label1.Text = "Status: File is being generated. Please wait.."

    Dim pPrintBrm As New ProcessStartInfo
    pPrintBrm.FileName = "C:\Windows\System32\spool\tools\PrintBrm.exe"
    pPrintBrm.Arguments = " " & "-B" & " " & "-F" & " " &
    My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport"
    pPrintBrm.WindowStyle = ProcessWindowStyle.Hidden
    Process.Start(pPrintBrm)

    Dim exists As Boolean
    Do
        Await Task.Delay(250) ' <-- code pauses here, but the UI is still responsive and updates
        exists = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")
    Loop While (Not exists)

    If exists Then
        Label1.Text = "Status: File is generated"
    Else
        Label1.Text = "Status: Failed" ' <-- how can you ever get here with the above loop?!
    End If
End Sub
</code>```

Note that the sub declaration has been marked with "Async".

Body:
I have written below piece of code to achieve my task of exporting printers details on the machine. Below code works without any issues.

Generally, it takes a few seconds or more to generate the printer details file, hence I would like to display the status of this process on a label or text box (like "File is being generated. Please wait..", "File is generated.." etc.)

I'm unable to get the right status on the label with below code. It directly shows the "File is generated" status. But if put messagebox before and after while loop then it works fine.

Any assistance is greatly helpful. Thank you.

Label1.Text = "Status: File is being generated. Please wait.."

Dim pPrintBrm As New ProcessStartInfo
pPrintBrm.FileName = "C:\Windows\System32\spool\tools\PrintBrm.exe"
pPrintBrm.Arguments = " " & "-B" & " " & "-F" & " " &
My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport"
pPrintBrm.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(pPrintBrm)

Dim exists As Boolean = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")

MessageBox.Show("before while " & exists)

While (exists = "False")

exists = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")

End While

MessageBox.Show("after while " & exists)

If File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport") Then

Label1.Text = "Status: File is generated"
Else
Label1.Text = "Status: Failed"
End If

Body:
You can use Async/Await to keep your app responsive while it is in the loop:

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Label1.Text = "Status: File is being generated. Please wait.."

    Dim pPrintBrm As New ProcessStartInfo
    pPrintBrm.FileName = "C:\Windows\System32\spool\tools\PrintBrm.exe"
    pPrintBrm.Arguments = " " & "-B" & " " & "-F" & " " &
    My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport"
    pPrintBrm.WindowStyle = ProcessWindowStyle.Hidden
    Process.Start(pPrintBrm)

    Dim exists As Boolean
    Do
        Await Task.Delay(250) ' <-- code pauses here, but the UI is still responsive and updates
        exists = File.Exists(My.Computer.FileSystem.CurrentDirectory & "\Extracted\Printer.PrinterExport")
    Loop While (Not exists)

    If exists Then
        Label1.Text = "Status: File is generated"
    Else
        Label1.Text = "Status: Failed" ' <-- how can you ever get here with the above loop?!
    End If
End Sub

Note that the sub declaration has been marked with "Async".


问:
RecyclerView/SnapHelper - How to set variable position of the cards so that they peek differently based on position
I am new to android and hence RV and I am trying to achieve the layout where the first and last card are not centered and instead show more of the cards after and before them. Maybe at In this case I can see 16dp for the second cards and same thing for the penultimate card which makes the first and last card not centered.
But 8dp each for the rest of the cards so the intermediate cards appear centered. Maybe using itemDecoration somehow for the 2nd and the penultimate card somehow.

I was able to achieve showing parts of next and prev cards by following what is suggested here, but that only centers all the cards uniformly :
How to show part of next/previous card RecyclerView

I tried overriding getItemOffsets but it gets triggered everytime I scroll to the first or the last card and moves the 2nd and 2nd to last card incorrectly
and also doesn't center them correctly when I scroll to them.

```<code>  public static class MyItemDecoration extends RecyclerView.ItemDecoration {

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
      super.getItemOffsets(outRect, view, parent, state);

      final int itemPosition = parent.getChildAdapterPosition(view);
      if (itemPosition == RecyclerView.NO_POSITION) {
        return;
      }

      final int itemCount = state.getItemCount();
      if (itemCount > 0 && itemPosition == 1) {
        outRect.left -= 16;
        outRect.right -= 16;
      }

      else if (itemCount > 0 && itemPosition == itemCount - 1) {
        outRect.left += 16;
        outRect.right += 16;
      }
    }
  }
</code>```

RV Setup

```<code> SnapHelper snapHelper = new PagerSnapHelper();
        RecyclerView rv = getBinding().rv;
        rv.setOnFlingListener(null);
        snapHelper.attachToRecyclerView(rv);
</code>```

答:
PagerSnapHelper centers the RecyclerView items including the decorations, so, unless the decoration widths are balanced, they won't always be centered. This may be what you are seeing.

Try the following for the decoration. This code applies the full-width decoration to the start of the first item and the end of the last item; otherwise, a half decoration width is used. By setting up the decorations this way, you are centering items that have balanced left and right decorations.

```<code>DividerItemDecoration decoration =
        new DividerItemDecoration(getApplicationContext(), HORIZONTAL) {
            private int mDecorationWidth = (int) (getResources().getDisplayMetrics().density * 8);

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                                       RecyclerView.State state) {
                final int pos = parent.getChildAdapterPosition(view);
                if (pos == RecyclerView.NO_POSITION) {
                    return;
                }
                if (pos == 0) {
                    outRect.set(mDecorationWidth, 0, mDecorationWidth / 2, 0);
                } else if (pos == parent.getAdapter().getItemCount() - 1) {
                    outRect.set(mDecorationWidth / 2, 0, mDecorationWidth, 0);
                } else {
                    outRect.set(mDecorationWidth / 2, 0, mDecorationWidth / 2, 0);
                }
            }
        };
</code>```

Here is a video showing the results with gray vertical dividers.

If you already have the decorations working to your satisfaction, you can override calculateDistanceToFinalSnap() in PagerSnapHelper to center all views except the first and last view as follows. See calculatedistancetofinalsnap(). Once the PageSnapHelper identifies a target view to snap to, calculatedistancetofinalsnap() is called to determine how many pixels to move to perform the snap. Here, we are moving just enough pixels to center the view (without decorations) in the RecyclerView. PageSnapHelper does the right thing for the first and last items, so we just call the super for these.

```<code>PagerSnapHelper pagerSnapHelper = new PagerSnapHelper() {

    @Override
  public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager,
                                              @NonNull View targetView) {
        LinearLayoutManager lm = (LinearLayoutManager) layoutManager;
        int pos = mRecycler.getChildAdapterPosition(targetView);
        // If first or last view, the default implementation works.
  if (pos == 0 || pos == lm.getItemCount() - 1) {
            return super.calculateDistanceToFinalSnap(layoutManager, targetView);
        }
        // Force centering in the view without its decorations.
        // targetCenter is the location of the center of the view we want to center.
        int targetCenter = targetView.getLeft() + targetView.getWidth() / 2;
        // Distance is the number of pixels to move the target so that its center
        // lines up with the center of the RecyclerView (mRecycler.getWidth() / 2)
        int distance = targetCenter - mRecycler.getWidth() / 2;
        return new int[]{distance, 0};
    }
};
</code>```

Either way will work.

Body:
I am new to android and hence RV and I am trying to achieve the layout where the first and last card are not centered and instead show more of the cards after and before them. Maybe at In this case I can see 16dp for the second cards and same thing for the penultimate card which makes the first and last card not centered.
But 8dp each for the rest of the cards so the intermediate cards appear centered. Maybe using itemDecoration somehow for the 2nd and the penultimate card somehow.

I was able to achieve showing parts of next and prev cards by following what is suggested here, but that only centers all the cards uniformly :
How to show part of next/previous card RecyclerView

I tried overriding getItemOffsets but it gets triggered everytime I scroll to the first or the last card and moves the 2nd and 2nd to last card incorrectly
and also doesn't center them correctly when I scroll to them.

  public static class MyItemDecoration extends RecyclerView.ItemDecoration {

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
      super.getItemOffsets(outRect, view, parent, state);

      final int itemPosition = parent.getChildAdapterPosition(view);
      if (itemPosition == RecyclerView.NO_POSITION) {
        return;
      }

      final int itemCount = state.getItemCount();
      if (itemCount > 0 && itemPosition == 1) {
        outRect.left -= 16;
        outRect.right -= 16;
      }

      else if (itemCount > 0 && itemPosition == itemCount - 1) {
        outRect.left += 16;
        outRect.right += 16;
      }
    }
  }

RV Setup

 SnapHelper snapHelper = new PagerSnapHelper();
        RecyclerView rv = getBinding().rv;
        rv.setOnFlingListener(null);
        snapHelper.attachToRecyclerView(rv);

Body:
PagerSnapHelper centers the RecyclerView items including the decorations, so, unless the decoration widths are balanced, they won't always be centered. This may be what you are seeing.

Try the following for the decoration. This code applies the full-width decoration to the start of the first item and the end of the last item; otherwise, a half decoration width is used. By setting up the decorations this way, you are centering items that have balanced left and right decorations.

DividerItemDecoration decoration =
        new DividerItemDecoration(getApplicationContext(), HORIZONTAL) {
            private int mDecorationWidth = (int) (getResources().getDisplayMetrics().density * 8);

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                                       RecyclerView.State state) {
                final int pos = parent.getChildAdapterPosition(view);
                if (pos == RecyclerView.NO_POSITION) {
                    return;
                }
                if (pos == 0) {
                    outRect.set(mDecorationWidth, 0, mDecorationWidth / 2, 0);
                } else if (pos == parent.getAdapter().getItemCount() - 1) {
                    outRect.set(mDecorationWidth / 2, 0, mDecorationWidth, 0);
                } else {
                    outRect.set(mDecorationWidth / 2, 0, mDecorationWidth / 2, 0);
                }
            }
        };

Here is a video showing the results with gray vertical dividers.

If you already have the decorations working to your satisfaction, you can override calculateDistanceToFinalSnap() in PagerSnapHelper to center all views except the first and last view as follows. See calculatedistancetofinalsnap(). Once the PageSnapHelper identifies a target view to snap to, calculatedistancetofinalsnap() is called to determine how many pixels to move to perform the snap. Here, we are moving just enough pixels to center the view (without decorations) in the RecyclerView. PageSnapHelper does the right thing for the first and last items, so we just call the super for these.

PagerSnapHelper pagerSnapHelper = new PagerSnapHelper() {

    @Override
  public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager,
                                              @NonNull View targetView) {
        LinearLayoutManager lm = (LinearLayoutManager) layoutManager;
        int pos = mRecycler.getChildAdapterPosition(targetView);
        // If first or last view, the default implementation works.
  if (pos == 0 || pos == lm.getItemCount() - 1) {
            return super.calculateDistanceToFinalSnap(layoutManager, targetView);
        }
        // Force centering in the view without its decorations.
        // targetCenter is the location of the center of the view we want to center.
        int targetCenter = targetView.getLeft() + targetView.getWidth() / 2;
        // Distance is the number of pixels to move the target so that its center
        // lines up with the center of the RecyclerView (mRecycler.getWidth() / 2)
        int distance = targetCenter - mRecycler.getWidth() / 2;
        return new int[]{distance, 0};
    }
};

Either way will work.


问:
How to check if url is pointing outside angular application
I want to show a popup, when user click on a link that is external to angular application.

How do I check whether the url is external?
E.g. pointing to the same domain, but different document

```<code><a [href]="someUrl" appCheckExternalUrl>{{someUrl}}</a>
</code>```

```<code>@Directive({
  selector: '[appCheckExternalUrl]'
})
export class CheckExternalUrlDirective {

  constructor(private el: ElementRef<HTMLAnchorElement>) { }

  get url() { return this.el.nativeElement.href; }

  get isExternalUrl() {
    return ???;
  }
}
</code>```

The tricky part is that it depends on router settings.

Let's say my app is hosted in mydomain.com/myapp and defines route /myroute. Then:

mydomain.com/myapp/myroute - internal route

mydomain.com/anotherapp - external route.

But if the router uses hashtag routing, then

mydomain.com/myapp/myroute is external.

Also this url is also external, because it is not handled by application:

mydomain.com/myapp/assets/logo.png

答:
You can use window.origin to get the url of the page you're in, so your angular Page.

So you just have to compare the origin of your site with the origin of the href.

Body:
I want to show a popup, when user click on a link that is external to angular application.

How do I check whether the url is external?
E.g. pointing to the same domain, but different document

{{someUrl}}

@Directive({
  selector: '[appCheckExternalUrl]'
})
export class CheckExternalUrlDirective {

  constructor(private el: ElementRef<HTMLAnchorElement>) { }

  get url() { return this.el.nativeElement.href; }

  get isExternalUrl() {
    return ???;
  }
}

The tricky part is that it depends on router settings.

Let's say my app is hosted in mydomain.com/myapp and defines route /myroute. Then:

mydomain.com/myapp/myroute - internal route

mydomain.com/anotherapp - external route.

But if the router uses hashtag routing, then

mydomain.com/myapp/myroute is external.

Also this url is also external, because it is not handled by application:

mydomain.com/myapp/assets/logo.png


问:
Why converting number to integer I get NA?
Hello I am trying to convert number to integer in R but when a number is too large it is converted to NA, why? How can I avoid this problem?

just some example

```<code>>df[,2]
[1]          0          0          0          0          0          0          0    5361230  780600500          0          0          0
 [13]  764111150          0          0          0          0         9999816350 0         23237410347   91198500 1957077150  124890245   64232150

>as.integer(df[,2])
 [1]          0          0          0          0          0          0          0    5361230  780600500          0          0          0
 [13]  764111150          0          0          0          0         NA          0         NA   91198500 1957077150  124890245   64232150
</code>```

I would like to mantain the NA as the original number is it possible?
thanks

答:
Your number is too large to fit into an integer:

```<code>23237410347 > .Machine$integer.max
## [1] TRUE
</code>```

Maybe it is good enough to use double.  Also, there is a package that supports 64 bit integers (R natively supports 32 bit).

```<code>library(bit64)

as.integer64(23237410347)
## integer64
## [1] 23237410347
</code>```

Body:
Hello I am trying to convert number to integer in R but when a number is too large it is converted to NA, why? How can I avoid this problem?

just some example

>df[,2]
[1]          0          0          0          0          0          0          0    5361230  780600500          0          0          0
 [13]  764111150          0          0          0          0         9999816350 0         23237410347   91198500 1957077150  124890245   64232150

>as.integer(df[,2])
 [1]          0          0          0          0          0          0          0    5361230  780600500          0          0          0
 [13]  764111150          0          0          0          0         NA          0         NA   91198500 1957077150  124890245   64232150

I would like to mantain the NA as the original number is it possible?
thanks

Body:
Your number is too large to fit into an integer:

23237410347 > .Machine$integer.max
## [1] TRUE

Maybe it is good enough to use double.  Also, there is a package that supports 64 bit integers (R natively supports 32 bit).

library(bit64)

as.integer64(23237410347)
## integer64
## [1] 23237410347


问:
extjs treenode appendchild not working correctly
I have a treepanel which is loaded on demand from a web rest api. The rest api will return an array with the data according to the id of the selected node. Here is the code:

```<code>itemdblclick: function(item, record, eOpts) {
        var store = Ext.getStore('mystore');
        var newStore = Ext.create('mystore', {
            autoDestroy: true,
            storeId: 'otherId'
        });
        var parentid = record.data.id;
        var that = this;

    newStore.proxy.extraParams = {...};
    newStore.autoDestroy = true;
    newStore.storeId = 'otherId';

    newStore.load({
        callback: function(items) {
            var node = store.getRootNode().findChild('id', record.data.idelement, true);

            for (var i = 0, l = items.length; i < l; i++) {
                var item = items[i].data;
                var child = {..., idparent: parentid};
                var newnode = node.createNode(child);
                node.appendChild(newnode, true);
            }
            node.expand();
        }
    });
}
</code>```

Thanks to norbeq who gave me the light to change the id of the second store. The thing is the tree is nicely populated and the node is expanded, but (why there is always a but?) next the expanded node there is no a -, the + remains the same.

This is what I mean:

I've sourrounded in red that the + mark remains and that the folder is still closed.

Also, if I click the + symbol this is what happend:

How can I solve this?

答:
Well, finally I have to say that the official extjs documentation is quite poor for me. I found a solution by test and reading a lot of posts in several foros. I found a solution that might be helpful to others:

```<code>var rootNode = store.getRootNode();

                for (var i = 0, l = records.length; i < l; i++) {
                    var x = records[i].data;
                    var child = { ... };

                    if (!child.idparent) {
                        rootNode.appendChild(child);
                    } else {
                        var parent = rootNode.findChild('idelement', child.idparent, true);
                        parent.appendChild(child);
                    }

                    if (!child.leaf) {
                        var node = store.findNode('idelement', child.idelement);
                        node.set('expanded', true);
                    }
                }

                rootNode.set('expanded', true);
</code>```

That's it

Body:
I have a treepanel which is loaded on demand from a web rest api. The rest api will return an array with the data according to the id of the selected node. Here is the code:

itemdblclick: function(item, record, eOpts) {
        var store = Ext.getStore('mystore');
        var newStore = Ext.create('mystore', {
            autoDestroy: true,
            storeId: 'otherId'
        });
        var parentid = record.data.id;
        var that = this;

    newStore.proxy.extraParams = {...};
    newStore.autoDestroy = true;
    newStore.storeId = 'otherId';

    newStore.load({
        callback: function(items) {
            var node = store.getRootNode().findChild('id', record.data.idelement, true);

            for (var i = 0, l = items.length; i < l; i++) {
                var item = items[i].data;
                var child = {..., idparent: parentid};
                var newnode = node.createNode(child);
                node.appendChild(newnode, true);
            }
            node.expand();
        }
    });
}

Thanks to norbeq who gave me the light to change the id of the second store. The thing is the tree is nicely populated and the node is expanded, but (why there is always a but?) next the expanded node there is no a -, the + remains the same.

This is what I mean:

I've sourrounded in red that the + mark remains and that the folder is still closed.

Also, if I click the + symbol this is what happend:

How can I solve this?

Body:
Well, finally I have to say that the official extjs documentation is quite poor for me. I found a solution by test and reading a lot of posts in several foros. I found a solution that might be helpful to others:

var rootNode = store.getRootNode();

                for (var i = 0, l = records.length; i < l; i++) {
                    var x = records[i].data;
                    var child = { ... };

                    if (!child.idparent) {
                        rootNode.appendChild(child);
                    } else {
                        var parent = rootNode.findChild('idelement', child.idparent, true);
                        parent.appendChild(child);
                    }

                    if (!child.leaf) {
                        var node = store.findNode('idelement', child.idelement);
                        node.set('expanded', true);
                    }
                }

                rootNode.set('expanded', true);

That's it


问:
How to change the path for local backend state when using workspaces in terraform?
What is the expected configuration for using terraform workspaces with the local backend?

The local backend supports workspacing, but it does not appear you have much control over where the actual state is stored.

When you are not using workspaces you can supply a path parameter to the local backend to control where the state files are stored.

```<code># Either in main.tf
terraform {
  backend "local" {
    path = "/path/to/terraform.tfstate
  }
}

# Or as a flag
terraform init -backend-config="path=/path/to/terraform.tfstate"
</code>```

I expected analogous functionality when using workspaces in that you would supply a directory for path and the workspaces would get created under that directory

For example:

```<code>terraform new workspace first
terraform init -backend-config="path=/path/to/terraform.tfstate.d"
terraform apply
terraform new workspace second
terraform init -backend-config="path=/path/to/terraform.tfstate.d"
terraform apply
</code>```

would result in the state

```<code>/path/to/terraform.tfstate.d/first/terraform.tfstate
/path/to/terraform.tfstate.d/second/terraform.tfstate
</code>```

This does not appear to be the case however. It looks like the local backend ignores the path parameter and puts the workspace configuration in the working directory.

Am I missing something or are you unable to control local backend workspace state?

答:
There is an undocumented flag for the local backend workspace_dir that solves this issue.

The documentation task is tracked here

```<code>terraform {
  backend "local" {
    workspace_dir = "/path/to/terraform.tfstate.d"
  }
}
</code>```

Body:
What is the expected configuration for using terraform workspaces with the local backend?

The local backend supports workspacing, but it does not appear you have much control over where the actual state is stored.

When you are not using workspaces you can supply a path parameter to the local backend to control where the state files are stored.

# Either in main.tf
terraform {
  backend "local" {
    path = "/path/to/terraform.tfstate
  }
}

# Or as a flag
terraform init -backend-config="path=/path/to/terraform.tfstate"

I expected analogous functionality when using workspaces in that you would supply a directory for path and the workspaces would get created under that directory

For example:

terraform new workspace first
terraform init -backend-config="path=/path/to/terraform.tfstate.d"
terraform apply
terraform new workspace second
terraform init -backend-config="path=/path/to/terraform.tfstate.d"
terraform apply

would result in the state

/path/to/terraform.tfstate.d/first/terraform.tfstate
/path/to/terraform.tfstate.d/second/terraform.tfstate

This does not appear to be the case however. It looks like the local backend ignores the path parameter and puts the workspace configuration in the working directory.

Am I missing something or are you unable to control local backend workspace state?

Body:
There is an undocumented flag for the local backend workspace_dir that solves this issue.

The documentation task is tracked here

terraform {
  backend "local" {
    workspace_dir = "/path/to/terraform.tfstate.d"
  }
}


问:
How can I serialize DateTime with miliseconds in CsvHelper
I wat to serialize object with DateTime field to csv with milliseconds. How can I do this?

I'm writing csv by this code:

```<code>using (var writer = new StreamWriter(_checksumsFilePath))
using (var csv = new CsvWriter(writer))
{
   csv.WriteRecords(_checksums.Values.ToList());
}
</code>```

And _checksums is Dictionary of this class:

```<code>public class SomeClass
{
    public string Name { get; set; }

    public string val{ get; set; }

    public DateTime lastTime{ get; set; }
}
</code>```

When I write, I see from debugger - in DateTime are some miliseconds but to csv file write only:

```<code>Name;val;lastTime
someName;49BC20DF15E412A64472421E13FE86FF1C5165E18B2AFCCF160D4DC19FE68A14;29.05.2019 16:13:08
</code>```

答:
If you're using this CsvHelper, there seems to be a way to configure it with a ClassMap:

https://joshclose.github.io/CsvHelper/api/CsvHelper.Configuration

Body:
I wat to serialize object with DateTime field to csv with milliseconds. How can I do this?

I'm writing csv by this code:

using (var writer = new StreamWriter(_checksumsFilePath))
using (var csv = new CsvWriter(writer))
{
   csv.WriteRecords(_checksums.Values.ToList());
}

And _checksums is Dictionary of this class:

public class SomeClass
{
    public string Name { get; set; }

    public string val{ get; set; }

    public DateTime lastTime{ get; set; }
}

When I write, I see from debugger - in DateTime are some miliseconds but to csv file write only:

Name;val;lastTime
someName;49BC20DF15E412A64472421E13FE86FF1C5165E18B2AFCCF160D4DC19FE68A14;29.05.2019 16:13:08


问:
Haskell function iter result
I am new to Haskell and I am working on a problem for this function:

```<code>iter :: (t -> t) -> t -> [t]
iter f a = a : iter f (f a)
myList = iter (\x -> x + 2) 1
</code>```

My understanding of this is that:

iter takes two arguments (t->t) and t and returns a list of [t].

I am confused on the next part:

```<code>iter f a = a : iter f (f a)
</code>```

is myList [1,3] or am I thinking about it in the wrong way?

Or would it be [1,3,5,7..]?

答:
myList does, indeed, represent the infinite list [1,3,..]. However, the list is generated lazily; the recursive call to iter is only made when required. Consider taking the head of myList:

```<code>head :: [a] -> a
head (x:_) = x

head myList == head (iter (\x -> x + 2) 1)  -- definition of myList
            == head (1 : iter (\x -> x + 2) ((\x -> x + 2) 1)) -- definition of iter
            == 1 -- definition of head
</code>```

The recursive call to iter specified by the definition of iter is never made, because head never tries to consume the tail of myList.

I'll note here that iter is really an example of a corecursive function, not a recursive function. Haskell's non-strict evaluation blurs the distinction between the two. See https://softwareengineering.stackexchange.com/q/144274/206609.

Title: Haskell function iter result

Body:
I am new to Haskell and I am working on a problem for this function:

iter :: (t -> t) -> t -> [t]
iter f a = a : iter f (f a)
myList = iter (\x -> x + 2) 1

My understanding of this is that:

iter takes two arguments (t->t) and t and returns a list of [t].

I am confused on the next part:

iter f a = a : iter f (f a)

is myList [1,3] or am I thinking about it in the wrong way?

Or would it be [1,3,5,7..]?

Body:
myList does, indeed, represent the infinite list [1,3,..]. However, the list is generated lazily; the recursive call to iter is only made when required. Consider taking the head of myList:

head :: [a] -> a
head (x:_) = x

head myList == head (iter (\x -> x + 2) 1)  -- definition of myList
            == head (1 : iter (\x -> x + 2) ((\x -> x + 2) 1)) -- definition of iter
            == 1 -- definition of head

The recursive call to iter specified by the definition of iter is never made, because head never tries to consume the tail of myList.

I'll note here that iter is really an example of a corecursive function, not a recursive function. Haskell's non-strict evaluation blurs the distinction between the two. See https://softwareengineering.stackexchange.com/q/144274/206609.


问:
C# Make Program Wait For Button To Be Pressed
I want to make the program wait for a button to be pressed before it continues, I tried creating a while loop and having it loop until the button is clicked and sets a bool to true for the while loop to end, this made it crash

```<code>while (!Redpress)
{
    // I'd like the wait here
}

Redpress = false;
</code>```

It doesn't matter whether or not the while is there, as long as the program waits for the button press before setting "Redpress" to false... Any Ideas?

答:
If you need the program to wait for that event then don't write the waitForTheButton code in your main access/Page load.

Instead write your code inside the event. So you don't have to make an active wait. Events are for that.

eg: If you have something like this

```<code>static void Main()
{
    while (notPressed) { }
    DoThis();
    DoThat();
}
</code>```

Then you could be changing it to:

```<code>static void Main
{
    myButton.OnClick += myButton_EventHandler;
}

private void myButton_EventHandler(object sender, EventArgs e)
{
    DoThis();
    DoThat();
}
</code>```

If you really want to work in a procedural paradigm even when you are using a OOP language, you should use a Semaphore or something like that. But that doesn't seem to be what you actually need, It's more like something you want.

Body:
I want to make the program wait for a button to be pressed before it continues, I tried creating a while loop and having it loop until the button is clicked and sets a bool to true for the while loop to end, this made it crash

while (!Redpress)
{
    // I'd like the wait here
}

Redpress = false;

It doesn't matter whether or not the while is there, as long as the program waits for the button press before setting "Redpress" to false... Any Ideas?

Body:
If you need the program to wait for that event then don't write the waitForTheButton code in your main access/Page load.

Instead write your code inside the event. So you don't have to make an active wait. Events are for that.

eg: If you have something like this

static void Main()
{
    while (notPressed) { }
    DoThis();
    DoThat();
}

Then you could be changing it to:

static void Main
{
    myButton.OnClick += myButton_EventHandler;
}

private void myButton_EventHandler(object sender, EventArgs e)
{
    DoThis();
    DoThat();
}

If you really want to work in a procedural paradigm even when you are using a OOP language, you should use a Semaphore or something like that. But that doesn't seem to be what you actually need, It's more like something you want.