问:
Easy way to "nudge" a server to keep a connection open?
Okay, so a little context:
I have an app running on an embedded system that sends a few different requests over HTTP (using libcurl in C++) at the following intervals:
5 minutes
15 minutes
1 hour
24 hours

My goal: Reduce data consumption (runs over cellular)

We have both client and server side TLS authentication, so the handshake is costly. The idea is that we use persistent connections (at least for the shorter interval files) to avoid doing the handshake every time.

Unfortunately, after much tinkering I've figured out that the server is closing the connection before the intervals pass. Maybe this is something we can extend? I'll have to talk to the server side guys.

I was under the impression that was the reason the "TCP keep-alive" packets existed, but supposedly those "check the connection" not "keep it open" like the name suggests.

My idea is this:

Have my app send a packet (as small as possible) every 2 minutes or so (however long the timeout is) to "nudge" the connection into staying open.

My questions are:

Does that make any sense?

I don't suppose there is an easy way to do this in libcurl is there?

If so, how small could we get the request?

Is there an even easier way to do it? My only issue here is that all the connection stuff "lives" in libcurl.

Thanks!

答:
It would be easier to give a more precise answer if you gave a little more detail on your application architecture. For example, is it a RESTful API? Is the use of HTTP absolutely mandatory? If so, what HTTP server are you using (nginx, apache, ...)? Could you consider websockets as an alternative to plain HTTP?

If you are at liberty to use something other than regular HTTP or HTTPs - and to use something other than libcurl on the client side - you would have more options.

If, on the other hand, if you are constrained to both

use HTTP (rather than a raw TCP connection or websockets), and

use libcurl

then I think your task is a good bit more difficult - but maybe still possible.

One of your first challenges is that the typical timeouts for a HTTP connection are quite low (as low as a few seconds for Apache 2). If you can configure the server you can increase this.

I was under the impression that was the reason the "TCP keep-alive" packets existed, but supposedly those "check the connection" not "keep it open" like the name suggests.

Your terminology is ambiguous here. Are you referring to TCP keep-alive packets or persistent HTTP connections? These don't necessarily have anything to do with each other. The former is an optional mechanism in TCP (which is disabled by default). The latter is an application-layer concept which is specific to HTTP - and may be used regardless of whether keep-alive packets are being used at the transport layer.

My only issue here is that all the connection stuff "lives" in libcurl.

The problem with using libcurl is that it first and foremost a transfer library. I don't think it is tailored for long-running, persistent TCP connections. Nonetheless, according to Daniel Stenberg (the author of libcurl), the library will automatically try to reuse existing connections where possible - as long as you re-use the same easy handle.

If so, how small could we get the request?

Assuming you are using a 'ping' endpoint on your server - which accepts no data and returns a 204 (success but no content) response, then the overhead - in the application layer - would be the size of the HTTP request headers + the size of the HTTP response headers. Maybe you could get it down to 200-300 bytes, or thereabouts.

Alternatives to (plain) HTTP

If you are using a RESTful API, this paradigm sort of goes against the idea of a persistent TCP connection - although I can not think of any reason why it would not work.

You might consider websockets as an alternative, but - again - libcurl is not ideal for this. Although I know very little about websockets, I believe they would offer some advantages.

Compared to plain HTTP, websockets offer:

significantly less overhead than HTTP per message;

the connection is automatically persistent: there is no need to send extra 'keep alive' messages to keep it open;

Compared to a raw TCP connection, the benefits of websockets are that:

you don't have to open a custom port on your server;

it automatically handles the TLS/SSL stuff for you.

(Someone who knows more about websockets is welcome to correct me on some of the above points - particularly regarding TLS/SSL and keep alive messages.)

Alternatives to libcurl

An alternative to libcurl which might be useful here is the Mongoose networking library. It would provide you with a few different alternatives:

use a plain TCP connection (and a custom application layer protocol),

use a TCP connection and handle the HTTP requests yourself manually,

use websockets - which it has very good support for (both as server and client).

Mongoose allows you to enable SSL for all of these options also.


来源: stackexchange

问:
Laravel migration can't create foreign key
I'm trying to create a foreign key, artisan does not show me any errors, just does not create my foreign key, it's probably my code:

1° table:

```<code>Schema::create('cooperados', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->timestamps();
        $table->string('nameCoop', 255);
        $table->integer('numCoop');
        $table->string('cpfCoop', 11);
        $table->date('dtCad');
        $table->date('dtDem')->nullable();
        $table->text('description')->nullable();
        $table->decimal('subscritas', 6, 2);
        $table->decimal('integralizadas', 6,2)->nullable();
        $table->decimal('aintegralizar', 6,2)->nullable();
        $table->enum('status', ['ativo','inativo'])->default('ativo');
    });
</code>```

the foreign key table

```<code>public function up()
    {
        Schema::create('mov', function (Blueprint $table) {
            $table->bigIncrements('idMov');
            $table->timestamps();
            $table->integer('id_coop')->unsigned;
            $table->foreign('id_coop')->references('id')->on('cooperados');
            $table->decimal('valor', 6, 2);
        });
    }
</code>```

答:
Change your code from

```<code>$table->integer('id_coop')->unsigned;
$table->foreign('id_coop')->references('id')->on('cooperados');
</code>```

To:

```<code>$table->unsignedBigInteger('id_coop')->index();
$table->foreign('id_coop')->references('id')->on('cooperados')->onDelete('cascade');
</code>```

Or you can also use below code

```<code> $table->integer('id_coop')->unsigned()->index();
 $table->foreign('id_coop')->references('id')->on('cooperados')->onDelete('cascade');
</code>```

Or also you can use below

```<code>$table->bigInteger('id_coop')->unsigned()->index();
$table->foreign('id_coop')->references('id')->on('cooperados')->onDelete('cascade');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a foreign key, artisan does not show me any errors, just does not create my foreign key, it's probably my code:

1° table:

Schema::create('cooperados', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->timestamps();
        $table->string('nameCoop', 255);
        $table->integer('numCoop');
        $table->string('cpfCoop', 11);
        $table->date('dtCad');
        $table->date('dtDem')->nullable();
        $table->text('description')->nullable();
        $table->decimal('subscritas', 6, 2);
        $table->decimal('integralizadas', 6,2)->nullable();
        $table->decimal('aintegralizar', 6,2)->nullable();
        $table->enum('status', ['ativo','inativo'])->default('ativo');
    });

the foreign key table

public function up()
    {
        Schema::create('mov', function (Blueprint $table) {
            $table->bigIncrements('idMov');
            $table->timestamps();
            $table->integer('id_coop')->unsigned;
            $table->foreign('id_coop')->references('id')->on('cooperados');
            $table->decimal('valor', 6, 2);
        });
    }

Body:
Change your code from

$table->integer('id_coop')->unsigned;
$table->foreign('id_coop')->references('id')->on('cooperados');

To:

$table->unsignedBigInteger('id_coop')->index();
$table->foreign('id_coop')->references('id')->on('cooperados')->onDelete('cascade');

Or you can also use below code

 $table->integer('id_coop')->unsigned()->index();
 $table->foreign('id_coop')->references('id')->on('cooperados')->onDelete('cascade');

Or also you can use below

$table->bigInteger('id_coop')->unsigned()->index();
$table->foreign('id_coop')->references('id')->on('cooperados')->onDelete('cascade');


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

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

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

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

The JSON expected response (tested with postman):

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

This is my main:

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

        var call = service.getAllLanguages()

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

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

My Interface:

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

My data class:

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

This is my string printed in textView:

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

答:
I've solved it. Not only was Taranjit Kaur correct in his assessment, but also I've had this code:

```<code>if (!response.isSuccessful)
                {
                    for (RestLanguage in restLanguages)
                        textView.text = "Code: " + response.code()
                    return
                }
</code>```

The exclamation mark made me search all day for my error.

Thanks everyone.

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

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

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

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

The JSON expected response (tested with postman):

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

This is my main:

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

        var call = service.getAllLanguages()

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

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

My Interface:

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

My data class:

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

This is my string printed in textView:

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

Body:
I've solved it. Not only was Taranjit Kaur correct in his assessment, but also I've had this code:

if (!response.isSuccessful)
                {
                    for (RestLanguage in restLanguages)
                        textView.text = "Code: " + response.code()
                    return
                }

The exclamation mark made me search all day for my error.

Thanks everyone.


问:
Warning on git bash start "bash: C:/Users/RS3/Anaconda3/etc/profile.d/conda.sh: No such file or directory"
Whenever I open git bash I get the following warning:
bash: C:/Users/RS3/Anaconda3/etc/profile.d/conda.sh: No such file or directory

The problem is that I uninstalled Anaconda, because I installed independent python, which resulted in giving that error.

How to remove this Warning.

答:
Check the content of ~/.bashrc (which was mentioned here)

Maybe that (or ~/.profile, mentioned here) includes a command for that old uni uninstalled program.

Remove those lines, and try to open again a git bash session.


问:
How to convert number to words in java
We currently have a crude mechanism to convert numbers to words (e.g. using a few static arrays) and based on the size of the number translating that into an english text. But we are running into issues for numbers which are huge.

```<code>10183 = Ten thousand one hundred eighty three
90 = Ninety
5888 = Five thousand eight hundred eighty eight
</code>```

Is there an easy to use function in any of the math libraries which I can use for this purpose?

答:
You can use ICU4J, Just need to add POM entry and code is below for any Number, Country and Language.

POM Entry

```<code>     <dependency>
        <groupId>com.ibm.icu</groupId>
        <artifactId>icu4j</artifactId>
        <version>64.2</version>
    </dependency>
</code>```

Code is

```<code>public class TranslateNumberToWord {

/**
 * Translate
 *
 * @param ctryCd
 * @param lang
 * @param reqStr
 * @param fractionUnitName
 * @return
 */
public static String translate(String ctryCd, String lang, String reqStr, String fractionUnitName) {
    StringBuffer result = new StringBuffer();

    Locale locale = new Locale(lang, ctryCd);
    Currency crncy = Currency.getInstance(locale);

    String inputArr[] = StringUtils.split(new BigDecimal(reqStr).abs().toPlainString(), ".");
    RuleBasedNumberFormat rule = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

    int i = 0;
    for (String input : inputArr) {
        CurrencyAmount crncyAmt = new CurrencyAmount(new BigDecimal(input), crncy);
        if (i++ == 0) {
            result.append(rule.format(crncyAmt)).append(" " + crncy.getDisplayName() + " and ");
        } else {
            result.append(rule.format(crncyAmt)).append(" " + fractionUnitName + " ");
        }
    }
    return result.toString();
}

public static void main(String[] args) {
    String ctryCd = "US";
    String lang = "en";
    String input = "95.17";

    String result = translate(ctryCd, lang, input, "Cents");
    System.out.println("Input: " + input + " result: " + result);
}}
</code>```

Tested with quite a big number and output would be

```<code>Input: 95.17 result: ninety-five US Dollar and seventeen Cents
Input: 999999999999999999.99 result: nine hundred ninety-nine quadrillion nine hundred ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine US Dollar and ninety-nine Cents
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to convert number to words in java

Body:
We currently have a crude mechanism to convert numbers to words (e.g. using a few static arrays) and based on the size of the number translating that into an english text. But we are running into issues for numbers which are huge.

10183 = Ten thousand one hundred eighty three
90 = Ninety
5888 = Five thousand eight hundred eighty eight

Is there an easy to use function in any of the math libraries which I can use for this purpose?

Body:
You can use ICU4J, Just need to add POM entry and code is below for any Number, Country and Language.

POM Entry

     <dependency>
        <groupId>com.ibm.icu</groupId>
        <artifactId>icu4j</artifactId>
        <version>64.2</version>
    </dependency>

Code is

public class TranslateNumberToWord {

/**
 * Translate
 *
 * @param ctryCd
 * @param lang
 * @param reqStr
 * @param fractionUnitName
 * @return
 */
public static String translate(String ctryCd, String lang, String reqStr, String fractionUnitName) {
    StringBuffer result = new StringBuffer();

    Locale locale = new Locale(lang, ctryCd);
    Currency crncy = Currency.getInstance(locale);

    String inputArr[] = StringUtils.split(new BigDecimal(reqStr).abs().toPlainString(), ".");
    RuleBasedNumberFormat rule = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

    int i = 0;
    for (String input : inputArr) {
        CurrencyAmount crncyAmt = new CurrencyAmount(new BigDecimal(input), crncy);
        if (i++ == 0) {
            result.append(rule.format(crncyAmt)).append(" " + crncy.getDisplayName() + " and ");
        } else {
            result.append(rule.format(crncyAmt)).append(" " + fractionUnitName + " ");
        }
    }
    return result.toString();
}

public static void main(String[] args) {
    String ctryCd = "US";
    String lang = "en";
    String input = "95.17";

    String result = translate(ctryCd, lang, input, "Cents");
    System.out.println("Input: " + input + " result: " + result);
}}

Tested with quite a big number and output would be

Input: 95.17 result: ninety-five US Dollar and seventeen Cents
Input: 999999999999999999.99 result: nine hundred ninety-nine quadrillion nine hundred ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine US Dollar and ninety-nine Cents


问:
Fetch with post data to expressjs leads to 404 server not found
Having a react frontend with my own expressjs api backend.
Express v. 4.16.0

Using fetch on the react frontend to get data works just fine.

```<code> fetch('/desResData')
      .then(res => {....}
</code>```

As soon as I try to post some data with the request I get: "POST http://localhost:3000/desResData 404 (Not Found)"
Code:

```<code> fetch('/desResData',
      {
        method: 'POST',
        body: { product: "test" }, // tried JSON.stringify as well
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      }
    )
      .then(res => {....}
</code>```

Roughly spoken I can have static communication from front to backend but I cant parametrize my requests.

ExpressJS:

```<code>router.get('/', async function (req, res, next) {

  console.log(req.body) // tried with using req and without using it

  findByProduct("product") // some async db operation // this part is working fine while fetching without any post parameters
    .then(data => {
       res.json()
      })

</code>```

答:
You have to write router.post (not router.get) to process an HTTP POST request.

Notice the method of your fetch is POST.  But you wrote router.get which handles a request where the method is GET.

If a POST request comes in for a route that doesn't exist, express will give 404.  This applies even if there is a GET handler for the same route.

(Hint: you can have separate GET, POST, PUT, DELETE, etc. handlers for the same route by using .get, .post, .put, .delete, etc.)

Body:
Having a react frontend with my own expressjs api backend.
Express v. 4.16.0

Using fetch on the react frontend to get data works just fine.

 fetch('/desResData')
      .then(res => {....}

As soon as I try to post some data with the request I get: "POST http://localhost:3000/desResData 404 (Not Found)"
Code:

 fetch('/desResData',
      {
        method: 'POST',
        body: { product: "test" }, // tried JSON.stringify as well
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      }
    )
      .then(res => {....}

Roughly spoken I can have static communication from front to backend but I cant parametrize my requests.

ExpressJS:

router.get('/', async function (req, res, next) {

  console.log(req.body) // tried with using req and without using it

  findByProduct("product") // some async db operation // this part is working fine while fetching without any post parameters
    .then(data => {
       res.json()
      })


问:
How to get many attributes data from a single tag?
I'm unable to get data from a single tag. Single tag have many data attributes like name, phone, company and url. i need to get data from many tags and all tags similar to this one.

HTML Code:

```<code> <div class="ListingDetails">
        <div class="ListingDisplayName">
            <a href="/members/jeremy.counter1/default.aspx">
                Jeremy Counter
            </a>
        </div>
                                        Mortgage Officer  -
        American Pacific Mortgage<br>

       Anchorage, Alaska  99503<br>
                                        phone: (907) 519-
       6656 | (907) 250-0766

      <div class="listingurl">
          <a rel="nofollow" href="http://www.jeremycounter.com" target="_blank">
            jeremycounter.com
          </a>
      </div>
 </div>
</code>```

Python Code:

```<code>data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find('div', class_="CommonContentBox DirectoryListings")

listing_box = page.find('div', class_="BusinessListingUser")
name  = listing_box.find('div', class_="ListingDisplayName").text
#print(name)

details  = listing_box.find('div',
class_="ListingDetails").text.strip('\n\t\r')
print(details)
</code>```

Output:

```<code>Tyler Tullis
                                          -
                                        Montgomery, Alabama  36117
                                         | (334) 322-3707
</code>```

Anyone tell me the best possible solution to get data.

Expected result:

```<code>name: Jeremy Counter

phone: (907) 519-6656

company: American Pacific Mortgage

url: jeremycounter.com
</code>```

答:
You can use selenium for this task:

```<code>from selenium import webdriver
import os

# setup path to chrome driver
chrome_driver = os.getcwd() + '/chromedriver'
# initialise chrome driver
browser = webdriver.Chrome(chrome_driver)

# load url
url = 'http://www.mortgagenewsdaily.com/directory/mortgage/alabama'
browser.get(url)
# find all elements
content = browser.find_elements_by_xpath('//*[@id="CommonContentInner"]/div/div/div/div/div')

# get text from each element
collected_data = []
for item in content:
    personal_data = item.get_attribute("innerText")
    collected_data.append(personal_data)

# clean list
collected_data = filter(None, collected_data)
</code>```

Output:

```<code>-----------
Tyler Tullis
  -
Montgomery, Alabama  36117
 | (334) 322-3707
-----------
Nathan Stotlar
Mortgage Production Manager  -  PrimeLending, a PlainsCapital
Company
Fitchburg, Wisconsin  53717
phone: (608) 467-4249
nathanstotlar.com
-----------
.
.
.
</code>```

Body:
I'm unable to get data from a single tag. Single tag have many data attributes like name, phone, company and url. i need to get data from many tags and all tags similar to this one.

HTML Code:

                Jeremy Counter

                                        Mortgage Officer  -
        American Pacific Mortgage

       Anchorage, Alaska  99503

                                        phone: (907) 519-
       6656 | (907) 250-0766

            jeremycounter.com

Python Code:

data=requests.get(url)
soup=bs4.BeautifulSoup(data.text,'html.parser')

page = soup.find('div', class_="CommonContentBox DirectoryListings")

listing_box = page.find('div', class_="BusinessListingUser")
name  = listing_box.find('div', class_="ListingDisplayName").text
#print(name)

details  = listing_box.find('div',
class_="ListingDetails").text.strip('\n\t\r')
print(details)

Output:

Tyler Tullis
                                          -
                                        Montgomery, Alabama  36117
                                         | (334) 322-3707

Anyone tell me the best possible solution to get data.

Expected result:

name: Jeremy Counter

phone: (907) 519-6656

company: American Pacific Mortgage

url: jeremycounter.com

Body:
You can use selenium for this task:

from selenium import webdriver
import os

# setup path to chrome driver
chrome_driver = os.getcwd() + '/chromedriver'
# initialise chrome driver
browser = webdriver.Chrome(chrome_driver)

# load url
url = 'http://www.mortgagenewsdaily.com/directory/mortgage/alabama'
browser.get(url)
# find all elements
content = browser.find_elements_by_xpath('//*[@id="CommonContentInner"]/div/div/div/div/div')

# get text from each element
collected_data = []
for item in content:
    personal_data = item.get_attribute("innerText")
    collected_data.append(personal_data)

# clean list
collected_data = filter(None, collected_data)

Output:

-----------
Tyler Tullis
  -
Montgomery, Alabama  36117
 | (334) 322-3707
-----------
Nathan Stotlar
Mortgage Production Manager  -  PrimeLending, a PlainsCapital
Company
Fitchburg, Wisconsin  53717
phone: (608) 467-4249
nathanstotlar.com
-----------
.
.
.


问:
Excel Dax Count Unique Values and filter on current week automatically
I am pretty new in wokrin with data models within Excel, especially in Dax formulas.

I have the following two tables in the data model.

Table_HS:
Product Code -  User

Table_IS:
Product Code - Work Order - Date Created - Date Started

Now I want to get an Pivot table with the Product Code (Tabel_HS) and I want to know, how many Work Orders were created (Date Created) this week, and how many were started this week.

How would you manage that?
Sure, I can add the Tabele_IS with =WEEKNUM the week number. But how can I filter the pivot automatically to the current week or the current and the last week?
I don't want to filter every week the specific week number.

Best Regards
Joshua

答:
Create two measures:

```<code>Work Orders Created This Week:=
VAR WeekCommencing = TODAY() - WEEKDAY(TODAY(),3)
VAR WeekEnding = WeekCommencing + 6
RETURN
    CALCULATE (
        DISTINCTCOUNT ( Table_IS[Work Order] ),
        Table_IS[Date Created] >= WeekCommencing && Table_IS[Date Created] <= WeekEnding
    )
</code>```

and

```<code>Work Orders Started This Week:=
VAR WeekCommencing = TODAY() - WEEKDAY(TODAY(),3)
VAR WeekEnding = WeekCommencing + 6
RETURN
    CALCULATE (
        DISTINCTCOUNT ( Table_IS[Work Order] ),
        Table_IS[Date Started] >= WeekCommencing && Table_IS[Date Started] <= WeekEnding
    )
</code>```

Body:
Create two measures:

Work Orders Created This Week:=
VAR WeekCommencing = TODAY() - WEEKDAY(TODAY(),3)
VAR WeekEnding = WeekCommencing + 6
RETURN
    CALCULATE (
        DISTINCTCOUNT ( Table_IS[Work Order] ),
        Table_IS[Date Created] >= WeekCommencing && Table_IS[Date Created] <= WeekEnding
    )

and

Work Orders Started This Week:=
VAR WeekCommencing = TODAY() - WEEKDAY(TODAY(),3)
VAR WeekEnding = WeekCommencing + 6
RETURN
    CALCULATE (
        DISTINCTCOUNT ( Table_IS[Work Order] ),
        Table_IS[Date Started] >= WeekCommencing && Table_IS[Date Started] <= WeekEnding
    )


问:
Telling return type of function with multiple possibilities
how could TS know the return type of functions with multiple return type like:

```<code>type VariantA = Variant & {
    a: number,
    b: string,
    c: string[]
}

type VariantB = Variant & {
    e: number,
    f: string,
    g: string[]
}

const CreateObject = (type: 'variantA' | 'variantB') => {
    if (type === 'variantA') {
        return { a: 5, b: 'hello', c: ['a', 'b'] } as VariantA
    } else {
        return { e: 5, f: 'hello', g: ['a', 'b'] } as VariantB
    }
}
</code>```

Here its would be cool if the editor could tell if I pass 'variantA' as type, then the return type is VariantA else VariantB. Is it possible?

答:
Ah I solved it (but there are might better alternatives?)

So I just created a few overloads:

```<code>function CreateObject(type: 'typeA' | 'typeB'): VariantA
function CreateObject(type: 'typeA' | 'typeB'): VariantB
function CreateObject(type: 'typeA' | 'typeB'): VariantA | VariantB {
    if (type === 'typeA') {
        return { a: 1, b: '2', c: ['3', '4'] } as VariantA
    } else {
        return { e: 1, f: '2', g: ['3', '4'] } as VariantB
    }
}
</code>```

Now TS gonna choose the best option (hopefully lol)

Body:
how could TS know the return type of functions with multiple return type like:

type VariantA = Variant & {
    a: number,
    b: string,
    c: string[]
}

type VariantB = Variant & {
    e: number,
    f: string,
    g: string[]
}

const CreateObject = (type: 'variantA' | 'variantB') => {
    if (type === 'variantA') {
        return { a: 5, b: 'hello', c: ['a', 'b'] } as VariantA
    } else {
        return { e: 5, f: 'hello', g: ['a', 'b'] } as VariantB
    }
}

Here its would be cool if the editor could tell if I pass 'variantA' as type, then the return type is VariantA else VariantB. Is it possible?

Body:
Ah I solved it (but there are might better alternatives?)

So I just created a few overloads:

function CreateObject(type: 'typeA' | 'typeB'): VariantA
function CreateObject(type: 'typeA' | 'typeB'): VariantB
function CreateObject(type: 'typeA' | 'typeB'): VariantA | VariantB {
    if (type === 'typeA') {
        return { a: 1, b: '2', c: ['3', '4'] } as VariantA
    } else {
        return { e: 1, f: '2', g: ['3', '4'] } as VariantB
    }
}

Now TS gonna choose the best option (hopefully lol)


问:
Unable to get pure json from a url
I've written a script in python to get the response from a url so that I can make use of it later. The response I wish to get is json. However, what I get instead is more like json:

```<code>{"DISPLAY":{"ADA":{"EUR":{"PRICE":"€ 0.07575","SPRICE":"€ 0.08","CHANGE24HOUR":"€ -0.011","CHANGEPCT24HOUR":"-12.58","CLOSED":"€ 0.08","DAY":-12.290825158684369,"HIGH24HOUR":"€ 0.087","LOW24HOUR":"€ 0.072","MKTCAP":"€ 1963975593.25","MKTCAP_ROUND":"€ 1.96 B","MONTH":27.26481127968117,"OPEN24HOUR":"€ 0.08665","SUPPLY":"ADA 25.93 B","TIMESTAMP":1559305128,"VOLUME24HOUR":"ADA 22.74 M","VOLUME24HOURTO":"€  1.78 M","WEEK":9.685520068120473,"DATA_PROVIDER":2}
</code>```

I've written so far:

```<code>import json
import requests

url = 'https://ticker.cointelegraph.com/tickers'

res = requests.get(url)
print(res.text)

#the following line throws an error
print(json.loads(res.text))
</code>```

Using json.loads(), I get the following error:

```<code>    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 14796 (char 14795)
</code>```

How can I fetch pure json content from that url?

答:
If you look at the content of res.text, or the content of page https://ticker.cointelegraph.com/tickers, there is a +Inf in the string which causes the error, perhaps replacing it with a parsable object, e.g the string +Inf or number 0

```<code>import json
import requests

url = 'https://ticker.cointelegraph.com/tickers'

res = requests.get(url)

#Replaced the +Inf with +Inf string
json_obj = json.loads(res.text.replace('+Inf','"+Inf'))

#Or replace the +Inf with 0 string
#json_obj = json.loads(res.text.replace('+Inf','0'))
</code>```

Then json_obj will have your expected output

Title: Unable to get pure json from a url

Body:
I've written a script in python to get the response from a url so that I can make use of it later. The response I wish to get is json. However, what I get instead is more like json:

{"DISPLAY":{"ADA":{"EUR":{"PRICE":"€ 0.07575","SPRICE":"€ 0.08","CHANGE24HOUR":"€ -0.011","CHANGEPCT24HOUR":"-12.58","CLOSED":"€ 0.08","DAY":-12.290825158684369,"HIGH24HOUR":"€ 0.087","LOW24HOUR":"€ 0.072","MKTCAP":"€ 1963975593.25","MKTCAP_ROUND":"€ 1.96 B","MONTH":27.26481127968117,"OPEN24HOUR":"€ 0.08665","SUPPLY":"ADA 25.93 B","TIMESTAMP":1559305128,"VOLUME24HOUR":"ADA 22.74 M","VOLUME24HOURTO":"€  1.78 M","WEEK":9.685520068120473,"DATA_PROVIDER":2}

I've written so far:

import json
import requests

url = 'https://ticker.cointelegraph.com/tickers'

res = requests.get(url)
print(res.text)

#the following line throws an error
print(json.loads(res.text))

Using json.loads(), I get the following error:

    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 14796 (char 14795)

How can I fetch pure json content from that url?

Body:
If you look at the content of res.text, or the content of page https://ticker.cointelegraph.com/tickers, there is a +Inf in the string which causes the error, perhaps replacing it with a parsable object, e.g the string +Inf or number 0

import json
import requests

url = 'https://ticker.cointelegraph.com/tickers'

res = requests.get(url)

#Replaced the +Inf with +Inf string
json_obj = json.loads(res.text.replace('+Inf','"+Inf'))

#Or replace the +Inf with 0 string
#json_obj = json.loads(res.text.replace('+Inf','0'))

Then json_obj will have your expected output


问:
Disable Required validation attribute under certain circumstances
I was wondering if it is possible to disable the Required validation attribute in certain controller actions. I am wondering this because on one of my edit forms I do not require the user to enter values for fields that they have already specified previously. However I then implement logic that when they enter a value it uses some special logic to update the model, such as hashing a value etc.

Any sugestions on how to get around this problem?

EDIT:

And yes client validation is a problem here to, as it will not allow them to submit the form without entering a value.

答:
In my case the same Model was used in many pages for re-usability purposes. So what i did was i have created a custom attribute which checks for exclusions

```<code>public class ValidateAttribute : ActionFilterAttribute
{
    public string Exclude { get; set; }
    public string Base { get; set; }
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!string.IsNullOrWhiteSpace(this.Exclude))
        {
            string[] excludes = this.Exclude.Split(',');
            foreach (var exclude in excludes)
            {
                actionContext.ModelState.Remove(Base + "." + exclude);
            }
        }
        if (actionContext.ModelState.IsValid == false)
        {
            var mediaType = new MediaTypeHeaderValue("application/json");
            var error = actionContext.ModelState;

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, error.Keys, mediaType);

        }
    }
}
</code>```

and in your controller

```<code>[Validate(Base= "person",Exclude ="Age,Name")]
    public async Task<IHttpActionResult> Save(User person)
    {

            //do something

    }
</code>```

Say the Model is

```<code>public class User
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Range(18,99)]
    public string Age { get; set; }
    [MaxLength(250)]
    public string Address { get; set; }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my case the same Model was used in many pages for re-usability purposes. So what i did was i have created a custom attribute which checks for exclusions

public class ValidateAttribute : ActionFilterAttribute
{
    public string Exclude { get; set; }
    public string Base { get; set; }
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!string.IsNullOrWhiteSpace(this.Exclude))
        {
            string[] excludes = this.Exclude.Split(',');
            foreach (var exclude in excludes)
            {
                actionContext.ModelState.Remove(Base + "." + exclude);
            }
        }
        if (actionContext.ModelState.IsValid == false)
        {
            var mediaType = new MediaTypeHeaderValue("application/json");
            var error = actionContext.ModelState;

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, error.Keys, mediaType);

        }
    }
}

and in your controller

[Validate(Base= "person",Exclude ="Age,Name")]
    public async Task<IHttpActionResult> Save(User person)
    {

            //do something

    }

Say the Model is

public class User
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Range(18,99)]
    public string Age { get; set; }
    [MaxLength(250)]
    public string Address { get; set; }
}


问:
How to use like query in mysql using nodejs
I have been trying to use like query on MySQL but it won't match the pattern with database and only works when the exact keyword is given(% sign doesn't work)

I have tried Concat method, using backslash for special characters,+ symbol and every other approach I can find but still, it isn't working

```<code>connection.query('SELECT * FROM job where domainname like ?', '%' + request.body.domain + '%' ,function(error, results){
            response.render('./results',{rows:results});

    });
and on front end part
  <tbody>
    <% for(var i=0; i < rows.length; i++) { %>
   <tr>
     <td><%= i %></td>
     <td><%= rows[i].companyname %></td>
     <td><%= rows[i].domainname %></td>
   </tr>
<% } %>
</code>```

Error: Cannot read property 'length' of undefined
it works if I don't use % and don't try pattern matching and then shows the results.

答:
try to keep the values in array

```<code>connection.query('SELECT * FROM job where domainname like ?', ['%' + request.body.domain + '%'] ,function(error, results){
        response.render('./results',{rows:results});

});
</code>```

print error and results if it is not working

for more info goto - https://www.npmjs.com/package/mysql#performing-queries

Body:
I have been trying to use like query on MySQL but it won't match the pattern with database and only works when the exact keyword is given(% sign doesn't work)

I have tried Concat method, using backslash for special characters,+ symbol and every other approach I can find but still, it isn't working

connection.query('SELECT * FROM job where domainname like ?', '%' + request.body.domain + '%' ,function(error, results){
            response.render('./results',{rows:results});

    });
and on front end part

    <% for(var i=0; i < rows.length; i++) { %>

     <%= i %>
     <%= rows[i].companyname %>
     <%= rows[i].domainname %>

<% } %>

Error: Cannot read property 'length' of undefined
it works if I don't use % and don't try pattern matching and then shows the results.

Body:
try to keep the values in array

connection.query('SELECT * FROM job where domainname like ?', ['%' + request.body.domain + '%'] ,function(error, results){
        response.render('./results',{rows:results});

});

print error and results if it is not working

for more info goto - https://www.npmjs.com/package/mysql#performing-queries


问:
Linking to a zip file creates a "soft 404" in Google Search Console
I Google Search Console, I keep getting a "Soft 404" error for links that point to a zip file.

The html looks like this:

```<code><a href="/downloads.php?id=7" title="Description" download>Click here</a>
</code>```

When clicked, the url is generated like this:

```<code>header("Location: " . $row["url"]);
</code>```

Where the url is something link: https://www.example.com/file.zip

So the page is not a 404 - in fact it's not a page, but a file. How can I fix this for Google?

答:
header("Location: " . $row["url"]);

This generates a 302 status code response by default.

You could make this a 301, that should make this “soft 404” go away - but then Google will identify https://www.example.com/file.zip as the actual target URL, and index that one, and show it as a search result.

Body:
I Google Search Console, I keep getting a "Soft 404" error for links that point to a zip file.

The html looks like this:

Click here

When clicked, the url is generated like this:

header("Location: " . $row["url"]);

Where the url is something link: https://www.example.com/file.zip

So the page is not a 404 - in fact it's not a page, but a file. How can I fix this for Google?


问:
How to ssh using JSch to ZXA10 C320 device
I am developing a Java application to ssh to a zxa10 c320 device. I used jsch library to ssh. But when I run the application its hold in the first while loop without returning any output. When I run this application by pointing to ssh some other Linux servers, it works properly.

Please advise me if I did anything wrong.

I try this in both 'exec' and 'shell' modes.

Also, I try to do this using sshj library. It also didn't work.

```<code>public class RunCommand {

    public String runCommand(String command) {
        String host = "XX.XX.X.XX";
        String user = "user";
        String password = "password";
        String result = "";

        try{
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();

            // Create a JSch session to connect to the server
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig(config);

            // Establish the connection
            session.connect();

            if(session.isConnected()) {
                System.out.println("Connected...");
            }

            ChannelExec channel = (ChannelExec) session.openChannel("exec");

            channel.setCommand("pwd");

            int stat = channel.getExitStatus();

            StringBuilder outputBuffer = new StringBuilder();
            StringBuilder errorBuffer = new StringBuilder();

            InputStream in = channel.getInputStream();
            InputStream err = channel.getExtInputStream();

            channel.setPty(true);
            channel.connect();

            System.out.println("Channel Connected");
            System.out.println("channel.isConnected() "+channel.isConnected());
            System.out.println("channel.isClosed() "+channel.isClosed());

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    outputBuffer.append(new String(tmp, 0, i));
                }
                while (err.available() > 0) {
                    int i = err.read(tmp, 0, 1024);
                    if (i < 0) break;
                    errorBuffer.append(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    if ((in.available() > 0) || (err.available() > 0)) continue;
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

            System.out.println("output: " + outputBuffer.toString());
            System.out.println("error: " + errorBuffer.toString());
            channel.disconnect();
            session.disconnect();
            System.out.println("Channel And Session Closed!!!");
        }catch(JSchException e){
            e.printStackTrace();
            result = "Auth fail";
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
</code>```

答: I wasn't able to do this using peo java. But i was able to this using paramiko module of python. What i did is i wrote two applications one with java and one with python, then i call python application from java application and ssh to gpon by python application.</p>

Body:
I am developing a Java application to ssh to a zxa10 c320 device. I used jsch library to ssh. But when I run the application its hold in the first while loop without returning any output. When I run this application by pointing to ssh some other Linux servers, it works properly.

Please advise me if I did anything wrong.

I try this in both 'exec' and 'shell' modes.

Also, I try to do this using sshj library. It also didn't work.

public class RunCommand {

    public String runCommand(String command) {
        String host = "XX.XX.X.XX";
        String user = "user";
        String password = "password";
        String result = "";

        try{
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();

            // Create a JSch session to connect to the server
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig(config);

            // Establish the connection
            session.connect();

            if(session.isConnected()) {
                System.out.println("Connected...");
            }

            ChannelExec channel = (ChannelExec) session.openChannel("exec");

            channel.setCommand("pwd");

            int stat = channel.getExitStatus();

            StringBuilder outputBuffer = new StringBuilder();
            StringBuilder errorBuffer = new StringBuilder();

            InputStream in = channel.getInputStream();
            InputStream err = channel.getExtInputStream();

            channel.setPty(true);
            channel.connect();

            System.out.println("Channel Connected");
            System.out.println("channel.isConnected() "+channel.isConnected());
            System.out.println("channel.isClosed() "+channel.isClosed());

            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    outputBuffer.append(new String(tmp, 0, i));
                }
                while (err.available() > 0) {
                    int i = err.read(tmp, 0, 1024);
                    if (i < 0) break;
                    errorBuffer.append(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    if ((in.available() > 0) || (err.available() > 0)) continue;
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

            System.out.println("output: " + outputBuffer.toString());
            System.out.println("error: " + errorBuffer.toString());
            channel.disconnect();
            session.disconnect();
            System.out.println("Channel And Session Closed!!!");
        }catch(JSchException e){
            e.printStackTrace();
            result = "Auth fail";
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
}


问:
Create and include new file into python package
I want to use version for my package base on git describe command. For this, I created setup.py with function get_version(). This function retrieves version from .version file if it exists, else computes new package version and writes it to a new .version file. However, when I call python setup.py sdist, .version is not copying inside .tar archive. This causes error when I'm trying to install package from PyPi repo. How to properly include my .version file "on the fly" into package?

setup.py:

import pathlib
from subprocess import check_output
from setuptools import find_packages, setup

_VERSION_FILE = pathlib.Path(".version")  # Add it to .gitignore!
_GIT_COMMAND = "git describe --tags --long --dirty"
_VERSION_FORMAT = "{tag}.dev{commit_count}+{commit_hash}"

def get_version() -> str:
    """ Return version from git, write commit to file
    """
    if _VERSION_FILE.is_file():
        with _VERSION_FILE.open() as f:
            return f.readline().strip()
    output = check_output(_GIT_COMMAND.split()).decode("utf-8").strip().split("-")

    tag, count, commit = output[:3]
    dirty = len(output) == 4

    if count == "0" and not dirty:
        return tag

    version = _VERSION_FORMAT.format(tag=tag, commit_count=count, commit_hash=commit)

    with _VERSION_FILE.open("w") as f:
        print(version, file=f, end="")

    return version

_version = get_version()

setup(
    name="mypackage",
    package_data={
        "": [str(_VERSION_FILE)]
    },
    version=_version,
    packages=find_packages(exclude=["tests"]),
)
```

答: It was a mistake in setup.py. I forgot to add file dumping in if count == "0" and not dirty:. Now it works with MANIFEST.in.


问:
Can alloca() memory be reallocated?
Memory allocated by malloc can be reallocated with realloc. Is there a similar function for alloca? Reallocating stack memory could be useful when you don't want memory to be allocated on the heap, and you need to allocate variable stack memory multiple times, for example in a library function, where you need dynamic memory, but don't want to allocate on the heap, because the user of the library might use a custom heap allocation strategy. It would look like this:

```<code>int main(void) {
    float * some_mem = alloca(40 * sizeof(float));
    // do something with this memory...

    // now we need a different amount of memory, but some_mem still occupies a lot of the stack, so just reallocate it.

    // is something like this possible?
    some_mem = realloca(some_mem, 50 * sizeof(float));
}
</code>```

The important thing is that this all happens on the stack. Q: is there a way to reallocate dynamic stack memory?

答:
The accepted answer has correctly pointed out that usually there is not enough benefit from realloca because allocations are difficult to "grow".

Another issue I see is that these allocations have a life time till the end of the function. What happens when you pass this pointer to another function and call realloca on it there? This function would not be able to change the stack frame of a function deeper on the stack. It also cannot reallocate it in its own frame because the object would be destroyed when it returns, whereas the original object would still have to be alive.

This problem is not there for malloc/realloc because the heap has a global lifetime.

One could argue that the semantics can be defined in such way that a function can be realloced only in the function it was alloc'd in. This greatly reduces the use such a function would have.

Title: Can alloca() memory be reallocated?

Body:
Memory allocated by malloc can be reallocated with realloc. Is there a similar function for alloca? Reallocating stack memory could be useful when you don't want memory to be allocated on the heap, and you need to allocate variable stack memory multiple times, for example in a library function, where you need dynamic memory, but don't want to allocate on the heap, because the user of the library might use a custom heap allocation strategy. It would look like this:

int main(void) {
    float * some_mem = alloca(40 * sizeof(float));
    // do something with this memory...

    // now we need a different amount of memory, but some_mem still occupies a lot of the stack, so just reallocate it.

    // is something like this possible?
    some_mem = realloca(some_mem, 50 * sizeof(float));
}

The important thing is that this all happens on the stack. Q: is there a way to reallocate dynamic stack memory?


问:
Binding boolean column to checkbox in ngx-datatable
How can I bind a Boolean column to a checkbox in ngx-datatable? Currently I am using angular material table and use the following method :

```<code>  <ng-container matColumnDef="Active">
    <mat-header-cell *matHeaderCellDef class="generic-centeredCell"> Active </mat-header-cell>
    <mat-cell *matCellDef="let element" class="generic-centeredCell">
      <span class="mobile-label">Active:</span>
      <mat-checkbox [(ngModel)]="element.active"></mat-checkbox>
    </mat-cell>
  </ng-container>
</code>```

How can I make use of above code when I move to ngx-datatable? I cant event find a sample. The only samples I have seen so far is
http://swimlane.github.io/ngx-datatable/#chkbox-selection
which doesn't explain how to bind the boolean column to a checkbox.

答:
I found the answer to my own question and I thought it might help someone in future. Above code would translate to something similar to below :

```<code>  <ngx-datatable-column name="Active">
    <ng-template ngx-datatable-cell-template let-value="value">
      <mat-checkbox [(ngModel)]="value"></mat-checkbox>
    </ng-template>
  </ngx-datatable-column>
</code>```

Simply just put the control inside

using this method not only allows you to have Boolean column bound to checkbox, you can also embed other controls inside the column.

Body:
How can I bind a Boolean column to a checkbox in ngx-datatable? Currently I am using angular material table and use the following method :

  <ng-container matColumnDef="Active">
    <mat-header-cell *matHeaderCellDef class="generic-centeredCell"> Active </mat-header-cell>
    <mat-cell *matCellDef="let element" class="generic-centeredCell">
      Active:
      <mat-checkbox [(ngModel)]="element.active"></mat-checkbox>
    </mat-cell>
  </ng-container>

How can I make use of above code when I move to ngx-datatable? I cant event find a sample. The only samples I have seen so far is
http://swimlane.github.io/ngx-datatable/#chkbox-selection
which doesn't explain how to bind the boolean column to a checkbox.

Body:
I found the answer to my own question and I thought it might help someone in future. Above code would translate to something similar to below :

  <ngx-datatable-column name="Active">
    <ng-template ngx-datatable-cell-template let-value="value">
      <mat-checkbox [(ngModel)]="value"></mat-checkbox>
    </ng-template>
  </ngx-datatable-column>

Simply just put the control inside

using this method not only allows you to have Boolean column bound to checkbox, you can also embed other controls inside the column.


问:
How to fix this error "Impossible to connect, please check your Algolia Application Id"?
I have everything correct, as written at laravel/algolia websites.

I tried to read lot of documentations and tutorials about Laravel Scout installation, but still can't find solution.

I have everything correct in my settings and also APIs are correct but still getting this error:

Impossible to connect, please check your Algolia Application Id.

答:
I had the same issue (with Windows 10) and found this exception in the stack trace:

```<code>cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

I found the solution for the error above in another StackOverflow post:

1) Download the latest cacert.pem from
  https://curl.haxx.se/ca/cacert.pem

2) Add the following line to php.ini (if this is shared hosting and
  you don't have access to php.ini then you could add this to .user.ini
  in public_html)

curl.cainfo="/path/to/downloaded/cacert.pem"

Make sure you enclose the path within double quotation marks!!!

It solved my problem, Laravel Scout is working fine after that. Hope this will help someone.

Body:
I had the same issue (with Windows 10) and found this exception in the stack trace:

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

I found the solution for the error above in another StackOverflow post:

1) Download the latest cacert.pem from
  https://curl.haxx.se/ca/cacert.pem

2) Add the following line to php.ini (if this is shared hosting and
  you don't have access to php.ini then you could add this to .user.ini
  in public_html)

curl.cainfo="/path/to/downloaded/cacert.pem"

Make sure you enclose the path within double quotation marks!!!

It solved my problem, Laravel Scout is working fine after that. Hope this will help someone.


问:
Custom error setting being ignored for locations denied in the web.config
In a ASP.Net 4 and MVC2 application we have an odd configuration error.

The web.config looks something like this:

```<code><configuration>
    <location path="blockedpath">
        <system.web>
            <authorization>
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
    <system.web>
        <customErrors mode="On" defaultRedirect="~/Error.aspx" />
    </system.web>
</configuration>
</code>```

Visiting the blocked location is correctly denied, but gives a verbose error message from IIS that we don't want.

Why doesn't it serve up the configured custom error?

Can we control what page it does serve up when page access is denied by config?

答:
According to this blog post, IIS7 is trying to be helpful and likes to steal your custom errors pages and replace them with its own.

Open the Error Pages feature in IIS and click Edit Feature Settings on the right hand menu. Set the Detailed errors option to have IIS pass through whatever errors you serve up from ASP.NET.

Body:
In a ASP.Net 4 and MVC2 application we have an odd configuration error.

The web.config looks something like this:

<configuration>
    <location path="blockedpath">
        <system.web>
            <authorization>
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
    <system.web>
        <customErrors mode="On" defaultRedirect="~/Error.aspx" />
    </system.web>
</configuration>

Visiting the blocked location is correctly denied, but gives a verbose error message from IIS that we don't want.

Why doesn't it serve up the configured custom error?

Can we control what page it does serve up when page access is denied by config?


问:
Customizing prefix and namespace location in soap request generated using wsdl file
I am struggling to understand why code-generated soap request on the left is not working, but if I tweak it to what's on the right, then it works?

Now that I know what needs to be done to make it work, how do I fix it ?

I added jaxws-maven-plugin to my java project:

```<code>     <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                   <sourceDestDir>src/main/java</sourceDestDir>
                   <wsdlDirectory>src/main/resources/wsdl</wsdlDirectory>
                   <wsdlFiles>
                       <wsdlFile>Flattened_Integrator7.0.wsdl</wsdlFile>
                   </wsdlFiles>
                   <keep>true</keep>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</code>```

Notice in the picture above without prefix wsse, it doesn't work.

It has to be that word. And it exists in wsdl file.

Does anyone know how:

I can force namespace prefix for "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" to be wsse

Force code to generate namespaces in soap envelope and not in Security section

答:
So, I had to manually add prefix/namespace to envelope and rename all children's prefixes to wsse.

Here is how I did it:

```<code>@Component
public class RequestClient {

    private static final String WSSE_PREFIX = "wsse";
    private static final String WSSE_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
    private static final String NS2_PREFIX = "ns2";
    private static final String NS2_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";

    private buildSoaprequest(){
        ...
        SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
        soapEnvelope.addNamespaceDeclaration(WSSE_PREFIX, WSSE_NAMESPACE);
        soapEnvelope.addNamespaceDeclaration(NS2_PREFIX, NS2_NAMESPACE);
        SOAPHeader soapHeader = soapMessage.getSOAPHeader();
        removeUndesiredBodyNamespaceEntries(soapHeader.getChildElements());
        soapHeader.setPrefix(WSSE_PREFIX);
        addDesiredBodyNamespaceEntries(soapHeader.getChildElements());
        soapMessage.saveChanges();
        ...
    }

    private void addDesiredBodyNamespaceEntries(Iterator childElements) {
        while (childElements.hasNext()) {
          final Object childElementNode = childElements.next();
          if (childElementNode instanceof SOAPElement) {
            SOAPElement soapElement = (SOAPElement) childElementNode;
            soapElement.setPrefix(WSSE_PREFIX);
            addDesiredBodyNamespaceEntries(soapElement.getChildElements());
          }
        }
      }

    private void removeUndesiredBodyNamespaceEntries(Iterator childElements) {
        while (childElements.hasNext()) {
          final Object childElementNode = childElements.next();
          if (childElementNode instanceof SOAPElement) {
            SOAPElement soapElement = (SOAPElement) childElementNode;

            //remove any prefix/namespace entries added by JAX-WS in the body element
            //it cannot be null, so it will leave wsse
            for (String prefix : getNamespacePrefixList(soapElement.getNamespacePrefixes())) {
              if (prefix != null) {
                soapElement.removeNamespaceDeclaration(prefix);
              }
            }
            // recursively remove prefix/namespace entries in child elements
            removeUndesiredBodyNamespaceEntries(soapElement.getChildElements());
          }
        }
      }

     private Set<String> getNamespacePrefixList(Iterator namespacePrefixIter) {
        Set<String> namespacePrefixesSet = new HashSet<>();
        while (namespacePrefixIter.hasNext()) {
          namespacePrefixesSet.add((String) namespacePrefixIter.next());
        }
        return namespacePrefixesSet;
      }
</code>```

Body:
I am struggling to understand why code-generated soap request on the left is not working, but if I tweak it to what's on the right, then it works?

Now that I know what needs to be done to make it work, how do I fix it ?

I added jaxws-maven-plugin to my java project:

     <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                   <sourceDestDir>src/main/java</sourceDestDir>
                   <wsdlDirectory>src/main/resources/wsdl</wsdlDirectory>
                   <wsdlFiles>
                       <wsdlFile>Flattened_Integrator7.0.wsdl</wsdlFile>
                   </wsdlFiles>
                   <keep>true</keep>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Notice in the picture above without prefix wsse, it doesn't work.

It has to be that word. And it exists in wsdl file.

Does anyone know how:

I can force namespace prefix for "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" to be wsse

Force code to generate namespaces in soap envelope and not in Security section

Body:
So, I had to manually add prefix/namespace to envelope and rename all children's prefixes to wsse.

Here is how I did it:

@Component
public class RequestClient {

    private static final String WSSE_PREFIX = "wsse";
    private static final String WSSE_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
    private static final String NS2_PREFIX = "ns2";
    private static final String NS2_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";

    private buildSoaprequest(){
        ...
        SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
        soapEnvelope.addNamespaceDeclaration(WSSE_PREFIX, WSSE_NAMESPACE);
        soapEnvelope.addNamespaceDeclaration(NS2_PREFIX, NS2_NAMESPACE);
        SOAPHeader soapHeader = soapMessage.getSOAPHeader();
        removeUndesiredBodyNamespaceEntries(soapHeader.getChildElements());
        soapHeader.setPrefix(WSSE_PREFIX);
        addDesiredBodyNamespaceEntries(soapHeader.getChildElements());
        soapMessage.saveChanges();
        ...
    }

    private void addDesiredBodyNamespaceEntries(Iterator childElements) {
        while (childElements.hasNext()) {
          final Object childElementNode = childElements.next();
          if (childElementNode instanceof SOAPElement) {
            SOAPElement soapElement = (SOAPElement) childElementNode;
            soapElement.setPrefix(WSSE_PREFIX);
            addDesiredBodyNamespaceEntries(soapElement.getChildElements());
          }
        }
      }

    private void removeUndesiredBodyNamespaceEntries(Iterator childElements) {
        while (childElements.hasNext()) {
          final Object childElementNode = childElements.next();
          if (childElementNode instanceof SOAPElement) {
            SOAPElement soapElement = (SOAPElement) childElementNode;

            //remove any prefix/namespace entries added by JAX-WS in the body element
            //it cannot be null, so it will leave wsse
            for (String prefix : getNamespacePrefixList(soapElement.getNamespacePrefixes())) {
              if (prefix != null) {
                soapElement.removeNamespaceDeclaration(prefix);
              }
            }
            // recursively remove prefix/namespace entries in child elements
            removeUndesiredBodyNamespaceEntries(soapElement.getChildElements());
          }
        }
      }

     private Set<String> getNamespacePrefixList(Iterator namespacePrefixIter) {
        Set<String> namespacePrefixesSet = new HashSet<>();
        while (namespacePrefixIter.hasNext()) {
          namespacePrefixesSet.add((String) namespacePrefixIter.next());
        }
        return namespacePrefixesSet;
      }


问:
Form input realtime feedback
I'm constructing a form with an input field for a username. I want to restrict the username to a pretty small range of characters using regex, changing the color of the text from red to green based on the validity of the input compared to the regex as the user types.

So far it isn't picking up any characters that aren't valid despite positive testing of the regex.

https://regex101.com/r/XPFy6c/1/

```<code>/^[A-Z0-9 -]+$/igm
</code>```

Here's the code, with a JSFiddle here.

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!check) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}</code>```

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>```

Update: Although this question is solved, if you try the code you will notice that there remains an issue with the regex alternating true/false. The solution to this problem is here.

答:
Your code had two problems:

The input event is fired oninput, select and textarea tags, not form. As such, addEventListener was on the wrong element

when you are verifying whether a RegExp works with test, the return value is a boolean indicating if it did, not the RegExp itself. As such, the if statement needed a tweak.

Corrected snippet below:

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

input.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!checkName) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}</code>```

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>```

Title: Form input realtime feedback

Body:
I'm constructing a form with an input field for a username. I want to restrict the username to a pretty small range of characters using regex, changing the color of the text from red to green based on the validity of the input compared to the regex as the user types.

So far it isn't picking up any characters that aren't valid despite positive testing of the regex.

https://regex101.com/r/XPFy6c/1/

/^[A-Z0-9 -]+$/igm

Here's the code, with a JSFiddle here.

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!check) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})

.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>

Update: Although this question is solved, if you try the code you will notice that there remains an issue with the regex alternating true/false. The solution to this problem is here.

Body:
Your code had two problems:

The input event is fired oninput, select and textarea tags, not form. As such, addEventListener was on the wrong element

when you are verifying whether a RegExp works with test, the return value is a boolean indicating if it did, not the RegExp itself. As such, the if statement needed a tweak.

Corrected snippet below:

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

input.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!checkName) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})

.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>


答:
if you only care about modern browsers, you don't even need JavaScript!

input { border: 2px solid #DDD; }
input:invalid { border-color: red; }
input:valid { border-color: green; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" pattern="^[A-Z0-9 -]{1,12}$"></code>```

Title: Form input realtime feedback

Body:
if you only care about modern browsers, you don't even need JavaScript!

input { border: 2px solid #DDD; }
input:invalid { border-color: red; }
input:valid { border-color: green; }

<input type="text" pattern="^[A-Z0-9 -]{1,12}$">


问:
How to find out which setup failed in Assert of `VerifyAll`?
I am writing the unit test for a method. I have properly configured all the setups. While debugging unit test it works and returns values as expected. But in assertion it still throws false.

Therefore, I am not able to understand why does VerifyAll throws false all the time? How to find out which setup failed the VerifyAll assert?

答:
VerifyAll verifies that all your Setups were called. It sounds like you have a Setup that is not relevant to your test, hence your are getting the expected output, yet the VerifyAll fails because that Setup was never called.

When VerifyAll fails you will get an exception, and the reason is given there. For example, if I create an unused Setup in a test I get:

Moq.MockVerificationException : The following setups were not matched:
  IMyClass m => m.MyMethod()


问:
Laravel returning server error 500 on CentOS 7
As the title says, I have a VPS running on CentOS 7, I installed all the requisites for Laravel, PHP 7.3, but it still giving me 'Server Error 500'.

Note that this is a fresh installation of Laravel with composer.

My CentOS version is CentOS Linux release 7.2.1511 (Core)

PHP version is PHP 7.3.6 (cli)

I manually installed all the necessary modules from PHP

What I have already tried

I already did quite a lot of research:

Laravel giving 500 internal error on centos 7 with apache and php 7

I followed what the answer to that questions says and still the same for me.

I did also set up permissions correctly following this other post:

How to set up File Permissions for Laravel 5 (and others)

Also these ones

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

https://www.ionos.com/community/server-cloud-infrastructure/apache/how-to-fix-http-error-code-500-internal-server-error/

And a bunch of more articles I read on another websites.

These are the permissions for the project folder:

drwxr-xr-x 13 apache apache 4096 May 31 05:23 laravel

And for storage:

drwxr-xr-x  5 apache apache   4096 May 31 04:44 storage

Tried generating the key and got this:

```<code>[root@server laravel]# php artisan key:generate

   ErrorException  : file_get_contents(/var/www/laravel/.env): failed to open stream: No such file or directory

  at /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96
     92|     {
     93|         file_put_contents($this->laravel->environmentFilePath(), preg_replace(
     94|             $this->keyReplacementPattern(),
     95|             'APP_KEY='.$key,
  >  96|             file_get_contents($this->laravel->environmentFilePath())
     97|         ));
     98|     }
     99|
    100|     /**

  Exception trace:

  1   file_get_contents("/var/www/laravel/.env")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96

  2   Illuminate\Foundation\Console\KeyGenerateCommand::writeNewEnvironmentFileWith("base64:soTdeaCmsY1ELnpJLCcYkBJjY6SWiLYwY+Mvoxl9wOw=")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:80

  Please use the argument -v to see more details.
[root@server laravel]#

</code>```

答:
Seems like you miss the Laravel environment configuration file.

In a fresh Laravel installation you should have a .env.example file. Duplicate that one and rename it to .env then run the php artisan key:generate command.

Body:
As the title says, I have a VPS running on CentOS 7, I installed all the requisites for Laravel, PHP 7.3, but it still giving me 'Server Error 500'.

Note that this is a fresh installation of Laravel with composer.

My CentOS version is CentOS Linux release 7.2.1511 (Core)

PHP version is PHP 7.3.6 (cli)

I manually installed all the necessary modules from PHP

What I have already tried

I already did quite a lot of research:

Laravel giving 500 internal error on centos 7 with apache and php 7

I followed what the answer to that questions says and still the same for me.

I did also set up permissions correctly following this other post:

How to set up File Permissions for Laravel 5 (and others)

Also these ones

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

https://www.ionos.com/community/server-cloud-infrastructure/apache/how-to-fix-http-error-code-500-internal-server-error/

And a bunch of more articles I read on another websites.

These are the permissions for the project folder:

drwxr-xr-x 13 apache apache 4096 May 31 05:23 laravel

And for storage:

drwxr-xr-x  5 apache apache   4096 May 31 04:44 storage

Tried generating the key and got this:

[root@server laravel]# php artisan key:generate

   ErrorException  : file_get_contents(/var/www/laravel/.env): failed to open stream: No such file or directory

  at /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96
     92|     {
     93|         file_put_contents($this->laravel->environmentFilePath(), preg_replace(
     94|             $this->keyReplacementPattern(),
     95|             'APP_KEY='.$key,
  >  96|             file_get_contents($this->laravel->environmentFilePath())
     97|         ));
     98|     }
     99|
    100|     /**

  Exception trace:

  1   file_get_contents("/var/www/laravel/.env")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:96

  2   Illuminate\Foundation\Console\KeyGenerateCommand::writeNewEnvironmentFileWith("base64:soTdeaCmsY1ELnpJLCcYkBJjY6SWiLYwY+Mvoxl9wOw=")
      /var/www/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Console/KeyGenerateCommand.php:80

  Please use the argument -v to see more details.
[root@server laravel]#


问:
How do I modify object key value in an array of objects and return the initial array?
I have the following array of objects. Each object is a legend element in a doughnut chart. What I want to achieve is that when I click on one element, the innerRadius should be set to value 2. If I click on another element, the innerRadius value of the previous one should be set to 0. So in the end only the element that I clicked on should have the value 2.

```<code>export const table1 = [
  {
    label: "p",
    angle: 5,
    style: {fill: "#1A3177"},
    innerRadius: 0,
    active: false,
    key: 0
  },{
    label: "ne",
    angle: 2,
    style: {fill: "#79C7E3"},
    innerRadius: 0,
    active: false,
    key: 1
  },{
    label: "nu",
    angle: 2,
    style: {fill: "#12939A"},
    innerRadius: 0,
    active: false,
    key: 2
  },{
    label: "na",
    angle: 1,
    style: {fill: "#FF9833"},
    innerRadius: 0,
    active: false,
    key: 3
  }
]
</code>```

I have tried to map the initial array, apply a filter, reduce, splice.
What I have tried so far it returns the array of objects with the innerRadius value of 2 for all the elements that I clicked on

```<code> toogleHighlightOn = key => {
    let item = table1.map(i => i)
    let aaa = item.filter(i => i.key === key).reduce(i => i)
    aaa.innerRadius = 2
    const index = item.indexOf(aaa)
    item.splice([index], 1, aaa)

    console.log(aaa)
    console.log(table1)
    return this.setState({
      default: [...item]
    })
  }
</code>```

答:
```<code>toggleHighlightOn = key => {
    table1.forEach(i => i.innerRadius = 0);
    const newElement = table1.find(i => i.key === key);
    if (newElement) {
        newElement.innerRadius = 2;
    }

    return this.setState({
      default: [...table1]
    })
}
</code>```

Body:
I have the following array of objects. Each object is a legend element in a doughnut chart. What I want to achieve is that when I click on one element, the innerRadius should be set to value 2. If I click on another element, the innerRadius value of the previous one should be set to 0. So in the end only the element that I clicked on should have the value 2.

export const table1 = [
  {
    label: "p",
    angle: 5,
    style: {fill: "#1A3177"},
    innerRadius: 0,
    active: false,
    key: 0
  },{
    label: "ne",
    angle: 2,
    style: {fill: "#79C7E3"},
    innerRadius: 0,
    active: false,
    key: 1
  },{
    label: "nu",
    angle: 2,
    style: {fill: "#12939A"},
    innerRadius: 0,
    active: false,
    key: 2
  },{
    label: "na",
    angle: 1,
    style: {fill: "#FF9833"},
    innerRadius: 0,
    active: false,
    key: 3
  }
]

I have tried to map the initial array, apply a filter, reduce, splice.
What I have tried so far it returns the array of objects with the innerRadius value of 2 for all the elements that I clicked on

 toogleHighlightOn = key => {
    let item = table1.map(i => i)
    let aaa = item.filter(i => i.key === key).reduce(i => i)
    aaa.innerRadius = 2
    const index = item.indexOf(aaa)
    item.splice([index], 1, aaa)

    console.log(aaa)
    console.log(table1)
    return this.setState({
      default: [...item]
    })
  }


问:
how do I group, sort and take out the first N in mysql?
I can get the sorted data in the group, and finally take out the first N in DolphinDB.

But how do I group, sort and take out the first N in mysql?

Thank you first.

The DolphinDB code is as follows：

```<code>sym = `C`MS`MS`MS`IBM`IBM`C`C`C$symbol;
price= 49.6 29.46 29.52 30.02 174.97 175.23 50.76 50.32 51.29;
qty = 2200 1900 2100 3200 6800 5400 1300 2500 8800;
timestamp = [09:34:07,09:36:42,09:36:51,09:36:59,09:32:47,09:35:26,09:34:16,09:34:26,09:38:12];
t1 = table(timestamp, sym, qty, price);
select top 2 * from t1 context by sym csort timestamp;

timestamp sym qty  price
--------- --- ---- ------
09:34:07  C   2200 49.6
09:34:16  C   1300 50.76
09:32:47  IBM 6800 174.97
09:35:26  IBM 5400 175.23
09:36:42  MS  1900 29.46
09:36:51  MS  2100 29.52

</code>```

答:
```<code>SELECT sym, sum(qty) FROM table_name GROUP BY sym ORDER BY qty LIMIT 5;
</code>```

Where
GROUP BY column - groups rows
ORDER BY column - orders rows
LIMIT number - picks the first number of rows

Body:
I can get the sorted data in the group, and finally take out the first N in DolphinDB.

But how do I group, sort and take out the first N in mysql?

Thank you first.

The DolphinDB code is as follows：

sym = `C`MS`MS`MS`IBM`IBM`C`C`C$symbol;
price= 49.6 29.46 29.52 30.02 174.97 175.23 50.76 50.32 51.29;
qty = 2200 1900 2100 3200 6800 5400 1300 2500 8800;
timestamp = [09:34:07,09:36:42,09:36:51,09:36:59,09:32:47,09:35:26,09:34:16,09:34:26,09:38:12];
t1 = table(timestamp, sym, qty, price);
select top 2 * from t1 context by sym csort timestamp;

timestamp sym qty  price
--------- --- ---- ------
09:34:07  C   2200 49.6
09:34:16  C   1300 50.76
09:32:47  IBM 6800 174.97
09:35:26  IBM 5400 175.23
09:36:42  MS  1900 29.46
09:36:51  MS  2100 29.52

Body:
SELECT sym, sum(qty) FROM table_name GROUP BY sym ORDER BY qty LIMIT 5;

Where
GROUP BY column - groups rows
ORDER BY column - orders rows
LIMIT number - picks the first number of rows


问:
Java and Hibernate - How to make OneToOne relation with SuperMappedClass and not an Entity
I have tree Entities: Client, ClientConfigurationA and ClientConfigurationB.

I try to make something like:

```<code>@Entity
@Table(name = "CLIENT")
public class Client {

    @Id
    private int id;

    @OneToOne(mappedBy = "client")
    private ClientConfiguration configuration

    // some getter and setter
}

@MappedSuperClass
public class ClientConfiguration {

    @Id
    private int id;

    @OneToOne
    @MapsId
    protected Client client;

    // getters and setters
}

@Entity(name = "CLIENT_CONF_A")
public class ClientConfigurationA extends ClientConfiguration { ... }

@Entity(name = "CLIENT_CONF_B")
public class ClientConfigurationB extends ClientConfiguration { ... }
</code>```

But actually I can't define a OneToOne related to MappedSuperClass and not an Entity.

So what's the best way to implement this case ?

I already tried this solution without succes.

Thanks for reading.

答:
After many attempts i finally succeeded.</p>

```<code>@Entity
@Table(name = "CLIENT")
public class Client {

    @Id
    private int id;

    @OneToOne(mappedBy = "client")
    private ClientConfiguration configuration

    // some getter and setter
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(name = "TYPE")
public abstract class ClientConfiguration {

    @Id
    private int id;

    @Column(name = "TYPE")
    private String type;

    @OneToOne
    @MapsId
    protected Client client;

    // getters and setters
}

@Entity(name = "CLIENT_CONF_A")
public class ClientConfigurationA extends ClientConfiguration { ... }

@Entity(name = "CLIENT_CONF_B")
public class ClientConfigurationB extends ClientConfiguration { ... }
</code>```

Body:
I have tree Entities: Client, ClientConfigurationA and ClientConfigurationB.

I try to make something like:

@Entity
@Table(name = "CLIENT")
public class Client {

    @Id
    private int id;

    @OneToOne(mappedBy = "client")
    private ClientConfiguration configuration

    // some getter and setter
}

@MappedSuperClass
public class ClientConfiguration {

    @Id
    private int id;

    @OneToOne
    @MapsId
    protected Client client;

    // getters and setters
}

@Entity(name = "CLIENT_CONF_A")
public class ClientConfigurationA extends ClientConfiguration { ... }

@Entity(name = "CLIENT_CONF_B")
public class ClientConfigurationB extends ClientConfiguration { ... }

But actually I can't define a OneToOne related to MappedSuperClass and not an Entity.

So what's the best way to implement this case ?

I already tried this solution without succes.

Thanks for reading.

Body:
After many attempts i finally succeeded.

@Entity
@Table(name = "CLIENT")
public class Client {

    @Id
    private int id;

    @OneToOne(mappedBy = "client")
    private ClientConfiguration configuration

    // some getter and setter
}

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(name = "TYPE")
public abstract class ClientConfiguration {

    @Id
    private int id;

    @Column(name = "TYPE")
    private String type;

    @OneToOne
    @MapsId
    protected Client client;

    // getters and setters
}

@Entity(name = "CLIENT_CONF_A")
public class ClientConfigurationA extends ClientConfiguration { ... }

@Entity(name = "CLIENT_CONF_B")
public class ClientConfigurationB extends ClientConfiguration { ... }


问:
Is there a way to make R strings verbatim (not escaped)?
Typical example:

```<code>path <- "C:/test/path" # great
path <- "C:\\test\\path" # also great
path <- "C:\test\path"
</code>```

Error: '\p' is an unrecognized escape in character string starting ""C:\test\p"

(of course - \t is actually an escape character.)

Is there any mark that can be used to treat the string as verbatim? Or can it be coded?

It would be really useful when copy/pasting path names in Windows...

答:
If you are copying and pasting in windows, you can set up a file connection to the clipboard.  Then you can use scan to read from it, with allowEscapes turned off.  However, Windows allows spaces in file paths, and scan doesn't understand that, so you have to wrap the result in paste0 with collapse set to a 0-length character string.

```<code>x = file(description = "clipboard")
y = paste0(scan(file = x, what = "character", allowEscapes = F), collapse = "")
</code>```

Unfortunately, this only works for the path currently in the clipboard, so if you are copying and pasting lots of paths into an R script, this is not a solution.  A workaround in that situation would be to paste each path into a separate text file and save it.  Then, in your main script, you could run the following

```<code>y = paste0(scan(file = "path1.txt", what = "character", allowEscapes = F), collapse = "")
</code>```

You would probably need one saved file for each path.

Body:
Typical example:

path <- "C:/test/path" # great
path <- "C:\\test\\path" # also great
path <- "C:\test\path"

Error: '\p' is an unrecognized escape in character string starting ""C:\test\p"

(of course - \t is actually an escape character.)

Is there any mark that can be used to treat the string as verbatim? Or can it be coded?

It would be really useful when copy/pasting path names in Windows...

Body:
If you are copying and pasting in windows, you can set up a file connection to the clipboard.  Then you can use scan to read from it, with allowEscapes turned off.  However, Windows allows spaces in file paths, and scan doesn't understand that, so you have to wrap the result in paste0 with collapse set to a 0-length character string.

x = file(description = "clipboard")
y = paste0(scan(file = x, what = "character", allowEscapes = F), collapse = "")

Unfortunately, this only works for the path currently in the clipboard, so if you are copying and pasting lots of paths into an R script, this is not a solution.  A workaround in that situation would be to paste each path into a separate text file and save it.  Then, in your main script, you could run the following

y = paste0(scan(file = "path1.txt", what = "character", allowEscapes = F), collapse = "")

You would probably need one saved file for each path.


问:
Fixing the pointcut definition error while defining an aspect for tracing the RabbitMQ send
The opentracing instrumentation for spring-rabbitmq doesn't have an aspect defined for tracing the org.springframework.amqp.rabbit.core.RabbitTemplate#send. Here is the link of the code: RabbitMqSendTracingAspect.java

I tried implementing it and got some serious errors while defining a pointcut.

Here is my code for the same:

@Aspect
@Configuration
public class AmqpSendTracingAspect {
    private final Tracer tracer;

    public AmqpSendTracingAspect(Tracer tracer) {
        this.tracer = tracer;
    }

    @Around(value = "execution(* org.springframework.amqp.core.AmqpTemplate.send(..)) " +
            "&& args(exchange,routingKey, message)",
            argNames = "pjp,exchange,routingKey,message")
    public Object traceAmqpSend(ProceedingJoinPoint pjp,
        String exchange, String routingKey, Message message) throws Throwable {

        final Object[] args = pjp.getArgs();

        System.out.println("Aspect RUnning");

        final MessageProperties messageProperties = message.getMessageProperties();

        Scope scope = AmqpTracingUtils.buildSendSpan(tracer, messageProperties);
        tracer.inject(
                scope.span().context(),
                Format.Builtin.TEXT_MAP,
                new AmqpInjectAdapter(messageProperties));

        AmqpSpanDecorator spanDecorator = new AmqpSpanDecorator();
        spanDecorator.onSend(messageProperties, exchange, routingKey, scope.span());

        args[2] = message;

        try {
            return pjp.proceed(args);
        } catch (Exception ex) {
            spanDecorator.onError(ex, scope.span());
            throw ex;
        } finally {
            scope.close();
        }
    }
}

```

<p>I am getting the following errors from <code>CglibAopProxy</code> framework even when I annotated with <code>@EnableAspectJAutoProxy(proxyTargetClass = false)</code></p>

```Unable to proxy interface-implementing method [public final void org.springframework.amqp.rabbit.core.RabbitTemplate.start()] because it is marked as final: Consider using interface-based JDK proxies instead!

Unable to proxy interface-implementing method [public final void org.springframework.amqp.rabbit.core.RabbitTemplate.stop()] because it is marked as final: Consider using interface-based JDK proxies instead!
```

Please help me out!

答:
It's not an error. the code producing that message is like this:

```<code>if (implementsInterface(method, ifcs)) {
                        logger.info("Unable to proxy interface-implementing method [" + method + "] because " +
                                "it is marked as final: Consider using interface-based JDK proxies instead!");
                    }
</code>```

So, it is an info and it fully doesn't stop your application to work afterward. Just a pointer that RabbitTemplate.start() method is not going to be proxied, which definitely should not be. So, you are good so far.

I think since you use Spring Cloud, you are not able to override the AOP config with that @EnableAspectJAutoProxy therefore it always uses CglibAopProxy.

I would just ignore that info. Would be better do not such a logging level for framework categories.

Body:
The opentracing instrumentation for spring-rabbitmq doesn't have an aspect defined for tracing the org.springframework.amqp.rabbit.core.RabbitTemplate#send. Here is the link of the code: RabbitMqSendTracingAspect.java

I tried implementing it and got some serious errors while defining a pointcut.

Here is my code for the same:

@Aspect
@Configuration
public class AmqpSendTracingAspect {
    private final Tracer tracer;

    public AmqpSendTracingAspect(Tracer tracer) {
        this.tracer = tracer;
    }

    @Around(value = "execution(* org.springframework.amqp.core.AmqpTemplate.send(..)) " +
            "&& args(exchange,routingKey, message)",
            argNames = "pjp,exchange,routingKey,message")
    public Object traceAmqpSend(ProceedingJoinPoint pjp,
        String exchange, String routingKey, Message message) throws Throwable {

        final Object[] args = pjp.getArgs();

        System.out.println("Aspect RUnning");

        final MessageProperties messageProperties = message.getMessageProperties();

        Scope scope = AmqpTracingUtils.buildSendSpan(tracer, messageProperties);
        tracer.inject(
                scope.span().context(),
                Format.Builtin.TEXT_MAP,
                new AmqpInjectAdapter(messageProperties));

        AmqpSpanDecorator spanDecorator = new AmqpSpanDecorator();
        spanDecorator.onSend(messageProperties, exchange, routingKey, scope.span());

        args[2] = message;

        try {
            return pjp.proceed(args);
        } catch (Exception ex) {
            spanDecorator.onError(ex, scope.span());
            throw ex;
        } finally {
            scope.close();
        }
    }
}

I am getting the following errors from CglibAopProxy framework even when I annotated with @EnableAspectJAutoProxy(proxyTargetClass = false)

Unable to proxy interface-implementing method [public final void org.springframework.amqp.rabbit.core.RabbitTemplate.start()] because it is marked as final: Consider using interface-based JDK proxies instead!

Unable to proxy interface-implementing method [public final void org.springframework.amqp.rabbit.core.RabbitTemplate.stop()] because it is marked as final: Consider using interface-based JDK proxies instead!

Please help me out!

Body:
It's not an error. the code producing that message is like this:

if (implementsInterface(method, ifcs)) {
                        logger.info("Unable to proxy interface-implementing method [" + method + "] because " +
                                "it is marked as final: Consider using interface-based JDK proxies instead!");
                    }

So, it is an info and it fully doesn't stop your application to work afterward. Just a pointer that RabbitTemplate.start() method is not going to be proxied, which definitely should not be. So, you are good so far.

I think since you use Spring Cloud, you are not able to override the AOP config with that @EnableAspectJAutoProxy therefore it always uses CglibAopProxy.

I would just ignore that info. Would be better do not such a logging level for framework categories.