问:
ASIHTTPRequest in iOS
I have been using ASIHTTPRequest for an application but it gives me error in topSecretFetchFailed method 5 out of 10 request, Not sure how to deal with it, Isn't ASIHTTPRequest stable enough?

```<code>[request setDidFailSelector:@selector(topSecretFetchFailed:)];
</code>```

EDIT:

This is my code or method which get called in each request. MARKET_INDEXES_URL its static string which has "someurl.com";

```<code>- (void)requestData {
   ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:[NSURLURLWithString:MARKET_INDEXES_URL]];
   [req setDelegate:self];
   [req setDidFailSelector:@selector(topSecretFetchFailed:)];
   [req setDidFinishSelector:@selector(topSecretFetchComplete:)];
   [self setRequest:req];
   [self.request startAsynchronous];
}
</code>```

and this is the fail handler

```<code>- (void)topSecretFetchFailed:(ASIHTTPRequest *)theRequest {
   [[NSNotificationCenter defaultCenter] postNotificationName:@"MarketIndexesError" object:nil];
   UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"Connection error, Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [view show];
  [view release];
  NSLog(@"MarketIndex service Fail: %d %@", [theRequest responseStatusCode], [theRequest responseStatusMessage]);
}
</code>```

答:
ASIHTTPRequest is stable. You are probably getting error because either your network is down or your server is taking too long to respond.

You should try changing the ASIHTTPRequest property numberOfTimesToRetryOnTimeout to something that suits you.

```<code>ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:....
request.numberOfTimesToRetryOnTimeout=10;
</code>```

Title: ASIHTTPRequest in iOS

Body:
I have been using ASIHTTPRequest for an application but it gives me error in topSecretFetchFailed method 5 out of 10 request, Not sure how to deal with it, Isn't ASIHTTPRequest stable enough?

[request setDidFailSelector:@selector(topSecretFetchFailed:)];

EDIT:

This is my code or method which get called in each request. MARKET_INDEXES_URL its static string which has "someurl.com";

- (void)requestData {
   ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:[NSURLURLWithString:MARKET_INDEXES_URL]];
   [req setDelegate:self];
   [req setDidFailSelector:@selector(topSecretFetchFailed:)];
   [req setDidFinishSelector:@selector(topSecretFetchComplete:)];
   [self setRequest:req];
   [self.request startAsynchronous];
}

and this is the fail handler

- (void)topSecretFetchFailed:(ASIHTTPRequest *)theRequest {
   [[NSNotificationCenter defaultCenter] postNotificationName:@"MarketIndexesError" object:nil];
   UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"Warning !" message:@"Connection error, Please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [view show];
  [view release];
  NSLog(@"MarketIndex service Fail: %d %@", [theRequest responseStatusCode], [theRequest responseStatusMessage]);
}

Body:
ASIHTTPRequest is stable. You are probably getting error because either your network is down or your server is taking too long to respond.

You should try changing the ASIHTTPRequest property numberOfTimesToRetryOnTimeout to something that suits you.

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:....
request.numberOfTimesToRetryOnTimeout=10;


来源: stackexchange

问:
Wrong date time getting extracted in my Django project
I am currently inserting current timestamp in my postgresdb. As shown below, the date 19th feb got inserted.

but when I got to Django shell and printed all the dates, its printing 18th feb. How can i solve this confusion.

In my settings.py, current timezone is set to UTC and I cannot change that. Please suggest

答:
The dates are actually never saved with timezone in the DB. PgAdmin just renders the data based on your local timezone. In order to set it to UTC, open a new Query Tool in PgAdmin and do:</p>

```<code>SET TIMEZONE='UTC';

select * from your_table
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The dates are actually never saved with timezone in the DB. PgAdmin just renders the data based on your local timezone. In order to set it to UTC, open a new Query Tool in PgAdmin and do:

SET TIMEZONE='UTC';

select * from your_table


问:
Cant Deploy To Real Android Device Xamarin
My problem is related to this post
Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

I am not able to deploy my app on a real device it works properly on the emulator , i get deployment error, but nothing in the errors tab.

This is from build output

2>Build succeeded.

2>An error occured. See full exception on logs for more details.

2>The installed package is incompatible. Please manually uninstall and
  try again.

2>

========== Build: 1 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
  ========== Deploy: 0 succeeded, 1 failed, 0 skipped ==========

even after uninstalling the app i was not able to deploy my app on my real device , other apps install fine thorough VS.

答:
If you have this problem, that's simple, if you have an older .apk of your application, then install this .apk, and after you uninstall.
This is the simple solution.</p>

ContentLicense: CC BY-SA 3.0


问:
Creating another column in R
This is my current data set

I want to take the numbers after "narrow" (e.g. 20) and make another vector. Any idea how I can do that?

答:
We can use sub to remove the substring "Narrow", followed by a , and zero or more spaces (\\s+), replace with blank ("") and convert to numeric

```<code>df1$New <- as.numeric(sub("Narrow,\\s*", "", df1$Stimulus))
</code>```

Title: Creating another column in R

Body:
We can use sub to remove the substring "Narrow", followed by a , and zero or more spaces (\\s+), replace with blank ("") and convert to numeric

df1$New <- as.numeric(sub("Narrow,\\s*", "", df1$Stimulus))


问:
Log API Gateway Events before EC2 Execution
We're working with AWS and wish to log all incoming http requests from our API Gateway to the EC2 box in their entirety (i.e. not truncated at 1024 bytes). As we know the logging for API Gateway is not configurable our next thought was to place a lambda between the api gateway and EC2 which would intercept the requests, log them to S3, and then forward the request to EC2.

My question is two fold:

How does one submit an API Gateway 'event' to an EC2 instance manually? I've gone over the boto3 documentation and there doesn't seem to be a good way to do this out of the box.

Is this a logical way to log requests in their entirety, or are we missing a built in connector between lambda -> ec2 or request logging in general?

```<code>def lambda_handler(event, context):
  #pass event to the ec2
  #log event (done)
  #return response

</code>```

答:
You can enable CloudWatch logging for API gateway. By enabling you can find the logs for your requests in the cloud watch.

Create an IAM role that gives permissions for the API gateway to write logs to cloud watch

set the IAM role to your API

set the desired log levels INFO/ERROR

you can also choose to log the full request/responses

To enable access logs, you also need to create a log group and provide the arn.

The detailed steps can be found in the reference below.

Hope this helps.

Reference:
https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cloudwatch-logs/

Body:
We're working with AWS and wish to log all incoming http requests from our API Gateway to the EC2 box in their entirety (i.e. not truncated at 1024 bytes). As we know the logging for API Gateway is not configurable our next thought was to place a lambda between the api gateway and EC2 which would intercept the requests, log them to S3, and then forward the request to EC2.

My question is two fold:

How does one submit an API Gateway 'event' to an EC2 instance manually? I've gone over the boto3 documentation and there doesn't seem to be a good way to do this out of the box.

Is this a logical way to log requests in their entirety, or are we missing a built in connector between lambda -> ec2 or request logging in general?

def lambda_handler(event, context):
  #pass event to the ec2
  #log event (done)
  #return response


问:
Unable to rearrange the Co-ordinates of an Ellipse after rotation
I have drawn an Ellipse. I have 8 handles to it.

The handles are TopLeft, MidTop,TopRight, MidLeft, MidRight, BottomLeft, MidBottom, BottomRight.

Whenever a user hovers on any of these handles cursor gets displayed. For displaying the cursor I have referred MS-WORD shape ellipse.

My problem arrives when I roatate or I make a mirror image of an ellipse. I am not able to rearrange the Co-ordinates, hence the cursors are not displayed properly.

Please Help.

Note: Please open MS-WoRD.
Goto "INSERT"
Select "SHAPPES"
In that select "Ellipse" shape.
Draw it.
If you click on it you will see 8 points surrounding ellipse shape. Those are called handles. If you hover your mouse on any of the handle check the cursor display. Cursor display is depending the handle.
I need to implement the same functionality as it is in MS-WORD in VC++. .

EDIT - Added information below from comments:

The problem is with rearranging the coordinates after I rotate. If I roatate the ellipse slightly towards the right (try in MS-WoRD). Which point do i consider as Top-Left? I tried to rearrange with the above code. But it didnt work for many cases. Getting the top-left point after I rotate the ellipse is the main big problem i am facing right now.

```<code>struct SortingFunction
{
    bool operator()(const CRect& a, const CRect& b)
    {
        if (a.left == b.left)
            return a.top <= b.top; else return a.left < b.left;
    }
}
</code>```

答: Handles are also points, all you need to do is to identify the amount of rotation ellipse has gone to and rotate the handles with that rotation. </p>

Body:
I have drawn an Ellipse. I have 8 handles to it.

The handles are TopLeft, MidTop,TopRight, MidLeft, MidRight, BottomLeft, MidBottom, BottomRight.

Whenever a user hovers on any of these handles cursor gets displayed. For displaying the cursor I have referred MS-WORD shape ellipse.

My problem arrives when I roatate or I make a mirror image of an ellipse. I am not able to rearrange the Co-ordinates, hence the cursors are not displayed properly.

Please Help.

Note: Please open MS-WoRD.
Goto "INSERT"
Select "SHAPPES"
In that select "Ellipse" shape.
Draw it.
If you click on it you will see 8 points surrounding ellipse shape. Those are called handles. If you hover your mouse on any of the handle check the cursor display. Cursor display is depending the handle.
I need to implement the same functionality as it is in MS-WORD in VC++. .

EDIT - Added information below from comments:

The problem is with rearranging the coordinates after I rotate. If I roatate the ellipse slightly towards the right (try in MS-WoRD). Which point do i consider as Top-Left? I tried to rearrange with the above code. But it didnt work for many cases. Getting the top-left point after I rotate the ellipse is the main big problem i am facing right now.

struct SortingFunction
{
    bool operator()(const CRect& a, const CRect& b)
    {
        if (a.left == b.left)
            return a.top <= b.top; else return a.left < b.left;
    }
}


问:
Filter out objects in array if one value is the same
I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.

For example, I might get back:

```<code>  [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ]
</code>```

So I want to check that no two objects have a key with the same "Language" value (in this case, "English").

I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.

There is an example here:
Unexpeected result when filtering one object array against two other object arrays

but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.

I would be looking for a way to compare

```<code>  arrayName[eachObject].Language === "English"
</code>```

and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().

答:
I would use the underscore module for JavaScript and the unique function in this scenario. Here is a sample array of data objects:

```<code>let data = [{
    name: 'blah',
    date: Date.now(),
    language: "en"
},
{
    name: 'noblah',
    date: Date.now(),
    language: 'es'
},
{
    name: 'blah',
    date: Date.now(),
    language: 'en'
}];
</code>```

Then we can use the unique function in the underscore library to only return a copy of the data that has unique values associated with the language key:

```<code>const result = _.unique(data, 'language');
</code>```

Body:
I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.

For example, I might get back:

  [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ]

So I want to check that no two objects have a key with the same "Language" value (in this case, "English").

I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.

There is an example here:
Unexpeected result when filtering one object array against two other object arrays

but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.

I would be looking for a way to compare

  arrayName[eachObject].Language === "English"

and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().

Body:
I would use the underscore module for JavaScript and the unique function in this scenario. Here is a sample array of data objects:

let data = [{
    name: 'blah',
    date: Date.now(),
    language: "en"
},
{
    name: 'noblah',
    date: Date.now(),
    language: 'es'
},
{
    name: 'blah',
    date: Date.now(),
    language: 'en'
}];

Then we can use the unique function in the underscore library to only return a copy of the data that has unique values associated with the language key:

const result = _.unique(data, 'language');


问:
java.lang.NoSuchMethodError: org.junit.platform.launcher.Launcher.execute
I'm trying to run the following example unit test case

```<code>class ExampleUnitTest {

    @Test
    fun addition_is_Correct() {
        assertEquals(4, (2 + 2).toLong())
    }

}
</code>```

but I get the following exception

```<code>Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.launcher.Launcher.execute(Lorg/junit/platform/launcher/LauncherDiscoveryRequest;)V
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:61)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
</code>```

even though I have updated all the Junit dependencies build.gradle file like given below

```<code>testImplementation 'junit:junit:4.12'
testImplementation 'org.jetbrains.spek:spek-api:1.1.5'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.5'
testImplementation 'org.junit.platform:junit-platform-launcher:1.0.0'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0'
testImplementation 'org.junit.vintage:junit-vintage-engine:4.12.3'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.0.0'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.0.0'
</code>```

is there any solution for this?

答:
I was experiencing something similar in VSCode, and thought I'd share my result.

I was using a mis-mash of testing dependencies in my pom.xml, which I saw by doing mvn dependency:tree. Removing Specific junit-jupiter dependencies and simply using org.junit.jupiter:junit-jupiter made everything work again (both the Test Execution in VSCode, and mvn test on the command line).

Ultimately the only Jupiter dependencies I have in my pom.xml now is:

```<code><dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.6.0</version>
    <scope>test</scope>
</dependency>
</code>```

Source: https://github.com/junit-team/junit5/issues/1773

Body:
I'm trying to run the following example unit test case

class ExampleUnitTest {

    @Test
    fun addition_is_Correct() {
        assertEquals(4, (2 + 2).toLong())
    }

}

but I get the following exception

Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.launcher.Launcher.execute(Lorg/junit/platform/launcher/LauncherDiscoveryRequest;)V
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:61)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

even though I have updated all the Junit dependencies build.gradle file like given below

testImplementation 'junit:junit:4.12'
testImplementation 'org.jetbrains.spek:spek-api:1.1.5'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.5'
testImplementation 'org.junit.platform:junit-platform-launcher:1.0.0'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0'
testImplementation 'org.junit.vintage:junit-vintage-engine:4.12.3'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.0.0'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.0.0'

is there any solution for this?

Body:
I was experiencing something similar in VSCode, and thought I'd share my result.

I was using a mis-mash of testing dependencies in my pom.xml, which I saw by doing mvn dependency:tree. Removing Specific junit-jupiter dependencies and simply using org.junit.jupiter:junit-jupiter made everything work again (both the Test Execution in VSCode, and mvn test on the command line).

Ultimately the only Jupiter dependencies I have in my pom.xml now is:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.6.0</version>
    <scope>test</scope>
</dependency>

Source: https://github.com/junit-team/junit5/issues/1773


问:
Azure Databrics - Running a Spark Jar from Gen2 DataLake Storage
I am trying to run a spark-submit from Azure Databrics. Currently I can create a job, with the jar uploaded within the Databrics workspace, and run it.

My queries are:

Is there a way to access a jar residing on a GEN2 DataLake storage and do a spark-submit from Databrics workspace, or even from Azure ADF ? (Because the communication between the workspace and GEN2 storage is protected "fs.azure.account.key")

Is there a way to do a spark-submit from a databrics notebook?

答:
Finally I figured out how to run this:

You can do a run a Databricks jar from an ADF, and attach it to an existing cluster, which will have the adls key configured in the cluster.

It is not possible to do a spark-submit from a notebook. But you can create a spark job in jobs, or you can use the Databricks Run Sumbit api, to do a spark-submit.


问:
How to traverse a 2D array using recursion
I'm looking for someone to help me to traverse and display the 2d array or matrix using recursion.

```<code>void display(int** matrix1,int row, int column)
</code>```

This is what I am doing for the 1D array:

```<code>void print_array(int arr[], int size, int i)
{

    if (i == size) {
        cout << endl;
        return;
    }
    cout << arr[i] << " ";
    print_array(arr, size, i+1);
}
</code>```

I know how to traverse 1D array but unable to do this.
I want to display each element in the matrix using recursion.

答:
I am sure that you need to write a C program or a C++ program but using functionality of C due to your declaration of "2D array" like int **.:)

The function can be easy implemented if to use one more auxiliary recursive function.

Here is a demonstrative program

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

void display_row( int *a, size_t column )
{
    column == 0 ? ( void )putchar( '\n' )
                : ( void )( printf( "%2d ", *a ), display_row ( ++a, --column ) );
}

void display( int **a, size_t row, size_t column )
{
    if ( row != 0 )
    {
        display_row( *a, column );
        display( ++a, --row, column );
    }
}

int main(void)
{
    enum { M = 3, N = 4 };

    int a1[N] = {  1,  2,  3,  4 };
    int a2[N] = {  5,  6,  7,  8 };
    int a3[N] = {  9, 10, 11, 12 };

    int *a[M] = { a1, a2, a3 };

    display( a, M, N );

    return 0;
}
</code>```

The program output is

```<code> 1  2  3  4
 5  6  7  8
 9 10 11 12
</code>```

If not to use an auxiliary function then another approach is to use a static variable inside the recursive function.

Here is a demonstrative program that uses a recursive function with a static variable.

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

void display( int** a, size_t row, size_t column )
{
    static size_t pos = 0;

    if ( row != 0 && column == 0 )
    {
        putchar( '\n' );
        size_t tmp = column;
        column = pos;
        pos = tmp;
        --row;
        ++a;
    }

    if ( row )
    {
        printf( "%2d ", a[0][pos++] );
        display( a, row, --column );
    }
}

int main(void)
{
    enum { M = 3, N = 4 };

    int a1[N] = {  1,  2,  3,  4 };
    int a2[N] = {  5,  6,  7,  8 };
    int a3[N] = {  9, 10, 11, 12 };

    int *a[M] = { a1, a2, a3 };

    display( a, M, N );

    return 0;
}
</code>```

Its output is the same as shown above.

If you need a C++ program then just include headers

```<code>#include <iostream>
#include <iomanip>
</code>```

and instead of for example this call of printf

```<code>printf( "%2d ", a[0][pos++] );
</code>```

use

```<code>std::cout << std::setw( 2 ) << a[0][pos++];
</code>```

Body:
I'm looking for someone to help me to traverse and display the 2d array or matrix using recursion.

void display(int** matrix1,int row, int column)

This is what I am doing for the 1D array:

void print_array(int arr[], int size, int i)
{

    if (i == size) {
        cout << endl;
        return;
    }
    cout << arr[i] << " ";
    print_array(arr, size, i+1);
}

I know how to traverse 1D array but unable to do this.
I want to display each element in the matrix using recursion.

Body:
I am sure that you need to write a C program or a C++ program but using functionality of C due to your declaration of "2D array" like int **.:)

The function can be easy implemented if to use one more auxiliary recursive function.

Here is a demonstrative program

#include <stdio.h>

void display_row( int *a, size_t column )
{
    column == 0 ? ( void )putchar( '\n' )
                : ( void )( printf( "%2d ", *a ), display_row ( ++a, --column ) );
}

void display( int **a, size_t row, size_t column )
{
    if ( row != 0 )
    {
        display_row( *a, column );
        display( ++a, --row, column );
    }
}

int main(void)
{
    enum { M = 3, N = 4 };

    int a1[N] = {  1,  2,  3,  4 };
    int a2[N] = {  5,  6,  7,  8 };
    int a3[N] = {  9, 10, 11, 12 };

    int *a[M] = { a1, a2, a3 };

    display( a, M, N );

    return 0;
}

The program output is

 1  2  3  4
 5  6  7  8
 9 10 11 12

If not to use an auxiliary function then another approach is to use a static variable inside the recursive function.

Here is a demonstrative program that uses a recursive function with a static variable.

#include <stdio.h>

void display( int** a, size_t row, size_t column )
{
    static size_t pos = 0;

    if ( row != 0 && column == 0 )
    {
        putchar( '\n' );
        size_t tmp = column;
        column = pos;
        pos = tmp;
        --row;
        ++a;
    }

    if ( row )
    {
        printf( "%2d ", a[0][pos++] );
        display( a, row, --column );
    }
}

int main(void)
{
    enum { M = 3, N = 4 };

    int a1[N] = {  1,  2,  3,  4 };
    int a2[N] = {  5,  6,  7,  8 };
    int a3[N] = {  9, 10, 11, 12 };

    int *a[M] = { a1, a2, a3 };

    display( a, M, N );

    return 0;
}

Its output is the same as shown above.

If you need a C++ program then just include headers

#include <iostream>
#include <iomanip>

and instead of for example this call of printf

printf( "%2d ", a[0][pos++] );

use

std::cout << std::setw( 2 ) << a[0][pos++];


问:
Getting DTMF signals when receiving a call on Android
Is there any way to receive and identify DTMF signals when you get a phonecall?
I found these two functions (extractNetworkPortion & extractPostDialPortion), but I can't seem to get DTMF signal send by phonecalls.

Also, what is the shortest delay you can have for sending DTMF signals when calling someone?

答: Unfortunately this is not possible in standard Android platform (as of the latest version,  3.1)</p>


问:
HTTP request header custom value not going to server C#
I am adding a custom header to my request. I can see it when I debug the code. But get an error that it's missing from the server.

```<code>HttpWebRequest request;
request = GenerateRequest("https://at.test.com/test/api/test/v1/TestApplications HTTP/1.1", content, "application/json", "POST");

request.Headers.Add("Custom-Signature", signature);
return GetResponseContent(request);
</code>```

That is how I'm adding my header.

答:
Long time ago since this question. I had the same problem using web api 2.0 and my solution was to use Request.Content.Headers instead of  Request.Headers

and then i declared an extestion as below

```<code>  /// <summary>
    /// Returns an individual HTTP Header value
    /// </summary>
    /// <param name="headers"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetHeader(this HttpContentHeaders headers, string key, string defaultValue)
    {
        IEnumerable<string> keys = null;
        if (!headers.TryGetValues(key, out keys))
            return defaultValue;

        return keys.First();
    }
</code>```

And then i invoked it by this way.

```<code>  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");
</code>```

I hope it might be helpful

Body:
I am adding a custom header to my request. I can see it when I debug the code. But get an error that it's missing from the server.

HttpWebRequest request;
request = GenerateRequest("https://at.test.com/test/api/test/v1/TestApplications HTTP/1.1", content, "application/json", "POST");

request.Headers.Add("Custom-Signature", signature);
return GetResponseContent(request);

That is how I'm adding my header.

Body:
Long time ago since this question. I had the same problem using web api 2.0 and my solution was to use Request.Content.Headers instead of  Request.Headers

and then i declared an extestion as below

  /// <summary>
    /// Returns an individual HTTP Header value
    /// </summary>
    /// <param name="headers"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetHeader(this HttpContentHeaders headers, string key, string defaultValue)
    {
        IEnumerable<string> keys = null;
        if (!headers.TryGetValues(key, out keys))
            return defaultValue;

        return keys.First();
    }

And then i invoked it by this way.

  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");

I hope it might be helpful


问:
Query for similar phrases
Is there any way to match 'United States of America' with 'United States' in SQL?

I have the country with the name 'United States' stored in the database.
The query below should retrieve the item from the database with the name 'United States'.

```<code>SELECT * FROM `countries` WHERE `name` LIKE '%United States of America%'
</code>```

Thank you!

答:
Is this what you want?</p>

```<code>where 'United States of America' like concat('%', name, '%')
</code>```

Title: Query for similar phrases

Body:
Is there any way to match 'United States of America' with 'United States' in SQL?

I have the country with the name 'United States' stored in the database.
The query below should retrieve the item from the database with the name 'United States'.

SELECT * FROM `countries` WHERE `name` LIKE '%United States of America%'

Thank you!

Body:
Is this what you want?

where 'United States of America' like concat('%', name, '%')


问:
My code is returning "Command '['python3']' timed out after 2 seconds"
Please help me with the following:

given a list of sublists: [['a', 3], ['b', 5], ['c', 5], ['d', 4]]

goal is to return the letter with the highest value attached

if there is a tie, return the latter (in the above list, 'c' should be returned)

Currently I have:

```<code>nums = []
for i in list:
    nums.append(i[1])
while i in list:
    if max(nums) == i[1]:
        return i[0]
</code>```

Can someone tell me why I'm seeing "Command '['python3']' timed out after 2 seconds"? Thanks in advance!

答:
Because at the end of the for loop i is equal to ['d', 4]. Now you are doing while i in list which is True. And since i[1] == 4 != 5 == max(nums) you, my sir, have an infinite loop.

A different approach for this would be using the built-in max function with a costume key that will compare the second element. Then, to get the letter we will take the first element of the result. And since you want to return the last occurence, we will check the list reversed (max returns the first occurence):

from operator import itemgetter

a = [['a', 3], ['b', 5], ['c', 5], ['d', 4]]

print(max(reversed(a), key=itemgetter(1))[0])
```

<p>Gives: <code>c</code></p>

<hr>

<p>Going with your initial line of thought, first of all you might want to save that <code>max</code> value in a variable because each time you call <code>max</code> you loop the list again. Then, change the <code>while</code> to a <code>for</code> and loop the list from the end to return the last occurence. Oh, and don't name your lists <code>list</code>!</p>

<pre class="lang-py prettyprint-override"><code>def find_max_letter(a):
    nums = []
    for i in a:
        nums.append(i[1])
    # you can also create this with list-comprehension: nums = [i[1] for i in list]
    max_num = max(nums)
    for i in a[::-1]:
        if max_num == i[1]:
            return i[0]
</code>```

Body:
Please help me with the following:

given a list of sublists: [['a', 3], ['b', 5], ['c', 5], ['d', 4]]

goal is to return the letter with the highest value attached

if there is a tie, return the latter (in the above list, 'c' should be returned)

Currently I have:

nums = []
for i in list:
    nums.append(i[1])
while i in list:
    if max(nums) == i[1]:
        return i[0]

Can someone tell me why I'm seeing "Command '['python3']' timed out after 2 seconds"? Thanks in advance!

Body:
Because at the end of the for loop i is equal to ['d', 4]. Now you are doing while i in list which is True. And since i[1] == 4 != 5 == max(nums) you, my sir, have an infinite loop.

A different approach for this would be using the built-in max function with a costume key that will compare the second element. Then, to get the letter we will take the first element of the result. And since you want to return the last occurence, we will check the list reversed (max returns the first occurence):

from operator import itemgetter

a = [['a', 3], ['b', 5], ['c', 5], ['d', 4]]

print(max(reversed(a), key=itemgetter(1))[0])

Gives: c

Going with your initial line of thought, first of all you might want to save that max value in a variable because each time you call max you loop the list again. Then, change the while to a for and loop the list from the end to return the last occurence. Oh, and don't name your lists list!

def find_max_letter(a):
    nums = []
    for i in a:
        nums.append(i[1])
    # you can also create this with list-comprehension: nums = [i[1] for i in list]
    max_num = max(nums)
    for i in a[::-1]:
        if max_num == i[1]:
            return i[0]


问:
Embedded MongoDB with Spring not working
I am trying to create a Spring application with WebFlux and an embedded MongoDB. However, even if my tests runs perfectly, I can't start my application because it seems that embedded mongodb has not started.

The exception that I get is the following:

```<code>com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.3.jar:na]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_144]
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_144]
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_144]
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_144]
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_144]
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_144]
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_144]
    at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_144]
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongodb-driver-core-3.6.3.jar:na]
    ... 3 common frames omitted

2018-03-25 17:47:15.372  INFO 14188 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.netty.NettyStream$2.operationComplete(NettyStream.java:158) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.netty.NettyStream$2.operationComplete(NettyStream.java:145) ~[mongodb-driver-core-3.6.3.jar:na]
    at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:511) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:504) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:483) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:424) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:121) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.fulfillConnectPromise(AbstractNioChannel.java:327) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:343) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:633) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
 Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:27017
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[na:1.8.0_144]
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717) ~[na:1.8.0_144]
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:325) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    ... 7 common frames omitted
Caused by: java.net.ConnectException: Connection refused: no further information
    ... 11 common frames omitted
</code>```

My pom.xml is the following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.lorescianatico</groupId>
<artifactId>driftcoin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>driftcoin</name>
<description>Driftcoin project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>24.0-jre</version>
    </dependency>
</dependencies>

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

</project>
</code>```

My application properties is just a blank file. My repository class is the following:

```<code>package com.lorescianatico.driftcoin.repository;

import com.lorescianatico.driftcoin.model.BlockChain;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;

public interface BlockChainRepository extends ReactiveMongoRepository<BlockChain, String> {
}
</code>```

As you can see, I am using reactive repository for mongodb. I already tried to activate via annotations reactive repositories but it didn't change the exception. Am I missing something, like a configuration or similar?

Thanks in advance.

答:
Posting my solution, as it may help someone - I've added version tode.flapdoodle.embed.mongo dependency and it did a trick:

Use this:

```<code>        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <version>2.2.0</version>
            <scope>test</scope>
        </dependency>
</code>```

instead of this:

```<code>        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <scope>test</scope>
        </dependency>
</code>```

Maven repository link: https://mvnrepository.com/artifact/de.flapdoodle.embed/de.flapdoodle.embed.mongo

Body:
I am trying to create a Spring application with WebFlux and an embedded MongoDB. However, even if my tests runs perfectly, I can't start my application because it seems that embedded mongodb has not started.

The exception that I get is the following:

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.3.jar:na]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_144]
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_144]
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_144]
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_144]
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_144]
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_144]
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_144]
    at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_144]
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongodb-driver-core-3.6.3.jar:na]
    ... 3 common frames omitted

2018-03-25 17:47:15.372  INFO 14188 --- [localhost:27017] org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017

com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.netty.NettyStream$2.operationComplete(NettyStream.java:158) ~[mongodb-driver-core-3.6.3.jar:na]
    at com.mongodb.connection.netty.NettyStream$2.operationComplete(NettyStream.java:145) ~[mongodb-driver-core-3.6.3.jar:na]
    at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:511) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:504) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:483) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:424) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:121) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.fulfillConnectPromise(AbstractNioChannel.java:327) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:343) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:633) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
 Caused by: io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:27017
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[na:1.8.0_144]
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717) ~[na:1.8.0_144]
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:325) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
    ... 7 common frames omitted
Caused by: java.net.ConnectException: Connection refused: no further information
    ... 11 common frames omitted

My pom.xml is the following:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.lorescianatico</groupId>
<artifactId>driftcoin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>driftcoin</name>
<description>Driftcoin project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.projectreactor</groupId>
        <artifactId>reactor-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>24.0-jre</version>
    </dependency>
</dependencies>

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

</project>

My application properties is just a blank file. My repository class is the following:

package com.lorescianatico.driftcoin.repository;

import com.lorescianatico.driftcoin.model.BlockChain;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;

public interface BlockChainRepository extends ReactiveMongoRepository<BlockChain, String> {
}

As you can see, I am using reactive repository for mongodb. I already tried to activate via annotations reactive repositories but it didn't change the exception. Am I missing something, like a configuration or similar?

Thanks in advance.

Body:
Posting my solution, as it may help someone - I've added version tode.flapdoodle.embed.mongo dependency and it did a trick:

Use this:

        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <version>2.2.0</version>
            <scope>test</scope>
        </dependency>

instead of this:

        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <scope>test</scope>
        </dependency>

Maven repository link: https://mvnrepository.com/artifact/de.flapdoodle.embed/de.flapdoodle.embed.mongo


问:
Python: Mock side_effect on object attribute
Is it possible to have a side_effect on a property? If I look at the Mock documentation it seems it's only possible on object methods.

I am trying to test the following:

```<code>def get_object(self):
    try:
        return self.request.user.shop
    except Shop.DoesNotExist:
        return None
</code>```

I want Shop to raise a DoesNotExist exception.

Guess maybe I wasn't clear enough but I am talking about the voidspace mock library.

http://www.voidspace.org.uk/python/mock/index.html

答:
As an aside, if you're trying to test for AttributeError as an side_effect you can use spec parameter and set it to empty list (i.e. []). Say you're trying to create a Mock object that throws an AttributeError when accessing attribute foo:

```<code>from unittest.mock import Mock
m = Mock(spec = [])
m.foo

# AttributeError: Mock object has no attribute 'foo'
</code>```

See Documentation:

spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an AttributeError.

Body:
Is it possible to have a side_effect on a property? If I look at the Mock documentation it seems it's only possible on object methods.

I am trying to test the following:

def get_object(self):
    try:
        return self.request.user.shop
    except Shop.DoesNotExist:
        return None

I want Shop to raise a DoesNotExist exception.

Guess maybe I wasn't clear enough but I am talking about the voidspace mock library.

http://www.voidspace.org.uk/python/mock/index.html

Body:
As an aside, if you're trying to test for AttributeError as an side_effect you can use spec parameter and set it to empty list (i.e. []). Say you're trying to create a Mock object that throws an AttributeError when accessing attribute foo:

from unittest.mock import Mock
m = Mock(spec = [])
m.foo

# AttributeError: Mock object has no attribute 'foo'

See Documentation:

spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an AttributeError.


问:
Memory managment. Dealloc. iOS
Is this correct?

```<code>- (void)dealloc {

    [super dealloc];

    [stageObjects release];
}
</code>```

Or should I call

```<code>[super dealloc]
</code>```

Always after all releases, I mean last line of this function?

答:
```<code>[super dealloc];
</code>```

should be the last line to call in dealloc method.

Title: Memory managment. Dealloc. iOS

Body:
Is this correct?

- (void)dealloc {

    [super dealloc];

    [stageObjects release];
}

Or should I call

[super dealloc]

Always after all releases, I mean last line of this function?

Body:
[super dealloc];

should be the last line to call in dealloc method.


问:
Styled Components not working after npm run build
I'm building a website using styled components. It works fine in my local environment but as soon as I run npm run build it no longer works on the hosted site. I have the latest version of styled components installed as a dependancy. The styled components names work but none of the styles are coming through.

This is how the Website looks in my local dev environment

This is how it looks after build

heres a link to the website after being posted
https://benmcloughlin.github.io/savvy-plan-lite/
here's a link to the github repository
https://github.com/BenMcLoughlin/savvy-plan-lite

答: I spent three hours rebuilding the app and deploying it after each change to determine where the issue was. It had to do with GlobayStyles, one of the styled-components features. If I was using global styles then nothing worked. If I removed global styles then it worked. I have no idea why but I just removed it and will no longer use it. Just wanted to answer my own question in case someone came across the same issue. </p>


问:
OOP inheritance, how to get variable of parent type in python?
i have this code so far:

```<code>class vehicle:
    def __init__(self, numWheels, listWeightOfItem):
        self.numWheels = numWheels
        self.listWeightOfItem = listWeightOfItem

class car(vehicle):
    def __init__(self, numWheels, listWeightOfItem, listWeightPeople):
        vehicle.__init__(self, numWheels, listOfWeightItem)
        self.listWeightPeople = listWeightPeople
</code>```

Car is going to inherit from vehicle.
Car is supposed to have a trailer of type vehicle and I do not know how to put this into code. I thought about creating a class variable but I do not think that it makes sense, and how do i make sure the trailer is of type vehicle and not car?

答:
You can just make another class of subclass vehicle. You didn't specify what you wanted trailed to have in it so I just left it empty for you to fill.</p>

```<code>class vehicle:
    def __init__(self, numWheels, listWeightOfItem):
        self.numWheels = numWheels
        self.listWeightOfItem = listWeightOfItem

class car(vehicle):
    def __init__(self, numWheels, listWeightOfItem, listWeightPeople):
        vehicle.__init__(self, numWheels, listOfWeightItem)
        self.listWeightPeople = listWeightPeople

class trailer(vehicle):
    def __init__(self):
        pass
</code>```

Body:
i have this code so far:

class vehicle:
    def __init__(self, numWheels, listWeightOfItem):
        self.numWheels = numWheels
        self.listWeightOfItem = listWeightOfItem

class car(vehicle):
    def __init__(self, numWheels, listWeightOfItem, listWeightPeople):
        vehicle.__init__(self, numWheels, listOfWeightItem)
        self.listWeightPeople = listWeightPeople

Car is going to inherit from vehicle.
Car is supposed to have a trailer of type vehicle and I do not know how to put this into code. I thought about creating a class variable but I do not think that it makes sense, and how do i make sure the trailer is of type vehicle and not car?

Body:
You can just make another class of subclass vehicle. You didn't specify what you wanted trailed to have in it so I just left it empty for you to fill.

class vehicle:
    def __init__(self, numWheels, listWeightOfItem):
        self.numWheels = numWheels
        self.listWeightOfItem = listWeightOfItem

class car(vehicle):
    def __init__(self, numWheels, listWeightOfItem, listWeightPeople):
        vehicle.__init__(self, numWheels, listOfWeightItem)
        self.listWeightPeople = listWeightPeople

class trailer(vehicle):
    def __init__(self):
        pass


答:
Using Set makes it easy to remove duplicates for as many keys as you like. I tried to be as verbose as possible so that each step was clear.

var objects = [{ "Name": "blah", "Date": "1992-02-18T00:00:00.000Z", "Language": "English", }, { "Name": "blah", "Date": "1998-02-18T00:00:00.000Z", "Language": "French", }, { "Name": "blah", "Date": "1999-02-18T00:00:00.000Z", "Language": "English" }];

function uniqueKeyVals(objects, key) {
  const objVals = objects.map(object => object[key]); // ex. ["English", "French", "English"]
  return objects.slice(0, new Set(objVals).size);     // ex. { "English", "French" }.size = 2
}

function removeKeyDuplicates(objects, keys) {
  keys.forEach(key => objects = uniqueKeyVals(objects, key));
  return objects;
}

// can also use uniqueKeyVals(key) directly for just one key
console.log("Unique 'Language': \n", removeKeyDuplicates(objects, ["Language"]));
console.log("Unique ['Language', 'Name']: \n", removeKeyDuplicates(objects, ["Language", "Name"]));```

Title: Filter out objects in array if one value is the same

Body:
I am fetching data from an api that, sometimes, gives me multiple objects with the same values, or very similar values, which I want to remove.

For example, I might get back:

  [
   {
    "Name": "blah",
    "Date": "1992-02-18T00:00:00.000Z",
    "Language": "English",
  },
   {
    "Name": "blahzay",
    "Date": "1998-02-18T00:00:00.000Z",
    "Language": "French",
  },       {
    "Name": "blah",                     // same name, no problem
    "Date": "1999-02-18T00:00:00.000Z", // different date
    "Language": "English",             // but same language
  },
 ]

So I want to check that no two objects have a key with the same "Language" value (in this case, "English").

I would like to get the general process of filtering out the entire object if it's "Language" value is duplicated, with the extra issue of not having the same number of objects returned each time. So, allowing for dynamic number of objects in the array.

There is an example here:
Unexpeected result when filtering one object array against two other object arrays

but it's assuming that you have a set number of objects in the array and you are only comparing the contents of those same objects each time.

I would be looking for a way to compare

  arrayName[eachObject].Language === "English"

and keep one of the objects but any others (an unknown number of objects) should be filtered out, most probably using .filter() method along with .map().


问:
Django -File field not showing the selected file name
When I fill out the form and select an image to use, it  all works fine and it gets uploaded and saves to my model as expected but for some reason the field wont show the name of the file I am trying to use

File upload field

This is my forms.py, and I am using crispy forms to render my form to the template. {{forms|crispy}}
I am wondering is there anyway I can make it so it does show the name of the file I have chosen

```<code>class TeamCreateForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ['name','image','looking_for_members','interests' ]
</code>```

You can see in the photo that it doesn't change but it does add the image as expected, I am using crispy forms to style the form.

答:
The file field is one of the more complex items in the bootstrap framework. It requires extra js to enable the file name functionality you describe. See the file field docs. https://getbootstrap.com/docs/4.0/components/forms/

Which version of crispy forms are you using. This additional JS was added in v.1.8.1 to the template. see the pr here.

https://github.com/django-crispy-forms/django-crispy-forms/pull/920

Body:
When I fill out the form and select an image to use, it  all works fine and it gets uploaded and saves to my model as expected but for some reason the field wont show the name of the file I am trying to use

File upload field

This is my forms.py, and I am using crispy forms to render my form to the template. {{forms|crispy}}
I am wondering is there anyway I can make it so it does show the name of the file I have chosen

class TeamCreateForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ['name','image','looking_for_members','interests' ]

You can see in the photo that it doesn't change but it does add the image as expected, I am using crispy forms to style the form.


问:
getting average of some digits from a csv file as input and Write the averages in an output csv file in python 3
I am learning python3 :), and I am trying to read a CSV file with different rows
and take the average of the scores for each person(in each row)
and write it in a CSV file as an output in python 3.
The input file is like below:

```<code>David,5,2,3,1,6
Adele,3,4,1,5,2,4,2,1
...
</code>```

The output file should seem like below:

```<code>David,4.75
Adele,2.75
...
</code>```

It seems that I am reading the file correctly, as I print
the average for each name in the terminal, but in CSV
output file it prints only the average of the last name
of the input file, while I want to print all names and
corresponding averages in CSV output file.
Anybody can help me with it?

```<code>import csv
from statistics import mean

these_grades = []
name_list = []
reader = csv.reader(open('input.csv', newline=''))
for row in reader:
    name = row[0]
    name_list.append(name)

    with open('result.csv', 'w', newline='\n') as f:
        writer = csv.writer(f,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_MINIMAL)

        for grade in row[1:]:
            these_grades.append(int(grade))
            for item in name_list:
                writer.writerow([''.join(item), mean(these_grades)])
    print('%s,%f' % (name , mean(these_grades)))
</code>```

答:
There are several issues in your code:

You're not using a context manager (with) when you read the input file. There's no reason to use it when writing but not when reading - you consequently don't close the "input.csv" file

You're using a list to store data from rows. This doesn't easily distinguish between the person's name and the scores associated with the person. It would be better to use a dictionary in which the key is the person's name, and the values stored against that key are the individual scores

You repeatedly open the file within a for loop in 'w' mode. Every time you open a file in write mode, it just wipes all the previous contents. You actually do write each row to the file, but you just wipe it again when you open the file on the next iteration.

You can use:

```<code>import csv
import statistics

# use a context manager to read the data in too, not just for writing
with open('input.csv') as infile:
    reader = csv.reader(infile)
    data = list(reader)

# Create a dictionary to store the scores against the name
scores = {}

for row in data:
    scores[row[0]] = row[1:] # First item in the row is the key (name) and the rest is values

with open('output.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

    # Now we need to iterate the dictionary and average the score on each iteration
    for name, scores in scores.items():
        ave_score = statistics.mean([int(item) for item in scores])
        writer.writerow([name, ave_score])
</code>```

This can be further consolidated, but it's less easy to see what's happening:

```<code>with open('input.csv') as infile, open('output.csv', 'w', newline='') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        name = row[0]
        values = row[1:]
        ave_score = statistics.mean(map(int, values))
        writer.writerow([name, ave_score])
</code>```

Body:
I am learning python3 :), and I am trying to read a CSV file with different rows
and take the average of the scores for each person(in each row)
and write it in a CSV file as an output in python 3.
The input file is like below:

David,5,2,3,1,6
Adele,3,4,1,5,2,4,2,1
...

The output file should seem like below:

David,4.75
Adele,2.75
...

It seems that I am reading the file correctly, as I print
the average for each name in the terminal, but in CSV
output file it prints only the average of the last name
of the input file, while I want to print all names and
corresponding averages in CSV output file.
Anybody can help me with it?

import csv
from statistics import mean

these_grades = []
name_list = []
reader = csv.reader(open('input.csv', newline=''))
for row in reader:
    name = row[0]
    name_list.append(name)

    with open('result.csv', 'w', newline='\n') as f:
        writer = csv.writer(f,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_MINIMAL)

        for grade in row[1:]:
            these_grades.append(int(grade))
            for item in name_list:
                writer.writerow([''.join(item), mean(these_grades)])
    print('%s,%f' % (name , mean(these_grades)))

Body:
There are several issues in your code:

You're not using a context manager (with) when you read the input file. There's no reason to use it when writing but not when reading - you consequently don't close the "input.csv" file

You're using a list to store data from rows. This doesn't easily distinguish between the person's name and the scores associated with the person. It would be better to use a dictionary in which the key is the person's name, and the values stored against that key are the individual scores

You repeatedly open the file within a for loop in 'w' mode. Every time you open a file in write mode, it just wipes all the previous contents. You actually do write each row to the file, but you just wipe it again when you open the file on the next iteration.

You can use:

import csv
import statistics

# use a context manager to read the data in too, not just for writing
with open('input.csv') as infile:
    reader = csv.reader(infile)
    data = list(reader)

# Create a dictionary to store the scores against the name
scores = {}

for row in data:
    scores[row[0]] = row[1:] # First item in the row is the key (name) and the rest is values

with open('output.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

    # Now we need to iterate the dictionary and average the score on each iteration
    for name, scores in scores.items():
        ave_score = statistics.mean([int(item) for item in scores])
        writer.writerow([name, ave_score])

This can be further consolidated, but it's less easy to see what's happening:

with open('input.csv') as infile, open('output.csv', 'w', newline='') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        name = row[0]
        values = row[1:]
        ave_score = statistics.mean(map(int, values))
        writer.writerow([name, ave_score])


问:
How to import Vanilla JS ES6 modules in TypeScript?
I'm trying to import this library: spotlight, which is plain JS.

In my project I created a fake d.ts:

```<code>declare module 'spotlight.js'
</code>```

as suggested by VSCode, then I tried every single import combination:

```<code>import * as spotlight from 'spotlight';
import spotlight from 'spotlight';
import { spotlight } from 'spotlight';
</code>```

but inside my code the spotlight expression is always an empty object.

What am I missing?

答:
As @Shinigami pointed out - there is an open issue. As I see it, right now, there is no elegant way to import the Spotlight object without modifications to the library (it also seems that npm run build doesn't help much). But, judging by the code, the Spotlight is accessible through window. So it should be possible to use it like so

import "spotlight"
window.Spotlight.show(...)
```

Body:
I'm trying to import this library: spotlight, which is plain JS.

In my project I created a fake d.ts:

declare module 'spotlight.js'

as suggested by VSCode, then I tried every single import combination:

import * as spotlight from 'spotlight';
import spotlight from 'spotlight';
import { spotlight } from 'spotlight';

but inside my code the spotlight expression is always an empty object.

What am I missing?


问:
Subtracting value from value above under certain conditions - no loop
I am trying to get a balance value from a df that looks like this

```<code>df1

Name   Year    Ch1    Origin
A      1995    x1      a
A      1996    x2      b
A      1997    x3      a
A      2000    x4      a
B      1997    y1      c
B      1998    y2      c
</code>```

while Ch1 is numerical. and I want to add an extra col to have this value:

```<code>Name   Year   Ch1    Bil
A      1995    x1
A      1996    x2    %
A      1997    x3    %
A      2000    x4    %
B      1997    y1
B      1998    y2    %
</code>```

I want "Bil" to be
- X2/X1 (value from previous year divided by recent year) IF X2>X1
- -X1/X2 IF X1

```<code>for (i in nrow(df1))
  if (df[i,1]==df[i-1,1]) {
      if (df[i,3]>df[i-1,3] {
          df$Bil<-(df[i,3]/df[i-1,3])
      } else df$Bil<-(-df[i-1,3]/df[i,3])
  }
</code>```

Is there a more elegant or quicker way to calculate this? This way I really need to make sure that the dataset is in the right order (going from older to recent years). Let's say also dependent on an extra detail such as origin so that the calculation only happens if name and origin are the same?

答:
Here is a base R code which applied ave + pmax. Hope the code below can reach your objective

```<code>df <- within(df,Bill <- ave(Ch1,Name,FUN = function(v) c(NA,sign(v[-1]-v[-length(v)])*pmax(v[-1]/v[-length(v)],v[-length(v)]/v[-1]))))
</code>```

such that

```<code>> df
  Name Year Ch1 Origin      Bill
1    A 1995  11      a        NA
2    A 1996  12      b  1.090909
3    A 1997   3      a -4.000000
4    A 2000  14      a  4.666667
5    B 1997  21      c        NA
6    B 1998  12      c -1.750000
</code>```

DATA

```<code>df <- structure(list(Name = c("A", "A", "A", "A", "B", "B"), Year = c(1995L,
1996L, 1997L, 2000L, 1997L, 1998L), Ch1 = c(11L, 12L, 3L, 14L,
21L, 12L), Origin = c("a", "b", "a", "a", "c", "c")), class = "data.frame", row.names = c(NA,
-6L))
</code>```

Body:
I am trying to get a balance value from a df that looks like this

df1

Name   Year    Ch1    Origin
A      1995    x1      a
A      1996    x2      b
A      1997    x3      a
A      2000    x4      a
B      1997    y1      c
B      1998    y2      c

while Ch1 is numerical. and I want to add an extra col to have this value:

Name   Year   Ch1    Bil
A      1995    x1
A      1996    x2    %
A      1997    x3    %
A      2000    x4    %
B      1997    y1
B      1998    y2    %

I want "Bil" to be
- X2/X1 (value from previous year divided by recent year) IF X2>X1
- -X1/X2 IF X1

for (i in nrow(df1))
  if (df[i,1]==df[i-1,1]) {
      if (df[i,3]>df[i-1,3] {
          df$Bil<-(df[i,3]/df[i-1,3])
      } else df$Bil<-(-df[i-1,3]/df[i,3])
  }

Is there a more elegant or quicker way to calculate this? This way I really need to make sure that the dataset is in the right order (going from older to recent years). Let's say also dependent on an extra detail such as origin so that the calculation only happens if name and origin are the same?

Body:
Here is a base R code which applied ave + pmax. Hope the code below can reach your objective

df <- within(df,Bill <- ave(Ch1,Name,FUN = function(v) c(NA,sign(v[-1]-v[-length(v)])*pmax(v[-1]/v[-length(v)],v[-length(v)]/v[-1]))))

such that

> df
  Name Year Ch1 Origin      Bill
1    A 1995  11      a        NA
2    A 1996  12      b  1.090909
3    A 1997   3      a -4.000000
4    A 2000  14      a  4.666667
5    B 1997  21      c        NA
6    B 1998  12      c -1.750000

DATA

df <- structure(list(Name = c("A", "A", "A", "A", "B", "B"), Year = c(1995L,
1996L, 1997L, 2000L, 1997L, 1998L), Ch1 = c(11L, 12L, 3L, 14L,
21L, 12L), Origin = c("a", "b", "a", "a", "c", "c")), class = "data.frame", row.names = c(NA,
-6L))


问:
Having trouble with undefined output from this code below
```<code>var output = [];
var count = 1;

function fizzbuzz() {
  while (count <= 100) {
    if (count % 3 === 0 && count % 5 === 0) {
      output.push("FizzBuzz");
    } else if (count % 5 === 0) {
      output.push("Buzz");
    } else if (count % 3 === 0) {
      output.push("Fizz");
    } else {
      output.push(count);
    }
    count++;
  }

  console.log(output);
}
</code>```

the output from the google chrome and Mozilla Firefox inspector page, says output is  not defined.

Seriously, don't know why.

答:
The undefined you're seeing isn't what's being logged in your console.log statement; your function hasn't been run yet, it's only being defined. The undefined is the value of the expression you're evaluating in the console, which isn't really relevant.

Simply add a fizzbuzz() statement to run your function and you'll see the expected output logged.

Body:
var output = [];
var count = 1;

function fizzbuzz() {
  while (count <= 100) {
    if (count % 3 === 0 && count % 5 === 0) {
      output.push("FizzBuzz");
    } else if (count % 5 === 0) {
      output.push("Buzz");
    } else if (count % 3 === 0) {
      output.push("Fizz");
    } else {
      output.push(count);
    }
    count++;
  }

  console.log(output);
}

the output from the google chrome and Mozilla Firefox inspector page, says output is  not defined.

Seriously, don't know why.


问:
Bootstrap 4 - hiding navbar collapse works, but links aren't working
I have a navbar that collapses to a mobile menu when the screen width decreases to a point, and the default behavior doesn't hide the menu after selecting a nav link, which ends up in content on the page being hidden.

I found this answer for someone else who was trying to get it to automatically hide, so I added data-toggle="collapse" data-target=".nav-collapse.show" to my  tags which causes the menu to close on click, however now it does not follow the links and update the url anymore.

Even this link for Bootstrap 4 from the answer linked above doesn't work properly, and will automatically close the menu, but the href="#whatever" is completely ignored.

In the codeply example above, when the  tag looks like this:

```<code><a class="nav-link" href="#about-us" data-toggle="collapse" data-target=".navbar-collapse.show">About</a>
</code>```

it will hide the collapsed menu after, but the url http://www.codeply.com/api/run in the demo window will not change.

However when the  tag doesn't have data-toggle="collapse" data-target=".navbar-collapse.show" like this:

```<code><a class="nav-link" href="#about-us">About</a>
</code>```

the url in the demo window will be updated to http://www.codeply.com/api/run#about-us, but the menu will no longer hide after selection.

Other answers like this one that I have found for similar problems tell people to add Javascript instead of editing the html, but being new to Bootstrap, I have absolutely no clue where to put the Javascript.

The browser I am currently trying this on is Chromium on Linux.

How do I get the menu to hide on click, and have the links actually be followed?

Edit: Here is my full code as requested (I edited out my personal information):

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <!--<link rel="icon" href="../../favicon.ico">-->

    <title>Portfolio</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="style.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#menuNavbar" aria-controls="menuNavbar" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="#">My Portfolio</a>

        <div class="collapse navbar-collapse" id="menuNavbar">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#" data-toggle="collapse" data-target="#menuNavbar.show">Home<span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#about" data-toggle="collapse" data-target="#menuNavbar.show">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#skills" data-toggle="collapse" data-target="#menuNavbar.show">Skills/knowledge</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" id="portfolio-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Portfolio</a>
                    <div class="dropdown-menu" aria-labelledby="portfolio-dropdown">
                        <a class="dropdown-item" href="https://github.com/username/repo1">repo1</a>
                        <a class="dropdown-item" href="https://github.com/username/repo2">repo2</a>
                        <a class="dropdown-item" href="https://github.com/username/repo3">repo3</a>
                        <a class="dropdown-item" href="#portfolio" data-toggle="collapse" data-target="#menuNavbar.show">More</a>
                    </div>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#resume" data-toggle="collapse" data-target="#menuNavbar.show">Résumé</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#contact" data-toggle="collapse" data-target="#menuNavbar.show">Contact</a>
                </li>
            </ul>
        </div>
    </nav>

    <div class="container">

        <div class="introduction" id="home">
            <h1>My Portfolio</h1>
            <p class="lead">Placeholder text</p>
        </div>

        <div class="about-me" id="about">
            <h2>About Me</h2>
            <p class="lead">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vehicula viverra metus. Etiam in vestibulum ipsum, ac dignissim libero. Morbi vel tortor hendrerit, mattis nunc ut, ornare dolor. Ut porttitor, augue in pellentesque facilisis, massa mauris faucibus lorem, eget tincidunt nisi massa sit amet urna. Donec eu libero vel nisl tempor ultrices at at diam. Cras pellentesque non purus vel consectetur. Sed eget molestie leo. Ut scelerisque nibh non tortor congue, non suscipit augue congue. Nunc suscipit libero accumsan facilisis vulputate. Etiam ornare, felis sit amet feugiat rhoncus, est nulla pellentesque mauris, eu vulputate est lectus vel diam. Maecenas vel congue ipsum. Etiam scelerisque, dolor eu mattis aliquam, nibh lacus finibus lectus, quis tempus dui turpis nec purus. Curabitur vel tortor ipsum. Maecenas lacinia porttitor molestie. Ut pulvinar dolor at risus consectetur pulvinar. Fusce posuere mauris ut dui scelerisque vulputate.</p>
        </div>

        <div class="skills-knowledge" id="skills">
            <h2>Skills and Knowledge</h2>
            <p class="lead">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam quam, consectetur volutpat nibh at, sagittis mollis nulla. Nunc id porta ante. Donec auctor, lorem eu efficitur dignissim, elit nulla congue ante, congue facilisis augue erat id risus. Nulla facilisi. Ut vitae consequat erat. Morbi volutpat sem vitae ex mattis molestie tristique vitae magna. Phasellus egestas rhoncus justo quis tincidunt. Nunc sed enim congue, posuere lectus et, placerat tortor. Aliquam purus orci, pharetra a tortor vel, posuere vehicula ipsum.</p>
        </div>

        <div class="portfolio" id="portfolio">
            <h2>Portfolio</h2>
            <p class="lead">Some projects I have worked on can be found on my <a href="https://github.com/username">GitHub</a>.</p>
        </div>

        <div class="resume" id="resume">
            <h2>Résumé</h2>
            <p class="lead">A link to my résumé will be here in the future.</p>
        </div>

        <div class="contact-info" id="contact">
            <h2>Contact Info</h2>
            <p class="lead">My phone number and email will be here in the future.</p>
        </div>

    </div><!-- /.container -->

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="js/bootstrap.js"></script>
</body>
</html>
</code>```

答:
Create a own javascript file for your extention of bootstrap. Example init.js include it both after bootstrap.js and jquery and do some stuff init .. hope its help other</p>

```<code>$(document).on('click','.navbar-collapse.show',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('hide');
    }
});
</code>```

Body:
I have a navbar that collapses to a mobile menu when the screen width decreases to a point, and the default behavior doesn't hide the menu after selecting a nav link, which ends up in content on the page being hidden.

I found this answer for someone else who was trying to get it to automatically hide, so I added data-toggle="collapse" data-target=".nav-collapse.show" to my  tags which causes the menu to close on click, however now it does not follow the links and update the url anymore.

Even this link for Bootstrap 4 from the answer linked above doesn't work properly, and will automatically close the menu, but the href="#whatever" is completely ignored.

In the codeply example above, when the  tag looks like this:

About

it will hide the collapsed menu after, but the url http://www.codeply.com/api/run in the demo window will not change.

However when the  tag doesn't have data-toggle="collapse" data-target=".navbar-collapse.show" like this:

About

the url in the demo window will be updated to http://www.codeply.com/api/run#about-us, but the menu will no longer hide after selection.

Other answers like this one that I have found for similar problems tell people to add Javascript instead of editing the html, but being new to Bootstrap, I have absolutely no clue where to put the Javascript.

The browser I am currently trying this on is Chromium on Linux.

How do I get the menu to hide on click, and have the links actually be followed?

Edit: Here is my full code as requested (I edited out my personal information):

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Portfolio</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="style.css" rel="stylesheet">

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#menuNavbar" aria-controls="menuNavbar" aria-expanded="false" aria-label="Toggle navigation">

        </button>
        My Portfolio

                    Home(current)

                    About

                    Skills/knowledge

                    Portfolio

                        repo1
                        repo2
                        repo3
                        More

                    Résumé

                    Contact

My Portfolio

Placeholder text

About Me

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vehicula viverra metus. Etiam in vestibulum ipsum, ac dignissim libero. Morbi vel tortor hendrerit, mattis nunc ut, ornare dolor. Ut porttitor, augue in pellentesque facilisis, massa mauris faucibus lorem, eget tincidunt nisi massa sit amet urna. Donec eu libero vel nisl tempor ultrices at at diam. Cras pellentesque non purus vel consectetur. Sed eget molestie leo. Ut scelerisque nibh non tortor congue, non suscipit augue congue. Nunc suscipit libero accumsan facilisis vulputate. Etiam ornare, felis sit amet feugiat rhoncus, est nulla pellentesque mauris, eu vulputate est lectus vel diam. Maecenas vel congue ipsum. Etiam scelerisque, dolor eu mattis aliquam, nibh lacus finibus lectus, quis tempus dui turpis nec purus. Curabitur vel tortor ipsum. Maecenas lacinia porttitor molestie. Ut pulvinar dolor at risus consectetur pulvinar. Fusce posuere mauris ut dui scelerisque vulputate.

Skills and Knowledge

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam quam, consectetur volutpat nibh at, sagittis mollis nulla. Nunc id porta ante. Donec auctor, lorem eu efficitur dignissim, elit nulla congue ante, congue facilisis augue erat id risus. Nulla facilisi. Ut vitae consequat erat. Morbi volutpat sem vitae ex mattis molestie tristique vitae magna. Phasellus egestas rhoncus justo quis tincidunt. Nunc sed enim congue, posuere lectus et, placerat tortor. Aliquam purus orci, pharetra a tortor vel, posuere vehicula ipsum.

Portfolio

Some projects I have worked on can be found on my GitHub.

Résumé

A link to my résumé will be here in the future.

Contact Info

My phone number and email will be here in the future.

Body:
Create a own javascript file for your extention of bootstrap. Example init.js include it both after bootstrap.js and jquery and do some stuff init .. hope its help other

$(document).on('click','.navbar-collapse.show',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('hide');
    }
});


问:
How to break dynamic json data into two lines after first comma only?
How to display dynamic json data into two lines after first comma only? Example my data is " sam T. Sam, france, italy"  I want "sam T. Sam," in one line and "france, italy" in next line....comma should not be replaced....is there a way to achieve this in javascript or jquery?

Json data in anchor tag =  abc d. E. Dfg, gf, gg
I want to display as below

Line1= abc d. E. Dfg,
Line2= gf, gg

答:
using JQUERY :
for every Anchor element split by comma then add new line and keep comma

$('a').each(function(){
  el=$(this).html();
  $(this).html(el.substring(0,el.indexOf(','))+',
'+el.slice(el.indexOf(',')+1));
    });

or this if you want to split  on every comma

$('a').each(function(){
 $(this).html($(this).html().split(',').join(',
'));
});

https://jsfiddle.net/rkv88/hr64cget/

Body:
using JQUERY :
for every Anchor element split by comma then add new line and keep comma

$('a').each(function(){
  el=$(this).html();
  $(this).html(el.substring(0,el.indexOf(','))+',<BR>'+el.slice(el.indexOf(',')+1));
    });

or this if you want to split  on every comma

$('a').each(function(){
 $(this).html($(this).html().split(',').join(',<BR>'));
});

https://jsfiddle.net/rkv88/hr64cget/


问:
Java generic type issue
Consider the following simplified example:

```<code>package com.test;

class B<S> {
    B(Class<S> clazz) {}
}

class A<T> {
    class SubB extends B<SubB> {
        SubB() {
            super(SubB.class);
        }
    }
}
</code>```

Although IntelliJ is not showing any error (as it usually does when compile errors exist), the actual compilation when starting the program ends with error located in super(SubB.class);:

Error:(8, 23) java: incompatible types: java.lang.Class<com.test.A.SubB> cannot be converted to java.lang.Class<com.test.A<T>.SubB>

I am curious, why is this happening? And how could I solve it?

Compilation is done with AdoptOpenJDK 11.

答:
I found this very interesting.

The problem here is that when you declare this:

```<code>class A<T> {

    class SubB extends B<SubB> {
        SubB() {
            super...
        }
    }
}
</code>```

that B<SubB> is actually B<A<T>.SubB> (I was not even aware this is possible). This is easy to prove thx for javap (just decompile the class and see for yourself). Once you write that in the "long" form:

```<code>class A<T> {
    class SubB extends B<A<T>.SubB> {
        SubB() {
            super(....);
        }
    }
}
</code>```

it starts to make a lot more sense.

Ideally for this to work, you have to be able to write:

```<code>super(A<T>.SubB.class);
</code>```

but java does not allow this, .class can only be invoked on raw types.

The best way to do it is to be explicit here:

```<code>class A<T> {
    class SubB extends B<A.SubB> {
        SubB() {
            super(SubB.class);
        }
    }
}
</code>```

in saying: I am using the raw type of A: B

Title: Java generic type issue

Body:
Consider the following simplified example:

package com.test;

class B<S> {
    B(Class<S> clazz) {}
}

class A<T> {
    class SubB extends B<SubB> {
        SubB() {
            super(SubB.class);
        }
    }
}

Although IntelliJ is not showing any error (as it usually does when compile errors exist), the actual compilation when starting the program ends with error located in super(SubB.class);:

Error:(8, 23) java: incompatible types: java.lang.Class<com.test.A.SubB> cannot be converted to java.lang.Class<com.test.A<T>.SubB>

I am curious, why is this happening? And how could I solve it?

Compilation is done with AdoptOpenJDK 11.

Body:
I found this very interesting.

The problem here is that when you declare this:

class A<T> {

    class SubB extends B<SubB> {
        SubB() {
            super...
        }
    }
}

that B<SubB> is actually B<A<T>.SubB> (I was not even aware this is possible). This is easy to prove thx for javap (just decompile the class and see for yourself). Once you write that in the "long" form:

class A<T> {
    class SubB extends B<A<T>.SubB> {
        SubB() {
            super(....);
        }
    }
}

it starts to make a lot more sense.

Ideally for this to work, you have to be able to write:

super(A<T>.SubB.class);

but java does not allow this, .class can only be invoked on raw types.

The best way to do it is to be explicit here:

class A<T> {
    class SubB extends B<A.SubB> {
        SubB() {
            super(SubB.class);
        }
    }
}

in saying: I am using the raw type of A: B<A.SubB>


问:
How do I remove a folder stuck in my GitHub portal?
I have been having a problem with a folder that shows in my GitHub desktop portal, but not in my GitHub repo page. Whenever I need to push commit to that repo, I have to uncheck the phantom folder or my changes do not commit.

Notice that the folder "PProject-1" (misspelled with 2 p's) exists on the portal but not the web page. How do I get rid of it?

答: The first "P" in "PProject-1" is grayed out, indicating that it is not part of the file name. In your comment, you noted that your local (cloned) repo has a folder called "Project-1," that does not exist in your remote (GitHub website) repo. Move that folder out of the local repo, and it should disappear from the queue in your app also.</p>


问:
What is wrong with my setup.py to install all dependencies in python 3.8.1
I have the below setup.py script. When I execute the command setup.py install, I do not see the python packages installed in my system. In case of java, we use maven or gradle so that it can automatically download and install in the system. I want exact feature in setup.py. I see that colorama, configparser are not installed, I manually installed setuptools and cx-Freeze using pip command. Below is my setup.py script contents.

```<code>from setuptools import setup, find_packages, Command

setup(
    name="Runner",  # program name
    version="0.0.1",
    description='A utility to build an exe',
    author="Debadatta Mishra",
    author_email="deba.java@gmail.com",
    python_requires='>=3.6',
    install_requires=['configparser==4.0.2', 'colorama==0.4.3', 'setuptools==45.2.0', 'cx-Freeze==6.1']
)
</code>```

If I execute pip list, I do not see colorama, configparser etc. Please help me , I am new to python programming.

To run the setup script, I use the command python setup.py install in command prompt.

答:
As suggested by @Iguananaut, if you have a setup.py and if it has install_requires with the mentioned python packages. You can use the below command in windows to install the python packages.

```<code>pip install -e .
</code>```

As mentioned above .(dot) is required.

Body:
I have the below setup.py script. When I execute the command setup.py install, I do not see the python packages installed in my system. In case of java, we use maven or gradle so that it can automatically download and install in the system. I want exact feature in setup.py. I see that colorama, configparser are not installed, I manually installed setuptools and cx-Freeze using pip command. Below is my setup.py script contents.

from setuptools import setup, find_packages, Command

setup(
    name="Runner",  # program name
    version="0.0.1",
    description='A utility to build an exe',
    author="Debadatta Mishra",
    author_email="deba.java@gmail.com",
    python_requires='>=3.6',
    install_requires=['configparser==4.0.2', 'colorama==0.4.3', 'setuptools==45.2.0', 'cx-Freeze==6.1']
)

If I execute pip list, I do not see colorama, configparser etc. Please help me , I am new to python programming.

To run the setup script, I use the command python setup.py install in command prompt.

Body:
As suggested by @Iguananaut, if you have a setup.py and if it has install_requires with the mentioned python packages. You can use the below command in windows to install the python packages.

pip install -e .

As mentioned above .(dot) is required.


问:
How to clear memory to prevent "out of memory error" in VBA?
I am running VBA code on a large Excel spreadsheet. How do I clear the memory between procedures/calls to prevent an "out of memory" issue occurring?</p>

答: I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.</p>


问:
Providing multiple realms/origins to coTurn from webRTC client
As coTurn server provides the option to create multiple realms throught its database, and when turning the server on, a default realm can be provided in the configuration.

When configuring the webRTC client to access TURN, it only allows the URIs, username and credentials properties, but does not have any way to provide a realm or origin (as coturn supports origin).

The default realm is always considered.

If I try to utilize the realms concepts, providing different user credentials under different realms in the webRTC client config, the server accepts only turn requests with users under the default realm.

Questions

Is there a way to overcome this matter to provide realms/origin to the server?

If not, why have realms been added to the coturn if they cannot be used?

答:
tl;dr: the realm is pretty useless in WebRTC.

In theory TURN as a protocol includes a realm. However, see the detailed example in the RFC this typically isn't sent in the initial allocate request, only subsequent ones. In theory the client could store the realm and use it for subsequent requests.
In WebRTC, the peerconnections are pretty much independent. There is no way to configure the realm in the ICE server configuration
See also this response from working on that in chrome/webrtc.org