问:
Find duplicates in array
```<code>int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int count = 0;
    for (int j = 0; j < array.Length; j++)
    {
        if (array[i] == array[j])
        {
            count = count + 1;
        }
    }
    Console.WriteLine(array[i] + " repeats " + count + " times");
}
Console.ReadKey();
</code>```

I don't want to use LINQ!
My question is, how to print results only once. For example:

10 repeats 2 times

5 repeats 3 times

2 repeats 2 times

...

Thanks.

答:
```<code>int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length; j++)
{
    if (array[i] == array[j])
    {
        count = count + 1;
    }
}
Console.WriteLine(array[i] + " repeats " + count + " times");
}
Console.ReadKey();
</code>```

There is a reason why you see multiple console writes. You are comparing first elem (10) with all elems in array. So there is another 10 and your code detects that.
But on third pass you are comparing third elem (10) with first elem (10). Didn't you already checked for that? if a == b, b == a :)

There is second mistake in your code. i = 0 and j = 0. Do you see that? You are comparing first elem with itself! Do you want what? Of course array[0] == array[0], it's the same elem :)

And you are comparing each elem with itself whenever i == j.

You may think of your code execution as square i*j, where i and j are array.Length. Because i == j, it's called quadratic. i*j == i*i == i^2. O(i^2)

.

What could you do? Look at this code:

```<code>int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 1;
for (int j = i + 1; j < array.Length; j++)
{
    if (array[i] == array[j])
    {
        count = count + 1;
    }
}
// if (count != 1)
Console.WriteLine(array[i] + " repeats " + count + " times");
}
Console.ReadKey();
</code>```

It look almost the same except int j = i + 1; With that you will never compare item to itself and you are cutting iterations in half. O(n^2/2). Basically cutting a square in a triangle. Sounds cool right? But that /2 optimization will disappear as soon as array.Length increases by 1. And our console report is still with duplicates.
There is commented if. That hack 'fixed' the report. Can you spot the error? What would report be if you change number 11 to 10?

So, this demonstrate it's impossible to write report while you are traversing an array, because you are not memorizing previous count. One option is to use hash or binary tree to commit each value in memory like suggested in other answers. That requires extra memory. Second option is to destroy/delete/null the same items, which is not cheap...

Happy learning :)

Title: Find duplicates in array

Body:
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
    int count = 0;
    for (int j = 0; j < array.Length; j++)
    {
        if (array[i] == array[j])
        {
            count = count + 1;
        }
    }
    Console.WriteLine(array[i] + " repeats " + count + " times");
}
Console.ReadKey();

I don't want to use LINQ!
My question is, how to print results only once. For example:

10 repeats 2 times

5 repeats 3 times

2 repeats 2 times

...

Thanks.

Body:
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length; j++)
{
    if (array[i] == array[j])
    {
        count = count + 1;
    }
}
Console.WriteLine(array[i] + " repeats " + count + " times");
}
Console.ReadKey();

There is a reason why you see multiple console writes. You are comparing first elem (10) with all elems in array. So there is another 10 and your code detects that.
But on third pass you are comparing third elem (10) with first elem (10). Didn't you already checked for that? if a == b, b == a :)

There is second mistake in your code. i = 0 and j = 0. Do you see that? You are comparing first elem with itself! Do you want what? Of course array[0] == array[0], it's the same elem :)

And you are comparing each elem with itself whenever i == j.

You may think of your code execution as square i*j, where i and j are array.Length. Because i == j, it's called quadratic. i*j == i*i == i^2. O(i^2)

.

What could you do? Look at this code:

int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 1;
for (int j = i + 1; j < array.Length; j++)
{
    if (array[i] == array[j])
    {
        count = count + 1;
    }
}
// if (count != 1)
Console.WriteLine(array[i] + " repeats " + count + " times");
}
Console.ReadKey();

It look almost the same except int j = i + 1; With that you will never compare item to itself and you are cutting iterations in half. O(n^2/2). Basically cutting a square in a triangle. Sounds cool right? But that /2 optimization will disappear as soon as array.Length increases by 1. And our console report is still with duplicates.
There is commented if. That hack 'fixed' the report. Can you spot the error? What would report be if you change number 11 to 10?

So, this demonstrate it's impossible to write report while you are traversing an array, because you are not memorizing previous count. One option is to use hash or binary tree to commit each value in memory like suggested in other answers. That requires extra memory. Second option is to destroy/delete/null the same items, which is not cheap...

Happy learning :)


来源: stackexchange

问:
Displaying Json object as a string instead of actual object
I have a function that populates a modal. I would like the modal to show the string from the data, not the JSON object or the JSON obj in string format. ... however it appears to be displaying the literal Json object...I cannot use a toString method because it appears it does not exist. Below is my code.

Modal:

```<code><div class="modal fade" id="receiptModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Receipt</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">×</span>
            </button>
        </div>
        <div class="modal-body">
           <div id="receiptTxt">

           </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div>
</div>
</code>```

JS:

```<code>  $(".viewReceipt").click(function (e) {

    var rowId = "#" + $(this).data("rowindex");
    var row = $(rowId);
    var transactionID = row.find(".transactionID").html().trim();

    var data = {
        receiptID: transactionID
    };

    console.log("data");
    console.log(data);

    $.ajax({
        url: '@Url.Action("ViewReceipt", "TerminalReceipts")',
        type: "POST",
        data: data,
        dataType: 'html',
        success: function (data) {
            console.log("Success");
            console.log(data)
            $("#receiptTxt").html(data);
            $("#receiptModal").modal('toggle');
        }
    });
});
</code>```

As you can see $("#receiptTxt").html(data); is the issue. It is literally displaying the data obj. I cannot do .html(data).toString().. what other options are there??

@edit

As requested, here is the output of console.log(data)

```<code>{"data":"                  Company Name                   \r\n          2222 Ridgelake Dr           \r\n              Cape Coral, FL, 90726               \r\n                                                \r\n                                                \r\n\r\n              10/4/2018 7:21:13 AM              \r\n\r\number: ABC123                        TID: ABC123\r\nBatch #:                                       0\r\nAccount #:                      XXXXXXXXXXXX2222\r\nTrans #:                                     378\r\nAuth #:                                 00056693\r\nHost Date:                             10/4/2018\r\nHost Time:                              09:24:50\r\nSoftware Version:                        1.0.0.0\r\n\r\n              THIS IS A DEMO                   \r\nTotal:                                    $5.00\r\n                    APPROVED                    \r\n\r\n              THANK YOU VERY MUCH!              \r\n\r\n"}
</code>```

答:
JSON.stringify(data).

You can store this in a new variable or set it up this way: $("#receiptTxt").html(JSON.stringify(data));

You can use JSON.parse() to convert strings back to a JSON object.

Hope this helps. :)

ContentLicense: CC BY-SA 4.0

Body:
I have a function that populates a modal. I would like the modal to show the string from the data, not the JSON object or the JSON obj in string format. ... however it appears to be displaying the literal Json object...I cannot use a toString method because it appears it does not exist. Below is my code.

Modal:

Receipt

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                ×
            </button>

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>

JS:

  $(".viewReceipt").click(function (e) {

    var rowId = "#" + $(this).data("rowindex");
    var row = $(rowId);
    var transactionID = row.find(".transactionID").html().trim();

    var data = {
        receiptID: transactionID
    };

    console.log("data");
    console.log(data);

    $.ajax({
        url: '@Url.Action("ViewReceipt", "TerminalReceipts")',
        type: "POST",
        data: data,
        dataType: 'html',
        success: function (data) {
            console.log("Success");
            console.log(data)
            $("#receiptTxt").html(data);
            $("#receiptModal").modal('toggle');
        }
    });
});

As you can see $("#receiptTxt").html(data); is the issue. It is literally displaying the data obj. I cannot do .html(data).toString().. what other options are there??

@edit

As requested, here is the output of console.log(data)

{"data":"                  Company Name                   \r\n          2222 Ridgelake Dr           \r\n              Cape Coral, FL, 90726               \r\n                                                \r\n                                                \r\n\r\n              10/4/2018 7:21:13 AM              \r\n\r\number: ABC123                        TID: ABC123\r\nBatch #:                                       0\r\nAccount #:                      XXXXXXXXXXXX2222\r\nTrans #:                                     378\r\nAuth #:                                 00056693\r\nHost Date:                             10/4/2018\r\nHost Time:                              09:24:50\r\nSoftware Version:                        1.0.0.0\r\n\r\n              THIS IS A DEMO                   \r\nTotal:                                    $5.00\r\n                    APPROVED                    \r\n\r\n              THANK YOU VERY MUCH!              \r\n\r\n"}


问:
Why does returning a string slice instead of a usize prevent mutating a String?
This code compiles:

```<code>fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}

fn f1(s: &String) -> usize {
    10
}

fn f2(s: &String) -> &str {
    "def"
}
</code>```

However, replacing the call to f1() by f2() causes a compilation failure. It appears to me that both f1() and f2() do an immutable borrow, and s.clear() does a mutable borrow, so I should get compilation error in both cases. What am I missing?

答:
The Rust reference says:

If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.

This means that your method

```<code>fn f2(s: &String) -> &str {
    "def"
}
</code>```

is interpreted by Rust as:

```<code>fn f2<'a>(s: &'a String) -> &'a str {
    "def"
}
</code>```

Since "def" has the lifetime 'static, its lifetime can be shortened to 'a when being returned from the function (so the compiler won't complain here), but when calling the function the compiler cannot infer that the true lifetime of the string was really 'static. To do this, you must explicitly mark it as 'static yourself:

```<code>fn f2(s: &String) -> &'static str {
    "def"
}
</code>```

Body:
This code compiles:

fn main() {
    let mut s = String::from("some_string");
    let n = f1(&s);
    s.clear();
    println!("n = {}", n);
}

fn f1(s: &String) -> usize {
    10
}

fn f2(s: &String) -> &str {
    "def"
}

However, replacing the call to f1() by f2() causes a compilation failure. It appears to me that both f1() and f2() do an immutable borrow, and s.clear() does a mutable borrow, so I should get compilation error in both cases. What am I missing?

Body:
The Rust reference says:

If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.

This means that your method

fn f2(s: &String) -> &str {
    "def"
}

is interpreted by Rust as:

fn f2<'a>(s: &'a String) -> &'a str {
    "def"
}

Since "def" has the lifetime 'static, its lifetime can be shortened to 'a when being returned from the function (so the compiler won't complain here), but when calling the function the compiler cannot infer that the true lifetime of the string was really 'static. To do this, you must explicitly mark it as 'static yourself:

fn f2(s: &String) -> &'static str {
    "def"
}


问:
Unable to invoke SageMaker endpoint(TensorFlow Model) using Boto3 client from AWS Lambda in python
I have a TensorFlow Model deployed with AWS SageMaker endpoint exposed .
From Lambda Python I am using boto3 client to invoke the endpoint .
The TensorFlow model accepts 3 inputs as follows

```<code>{'input1' : numpy array , 'input2' : integer ,'input3' :numpy array }
</code>```

From Lambda using runtime.invoke_endpoint to invoke the SageMaker endpoint .
Getting the error as Parse Error when the API is invoked from boto3client
I tried serializing the data into csv format before calling the API endpoint

Below code written in Lambda

```<code>payload = {'input1': encoded_enc_inputstanza_in_batch,
'input2' : encoded_enc_inputstanza_in_batch.shape[1],
'input3' : np.reshape([[15]*20],20) }
infer_file = io.StringIO()
writer = csv.writer(infer_file)
for key, value in payload.items():
  writer.writerow([key, value])
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
           ContentType='text/csv',
           Body=infer_file.getvalue())
</code>```

Additional Details
These are the additional details
- Sagemaker Model expects 3 fields as input - 'input1' - Numpy array
 'input2' - Int data type ,
 'input3' - numpy array

Actual result -

```<code>Traceback (most recent call last):
        File "/var/task/lambda_function.py", line 143, in lambda_handler
        Body=infer_file.getvalue())
        File "/var/runtime/botocore/client.py", line 320, in _api_call
        return self._make_api_call(operation_name, kwargs)
        File "/var/runtime/botocore/client.py", line 623, in _make_api_call
        raise error_class(parsed_response, operation_name)
        END RequestId: fa70e1f3-763b-41be-ad2d-76ae80aefcd0
</code>```

Expected Result - Successful invocation of the API endpoint .

答:
For text/csv the value for the Body argument to invoke_endpoint should be a string with commas separating the values for each feature. For example, a record for a model with four features might look like: 1.5,16.0,14,23.0. You can try the following:

dp = ','.join(str(a) for a in payload)

Body:
I have a TensorFlow Model deployed with AWS SageMaker endpoint exposed .
From Lambda Python I am using boto3 client to invoke the endpoint .
The TensorFlow model accepts 3 inputs as follows

{'input1' : numpy array , 'input2' : integer ,'input3' :numpy array }

From Lambda using runtime.invoke_endpoint to invoke the SageMaker endpoint .
Getting the error as Parse Error when the API is invoked from boto3client
I tried serializing the data into csv format before calling the API endpoint

Below code written in Lambda

payload = {'input1': encoded_enc_inputstanza_in_batch,
'input2' : encoded_enc_inputstanza_in_batch.shape[1],
'input3' : np.reshape([[15]*20],20) }
infer_file = io.StringIO()
writer = csv.writer(infer_file)
for key, value in payload.items():
  writer.writerow([key, value])
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
           ContentType='text/csv',
           Body=infer_file.getvalue())

Additional Details
These are the additional details
- Sagemaker Model expects 3 fields as input - 'input1' - Numpy array
 'input2' - Int data type ,
 'input3' - numpy array

Actual result -

Traceback (most recent call last):
        File "/var/task/lambda_function.py", line 143, in lambda_handler
        Body=infer_file.getvalue())
        File "/var/runtime/botocore/client.py", line 320, in _api_call
        return self._make_api_call(operation_name, kwargs)
        File "/var/runtime/botocore/client.py", line 623, in _make_api_call
        raise error_class(parsed_response, operation_name)
        END RequestId: fa70e1f3-763b-41be-ad2d-76ae80aefcd0

Expected Result - Successful invocation of the API endpoint .


问:
Sum of two arrays
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

```<code>#include <stdio.h>
#include <stdlib.h>

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}
</code>```

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

答:
This:

```<code>int i,g,a[g],b[g];
</code>```

causes undefined behaviour.  The value of g is undefined upon initialisation, so therefore the length of a and b will be undefined.

You probably want something like:

```<code>int i, g;
int *a;
int *b;  // Note: recommend declaring on separate lines, to avoid issues
scanf("%d", &g);
a = malloc(sizeof(*a) * g);
b = malloc(sizeof(*b) * g);
...
free(a);
free(b);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sum of two arrays

Body:
The exercise says "Make a function with parameters two int arrays and k which is their size. The function should return another array (size k) where every element of it is the sum of the two arrays of the same position. That's what I wrote, but it crashes. Do I have to do it with pointers?

#include <stdio.h>
#include <stdlib.h>

void sumarray(int k,int A[k],int B[k]){
   int sum[k],i;
   for(i=0;i<k;i++){
   sum[i]=A[i]+B[i];
   printf("sum[%d]=%d\n",i,sum[i]);}

 }

main(){
   int i,g,a[g],b[g];
   printf("Give size of both arrays: ");
   scanf("%d",&g);
   for(i=0;i<g;i++){
      a[i]=rand();
      b[i]=rand();
   }
   sumarray(g,a,b);
   system("pause");
}

Example: If i have A={1,2,3,4} and B={4,3,2,1} the program will return C={5,5,5,5).

Body:
This:

int i,g,a[g],b[g];

causes undefined behaviour.  The value of g is undefined upon initialisation, so therefore the length of a and b will be undefined.

You probably want something like:

int i, g;
int *a;
int *b;  // Note: recommend declaring on separate lines, to avoid issues
scanf("%d", &g);
a = malloc(sizeof(*a) * g);
b = malloc(sizeof(*b) * g);
...
free(a);
free(b);


问:
Assistance needed for code for Currency Converter. Is there a solution?
I have started the online course "The Complete Android N Developer Course " and am at a section where I have questions about my code and the community really isn't of much assistance.

I've constantly tried looking at questions online and asking questions o the course community Q&A.

```<code>public void convert(View view){
    editText dollarAmounteditText = (editText) findViewById(R.id.dollarAmounteditText);
    Double dollarAmountDouble = Double.parseDouble(dollarAmounteditText);
    Double poundAmount = dollarAmountDouble = 0.75;
    Toast.makeText(mainActivity.this,  "£" + String.format("%.2f", poundAmount ), Toast.LENGTH_SHORT).show();
    Log.i("amount" , dollarAmounteditText.getText().toString());
}
</code>```

I also have been getting this error message whenever I try to run the emulator.

"M  Emulator: emulator: ERROR: x86 emulation currently requires hardware acceleration!"

答:
Never use double or BigDecimal for currency; both are ridiculous.

You should always identify the appropriate fraction of the currency to be the unit and use a long to represent that.
For example,
if you are working with USD,
then a penny (1/100 of a USD) may be good.
If you are converting between currencies,
then 1/10_000 of the base currency (for example, USD) may be reasonable.
In the case of 1/10_000 of the base currency,
in my example 10_000 would be the value to store for $1 (one USD).
for Yen to USD you might want to use 1/10_000_000 USD as the 1 value (i.e. store 10_000_000 for $1).

Once you have a reasonable representation,
do integer math for currency (a long holds integer values).

Run this to see why double and BigDecimal are bad.

import java.math.BigDecimal;

import org.junit.Test;

public class GoofballsUseDouble
{
    public void bigdecimalTest1()
    {
        final BigDecimal m1 = new BigDecimal(
            0.1d);
        final BigDecimal m2 = new BigDecimal(
            0.2d);
        final BigDecimal sum;

        sum = m1.add(m2);

        System.out.println("");
        System.out.println("bigdecimalTest1");
        System.out.println(" v1.a (0.1bd): " + m1);
        System.out.println(" v2.a (0.2bd): " + m2);
        System.out.println("sum.a (?): " + sum);
    }

    public void bigdecimalTest2()
    {
        final BigDecimal m1 = new BigDecimal(
            "0.1");
        final BigDecimal m2 = new BigDecimal(
            "0.2");
        final BigDecimal sum;

        sum = m1.add(m2);

        System.out.println("");
        System.out.println("bigdecimalTest2");
        System.out.println(" v1.a (0.1bds): " + m1);
        System.out.println(" v2.a (0.2bds): " + m2);
        System.out.println("sum.a (?): " + sum);
    }

    public void doubleTest()
    {
        final double m1 = 0.1d;
        final double m2 = 0.2d;
        final double sumM;

        sumM = m1 + m2;

        System.out.println("");
        System.out.println("doubleTest");
        System.out.println(" v1.a (0.1d): " + m1);
        System.out.println(" v2.a (0.2d): " + m2);
        System.out.println("sum.a (?): " + sumM);

        System.out.printf(" v1.b (0.1d): %f%n",
            m1);
        System.out.printf(" v2.b (0.2d): %f%n",
            m2);

        if (.3d == sumM)
        {
            System.out.println("it r equalz");
        }
        else
        {
            System.out.println("double is not exact, of course");
        }
    }

    @Test
    public void theTest()
    {
        doubleTest();

        bigdecimalTest1();

        bigdecimalTest2();
    }
}
```

Body:
I have started the online course "The Complete Android N Developer Course " and am at a section where I have questions about my code and the community really isn't of much assistance.

I've constantly tried looking at questions online and asking questions o the course community Q&A.

public void convert(View view){
    editText dollarAmounteditText = (editText) findViewById(R.id.dollarAmounteditText);
    Double dollarAmountDouble = Double.parseDouble(dollarAmounteditText);
    Double poundAmount = dollarAmountDouble = 0.75;
    Toast.makeText(mainActivity.this,  "£" + String.format("%.2f", poundAmount ), Toast.LENGTH_SHORT).show();
    Log.i("amount" , dollarAmounteditText.getText().toString());
}

I also have been getting this error message whenever I try to run the emulator.

"M  Emulator: emulator: ERROR: x86 emulation currently requires hardware acceleration!"


问:
Parse JSON property during deserialization
With the following portion of a JSON:

```<code>"tags":
{
  "tiger:maxspeed": "65 mph"
}
</code>```

And I have the corresponding C# class I am using to deserialize:

```<code>public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public string Maxspeed { get; set; }

}
</code>```

I would like to deserialize it into an integer property instead:

```<code>public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed { get; set; }

}
</code>```

Is it possible to parse the numeric part of the string from the JSON to an int during deserialization?

I think I want something like:

```<code>public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed
    {
        get
        {
            return _maxspeed;
        }
        set
        {
            _maxspeed = Maxspeed.Parse(<incoming string>.split(" ")[0]);
        }
    }
}
</code>```

答:
I would suggest a variation of @djv's idea.  Make the string property private and put the conversion logic there.  The serializer will pick it up due to the [JsonProperty] attribute, but it will not muddy up the public interface of the class.

```<code>public class Tags
{
    [JsonIgnore]
    public int MaxSpeed { get; set; }

    [JsonProperty("tiger:maxspeed")]
    private string MaxSpeedString
    {
        get { return MaxSpeed + " mph"; }
        set
        {
            if (value != null && int.TryParse(value.Split(' ')[0], out int speed))
                MaxSpeed = speed;
            else
                MaxSpeed = 0;
        }
    }
}
</code>```

Fiddle: https://dotnetfiddle.net/SR9xJ9

Alternatively you could use a custom JsonConverter to keep the conversion logic separate from the model class:

```<code>public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    [JsonConverter(typeof(MaxSpeedConverter))]
    public int MaxSpeed { get; set; }
}

class MaxSpeedConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // CanConvert is not called when the converter is used with a [JsonConverter] attribute
        return false;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string val = (string)reader.Value;

        int speed;
        if (val != null && int.TryParse(val.Split(' ')[0], out speed))
            return speed;

        return 0;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue((int)value + " mph");
    }
}
</code>```

Fiddle: https://dotnetfiddle.net/giCDZW

Body:
With the following portion of a JSON:

"tags":
{
  "tiger:maxspeed": "65 mph"
}

And I have the corresponding C# class I am using to deserialize:

public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public string Maxspeed { get; set; }

}

I would like to deserialize it into an integer property instead:

public class Tags
{

    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed { get; set; }

}

Is it possible to parse the numeric part of the string from the JSON to an int during deserialization?

I think I want something like:

public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    public int Maxspeed
    {
        get
        {
            return _maxspeed;
        }
        set
        {
            _maxspeed = Maxspeed.Parse(<incoming string>.split(" ")[0]);
        }
    }
}

Body:
I would suggest a variation of @djv's idea.  Make the string property private and put the conversion logic there.  The serializer will pick it up due to the [JsonProperty] attribute, but it will not muddy up the public interface of the class.

public class Tags
{
    [JsonIgnore]
    public int MaxSpeed { get; set; }

    [JsonProperty("tiger:maxspeed")]
    private string MaxSpeedString
    {
        get { return MaxSpeed + " mph"; }
        set
        {
            if (value != null && int.TryParse(value.Split(' ')[0], out int speed))
                MaxSpeed = speed;
            else
                MaxSpeed = 0;
        }
    }
}

Fiddle: https://dotnetfiddle.net/SR9xJ9

Alternatively you could use a custom JsonConverter to keep the conversion logic separate from the model class:

public class Tags
{
    [JsonProperty("tiger:maxspeed")]
    [JsonConverter(typeof(MaxSpeedConverter))]
    public int MaxSpeed { get; set; }
}

class MaxSpeedConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        // CanConvert is not called when the converter is used with a [JsonConverter] attribute
        return false;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string val = (string)reader.Value;

        int speed;
        if (val != null && int.TryParse(val.Split(' ')[0], out speed))
            return speed;

        return 0;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue((int)value + " mph");
    }
}

Fiddle: https://dotnetfiddle.net/giCDZW


问:
Default sub-command, or handling no sub-command with argparse
How can I have a default sub-command, or handle the case where no sub-command is given using argparse?

```<code>import argparse

a = argparse.ArgumentParser()
b = a.add_subparsers()
b.add_parser('hi')
a.parse_args()
</code>```

Here I'd like a command to be selected, or the arguments to be handled based only on the next highest level of parser (in this case the top-level parser).

```joiner@X:~/src> python3 default_subcommand.py
usage: default_subcommand.py [-h] {hi} ...
default_subcommand.py: error: too few arguments```

答:
In my case I found it easiest to explicitly provide the subcommand name to parse_args() when argv was empty.

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='commands')

runParser = subparsers.add_parser('run', help='[DEFAULT ACTION]')

altParser = subparsers.add_parser('alt', help='Alternate command')
altParser.add_argument('alt_val', type=str, help='Value required for alt command.')

# Here's my shortcut: If `argv` only contains the script name,
# manually inject our "default" command.
args = parser.parse_args(['run'] if len(sys.argv) == 1 else None)
print args
```

<p>Example runs:</p>

<pre class="lang-sh prettyprint-override"><code>$ ./test.py
Namespace()

$ ./test.py alt blah
Namespace(alt_val='blah')

$ ./test.py blah
usage: test.py [-h] {run,alt} ...
test.py: error: invalid choice: 'blah' (choose from 'run', 'alt')
</code>```

Body:
How can I have a default sub-command, or handle the case where no sub-command is given using argparse?

import argparse

a = argparse.ArgumentParser()
b = a.add_subparsers()
b.add_parser('hi')
a.parse_args()

Here I'd like a command to be selected, or the arguments to be handled based only on the next highest level of parser (in this case the top-level parser).

joiner@X:~/src> python3 default_subcommand.py
usage: default_subcommand.py [-h] {hi} ...
default_subcommand.py: error: too few arguments

Body:
In my case I found it easiest to explicitly provide the subcommand name to parse_args() when argv was empty.

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='commands')

runParser = subparsers.add_parser('run', help='[DEFAULT ACTION]')

altParser = subparsers.add_parser('alt', help='Alternate command')
altParser.add_argument('alt_val', type=str, help='Value required for alt command.')

# Here's my shortcut: If `argv` only contains the script name,
# manually inject our "default" command.
args = parser.parse_args(['run'] if len(sys.argv) == 1 else None)
print args

Example runs:

$ ./test.py
Namespace()

$ ./test.py alt blah
Namespace(alt_val='blah')

$ ./test.py blah
usage: test.py [-h] {run,alt} ...
test.py: error: invalid choice: 'blah' (choose from 'run', 'alt')


问:
Unable to generate refresh token for IBM Visual Recognition API
I am trying to work with IAM token based authentication. I am able to generate 'access token' and could do operations using the 'access token'. Now I am having issue while generating 'refresh token'. I am following this link https://cloud.ibm.com/docs/services/watson?topic=watson-iam.

I am using below command to generate refresh token. Here Authorization header value obtained using username as 'apikey' and value as my key. {refreh-token} value I am using which I received while generating 'access token'.

curl -k -X POST --header "Authorization: Basic Yng6Yng=" --data-urlencode "grant_type=refresh_token" \ --data-urlencode "refresh_token={refresh-token}" "https://iam.bluemix.net/identity/token"

I expect to get refresh token but get error {"context":"requestId":"021c3482...""},"errorCode":"BXNIM0507E","errorMessage":"For OpenID Connect related APIs, you need to send your client credentials as basic authorization header"}

Can some one help me in understanding what is going wrong

答:
The description in https://cloud.ibm.com/docs/services/watson?topic=watson-iam is incorrectly describing the refresh case. I will follow-up with the docs team to update that section.
This is the generic description how to get tokens for API keys:
https://cloud.ibm.com/docs/iam?topic=iam-iamtoken_from_apikey

For API usage, IBM Cloud allows you to generate access token's without providing a client id / secret. In this case, a default client id is assumed which is only allowed to create tokens for API keys, but not authorized to use any other grant type - including the grant_type refresh_token. Therefore, simply dismiss the refresh token from the response of the API key grant in the first call - you won't be able to use it.

In the API key use case, there is no benefit of using the grant_type refresh_token over getting a new access token with the API key grant type anyway - all validation steps that are done internally (does the user stil exist / is the user still in the account / ...) are identical. But the refresh token eventually will expire - the API key not.


问:
Node.js: Returning inserted row from PostgreSQL v.11 to browser

I'm new to using Node.js and PostgreSQL.

I'm creating a post request with insert query.

How can I return inserted values to browser at the same time?

```<code>app.post('/car_create', (req, res) => {
    const make = req.body.create_make;
    const model = req.body.create_model;

        client.query(`INSERT INTO cars (make, model) VALUES ($1, $2)`, [make, model], (error, results) => {
            if (error) {
                throw error
            }
            res.status(201).send(`Car added with ID: ${results};`);
            console.log(res);
            res.end();
        });
});
</code>```

How I can retrieve the data from response ?

Do I need to modify this line somehow?

```<code>            res.status(201).send(`Car added with ID: ${results};`);
</code>```

答:
First you need return the values after you insert them in PostgreSQL. To do so, add a RETURNING clause to your query, like so: INSERT INTO cars (make, model) VALUES ($1, $2) RETURNING id, make, model. Add more columns in the RETURNING clause if you have and want more.

Then in the callback, the results variable should contain information about your query, including what it returned (in the rows key). You can send it to the client in many ways, but to return it in a similar way as you currently do , you could do this:

```<code>const {id, make, model} = result.rows[0]; // rows is an array of rows returned, and since we do a single INSERT we only have one row, with the returned columns from the query
res.status(201).send(`Car added with ID ${id}, make "${make}" and model "${model}".`);
</code>```

If you want to use this data on the frontend it would be easier and more convenient to possibly send the data as JSON, like so: res.status(201).send(results.rows[0]);

Body:
I'm new to using Node.js and PostgreSQL.

I'm creating a post request with insert query.

How can I return inserted values to browser at the same time?

app.post('/car_create', (req, res) => {
    const make = req.body.create_make;
    const model = req.body.create_model;

        client.query(`INSERT INTO cars (make, model) VALUES ($1, $2)`, [make, model], (error, results) => {
            if (error) {
                throw error
            }
            res.status(201).send(`Car added with ID: ${results};`);
            console.log(res);
            res.end();
        });
});

How I can retrieve the data from response ?

Do I need to modify this line somehow?

            res.status(201).send(`Car added with ID: ${results};`);

Body:
First you need return the values after you insert them in PostgreSQL. To do so, add a RETURNING clause to your query, like so: INSERT INTO cars (make, model) VALUES ($1, $2) RETURNING id, make, model. Add more columns in the RETURNING clause if you have and want more.

Then in the callback, the results variable should contain information about your query, including what it returned (in the rows key). You can send it to the client in many ways, but to return it in a similar way as you currently do , you could do this:

const {id, make, model} = result.rows[0]; // rows is an array of rows returned, and since we do a single INSERT we only have one row, with the returned columns from the query
res.status(201).send(`Car added with ID ${id}, make "${make}" and model "${model}".`);

If you want to use this data on the frontend it would be easier and more convenient to possibly send the data as JSON, like so: res.status(201).send(results.rows[0]);


问:
Kotlin - Can't create two constructors with different List types parameters
I was trying to create the following class:

```<code>class MyClass {

    var foos: List<Foo> = listOf()

    constructor(foos: List<Foo>) {
        this.foos = foos
    }

    constructor(bars: List<Bar>) : super() {
        this.foos = bars.map { bar ->
            Foo(bar)
        }
    }
}
</code>```

However, I get an error saying:

Platform declaration clash: The following declarations have the same JVM signature ( (Ljava/util/List;)V):

I understand that they are both List objects, but they are typed with generics so I was sure it would not be a problem.

答:
This is not a Kotlin problem, but rather a mechanism on Java generics.
This mechanism is intended to avoid conflicts in legacy code that still uses raw types.

For example, if you create a class in Java like this one:

public class MyClass {

    private List<Foo> foos;

    MyClass(List<Foo> foos) {
        this.foos = foos;
    }

    MyClass(List<Bar> bars) {
        List<Foo> foos = new ArrayList<>();
        bars.forEach(bar -> foos.add(new Foo(bar)));
        this.foos = foos;
    }
}

```

You will get a compile time error saying:

'MyClass(List)' clases with 'MyClass(List)'; both methods have the same erasure

What type erasure does is enforcing type constraints only at compile time and discarding the element type information at runtime. Type parameters on the class are discarded during code compilation and replaced with its first bound or Object if the type parameter is unbound. Therefore, both constructors (since they're both unbounded) will be of List, hence the error.

Body:
I was trying to create the following class:

class MyClass {

    var foos: List<Foo> = listOf()

    constructor(foos: List<Foo>) {
        this.foos = foos
    }

    constructor(bars: List<Bar>) : super() {
        this.foos = bars.map { bar ->
            Foo(bar)
        }
    }
}

However, I get an error saying:

Platform declaration clash: The following declarations have the same JVM signature ( (Ljava/util/List;)V):

I understand that they are both List objects, but they are typed with generics so I was sure it would not be a problem.

Body:
This is not a Kotlin problem, but rather a mechanism on Java generics.
This mechanism is intended to avoid conflicts in legacy code that still uses raw types.

For example, if you create a class in Java like this one:

public class MyClass {

    private List<Foo> foos;

    MyClass(List<Foo> foos) {
        this.foos = foos;
    }

    MyClass(List<Bar> bars) {
        List<Foo> foos = new ArrayList<>();
        bars.forEach(bar -> foos.add(new Foo(bar)));
        this.foos = foos;
    }
}

You will get a compile time error saying:

'MyClass(List)' clases with 'MyClass(List)'; both methods have the same erasure

What type erasure does is enforcing type constraints only at compile time and discarding the element type information at runtime. Type parameters on the class are discarded during code compilation and replaced with its first bound or Object if the type parameter is unbound. Therefore, both constructors (since they're both unbounded) will be of List, hence the error.


问:
Bash Script hangs when run in go program
I have a bash script postinstall.sh that executes normally when run from the terminal

```<code>./postinstall.sh
</code>```

the script runs a bunch of commands, creating directorys, chown,chmod files and directorys,

at the end of the script is

```<code>echo "Done"
exit 0
</code>```

When i run this as a exec.Cmd in go, and call the cmd.Wait() funtion, it never returns.

So I modifed my code to use the package from https://github.com/go-cmd/cmd since I wanted to be able to log the output of the scripts I run in 'real time' but also detect when they are complete.  So after a bunch of work I can now log the stdOut of the Cmd to my logging at logLevel STATUS and the stdErr of the Cmd to my logLevel ERROR. I can also set a timeout for the command, and log its progress in real time.

This new process works as expected for some simple cases, but when I thow the big postinstall.sh script at it, it runs all the way to the end, and then hangs, and eventually times out.  The process takes a few seconds when run manually on the command line, I set the timeout to be 30 seconds.  the logging shows the

```<code>STATUS- Done
</code>```

which is the line right before the

```<code>exit 0
</code>```

The docs for the go-cmd package show a non locking way to tell that the process has finished, which I am checking (and works my test cases) I also am checking the cmd.Status().finished flag (bool) and neither of these are reporting that the process has finished. This is the same result I was seeing by just using the cmd.Wait() function from the built in exec.Cmd, only now I can see that the script makes it all the way to the end, but for some reason is either not returning, or the go program can not tell that is has returned.

Some of what the script is doing is starting or restarting services in /etc/init.d, if one of those launches a process in the backround, since the parent process is the postinstall script could that cause the process to not fully complete in the eye of the go program?

Or any other types of commands that could cause this type of behavior?

I may just have to start removing parts of the script and see if I can get it to complete to narrow down what is causing this to act different then my test script, but its around 100 lines, and the process to get the script into the device is a multi step process.

testscript was something along the lines of

```<code>#!/bin/bash

echo "stdOut"
sleep 1
>2& echo "stdErr"
sleep 2
echo "Finsihed"
sleep 1
</code>```

and this worked as expected(timed out when limit was 1 second, showed completed when timeout was set to 4 seconds)

Should Also note that the process works on other scripts.
this is part of an updating process that does a preinstall.sh, then uses this same process to call tar -xvf on the file containing the update, and then goes on to this postinstall script.  So most of the time my process succesfully detects that the process has exited, there is just something about the postinstall thats the issue, but I cant think of what would make it hang in go, but exit fine when run from the terminal.

答:
Here's from the docs for Cmd.wait with emphasis:

```<code>func (c *Cmd) Wait() error
</code>```

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

This means that it will wait for all processes to close the relevant pipe, not just for the given process to exit. This is a problem when you start processes in the background:

Here's an example:

```<code>#!/bin/bash
sleep 3600 &
echo "Exit"
</code>```

sleep inherits stdin/out/err and keeps them open for an hour. It will exit immediately in a terminal because Bash doesn't and can't care what has the terminal open:

```<code>$ ./testscript; echo "Returned"
Exit
Returned
$
</code>```

However, if you pipe to cat, it will wait for all potential data to finish (in case sleep decides to write something later), and bash in turns waits on cat:

```<code>$ ./testscript | cat; echo "Returned"
Exit
(Hangs for an hour)
</code>```

You can fix this by making sure any forked processes won't be writing to the pipe by redirecting somewhere else:

```<code>#!/bin/bash
sleep 3600 < /dev/null > /dev/null 2>&1 &
echo "Exit"
</code>```

Since sleep no longer holds the pipe open, it returns immediately, both in the shell and with Cmd.Wait():

```<code>$ ./testscript | cat; echo "Returned"
Exit
Returned
</code>```

Body:
I have a bash script postinstall.sh that executes normally when run from the terminal

./postinstall.sh

the script runs a bunch of commands, creating directorys, chown,chmod files and directorys,

at the end of the script is

echo "Done"
exit 0

When i run this as a exec.Cmd in go, and call the cmd.Wait() funtion, it never returns.

So I modifed my code to use the package from https://github.com/go-cmd/cmd since I wanted to be able to log the output of the scripts I run in 'real time' but also detect when they are complete.  So after a bunch of work I can now log the stdOut of the Cmd to my logging at logLevel STATUS and the stdErr of the Cmd to my logLevel ERROR. I can also set a timeout for the command, and log its progress in real time.

This new process works as expected for some simple cases, but when I thow the big postinstall.sh script at it, it runs all the way to the end, and then hangs, and eventually times out.  The process takes a few seconds when run manually on the command line, I set the timeout to be 30 seconds.  the logging shows the

STATUS- Done

which is the line right before the

exit 0

The docs for the go-cmd package show a non locking way to tell that the process has finished, which I am checking (and works my test cases) I also am checking the cmd.Status().finished flag (bool) and neither of these are reporting that the process has finished. This is the same result I was seeing by just using the cmd.Wait() function from the built in exec.Cmd, only now I can see that the script makes it all the way to the end, but for some reason is either not returning, or the go program can not tell that is has returned.

Some of what the script is doing is starting or restarting services in /etc/init.d, if one of those launches a process in the backround, since the parent process is the postinstall script could that cause the process to not fully complete in the eye of the go program?

Or any other types of commands that could cause this type of behavior?

I may just have to start removing parts of the script and see if I can get it to complete to narrow down what is causing this to act different then my test script, but its around 100 lines, and the process to get the script into the device is a multi step process.

testscript was something along the lines of

#!/bin/bash

echo "stdOut"
sleep 1
>2& echo "stdErr"
sleep 2
echo "Finsihed"
sleep 1

and this worked as expected(timed out when limit was 1 second, showed completed when timeout was set to 4 seconds)

Should Also note that the process works on other scripts.
this is part of an updating process that does a preinstall.sh, then uses this same process to call tar -xvf on the file containing the update, and then goes on to this postinstall script.  So most of the time my process succesfully detects that the process has exited, there is just something about the postinstall thats the issue, but I cant think of what would make it hang in go, but exit fine when run from the terminal.

Body:
Here's from the docs for Cmd.wait with emphasis:

func (c *Cmd) Wait() error

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

This means that it will wait for all processes to close the relevant pipe, not just for the given process to exit. This is a problem when you start processes in the background:

Here's an example:

#!/bin/bash
sleep 3600 &
echo "Exit"

sleep inherits stdin/out/err and keeps them open for an hour. It will exit immediately in a terminal because Bash doesn't and can't care what has the terminal open:

$ ./testscript; echo "Returned"
Exit
Returned
$

However, if you pipe to cat, it will wait for all potential data to finish (in case sleep decides to write something later), and bash in turns waits on cat:

$ ./testscript | cat; echo "Returned"
Exit
(Hangs for an hour)

You can fix this by making sure any forked processes won't be writing to the pipe by redirecting somewhere else:

#!/bin/bash
sleep 3600 < /dev/null > /dev/null 2>&1 &
echo "Exit"

Since sleep no longer holds the pipe open, it returns immediately, both in the shell and with Cmd.Wait():

$ ./testscript | cat; echo "Returned"
Exit
Returned


问:
ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems
ReSharper Code cleanup feature (with "reorder members" and "reformat code" enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template.

Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc. ? Is there a chance that it causes many undesired conflicts ?

Thank you.

答:
I'm waiting for an IDE or an editor that always saves source code using some baseline formatting rules, but allows each individual developer to display and edit the code in their own preferred format.  That way I can put my open curly brace at the beginning of the next line and not at the end of the current line where all you heathens seem to think it goes.

My guess is I'll be waiting for a long time.

OwnerDisplayName: Romain Verdier

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Julio


问:
Archive/Serialize Objective-C Object with C++ Instance Variables
I am using OpenCV static library in Objective-C to do some image processing, and although my app is working quite well, on the device itself it is rather slow. A large chunk of the processing can actually done beforehand, so I have decided I will serialize this data and just load that up when the app starts instead.

The data I need to serialize/archive is in an object of type CvSeq (openCV sequence - a pointer to a sequence of values). I basically want to save this to file so that it can be loaded up later. I thought I could do this by making a class that adhered to the NSCoding protocol and encode/decode from there:

```<code>@implementation MyObject

@synthesize point = _point;
@synthesize description = _description;

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.point = [decoder decodeObjectForKey:@"point"];
        self.description = [decoder decodeObjectForKey:@"description"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.point forKey:@"point"];
    [encoder encodeObject:self.description forKey:@"description"];
}

@end
</code>```

But on the decodeObjectForKey: and encodeObject: calls I get the error

```<code>error: cannot convert 'objc_object*' to 'CvSeq*' in argument passing
</code>```

Is there a problem with my code, or do I need to take another route to be able to achieve the same thing with non-objective-C instance variables being in my objects?

答:
Objective-C's serialization code is not going to know how to archive your C++ classes. You're going to need to explicitly write code to do that.  Assuming "description" is the CvSeq* in the above code, you will need to write methods that convert from CvSeq to something that Cocoa knows how to archive.  An NSString is probably the easiest place to start, even if it's not the most efficient scheme.

```<code>NSString* NSStringFromCvSeq(CvSeq* cppObj)
{
    // You have to write this, but at it's simplest it might be something like...
    return [NSString stringWithFormat: @"%d|%d|%d", cppObj->foo, cppObj->bar, cppObj->baz];
}

CvSeq* NewCvSeqFromNSString(NSString* encodedString)
{
    // You have to write this, but at it's simplest it might be something like...
    NSScanner* scanner = [NSScanner scannerWithString: encodedString];
    [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString: @"|"]];
    int foo = [scanner scanInt];
    int bar = [scanner scanInt];
    int baz = [scanner scanInt];

    return new CvSeq(foo, bar, baz);
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.point = [decoder decodeObjectForKey:@"point"];
        self.description = NewCvSeqFromNSString([decoder decodeObjectForKey:@"description"]);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.point forKey:@"point"];
    [encoder encodeObject: NSStringFromCvSeq(self.description) forKey:@"description"];
}
</code>```

The key takeaway here is that Cocoa has no idea how to archive arbitrary types (excepting Objective-C types that already adopt NSCoding), and will never archive a C++ object "for free" without some sort of glue layer, since a C++ object has no way of adopting the NSCoding protocol.

Hope that helps!

Body:
I am using OpenCV static library in Objective-C to do some image processing, and although my app is working quite well, on the device itself it is rather slow. A large chunk of the processing can actually done beforehand, so I have decided I will serialize this data and just load that up when the app starts instead.

The data I need to serialize/archive is in an object of type CvSeq (openCV sequence - a pointer to a sequence of values). I basically want to save this to file so that it can be loaded up later. I thought I could do this by making a class that adhered to the NSCoding protocol and encode/decode from there:

@implementation MyObject

@synthesize point = _point;
@synthesize description = _description;

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.point = [decoder decodeObjectForKey:@"point"];
        self.description = [decoder decodeObjectForKey:@"description"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.point forKey:@"point"];
    [encoder encodeObject:self.description forKey:@"description"];
}

@end

But on the decodeObjectForKey: and encodeObject: calls I get the error

error: cannot convert 'objc_object*' to 'CvSeq*' in argument passing

Is there a problem with my code, or do I need to take another route to be able to achieve the same thing with non-objective-C instance variables being in my objects?

Body:
Objective-C's serialization code is not going to know how to archive your C++ classes. You're going to need to explicitly write code to do that.  Assuming "description" is the CvSeq* in the above code, you will need to write methods that convert from CvSeq to something that Cocoa knows how to archive.  An NSString is probably the easiest place to start, even if it's not the most efficient scheme.

NSString* NSStringFromCvSeq(CvSeq* cppObj)
{
    // You have to write this, but at it's simplest it might be something like...
    return [NSString stringWithFormat: @"%d|%d|%d", cppObj->foo, cppObj->bar, cppObj->baz];
}

CvSeq* NewCvSeqFromNSString(NSString* encodedString)
{
    // You have to write this, but at it's simplest it might be something like...
    NSScanner* scanner = [NSScanner scannerWithString: encodedString];
    [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString: @"|"]];
    int foo = [scanner scanInt];
    int bar = [scanner scanInt];
    int baz = [scanner scanInt];

    return new CvSeq(foo, bar, baz);
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.point = [decoder decodeObjectForKey:@"point"];
        self.description = NewCvSeqFromNSString([decoder decodeObjectForKey:@"description"]);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.point forKey:@"point"];
    [encoder encodeObject: NSStringFromCvSeq(self.description) forKey:@"description"];
}

The key takeaway here is that Cocoa has no idea how to archive arbitrary types (excepting Objective-C types that already adopt NSCoding), and will never archive a C++ object "for free" without some sort of glue layer, since a C++ object has no way of adopting the NSCoding protocol.

Hope that helps!


问:
How to I customize certain text in d3.js?
I have some code where I'm adding an asterisk to the end of a template literal in d3js. I want to be able to customize the size and color of the asterisk independent of the variable. Here is my code.

```<code>svg.selectAll('.text')
    .data(data)
    .enter()
    .append('text')
      .attr('class', d => {
        const shortName = getChannelShortName(d.name).toLowerCase();
        const channelEnabled = disabledChannels.includes(shortName);
        return !channelEnabled ? 'label x-axis-conversion-rate' : 'label x-axis-conversion-rate-disabled'
      })
      .attr('text-anchor', 'middle')
      .attr('x', d => xScaleBottom(d.name) + (d.subsetValue > 9 ? 45 : 45))
      .attr('y', d => -50)
      .text(d => {
        const shortName = getChannelShortName(d.name).toLowerCase();
        const channelEnabled = disabledChannels.includes(shortName);
        return !channelEnabled ? `${d.conversationRate}%` : `${d.conversationRate}%*`
      });
</code>```

On ${d.conversationRate}%*, I'd like to get control of this asterisk and  change the size and color of it.

答:
You can use an svg tspan to set font size and color for text within svg text elements:

Inside a  element, text position, text properties, and font properties can be adjusted with with the  element (MDN)

You can either append the tspan with the text using selection.append("text").html(string) where the string is something like text <tspan font-size="10" fill="orange">text</tspan>.

Or you can chain two appends together: one to append and set the text, and one to add a tspan to the text (since your tspan will fall at the end of the text):

```<code>selection.append("text")
 .text(d=>d.someText)
 .filter(function(d) { return d.doesElementNeedAsterisk })
 .append("tspan")
 .text("*");
</code>```

The latter option is demonstrated below:

var data = [
  {text1:"text1",color:"steelblue",size:"30px",asterisk:true},
  {text1:"text2",color:"crimson",size:"40px",asterisk:true},
  {text1:"text3",asterisk:false},
 ];

var svg = d3.select("body")
  .append("svg");

svg.selectAll("text")
  .data(data)
  .enter()
  .append("text")             // add text elements
  .attr("x", 20)
  .attr("y", (d,i)=> i* 50+50)
  .text(d=>d.text1)          // set the text
  .attr("font-size",20)
  .filter(function(d) {
    return d.asterisk;       // filter for values that show asterisks
  })
  .append("tspan")           // append a tspan to these text elements
  .text("*")
  .attr("fill", d=>d.color)  // set color
  .attr("font-size",d=>d.size);  // set font size.```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script></code>```

Body:
I have some code where I'm adding an asterisk to the end of a template literal in d3js. I want to be able to customize the size and color of the asterisk independent of the variable. Here is my code.

svg.selectAll('.text')
    .data(data)
    .enter()
    .append('text')
      .attr('class', d => {
        const shortName = getChannelShortName(d.name).toLowerCase();
        const channelEnabled = disabledChannels.includes(shortName);
        return !channelEnabled ? 'label x-axis-conversion-rate' : 'label x-axis-conversion-rate-disabled'
      })
      .attr('text-anchor', 'middle')
      .attr('x', d => xScaleBottom(d.name) + (d.subsetValue > 9 ? 45 : 45))
      .attr('y', d => -50)
      .text(d => {
        const shortName = getChannelShortName(d.name).toLowerCase();
        const channelEnabled = disabledChannels.includes(shortName);
        return !channelEnabled ? `${d.conversationRate}%` : `${d.conversationRate}%*`
      });

On ${d.conversationRate}%*, I'd like to get control of this asterisk and  change the size and color of it.

Body:
You can use an svg tspan to set font size and color for text within svg text elements:

Inside a  element, text position, text properties, and font properties can be adjusted with with the  element (MDN)

You can either append the tspan with the text using selection.append("text").html(string) where the string is something like text <tspan font-size="10" fill="orange">text</tspan>.

Or you can chain two appends together: one to append and set the text, and one to add a tspan to the text (since your tspan will fall at the end of the text):

selection.append("text")
 .text(d=>d.someText)
 .filter(function(d) { return d.doesElementNeedAsterisk })
 .append("tspan")
 .text("*");

The latter option is demonstrated below:

var data = [
  {text1:"text1",color:"steelblue",size:"30px",asterisk:true},
  {text1:"text2",color:"crimson",size:"40px",asterisk:true},
  {text1:"text3",asterisk:false},
 ];

var svg = d3.select("body")
  .append("svg");

svg.selectAll("text")
  .data(data)
  .enter()
  .append("text")             // add text elements
  .attr("x", 20)
  .attr("y", (d,i)=> i* 50+50)
  .text(d=>d.text1)          // set the text
  .attr("font-size",20)
  .filter(function(d) {
    return d.asterisk;       // filter for values that show asterisks
  })
  .append("tspan")           // append a tspan to these text elements
  .text("*")
  .attr("fill", d=>d.color)  // set color
  .attr("font-size",d=>d.size);  // set font size.

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


问:
Add textbox when button is pressed
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

```<code> <input name="userfile[]" type="file" /><br />
    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</code>```

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

答:
Try this:</p>

```<code>var i = 2;
var sourceTextNode = document.getElementsByName("imagedescription2")[0];
function createTextBox(){
    var newNode = sourceTextNode.cloneNode(false);
    newNode.setAttribute("name", ++i);
    var parent = sourceTextNode.parentNode;
    if(parent.lastchild == sourceTextNode) {
        parent.appendChild(newNode);
    } else {
        parent.insertBefore(newNode, sourceTextNode.nextSibling);
    }
}

function btnClicked(){
    createTextBox();
}
</code>```

Title: Add textbox when button is pressed

Body:
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

 <input name="userfile[]" type="file" />

    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" />

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

Body:
Try this:

var i = 2;
var sourceTextNode = document.getElementsByName("imagedescription2")[0];
function createTextBox(){
    var newNode = sourceTextNode.cloneNode(false);
    newNode.setAttribute("name", ++i);
    var parent = sourceTextNode.parentNode;
    if(parent.lastchild == sourceTextNode) {
        parent.appendChild(newNode);
    } else {
        parent.insertBefore(newNode, sourceTextNode.nextSibling);
    }
}

function btnClicked(){
    createTextBox();
}


问:
How to identify changes to a list of customers over time
I have a cohort of customers that changes fairly regularly. Each time the cohort changes, a complete dump of the new customers is appended to the table and given a new List_Name. Alpha, Beta, Gamma, etc. Each list generally add some customers, removes some customers, and keeps some customers. I'm trying to create a simple waterfall chart to show the changes from list to list. Typically I would just FULL OUTER JOIN Alpha<->Beta, then FULL OUTER JOIN Beta<->Gamma, etc etc to get the customers that are staying, leaving, and being added. But the List_Versions are growing quite a bit and I am wondering if there is an easier way to do this calc instead of having to edit it every time a new list is appended. I am not able to change this process since it supports legacy systems and is controlled by another department. Thoughts?

EDIT: Sql Server 2016 SP2.

```<code>CREATE TABLE #customers(cust_id int, list_name varchar(10), create_dt date)
INSERT INTO #customers values (1,'Alpha','2019-01-01')
    ,(2,'Alpha','2019-01-01')
    ,(3,'Alpha','2019-01-01')
    ,(4,'Alpha','2019-01-01')
    ,(5,'Alpha','2019-01-01')
    ,(2,'Beta','2019-03-01')
    ,(3,'Beta','2019-03-01')
    ,(4,'Beta','2019-03-01')
    ,(5,'Beta','2019-03-01')
    ,(6,'Beta','2019-03-01')
    ,(7,'Beta','2019-03-01')
    ,(1,'Gamma','2019-05-05')
    ,(6,'Gamma','2019-05-05')
    ,(7,'Gamma','2019-05-05')
    ,(9,'Gamma','2019-05-05')

--Desired Output (long way that needs to be edited every time there is a new list)
SELECT List_Name, 'Starting' Descrip, count(*) Custs FROM #customers WHERE list_name = 'alpha' group by list_name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Alpha' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Beta', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Alpha' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Gamma' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Gamma', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Gamma' AND a.cust_id = x.cust_id) GROUP BY List_Name
</code>```

答:
Instead of hard coding the list names, you can create a temp table to generate ids, and then use the ids as join conditions for the aggregations. This will allow you to a list to the previous list without relying on knowing the names and the order they were generated.

```<code>CREATE TABLE #customers(cust_id int, list_name varchar(10), list_date date)
INSERT INTO #customers
(
    cust_id
    ,list_name
    ,list_date
)
values (1,'Alpha', '01-01-2019')
    ,(2,'Alpha', '01-01-2019')
    ,(3,'Alpha', '01-01-2019')
    ,(4,'Alpha', '01-01-2019')
    ,(5,'Alpha', '01-01-2019')
    ,(2,'Beta', '02-01-2019')
    ,(3,'Beta', '02-01-2019')
    ,(4,'Beta', '02-01-2019')
    ,(5,'Beta', '02-01-2019')
    ,(6,'Beta', '02-01-2019')
    ,(7,'Beta', '02-01-2019')
    ,(1,'Gamma', '03-01-2019')
    ,(6,'Gamma', '03-01-2019')
    ,(7,'Gamma', '03-01-2019')
    ,(9,'Gamma', '03-01-2019')

CREATE TABLE #lists
(
    list_id INT IDENTITY(1,1)
    ,list_name varchar(10)
    ,Starting INT
    ,Added INT
    ,Removed INT
    ,list_date date
)

INSERT INTO #lists
(
    list_name
    ,Starting
    ,Added
    ,Removed
    ,list_date
)
SELECT DISTINCT
    a.list_name
    ,Starting = (SELECT COUNT(*) FROM #customers b WHERE b.list_name = a.list_name)
    ,Added = 0
    ,Removed = 0
    ,a.list_date
FROM #customers a
ORDER BY a.list_date ASC
</code>```

Now use this temp table to create another temp table with customer ids and list ids. I do this so I don't have to keep writing joins to link list names and list ids.

```<code>SELECT c.cust_id
      ,l.list_id
INTO #ListCus
FROM #customers c
INNER JOIN #lists l ON l.list_name = c.list_name
</code>```

Next you can calculate the Added and Removed numbers.

```<code>UPDATE l
SET l.Added = (SELECT COUNT(*) FROM #ListCus c1 WHERE c1.list_id = l.list_id AND NOT EXISTS (SELECT * FROM #ListCus x WHERE x.list_id = l.list_id-1 AND c1.cust_id = x.cust_id))
    ,l.Removed = (SELECT -COUNT(*) FROM #ListCus c1 WHERE c1.list_id = l.list_id-1 AND NOT EXISTS (SELECT * FROM #ListCus x WHERE x.list_id = l.list_id AND c1.cust_id = x.cust_id))
FROM #lists l
WHERE l.list_id > 1 --the first list won't have Added or Removed records
</code>```

Finally we format the data by unpivoting and filtering out unneeded Descrips.

```<code>;WITH unpivoted AS
(
    SELECT
        u.list_id
        ,u.Descrip
        ,u.custs
    FROM #lists l
    UNPIVOT
    (
        custs
        FOR Descrip IN (Starting, Added, Removed)
    )u
)
,SubResults AS
(
    SELECT u.list_id
          ,u.Descrip
          ,u.custs
    FROM unpivoted u
    WHERE u.list_id = 1
        AND u.Descrip = 'Starting'

    UNION ALL

    SELECT u.list_id
          ,u.Descrip
          ,u.custs
    FROM unpivoted u
    WHERE u.list_id <> 1
        AND u.Descrip <> 'Starting'
)
SELECT
    l.list_name
    ,s.Descrip
    ,s.custs
FROM SubResults s
INNER JOIN #lists l ON l.list_id = s.list_id
ORDER BY s.list_id ASC, s.Descrip
</code>```

Body:
I have a cohort of customers that changes fairly regularly. Each time the cohort changes, a complete dump of the new customers is appended to the table and given a new List_Name. Alpha, Beta, Gamma, etc. Each list generally add some customers, removes some customers, and keeps some customers. I'm trying to create a simple waterfall chart to show the changes from list to list. Typically I would just FULL OUTER JOIN Alpha<->Beta, then FULL OUTER JOIN Beta<->Gamma, etc etc to get the customers that are staying, leaving, and being added. But the List_Versions are growing quite a bit and I am wondering if there is an easier way to do this calc instead of having to edit it every time a new list is appended. I am not able to change this process since it supports legacy systems and is controlled by another department. Thoughts?

EDIT: Sql Server 2016 SP2.

CREATE TABLE #customers(cust_id int, list_name varchar(10), create_dt date)
INSERT INTO #customers values (1,'Alpha','2019-01-01')
    ,(2,'Alpha','2019-01-01')
    ,(3,'Alpha','2019-01-01')
    ,(4,'Alpha','2019-01-01')
    ,(5,'Alpha','2019-01-01')
    ,(2,'Beta','2019-03-01')
    ,(3,'Beta','2019-03-01')
    ,(4,'Beta','2019-03-01')
    ,(5,'Beta','2019-03-01')
    ,(6,'Beta','2019-03-01')
    ,(7,'Beta','2019-03-01')
    ,(1,'Gamma','2019-05-05')
    ,(6,'Gamma','2019-05-05')
    ,(7,'Gamma','2019-05-05')
    ,(9,'Gamma','2019-05-05')

--Desired Output (long way that needs to be edited every time there is a new list)
SELECT List_Name, 'Starting' Descrip, count(*) Custs FROM #customers WHERE list_name = 'alpha' group by list_name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Alpha' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Beta', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Alpha' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT List_Name, 'Add', count(*) FROM #customers a WHERE list_name = 'Gamma' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Beta' AND a.cust_id = x.cust_id) GROUP BY List_Name
UNION ALL
SELECT 'Gamma', 'Remove', -count(*) FROM #customers a WHERE list_name = 'Beta' AND not exists(SELECT * FROM #customers x WHERE List_Name = 'Gamma' AND a.cust_id = x.cust_id) GROUP BY List_Name

Body:
Instead of hard coding the list names, you can create a temp table to generate ids, and then use the ids as join conditions for the aggregations. This will allow you to a list to the previous list without relying on knowing the names and the order they were generated.

CREATE TABLE #customers(cust_id int, list_name varchar(10), list_date date)
INSERT INTO #customers
(
    cust_id
    ,list_name
    ,list_date
)
values (1,'Alpha', '01-01-2019')
    ,(2,'Alpha', '01-01-2019')
    ,(3,'Alpha', '01-01-2019')
    ,(4,'Alpha', '01-01-2019')
    ,(5,'Alpha', '01-01-2019')
    ,(2,'Beta', '02-01-2019')
    ,(3,'Beta', '02-01-2019')
    ,(4,'Beta', '02-01-2019')
    ,(5,'Beta', '02-01-2019')
    ,(6,'Beta', '02-01-2019')
    ,(7,'Beta', '02-01-2019')
    ,(1,'Gamma', '03-01-2019')
    ,(6,'Gamma', '03-01-2019')
    ,(7,'Gamma', '03-01-2019')
    ,(9,'Gamma', '03-01-2019')

CREATE TABLE #lists
(
    list_id INT IDENTITY(1,1)
    ,list_name varchar(10)
    ,Starting INT
    ,Added INT
    ,Removed INT
    ,list_date date
)

INSERT INTO #lists
(
    list_name
    ,Starting
    ,Added
    ,Removed
    ,list_date
)
SELECT DISTINCT
    a.list_name
    ,Starting = (SELECT COUNT(*) FROM #customers b WHERE b.list_name = a.list_name)
    ,Added = 0
    ,Removed = 0
    ,a.list_date
FROM #customers a
ORDER BY a.list_date ASC

Now use this temp table to create another temp table with customer ids and list ids. I do this so I don't have to keep writing joins to link list names and list ids.

SELECT c.cust_id
      ,l.list_id
INTO #ListCus
FROM #customers c
INNER JOIN #lists l ON l.list_name = c.list_name

Next you can calculate the Added and Removed numbers.

UPDATE l
SET l.Added = (SELECT COUNT(*) FROM #ListCus c1 WHERE c1.list_id = l.list_id AND NOT EXISTS (SELECT * FROM #ListCus x WHERE x.list_id = l.list_id-1 AND c1.cust_id = x.cust_id))
    ,l.Removed = (SELECT -COUNT(*) FROM #ListCus c1 WHERE c1.list_id = l.list_id-1 AND NOT EXISTS (SELECT * FROM #ListCus x WHERE x.list_id = l.list_id AND c1.cust_id = x.cust_id))
FROM #lists l
WHERE l.list_id > 1 --the first list won't have Added or Removed records

Finally we format the data by unpivoting and filtering out unneeded Descrips.

;WITH unpivoted AS
(
    SELECT
        u.list_id
        ,u.Descrip
        ,u.custs
    FROM #lists l
    UNPIVOT
    (
        custs
        FOR Descrip IN (Starting, Added, Removed)
    )u
)
,SubResults AS
(
    SELECT u.list_id
          ,u.Descrip
          ,u.custs
    FROM unpivoted u
    WHERE u.list_id = 1
        AND u.Descrip = 'Starting'

    UNION ALL

    SELECT u.list_id
          ,u.Descrip
          ,u.custs
    FROM unpivoted u
    WHERE u.list_id <> 1
        AND u.Descrip <> 'Starting'
)
SELECT
    l.list_name
    ,s.Descrip
    ,s.custs
FROM SubResults s
INNER JOIN #lists l ON l.list_id = s.list_id
ORDER BY s.list_id ASC, s.Descrip


问:
Discord JS, reply to certain user ID
I want to make a command where the bot will only reply to a certain user id. But I'm confused how to make it so (FYI I'm new on JS)</p>

```<code>const userID = '<@4608164XXX93150209>'

bot.on("message", function(message){
if(!message.author === userID)
{

if(message.content === 'psst')
    {
        message.channel.send('Hello there!');
    }
}});
</code>```

答:
A little late to reply, but I had the same question and I used msg.sender instead of msg.author

```<code>const userID = "4608164XXX93150209"

bot.on("message", function(message){
if(!message.sender === userID)
{

if(message.content === 'psst')
{
    message.channel.send('Hello there!');
}
}});
</code>```

Note that msg.sender is a string and not numeric

Title: Discord JS, reply to certain user ID

Body:
I want to make a command where the bot will only reply to a certain user id. But I'm confused how to make it so (FYI I'm new on JS)

const userID = '<@4608164XXX93150209>'

bot.on("message", function(message){
if(!message.author === userID)
{

if(message.content === 'psst')
    {
        message.channel.send('Hello there!');
    }
}});

Body:
A little late to reply, but I had the same question and I used msg.sender instead of msg.author

const userID = "4608164XXX93150209"

bot.on("message", function(message){
if(!message.sender === userID)
{

if(message.content === 'psst')
{
    message.channel.send('Hello there!');
}
}});

Note that msg.sender is a string and not numeric


问:
How do you render a rails partial that is outside of a namespace in a view that is inside of a namespace?
I've got a 'static' controller and static views that are pages that don't utilize ruby in their views. For these pages, I have a sitemap partial that is generated programatically and used in the application layout file. Namespaced routes still use the application layout file but are taking the static routes and trying to namespace them too.

Here's the relevant portion of the route file:

```<code>namespace :admin do
  resources :verse_categories
  resources :verses
  resources :songs
  resources :flowers
  resources :visits, :except => [:new, :create]
end
match ':action' => 'static'
root :to => 'static#home'
</code>```

Here's the error I'm getting:

```<code>No route matches {:controller=>"admin/static", :action=>"about"}
</code>```

Note that about is one of the static pages that the sitemap partial uses.

So, how can I resolve this routing issue so that it's not trying to find my static sites inside of the admin namespace? Any help would be appreciated!

答:
This gist explains how to add directories to the search path for namespaced directories. I ended up doing the following:</p>

```<code>class Static::BaseController < ApplicationController
  def self._prefixes
    super | ["other_directory"]
  end
end
</code>```

Body:
I've got a 'static' controller and static views that are pages that don't utilize ruby in their views. For these pages, I have a sitemap partial that is generated programatically and used in the application layout file. Namespaced routes still use the application layout file but are taking the static routes and trying to namespace them too.

Here's the relevant portion of the route file:

namespace :admin do
  resources :verse_categories
  resources :verses
  resources :songs
  resources :flowers
  resources :visits, :except => [:new, :create]
end
match ':action' => 'static'
root :to => 'static#home'

Here's the error I'm getting:

No route matches {:controller=>"admin/static", :action=>"about"}

Note that about is one of the static pages that the sitemap partial uses.

So, how can I resolve this routing issue so that it's not trying to find my static sites inside of the admin namespace? Any help would be appreciated!

Body:
This gist explains how to add directories to the search path for namespaced directories. I ended up doing the following:

class Static::BaseController < ApplicationController
  def self._prefixes
    super | ["other_directory"]
  end
end


问:
Integrate function returning roundoff error after working previously
When using integrate to integrate a lognormal density function from 2000 -> Inf, I am returned with an error. I had used a very similar equation previously with no problems.

I have tried disabling stop on error, and setting rel.tol lower. I am fairly new and unfamilar with r so I apologize if neither of those are expected to have done anything.

> integrand = function(x) {(x-2000)*(1/x)*(1/(.99066*((2*pi)^.5)))*exp(-((log(x)-7.641)^2)/((2*(.99066)^2)))}
> integrate(integrand,lower=2000,upper=Inf)
1854.002 with absolute error < 0.018
#returns value fine

> integrand = function(x) {(x-2000)*(1/x)*(1/(1.6247*((2*pi)^.5)))*exp(-((log(x)-9.0167)^2)/((2*(1.6247)^2)))}
> integrate(integrand,lower=2000,upper=Inf)
Error in integrate(integrand, lower = 2000, upper = Inf) :
  roundoff error is detected in the extrapolation table
#small change in the mu and sigma in the lognormal density function results in roundoff error

> integrate(integrand,lower=1293,upper=Inf)
29005.08 with absolute error < 2
#integrating on lower bound works fine, but having lower=1294 returns a roundoff error again
> integrate(integrand,lower=1294,upper=Inf)
Error in integrate(integrand, lower = 1294, upper = Inf) :
  roundoff error is detected in the extrapolation table
```

I should be getting returned a value, no? I struggle to see how very slightly altering the values would cause the function to no longer integrate.

答:
First of all, I believe you are complicating when you define the integrand by writing down the entire expression, it seems better to use the built-in dlnorm function.

```<code>g <- function(x, deduce, meanlog, sdlog){
  (x - deduce) * dlnorm(x, meanlog = meanlog, sdlog = sdlog)
}

curve(g(x, deduce = 2000, meanlog = 9.0167, sdlog = 1.6247),
      from = 1294, to = 1e4)
</code>```

As for the integration problem, package cubature generally does a better job when integrate fails. All of the following produce the results, with no errors.

```<code>library(cubature)

cubintegrate(g, lower = 1293, upper = Inf, method = "pcubature",
             deduce = 2000, meanlog = 9.0167, sdlog = 1.6247)

cubintegrate(g, lower = 1294, upper = Inf, method = "pcubature",
             deduce = 2000, meanlog = 9.0167, sdlog = 1.6247)

cubintegrate(g, lower = 2000, upper = Inf, method = "pcubature",
             deduce = 2000, meanlog = 9.0167, sdlog = 1.6247)
</code>```

Body:
When using integrate to integrate a lognormal density function from 2000 -> Inf, I am returned with an error. I had used a very similar equation previously with no problems.

I have tried disabling stop on error, and setting rel.tol lower. I am fairly new and unfamilar with r so I apologize if neither of those are expected to have done anything.

> integrand = function(x) {(x-2000)*(1/x)*(1/(.99066*((2*pi)^.5)))*exp(-((log(x)-7.641)^2)/((2*(.99066)^2)))}
> integrate(integrand,lower=2000,upper=Inf)
1854.002 with absolute error < 0.018
#returns value fine

> integrand = function(x) {(x-2000)*(1/x)*(1/(1.6247*((2*pi)^.5)))*exp(-((log(x)-9.0167)^2)/((2*(1.6247)^2)))}
> integrate(integrand,lower=2000,upper=Inf)
Error in integrate(integrand, lower = 2000, upper = Inf) :
  roundoff error is detected in the extrapolation table
#small change in the mu and sigma in the lognormal density function results in roundoff error

> integrate(integrand,lower=1293,upper=Inf)
29005.08 with absolute error < 2
#integrating on lower bound works fine, but having lower=1294 returns a roundoff error again
> integrate(integrand,lower=1294,upper=Inf)
Error in integrate(integrand, lower = 1294, upper = Inf) :
  roundoff error is detected in the extrapolation table

I should be getting returned a value, no? I struggle to see how very slightly altering the values would cause the function to no longer integrate.

Body:
First of all, I believe you are complicating when you define the integrand by writing down the entire expression, it seems better to use the built-in dlnorm function.

g <- function(x, deduce, meanlog, sdlog){
  (x - deduce) * dlnorm(x, meanlog = meanlog, sdlog = sdlog)
}

curve(g(x, deduce = 2000, meanlog = 9.0167, sdlog = 1.6247),
      from = 1294, to = 1e4)

As for the integration problem, package cubature generally does a better job when integrate fails. All of the following produce the results, with no errors.

library(cubature)

cubintegrate(g, lower = 1293, upper = Inf, method = "pcubature",
             deduce = 2000, meanlog = 9.0167, sdlog = 1.6247)

cubintegrate(g, lower = 1294, upper = Inf, method = "pcubature",
             deduce = 2000, meanlog = 9.0167, sdlog = 1.6247)

cubintegrate(g, lower = 2000, upper = Inf, method = "pcubature",
             deduce = 2000, meanlog = 9.0167, sdlog = 1.6247)


问:
How to parse an object instead of an array with retrofit2
So I'm a beginning android dev and I'm using retrofit2 to perform a GET request to my API. However I'm getting a "expected begin_array but was begin_object".

I've tried reading up on the issue on many websites but none of them was helpful (for me) including the documentation of retrofit.

I tried creating a POJO class in kotlin and following this tutorial: https://www.freshbytelabs.com/2018/05/how-to-fix-expected-beginarray-but-was.html.

But I'm simply lost when the author uses variables that I don't see declared in his code. So copy/pasting the example didn't work. Maybe because I'm plain stupid, but I'd appreciate any help.

The JSON expected response (tested with postman):

```<code>{
    "value": [
        {
            "id": 1,
            "uniqueId": "1b97653d-bafe-461f-b609-72ab6795737f",
            "code": "NL",
            "description": "something",
            "isActive": true,
            "dateCreated": "2019-04-12T22:41:28.4966667",
            "dateModified": "2019-04-12T22:41:28.4966667",
            "dateExpired": "9999-12-31T00:00:00",
            "timestamp": "AAAAAAAAB9E=",
            "responseUserList": []
        }
    ],
    "success": true,
    "errorCode": null,
    "errorMessage": null
}
</code>```

This is my main:

```<code>var restLanguageService = Retrofit.Builder()
            .baseUrl("https://30cookweb20190412110132.azurewebsites.net/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        var service = restLanguageService.create(RequestInterface::class.java)

        var call = service.getAllLanguages()

        call.enqueue(object: Callback<List<RequestInterface>>
        {
            override fun onResponse(call: Call<List<RequestInterface>>, response: Response<List<RequestInterface>>)
            {
                var restLanguages = response.body().toString()
                if (!response.isSuccessful)
                {
                    for (RestLanguage in restLanguages)
                        textView.text = "Code: " + response.code()
                    return
                }
            }

            override fun onFailure(call: Call<List<RequestInterface>>, t: Throwable)
            {
                textView.text = t.message
            }
        })
</code>```

My Interface:

```<code>interface RequestInterface
{
    @GET("api/language/getalllangaugesasync")
    fun getAllLanguages(): Call<List<RequestInterface>>
}
</code>```

My data class:

```<code>data class LanguageResponse(
    @SerializedName("errorCode")
    @Expose
    private val errorCode: Any,
    @SerializedName("errorMessage")
    @Expose
    private val errorMessage: Any,
    @SerializedName("success")
    @Expose
    private val success: Boolean,
    @SerializedName("languageValue")
    @Expose
    private val value: List<Value>
)
</code>```

This is my string printed in textView:

"expected begin_array but was begin_object at line 1 column 2 path$"

答:
Your interface should be returning the response which according to the details should be

```<code>    interface RequestInterface
{
    @GET("api/language/getalllangaugesasync")
    fun getAllLanguages(): Call<LanguageResponse>
}
</code>```

instead of

```<code>    interface RequestInterface
{
    @GET("api/language/getalllangaugesasync")
    fun getAllLanguages(): Call<List<RequestInterface>>
}
</code>```

Body:
So I'm a beginning android dev and I'm using retrofit2 to perform a GET request to my API. However I'm getting a "expected begin_array but was begin_object".

I've tried reading up on the issue on many websites but none of them was helpful (for me) including the documentation of retrofit.

I tried creating a POJO class in kotlin and following this tutorial: https://www.freshbytelabs.com/2018/05/how-to-fix-expected-beginarray-but-was.html.

But I'm simply lost when the author uses variables that I don't see declared in his code. So copy/pasting the example didn't work. Maybe because I'm plain stupid, but I'd appreciate any help.

The JSON expected response (tested with postman):

{
    "value": [
        {
            "id": 1,
            "uniqueId": "1b97653d-bafe-461f-b609-72ab6795737f",
            "code": "NL",
            "description": "something",
            "isActive": true,
            "dateCreated": "2019-04-12T22:41:28.4966667",
            "dateModified": "2019-04-12T22:41:28.4966667",
            "dateExpired": "9999-12-31T00:00:00",
            "timestamp": "AAAAAAAAB9E=",
            "responseUserList": []
        }
    ],
    "success": true,
    "errorCode": null,
    "errorMessage": null
}

This is my main:

var restLanguageService = Retrofit.Builder()
            .baseUrl("https://30cookweb20190412110132.azurewebsites.net/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        var service = restLanguageService.create(RequestInterface::class.java)

        var call = service.getAllLanguages()

        call.enqueue(object: Callback<List<RequestInterface>>
        {
            override fun onResponse(call: Call<List<RequestInterface>>, response: Response<List<RequestInterface>>)
            {
                var restLanguages = response.body().toString()
                if (!response.isSuccessful)
                {
                    for (RestLanguage in restLanguages)
                        textView.text = "Code: " + response.code()
                    return
                }
            }

            override fun onFailure(call: Call<List<RequestInterface>>, t: Throwable)
            {
                textView.text = t.message
            }
        })

My Interface:

interface RequestInterface
{
    @GET("api/language/getalllangaugesasync")
    fun getAllLanguages(): Call<List<RequestInterface>>
}

My data class:

data class LanguageResponse(
    @SerializedName("errorCode")
    @Expose
    private val errorCode: Any,
    @SerializedName("errorMessage")
    @Expose
    private val errorMessage: Any,
    @SerializedName("success")
    @Expose
    private val success: Boolean,
    @SerializedName("languageValue")
    @Expose
    private val value: List<Value>
)

This is my string printed in textView:

"expected begin_array but was begin_object at line 1 column 2 path$"

Body:
Your interface should be returning the response which according to the details should be

    interface RequestInterface
{
    @GET("api/language/getalllangaugesasync")
    fun getAllLanguages(): Call<LanguageResponse>
}

instead of

    interface RequestInterface
{
    @GET("api/language/getalllangaugesasync")
    fun getAllLanguages(): Call<List<RequestInterface>>
}


问:
writing fixed width, space delimited CSV output in Python
I would like to write a fixed width, space delimited and minimally quoted CSV file using Python's csv writer.
An example of the output:

```<code>item1           item2
"next item1"    "next item2"
anotheritem1    anotheritem2
</code>```

If I use

writer.writerow( ("{0:15s}".format(item1), "{0:15s}".format(item2)) )

  ...

then, with the space delimiter, the formatting is broken as either quotes or escapes (depending on the csv.QUOTE_* constant) are added due to the trailing spaces of the items formatting:

```<code>"item1          " "item2          "
"next item1     " "next item2     "
"anotheritem1   " "anotheritem2   "
</code>```

Of course, I could format everything myself:

writer.writerow( ("{0:15s}{1:15s}".format(item1, item2)) )

but then there is not much point in using the csv writer. Also, I would have to sort out manually those cases when the space is embedded in the items and quoting/escaping should be used. In other words, it seems I would need a (non-existing) "QUOTE_ABSOLUTELYMINIMAL" csv constant that would act as the "QUOTE_MINIMAL" one but would also ignore trailing spaces.

Is there a way to achieve the "QUOTE_ABSOLUTELYMINIMAL" behaviour or another way to get a fixed width, space delimited CSV output using Python's CSV module?

The reason why I want the fixed-width feature in a CSV file is a better readability. So it will be processed as CSV for both reading and writing but better readable due to the column structure. Reading is not a problem as the csv skipinitialspace option takes care of ignoring the extra spaces. To my surprise, writing seems to be a problem...

EDIT: I conclude it is impossible to achieve with the current csv plugin. It is not a built-in option and I cannot see any reasonable way how to achieve it manually as it seems there is no way to write extra delimiters by the Python's csv writer without quoting or escaping them. Thus, I will probably have to write my own csv writer.

答:
This active state recipe shows how to output table-ized data in python:
http://code.activestate.com/recipes/267662-table-indentation/

You might be able to glean enough from that example to do what you want.

Body:
I would like to write a fixed width, space delimited and minimally quoted CSV file using Python's csv writer.
An example of the output:

item1           item2
"next item1"    "next item2"
anotheritem1    anotheritem2

If I use

writer.writerow( ("{0:15s}".format(item1), "{0:15s}".format(item2)) )

  ...

then, with the space delimiter, the formatting is broken as either quotes or escapes (depending on the csv.QUOTE_* constant) are added due to the trailing spaces of the items formatting:

"item1          " "item2          "
"next item1     " "next item2     "
"anotheritem1   " "anotheritem2   "

Of course, I could format everything myself:

writer.writerow( ("{0:15s}{1:15s}".format(item1, item2)) )

but then there is not much point in using the csv writer. Also, I would have to sort out manually those cases when the space is embedded in the items and quoting/escaping should be used. In other words, it seems I would need a (non-existing) "QUOTE_ABSOLUTELYMINIMAL" csv constant that would act as the "QUOTE_MINIMAL" one but would also ignore trailing spaces.

Is there a way to achieve the "QUOTE_ABSOLUTELYMINIMAL" behaviour or another way to get a fixed width, space delimited CSV output using Python's CSV module?

The reason why I want the fixed-width feature in a CSV file is a better readability. So it will be processed as CSV for both reading and writing but better readable due to the column structure. Reading is not a problem as the csv skipinitialspace option takes care of ignoring the extra spaces. To my surprise, writing seems to be a problem...

EDIT: I conclude it is impossible to achieve with the current csv plugin. It is not a built-in option and I cannot see any reasonable way how to achieve it manually as it seems there is no way to write extra delimiters by the Python's csv writer without quoting or escaping them. Thus, I will probably have to write my own csv writer.


问:
IPython: How to wipe IPython's history selectively & securely?
I have been learning how to use the paramiko package only to discover that all I stored passwords in plain text in IPython's %hist. Not so good.

I therefore need to get rid of particular parts of what is stored in %hist. Saying that, I do not want to wipe the whole history. - Only the parts where I have been careless enough to type password = or similar chosen terms.

Thanks

Comments I don't need:

%clear only clears the session. It does not wipe the history.

Yes. I will only use xSA_keys from now on.

答:
If you want to delete history from a particular session, run:

```<code>sqlite ~/.ipython/profile_default/history.sqlite
</code>```

Note that on some systems, you will need to run sqlite3 rather than sqlite.

Inside SQLite:

```<code>select * from history;
# session is the first column in history
delete from history where session=XXX;
</code>```

Also, here is a SQLite query that will give you the id of your last session:

```<code>select session from history order by -session limit 1;
</code>```

Body:
If you want to delete history from a particular session, run:

sqlite ~/.ipython/profile_default/history.sqlite

Note that on some systems, you will need to run sqlite3 rather than sqlite.

Inside SQLite:

select * from history;
# session is the first column in history
delete from history where session=XXX;

Also, here is a SQLite query that will give you the id of your last session:

select session from history order by -session limit 1;