问:
i am getting a deprecated API error in my project
I have been getting an error while creating a WebView in android studio, the error says the API is deprecated. I'm adding the code of my file. I think it would be easy to find, but I have no experience in android so I'm not able to find the error.

I have read about the updates of the android / java but could not find this

```<code>import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
private WebView MywebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MywebView = (WebView) findViewById(R.id.view2);
    WebSettings webSettings = MywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    MywebView.loadUrl("http://www.ynaps.com");

    MywebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel:")) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }else{
                return false;
            }
        }
    });

}

@Override
public void onBackPressed() {
    if (MywebView.canGoBack()) {
        MywebView.goBack();
    } else {
        super.onBackPressed();
    }
}
 }
</code>```

I should not get this error:

```<code> E:\APP\pro\sdddd-
 dunia\app\src\main\java\com\business\ynaps_app\MainActivity.java:
  uses or overrides a deprecated API.
  Recompile with -Xlint:deprecation for details.
</code>```

答:
You must use shouldOverrideUrlLoading(WebView view, WebResourceRequest request) instead of shouldOverrideUrlLoading(WebView view, String url) which has been deprecated in API 24.
You can check the doc page here.

Body:
I have been getting an error while creating a WebView in android studio, the error says the API is deprecated. I'm adding the code of my file. I think it would be easy to find, but I have no experience in android so I'm not able to find the error.

I have read about the updates of the android / java but could not find this

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
private WebView MywebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MywebView = (WebView) findViewById(R.id.view2);
    WebSettings webSettings = MywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    MywebView.loadUrl("http://www.ynaps.com");

    MywebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel:")) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }else{
                return false;
            }
        }
    });

}

@Override
public void onBackPressed() {
    if (MywebView.canGoBack()) {
        MywebView.goBack();
    } else {
        super.onBackPressed();
    }
}
 }

I should not get this error:

 E:\APP\pro\sdddd-
 dunia\app\src\main\java\com\business\ynaps_app\MainActivity.java:
  uses or overrides a deprecated API.
  Recompile with -Xlint:deprecation for details.


来源: stackexchange

问:
How to connect html file with a js file from node_modules?
I'm trying to add \node_modules\sip.js\dist\sip.min.js , to my html file. I tried to import like import * as SIP from 'sip.js/dist/sip'; in my component.ts but this work only if I call some function from it. But I need my html file to read this sip.min.js.

Also I tried to download local this files and added in my html file

```<code>       <script src="js/sip-0.5.0.js"></script>
       <script src="js/ua.js"></script>
</code>```

and added:

```<code>   public loadScript() {
        console.log("preparing to load...");
        let node = document.createElement('script');
        node.src = this.url;
         node.type = "text/javascript";
        node.async = true;
        node.charset = "utf-8";
        document.getElementsByTagName("head")[0].appendChild(node);
   }

   ngOnInit() {
        this.loadAPI = new Promise(resolve => {
            console.log("resolving promise...");
            this.loadScript();
        });
   }
</code>```

But this is not working

答:
You could add them to body.  Also your paths should be available  from client side. But adding scripts in Init event is bad practice - it is added each time as component is created. I have added scripts in service - it executes once.

```<code>     const files = ['js/sip-0.5.0.js','js/ua.js']
     files.forEach((file) => {
                const fileRef = document.createElement('script');
                fileRef.setAttribute('type', 'text/javascript');
                fileRef.setAttribute('src',  file);
                fileRef.onload = function () {
                    console.log('loaded' + file);
                };
                document.body.appendChild(fileRef);
            });
</code>```

But this approach is good only for dynamic adding scripts based on some condition. If your scripts are independent from other files you could just add it to bundle file without any manually struggling.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add \node_modules\sip.js\dist\sip.min.js , to my html file. I tried to import like import * as SIP from 'sip.js/dist/sip'; in my component.ts but this work only if I call some function from it. But I need my html file to read this sip.min.js.

Also I tried to download local this files and added in my html file

and added:

   public loadScript() {
        console.log("preparing to load...");
        let node = document.createElement('script');
        node.src = this.url;
         node.type = "text/javascript";
        node.async = true;
        node.charset = "utf-8";
        document.getElementsByTagName("head")[0].appendChild(node);
   }

   ngOnInit() {
        this.loadAPI = new Promise(resolve => {
            console.log("resolving promise...");
            this.loadScript();
        });
   }

But this is not working

Body:
You could add them to body.  Also your paths should be available  from client side. But adding scripts in Init event is bad practice - it is added each time as component is created. I have added scripts in service - it executes once.

     const files = ['js/sip-0.5.0.js','js/ua.js']
     files.forEach((file) => {
                const fileRef = document.createElement('script');
                fileRef.setAttribute('type', 'text/javascript');
                fileRef.setAttribute('src',  file);
                fileRef.onload = function () {
                    console.log('loaded' + file);
                };
                document.body.appendChild(fileRef);
            });

But this approach is good only for dynamic adding scripts based on some condition. If your scripts are independent from other files you could just add it to bundle file without any manually struggling.


问:
How to verify presence of a modal dialog
I have a webpage that has a button to download a file. Once clicking the button there appears a modal dialog popup which has no buttons for 'Ok' or 'Cancel' it is just informative dialog that says 'Generating the debuginfo file. Please wait.'. In my ui testing I need to check for the presence of that dialog. The html code for this modal dialog is as provided below. How should I check the presence of the dialog?

I have tried using Alert class and using Alert(driver).switch_to.alert() and Alert(driver).dismiss() and accept()
I have also tried

```<code>WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "id_value")))
</code>```

EDIT: edited to add actual code.

The html code for this element has following parameters:

```<code>     <div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable" style="position: fixed; height: auto; width: 400px; top: 143px; left: 555.5px; display: block;" tabindex="-1" role="dialog" aria-describedby="dialog" aria-labelledby="ui-id-1">
      <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
      <span id="ui-id-1" class="ui-dialog-title">Download debug info</span>
      <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">
        <span class="ui-button-icon-primary ui-icon ui-icon-closethick">
        </span>
        <span class="ui-button-text">close</span>
      </button>
    </div>
    <div id="dialog" class="ui-dialog-content ui-widget-content" style="width: auto; min-height: 0px; max-height: none; height: 177px;">
      <br>Generating the debuginfo file. Please wait.</div>
      <div class="ui-resizable-handle ui-resizable-n" style="z-index: 90;">
      </div>
      <div class="ui-resizable-handle ui-resizable-e" style="z-index: 90;">
      </div>
      <div class="ui-resizable-handle ui-resizable-s" style="z-index: 90;">
      </div>
      <div class="ui-resizable-handle ui-resizable-w" style="z-index: 90;">
      </div>
      <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90;">
      </div>
      <div class="ui-resizable-handle ui-resizable-sw" style="z-index: 90;">
      </div>
      <div class="ui-resizable-handle ui-resizable-ne" style="z-index: 90;">
      </div>
      <div class="ui-resizable-handle ui-resizable-nw" style="z-index: 90;">

  </div>
</code>```

答:
The desired element is with a Modal Dialog Box so to locate and extract the element text Generating the debuginfo file. Please wait. you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ui-dialog-content.ui-widget-content#dialog"))).get_attribute("innerHTML").split(">")[1])
</code>```

Using XPATH:

```<code>print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='ui-dialog-content ui-widget-content' and @id='dialog']"))).get_attribute("innerHTML").split(">")[1])
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
I have a webpage that has a button to download a file. Once clicking the button there appears a modal dialog popup which has no buttons for 'Ok' or 'Cancel' it is just informative dialog that says 'Generating the debuginfo file. Please wait.'. In my ui testing I need to check for the presence of that dialog. The html code for this modal dialog is as provided below. How should I check the presence of the dialog?

I have tried using Alert class and using Alert(driver).switch_to.alert() and Alert(driver).dismiss() and accept()
I have also tried

WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "id_value")))

EDIT: edited to add actual code.

The html code for this element has following parameters:

      Download debug info
      <button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close" role="button" aria-disabled="false" title="close">

        close
      </button>

Generating the debuginfo file. Please wait.

Body:
The desired element is with a Modal Dialog Box so to locate and extract the element text Generating the debuginfo file. Please wait. you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.ui-dialog-content.ui-widget-content#dialog"))).get_attribute("innerHTML").split(">")[1])

Using XPATH:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='ui-dialog-content ui-widget-content' and @id='dialog']"))).get_attribute("innerHTML").split(">")[1])

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Defining shared Prometheus alerts with different alert thresholds per service
I have defined some alerts with expressions that look like this:

```<code>sum(rate(some_error_metric[1m])) BY (namespace,application) > 10
sum(rate(some_other_error_metric[1m])) BY (namespace,application) > 10
...
</code>```

The above alerts currently fire when any of our applications emit these metrics at a rate of more than 10 per minute.

Rather than hard-coding a threshold of 10, I want to be able to specify a different threshold for each application.

e.g. application_1 should alert at a rate of 10 per minute, application_2 should alert at a rate of 20 per minute, etc.

Is this possible without duplicating the alerts for each application?

This stackoverflow question: Dynamic label values in Promethues alerting rules suggests that it might be possible to achieve what I want using recording rules, however following the pattern suggested in the only answer to this question results in recording rules that Prometheus doesn't seem to be able to parse:

```<code>  - record: application_1_warning_threshold
    expr: warning_threshold{application="application_1"} 10
  - record: application_2_warning_threshold
    expr: warning_threshold{application="application_2"} 20
  ...
</code>```

答:
Here's my configuration for a TasksMissing alert with varying per-job thresholds:

```<code>groups:
- name: availability.rules
  rules:

  # Expected number of tasks per job and environment.
  - record: job_env:up:count
    expr: count(up) without (instance)

  # Actually up and running tasks per job and environment.
  - record: job_env:up:sum
    expr: sum(up) without (instance)

  # Ratio of up and running to expected tasks per job and environment.
  - record: job_env:up:ratio
    expr: job_env:up:sum / job_env:up:count

  # Global warning and critical availability ratio thresholds.
  - record: job:up:ratio_warning_threshold
    expr: 0.7
  - record: job:up:ratio_critical_threshold
    expr: 0.5

  # Job-specific warning and critical availability ratio thresholds.

  # Always alert if one Prometheus instance is down.
  - record: job:up:ratio_critical_threshold
    labels:
      job: prometheus
    expr: 0.99

  # Never alert for some-batch-job instances down:
  - record: job:up:ratio_warning_threshold
    labels:
      job: some-batch-job
    expr: 0
  - record: job:up:ratio_critical_threshold
    labels:
      job: some-batch-job
    expr: 0

  # TasksMissing is fired when a certain percentage of tasks belonging to a job are down. Namely:
  #
  #     job_env:up:ratio < job:up:ratio_(warning|critical)_threshold
  #
  # with a job-specific warning/critical threshold when defined, or the global default otherwise.

  - alert: TasksMissing
    expr: |
      # Default warning threshold is < 70%
        job_env:up:ratio
      < on(job) group_left()
        (
            job:up:ratio_warning_threshold
          or on(job)
              count by(job) (job_env:up:ratio) * 0
            + on() group_left()
              job:up:ratio_warning_threshold{job=""}
        )
    for: 2m
    labels:
      severity: warning
    annotations:
      summary: Tasks missing for {{ $labels.job }} in {{ $labels.env }}
      description:
       '...'

  - alert: TasksMissing
    expr: |
      # Default critical threshold is < 50%
        job_env:up:ratio
      < on(job) group_left()
        (
            job:up:ratio_critical_threshold
          or on(job)
              count by(job) (job_env:up:ratio) * 0
            + on() group_left()
              job:up:ratio_critical_threshold{job=""}
        )
    for: 2m
    labels:
      severity: critical
    annotations:
      summary: Tasks missing for {{ $labels.job }} in {{ $labels.env }}
      description:
       '...'

</code>```

Body:
I have defined some alerts with expressions that look like this:

sum(rate(some_error_metric[1m])) BY (namespace,application) > 10
sum(rate(some_other_error_metric[1m])) BY (namespace,application) > 10
...

The above alerts currently fire when any of our applications emit these metrics at a rate of more than 10 per minute.

Rather than hard-coding a threshold of 10, I want to be able to specify a different threshold for each application.

e.g. application_1 should alert at a rate of 10 per minute, application_2 should alert at a rate of 20 per minute, etc.

Is this possible without duplicating the alerts for each application?

This stackoverflow question: Dynamic label values in Promethues alerting rules suggests that it might be possible to achieve what I want using recording rules, however following the pattern suggested in the only answer to this question results in recording rules that Prometheus doesn't seem to be able to parse:

  - record: application_1_warning_threshold
    expr: warning_threshold{application="application_1"} 10
  - record: application_2_warning_threshold
    expr: warning_threshold{application="application_2"} 20
  ...

Body:
Here's my configuration for a TasksMissing alert with varying per-job thresholds:

groups:
- name: availability.rules
  rules:

  # Expected number of tasks per job and environment.
  - record: job_env:up:count
    expr: count(up) without (instance)

  # Actually up and running tasks per job and environment.
  - record: job_env:up:sum
    expr: sum(up) without (instance)

  # Ratio of up and running to expected tasks per job and environment.
  - record: job_env:up:ratio
    expr: job_env:up:sum / job_env:up:count

  # Global warning and critical availability ratio thresholds.
  - record: job:up:ratio_warning_threshold
    expr: 0.7
  - record: job:up:ratio_critical_threshold
    expr: 0.5

  # Job-specific warning and critical availability ratio thresholds.

  # Always alert if one Prometheus instance is down.
  - record: job:up:ratio_critical_threshold
    labels:
      job: prometheus
    expr: 0.99

  # Never alert for some-batch-job instances down:
  - record: job:up:ratio_warning_threshold
    labels:
      job: some-batch-job
    expr: 0
  - record: job:up:ratio_critical_threshold
    labels:
      job: some-batch-job
    expr: 0

  # TasksMissing is fired when a certain percentage of tasks belonging to a job are down. Namely:
  #
  #     job_env:up:ratio < job:up:ratio_(warning|critical)_threshold
  #
  # with a job-specific warning/critical threshold when defined, or the global default otherwise.

  - alert: TasksMissing
    expr: |
      # Default warning threshold is < 70%
        job_env:up:ratio
      < on(job) group_left()
        (
            job:up:ratio_warning_threshold
          or on(job)
              count by(job) (job_env:up:ratio) * 0
            + on() group_left()
              job:up:ratio_warning_threshold{job=""}
        )
    for: 2m
    labels:
      severity: warning
    annotations:
      summary: Tasks missing for {{ $labels.job }} in {{ $labels.env }}
      description:
       '...'

  - alert: TasksMissing
    expr: |
      # Default critical threshold is < 50%
        job_env:up:ratio
      < on(job) group_left()
        (
            job:up:ratio_critical_threshold
          or on(job)
              count by(job) (job_env:up:ratio) * 0
            + on() group_left()
              job:up:ratio_critical_threshold{job=""}
        )
    for: 2m
    labels:
      severity: critical
    annotations:
      summary: Tasks missing for {{ $labels.job }} in {{ $labels.env }}
      description:
       '...'


问:
Why different result of HoughLines of opencv in java and c++
I am new to Opencv and I am reading the book named OpenCV 3.0 Computer Vision
with Java from Daniel Lélis Baggio. I test a image from opencv site that tries to detect lines but I got different result with only one line detection with Daniel Lélis Baggio java code. I don't know why this code doesn't work properly. The Code from the book:

```<code>else if(houghString.equals(operation)){
        Mat canny = new Mat();
        Imgproc.Canny(originalImage, canny,10 , 50, aperture, false);
        image = originalImage.clone();
        Mat lines = new Mat();

        Imgproc.HoughLines(canny, lines, 1, Math.PI/180, lowThreshold);

        for( int i = 0; i < lines.cols(); i++ )
        {
          double rho = lines.get(0, i)[0];
          double theta = lines.get(0, i)[1];
          Point pt1 = new Point(), pt2= new Point();
          double a = Math.cos(theta), b = Math.sin(theta);
          double x0 = a*rho, y0 = b*rho;
          pt1.x = Math.round(x0 + 1000*(-b));
          pt1.y = Math.round(y0 + 1000*(a));
          pt2.x = Math.round(x0 - 1000*(-b));
          pt2.y = Math.round(y0 - 1000*(a));
          Imgproc.line( image, pt1, pt2, new Scalar(255,0,0), 2, Core.LINE_AA,0);
        }
    }
else if(pHoughString.equals(operation)){
        Mat canny = new Mat();
        Imgproc.Canny(originalImage, canny,10 , 50, aperture, false);
        //canny = originalImage.clone();
        image = originalImage.clone();

        //Imgproc.cvtColor(image, image, Imgproc.COLOR_GRAY2BGR);

    Mat lines = new Mat();

    Imgproc.HoughLinesP(canny, lines, 1, 360,  lowThreshold, 50, 5 );
    for( int i = 0; i < lines.cols(); i++ )
    {
        double a = lines.get(0, i)[0];
        double b = lines.get(0, i)[1];
        double c = lines.get(0, i)[2];
        double d = lines.get(0, i)[3];
        Imgproc.line( image, new Point(a, b), new Point(c, d), new Scalar(0,0,255), 1, Core.LINE_AA,0);

    }
</code>```

And the code from opencv site for c++ is below:

```<code>Mat dst, cdst;
 Canny(src, dst, 50, 200, 3);
 cvtColor(dst, cdst, CV_GRAY2BGR);

 #if 0
  vector<Vec2f> lines;
  HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );

  for( size_t i = 0; i < lines.size(); i++ )
  {
 float rho = lines[i][0], theta = lines[i][1];
 Point pt1, pt2;
 double a = cos(theta), b = sin(theta);
 double x0 = a*rho, y0 = b*rho;
 pt1.x = cvRound(x0 + 1000*(-b));
 pt1.y = cvRound(y0 + 1000*(a));
 pt2.x = cvRound(x0 - 1000*(-b));
 pt2.y = cvRound(y0 - 1000*(a));
 line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
  }
 #else
  vector<Vec4i> lines;
  HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
  for( size_t i = 0; i < lines.size(); i++ )
  {
  Vec4i l = lines[i];
line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
  }
 #endif
</code>```

The result from Java code:

and the result from opencv site:

Why are different results from an image with java and c++?

答:
It's late but I just hit the same szenario and it may help some other...

lines are returned in rows not columns, so correct loop should be:

```<code>for( int i = 0; i < lines.rows(); i++ ) {
      double rho = lines.get(i, 0)[0];
      double theta = lines.get(i, 0)[1];
      ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Opencv and I am reading the book named OpenCV 3.0 Computer Vision
with Java from Daniel Lélis Baggio. I test a image from opencv site that tries to detect lines but I got different result with only one line detection with Daniel Lélis Baggio java code. I don't know why this code doesn't work properly. The Code from the book:

else if(houghString.equals(operation)){
        Mat canny = new Mat();
        Imgproc.Canny(originalImage, canny,10 , 50, aperture, false);
        image = originalImage.clone();
        Mat lines = new Mat();

        Imgproc.HoughLines(canny, lines, 1, Math.PI/180, lowThreshold);

        for( int i = 0; i < lines.cols(); i++ )
        {
          double rho = lines.get(0, i)[0];
          double theta = lines.get(0, i)[1];
          Point pt1 = new Point(), pt2= new Point();
          double a = Math.cos(theta), b = Math.sin(theta);
          double x0 = a*rho, y0 = b*rho;
          pt1.x = Math.round(x0 + 1000*(-b));
          pt1.y = Math.round(y0 + 1000*(a));
          pt2.x = Math.round(x0 - 1000*(-b));
          pt2.y = Math.round(y0 - 1000*(a));
          Imgproc.line( image, pt1, pt2, new Scalar(255,0,0), 2, Core.LINE_AA,0);
        }
    }
else if(pHoughString.equals(operation)){
        Mat canny = new Mat();
        Imgproc.Canny(originalImage, canny,10 , 50, aperture, false);
        //canny = originalImage.clone();
        image = originalImage.clone();

        //Imgproc.cvtColor(image, image, Imgproc.COLOR_GRAY2BGR);

    Mat lines = new Mat();

    Imgproc.HoughLinesP(canny, lines, 1, 360,  lowThreshold, 50, 5 );
    for( int i = 0; i < lines.cols(); i++ )
    {
        double a = lines.get(0, i)[0];
        double b = lines.get(0, i)[1];
        double c = lines.get(0, i)[2];
        double d = lines.get(0, i)[3];
        Imgproc.line( image, new Point(a, b), new Point(c, d), new Scalar(0,0,255), 1, Core.LINE_AA,0);

    }

And the code from opencv site for c++ is below:

Mat dst, cdst;
 Canny(src, dst, 50, 200, 3);
 cvtColor(dst, cdst, CV_GRAY2BGR);

 #if 0
  vector<Vec2f> lines;
  HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );

  for( size_t i = 0; i < lines.size(); i++ )
  {
 float rho = lines[i][0], theta = lines[i][1];
 Point pt1, pt2;
 double a = cos(theta), b = sin(theta);
 double x0 = a*rho, y0 = b*rho;
 pt1.x = cvRound(x0 + 1000*(-b));
 pt1.y = cvRound(y0 + 1000*(a));
 pt2.x = cvRound(x0 - 1000*(-b));
 pt2.y = cvRound(y0 - 1000*(a));
 line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
  }
 #else
  vector<Vec4i> lines;
  HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
  for( size_t i = 0; i < lines.size(); i++ )
  {
  Vec4i l = lines[i];
line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
  }
 #endif

The result from Java code:

and the result from opencv site:

Why are different results from an image with java and c++?

Body:
It's late but I just hit the same szenario and it may help some other...

lines are returned in rows not columns, so correct loop should be:

for( int i = 0; i < lines.rows(); i++ ) {
      double rho = lines.get(i, 0)[0];
      double theta = lines.get(i, 0)[1];
      ...
}


问:
How to get table name for a simple Sequel Dataset object?
Ie, given a dataset object ds = DB[:transactions].where{updated_at > 1.day.ago} - no funny joins and stuff going on - how could I fetch the table name (:transactions) ?

答: If you want the first table in the dataset, you can use ds.first_source.


问:
compare two lists to get non matching elements
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

```<code>len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890
</code>```

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

答:
The answer you linked to suggests using sets, because they use hashes to look thing up quickly.
With lists, and in, like

```<code>new_list = [i for i in h if i not in y]
</code>```

the whole of list y needs checking each time for each i in h.

You could use sets, but as has been pointed out need to be careful with duplicates getting lost.

You could use a Counter:

```<code>from collections import Counter
</code>```

the with two lists, say

```<code>l1 = [1,1,2,3,4]
l2 = [3,3,4,5,6]
</code>```

for examples' sake, can use fed into a Counter each

```<code>>>> Counter(l1)
Counter({1: 2, 2: 1, 3: 1, 4: 1})
>>> Counter(l2)
Counter({3: 2, 4: 1, 5: 1, 6: 1})
</code>```

This just walks each list once.
Subtracting them gives what's in the first but not the second:

```<code>>>> Counter(l1)-Counter(l2)
Counter({1: 2, 2: 1})
</code>```

The elements tell you what you want

```<code>>>> diff = Counter(l1)-Counter(l2)
>>> list(diff.elements())
[1, 1, 2]
</code>```

Body:
I checked this comparing lists, Only one answer is relative to what I am trying to do. I have to lists with some similiar elements, I want to get the non -matching elements.

len(h) = 1973182  #h[0] = 'B00006J8F4F2', y[0] = 'B0075Y2X2GO6'
len(y) = 656890

I am doing

new_list = [i for i in h if i not in y],however this takes about 13 minutes to do, Is there a faster way of doing this?

In refer to "duplicate" question, Finding elements not in a list, I use the same code, What I am looking for is a faster way of doing it.

Body:
The answer you linked to suggests using sets, because they use hashes to look thing up quickly.
With lists, and in, like

new_list = [i for i in h if i not in y]

the whole of list y needs checking each time for each i in h.

You could use sets, but as has been pointed out need to be careful with duplicates getting lost.

You could use a Counter:

from collections import Counter

the with two lists, say

l1 = [1,1,2,3,4]
l2 = [3,3,4,5,6]

for examples' sake, can use fed into a Counter each

>>> Counter(l1)
Counter({1: 2, 2: 1, 3: 1, 4: 1})
>>> Counter(l2)
Counter({3: 2, 4: 1, 5: 1, 6: 1})

This just walks each list once.
Subtracting them gives what's in the first but not the second:

>>> Counter(l1)-Counter(l2)
Counter({1: 2, 2: 1})

The elements tell you what you want

>>> diff = Counter(l1)-Counter(l2)
>>> list(diff.elements())
[1, 1, 2]


问:
Nodejs not able to concurrently access a file from two apps
I have two nodejs apps. One is writing logs to a file using rotating-file-stream.
The second app needs to consume these logs and process by reading the log file as it is changing. Basically I am trying to setup a crude disk based queue. The issue I am seeing is that the consumer app is not able to see the logs until the stream from producer app is closed.

On this consumer app I tried fs.watch, chokidar and tail (I am not even getting change event). However, when I tried running 'tail -f' on the terminal that is able to pick up changes right away.

答: From what I found it seems like it is a platform related issue, which in my case is macOS. Using fs.watchFile instead of fs.watch fixed the issue. Thankfully the libraries I am using (chokidar and tail) provides api flags to do just that. </p>


问:
Converting from BTC to another currency
From Coinbase API can you convert from Bitcoin to, for example, USDC? I cannot see any reference but I have this feature on the app. I wonder if API supports (or expects support for) this operation, or it just that I'm missing something.</p>

答:
Looking at the Coinbase API PRO Documentation you can create a conversion by:

HTTP REQUEST

POST /conversions

API KEY PERMISSIONS

This endpoint requires the “trade” permission.

Request

{

"from": "USD",

"to": "USDC",

"amount": "10000.00"
}

PARAMETERS

from:   A valid currency id

to:     A valid currency id

amount: Amount of from to convert to to

Probably more of a question of what the valid currencies are

Title: Converting from BTC to another currency


问:
How to set locale to child locals (e.g. en-GB, en-US or fr-CA) with locales in react-intl v2
I am trying to use react-intl in order to localise a react app.

It is set up and works with all parent locales such as EN, DE, FR etc. I can view the child locales such as en-GB and en-US, however, I cannot display them in the browser.

This is how I am importing the locale at the moment:

import en from 'react-intl/locale-data/en';

I would expect react-intl to be able to go into the child locale automatically, is this not the case?

Any help welcome!

答:
It should be worked. do you use addLocaleData?

https://codesandbox.io/s/reactintl-formattedtime-s09vo?fontsize=14


问:
Invert of a shift operation - determine shift count used to generate value
I have code that generates a value from an initial value of 1 by using a left shift. At a different point in the code, I know the value generated and need to calculate the shift count used to generate the value.

In other words I need to determine the shift count used to generate the result of a shift operation by performing an operation on the value generated.

Is it possible to invert a shift operation of a base two variable without using a dedicated function? I am looking for the value of a shift count variable y when the shifted value, x, and result of the shift operation, z, are known.

Example:

```<code>x << y = z
1 << 6 = 64

z = 64 and x is 1 but what is y???  // how to calculate y, the shift count?
</code>```

There are many solutions including log(64)/log(2), but I would have to use math.h. I am looking for some sort of bitwise operation that is fast and doesn't require a function.

EDIT: Thank you for your answers! My question is answered, there is no way to this with a simple operation, my compiler does not have CTZ. BR

答:
Assuming you know x and z from z = x << y, and want to find out y using bitwise operations, a simple way would be to take x and shift it one bit at a time, comparing the result to z (i.e., start from y = 0 and increment y by one after each failed comparison).

edit: On the other hand, if x is 1 (or indeed if x has the lowest bit set), you can also count the trailing zeroes in z. Your processor may have a single instruction for this, which your C compiler may expose as a non-portable extension, such as __builtin_ctz (you could consider using the pre-processor to toggle between this and a portable solution). There are also faster, portable solutions to this problem than the trivial loop – search for "count trailing zeroes".

(In cases where x does not have the lowest bit set, one might count the trailing zeroes in both x and z to find out the difference.)

Body:
I have code that generates a value from an initial value of 1 by using a left shift. At a different point in the code, I know the value generated and need to calculate the shift count used to generate the value.

In other words I need to determine the shift count used to generate the result of a shift operation by performing an operation on the value generated.

Is it possible to invert a shift operation of a base two variable without using a dedicated function? I am looking for the value of a shift count variable y when the shifted value, x, and result of the shift operation, z, are known.

Example:

x << y = z
1 << 6 = 64

z = 64 and x is 1 but what is y???  // how to calculate y, the shift count?

There are many solutions including log(64)/log(2), but I would have to use math.h. I am looking for some sort of bitwise operation that is fast and doesn't require a function.

EDIT: Thank you for your answers! My question is answered, there is no way to this with a simple operation, my compiler does not have CTZ. BR


问:
System.Net.HttpListenerException: Failed to listen on prefix 'http://localhost:8080
I am running the following code from Scott Allen's ASP.Net Fundamentals course

```<code>using System;
using Microsoft.Owin.Hosting;
using Owin;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string uri = "http://localhost:8080";
            using (WebApp.Start<Startup>(uri))
            {
                Console.WriteLine("Started!");
                Console.ReadKey();
                Console.WriteLine("Stopping!");
            }
        }
    }

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseWelcomePage();
            //app.Run(
            //  ctx => ctx.Response.WriteAsync("Hello Owin!"));
        }
    }
}
</code>```

However when I run the console app I get a message

```<code>    Unhandled Exception: System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation. ---> System.Net.HttpListenerExceptio
n: Failed to listen on prefix 'http://localhost:8080/' because it conflicts with
 an existing registration on the machine.
   at System.Net.HttpListener.AddAllPrefixes()
   at System.Net.HttpListener.Start()
   at Microsoft.Owin.Host.HttpListener.OwinHttpListener.Start(HttpListener liste
ner, Func`2 appFunc, IList`1 addresses, IDictionary`2 capabilities, Func`2 logge
rFactory)
   at Microsoft.Owin.Host.HttpListener.OwinServerFactory.Create(Func`2 app, IDic
tionary`2 properties)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments,
 Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Objec
t[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invoke
Attr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter.Create(IAppBuild
er builder)
   at Microsoft.Owin.Hosting.Engine.HostingEngine.StartServer(StartContext conte
xt)
   at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
   at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions opt
ions)
   at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider service
s, StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.Start[TStartup](String url)
   at ConsoleApplication1.Program.Main(String[] args) in e:\EShared\Dev2015\WebA
ppScottAllen\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
Press any key to continue . . .
</code>```

I ran the Resource Monitor from the Task Manager Performance Tab and can see that there are 2 entries on Listening Ports for 8080.

Both have Image=System, PID=4, IPv6 unspecified, Protocol TCP, Firewall Status Not allowed, not restricted

I am new to Listening Ports, how do I get the code working?

答: I had the same issue, and it was a silly fix. I had other console apps open that was using the same port number, so after I have closed all the console apps, I was able to run and did not get this error. </p>

Body:
I am running the following code from Scott Allen's ASP.Net Fundamentals course

using System;
using Microsoft.Owin.Hosting;
using Owin;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string uri = "http://localhost:8080";
            using (WebApp.Start<Startup>(uri))
            {
                Console.WriteLine("Started!");
                Console.ReadKey();
                Console.WriteLine("Stopping!");
            }
        }
    }

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseWelcomePage();
            //app.Run(
            //  ctx => ctx.Response.WriteAsync("Hello Owin!"));
        }
    }
}

However when I run the console app I get a message

    Unhandled Exception: System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation. ---> System.Net.HttpListenerExceptio
n: Failed to listen on prefix 'http://localhost:8080/' because it conflicts with
 an existing registration on the machine.
   at System.Net.HttpListener.AddAllPrefixes()
   at System.Net.HttpListener.Start()
   at Microsoft.Owin.Host.HttpListener.OwinHttpListener.Start(HttpListener liste
ner, Func`2 appFunc, IList`1 addresses, IDictionary`2 capabilities, Func`2 logge
rFactory)
   at Microsoft.Owin.Host.HttpListener.OwinServerFactory.Create(Func`2 app, IDic
tionary`2 properties)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments,
 Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Objec
t[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invoke
Attr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter.Create(IAppBuild
er builder)
   at Microsoft.Owin.Hosting.Engine.HostingEngine.StartServer(StartContext conte
xt)
   at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
   at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions opt
ions)
   at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider service
s, StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
   at Microsoft.Owin.Hosting.WebApp.Start[TStartup](String url)
   at ConsoleApplication1.Program.Main(String[] args) in e:\EShared\Dev2015\WebA
ppScottAllen\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
Press any key to continue . . .

I ran the Resource Monitor from the Task Manager Performance Tab and can see that there are 2 entries on Listening Ports for 8080.

Both have Image=System, PID=4, IPv6 unspecified, Protocol TCP, Firewall Status Not allowed, not restricted

I am new to Listening Ports, how do I get the code working?


问:
How can I pass variable into an evaluate function?
I'm trying to pass a variable into a page.evaluate() function in Puppeteer, but when I use the following very simplified example, the variable evalVar is undefined.

I can't find any examples to build on, so I need help passing that variable into the page.evaluate() function so I can use it inside.

```<code>const puppeteer = require('puppeteer');

(async() => {

  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  const evalVar = 'WHUT??';

  try {

    await page.goto('https://www.google.com.au');
    await page.waitForSelector('#fbar');
    const links = await page.evaluate((evalVar) => {

      console.log('evalVar:', evalVar); // appears undefined

      const urls = [];
      hrefs = document.querySelectorAll('#fbar #fsl a');
      hrefs.forEach(function(el) {
        urls.push(el.href);
      });
      return urls;
    })
    console.log('links:', links);

  } catch (err) {

    console.log('ERR:', err.message);

  } finally {

    // browser.close();

  }

})();
</code>```

答:
It took me quite a while to figure out that console.log() in evaluate() can't show in node console.

Ref: https://github.com/GoogleChrome/puppeteer/issues/1944

everything that is run inside the page.evaluate function is done in the context of the browser page. The script is running in the browser not in node.js so if you log it will show in the browsers console which if you are running headless you will not see. You also can't set a node breakpoint inside the function.

Hope this can help.

Body:
I'm trying to pass a variable into a page.evaluate() function in Puppeteer, but when I use the following very simplified example, the variable evalVar is undefined.

I can't find any examples to build on, so I need help passing that variable into the page.evaluate() function so I can use it inside.

const puppeteer = require('puppeteer');

(async() => {

  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();

  const evalVar = 'WHUT??';

  try {

    await page.goto('https://www.google.com.au');
    await page.waitForSelector('#fbar');
    const links = await page.evaluate((evalVar) => {

      console.log('evalVar:', evalVar); // appears undefined

      const urls = [];
      hrefs = document.querySelectorAll('#fbar #fsl a');
      hrefs.forEach(function(el) {
        urls.push(el.href);
      });
      return urls;
    })
    console.log('links:', links);

  } catch (err) {

    console.log('ERR:', err.message);

  } finally {

    // browser.close();

  }

})();


问:
Module six not found, although module six is installed
I cannot run jupyter lab as it complains about module six. Module six is already installed with conda. I even tried to install with pip too, but it says it is already installed and doesn't do anything. So, what to do here?

```<code>jupyter lab
Traceback (most recent call last):
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\ilyas\Anaconda3\Scripts\jupyter-lab.EXE\__main__.py", line 5, in <module>
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyterlab\labapp.py", line 11, in <module>
    from jupyter_core.application import JupyterApp, base_aliases
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyter_core\application.py", line 30, in <module>
    from traitlets.config.application import Application, catch_config_error
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\__init__.py", line 1, in <module>
    from .traitlets import *
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\traitlets.py", line 57, in <module>
    import six
ModuleNotFoundError: No module named 'six'
</code>```

I tried to remove with conda, and then re-install but that also did not work:

```<code>conda remove six
RemoveError: This operation will remove conda without replacing it with
another version of conda.
</code>```

Install with pip:

```<code>pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)

python -m pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)
</code>```

Environment:

Windows 10

python 3.7

jupyter-lab 1.0.0a3

six 1.12.0

答:
you are installing six for Python 2, but trying to use it from Python 3.

install for Python 3 with:

python3 -m pip install six

Body:
I cannot run jupyter lab as it complains about module six. Module six is already installed with conda. I even tried to install with pip too, but it says it is already installed and doesn't do anything. So, what to do here?

jupyter lab
Traceback (most recent call last):
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\ilyas\anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\ilyas\Anaconda3\Scripts\jupyter-lab.EXE\__main__.py", line 5, in <module>
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyterlab\labapp.py", line 11, in <module>
    from jupyter_core.application import JupyterApp, base_aliases
  File "c:\users\ilyas\anaconda3\lib\site-packages\jupyter_core\application.py", line 30, in <module>
    from traitlets.config.application import Application, catch_config_error
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\__init__.py", line 1, in <module>
    from .traitlets import *
  File "c:\users\ilyas\anaconda3\lib\site-packages\traitlets\traitlets.py", line 57, in <module>
    import six
ModuleNotFoundError: No module named 'six'

I tried to remove with conda, and then re-install but that also did not work:

conda remove six
RemoveError: This operation will remove conda without replacing it with
another version of conda.

Install with pip:

pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)

python -m pip install six
Requirement already satisfied: six in c:\users\ilyas\anaconda3\lib\site-packages (1.12.0)

Environment:

Windows 10

python 3.7

jupyter-lab 1.0.0a3

six 1.12.0


问:
How can I render a component in React to 2 different components?
I'm working on a ReactJS project. I have 3 components in the main page "Index component" as follows,

Nav-
Featured-
Footer

My Nav component has 2 links to 2 different components.
My Switch is as follows,

```<code>  <Switch>
      <Route path="/home" component={props => <Index {...props} />} />
      <Route path="/register" component={Register} />
      <Route path="/login" component={Login} />
      <Route path="/cart" component={Cart} />
      <Redirect from="/" to="home" />
  </Switch>
</code>```

I also have my Index component as follows,

```<code>   <React.Fragment>
       <Search />
       <Nav history={history} />
    {this.homePageComponents()}
       <Route
      path="/home/bedding"
      component={props => (
        <Bedding beddingProducts={this.beddingProducts()} {...props} />
      )}
    />
       <Route
      path="/home/bath"
      component={props => (
        <Bath bathProducts={this.bathProducts()} {...props} />
      )}
    />
       <Route path="/home/search" component={Search} />
  </React.Fragment>
</code>```

I'm trying to render the Nav component to both Bath and Bedding products but whenever I import it and use it there it gives me an Error saying this.props.history.replace is undefined.
This is the project's link.
https://github.com/MaxOffline/beetle

答:
If you console.log(this.props) in the render method of nav.jsx you'll see that it contains a history object but that there is no replace method on that object.

You may be looking for the this.props.history.push method?

Body:
I'm working on a ReactJS project. I have 3 components in the main page "Index component" as follows,

Nav-
Featured-
Footer

My Nav component has 2 links to 2 different components.
My Switch is as follows,

  <Switch>
      <Route path="/home" component={props => <Index {...props} />} />
      <Route path="/register" component={Register} />
      <Route path="/login" component={Login} />
      <Route path="/cart" component={Cart} />
      <Redirect from="/" to="home" />
  </Switch>

I also have my Index component as follows,

   <React.Fragment>
       <Search />

    {this.homePageComponents()}
       <Route
      path="/home/bedding"
      component={props => (
        <Bedding beddingProducts={this.beddingProducts()} {...props} />
      )}
    />
       <Route
      path="/home/bath"
      component={props => (
        <Bath bathProducts={this.bathProducts()} {...props} />
      )}
    />
       <Route path="/home/search" component={Search} />
  </React.Fragment>

I'm trying to render the Nav component to both Bath and Bedding products but whenever I import it and use it there it gives me an Error saying this.props.history.replace is undefined.
This is the project's link.
https://github.com/MaxOffline/beetle


问:
Trying to return both the value and innerText of Angular select option
Here is an example of my payload

```<code>    0: { category: “BRAINS”,
        description: "test 1234124”,
        userNumber: “789456123”,
        accountType: “WOW”,
        balance: {amount: 12.34, currency: “USD”},
        uniqueId: “47823748923hfhjfew32847hw43879=” },

1: { category: “DIET”,
        description: "test 1234124”, userNumber: “123456789”,
        accountType: “WOW”,
        balance: {amount: 43.21, currency: “GBP”},
        uniqueId: “47823748923hfhjfew32847hw43879=” },

    2: { category: “MEAT”,
        description: "test 1234124”,
        userNumber: “951234679”,
        accountType: “WOW”,
        balance: {amount: 26.56, currency: “EUR”},
        uniqueId: “47823748923hfhjfew32847hw43879=” },
</code>```

I want to return both the value and the inner text of the select option,
so both the value ‘uniqueId’ and the inner text ‘userNumber’

My HTML

```<code><select #category="ngModel" name=“user” id=“user” class="form-control" #test [(ngModel)]="model.user” (change)="doSomething(test.value)">
    <option *ngFor="let user of users” [value]=“user.uniqueId”>
       {{user.userNumber}}
    </option>
</select>
</code>```

My .ts file

```<code>doSomething(value) {
      console.log(value);
      // returns the value 47823748923hfhjfew32847hw43879=
}

    onAddValue() {
          console.log('yoyoyoy', this.model);
         // returns {value: undefined, uniqueId: "47823748923hfhjfew32847hw43879="}
          console.log('accountNumber', this.model.user); //returns 47823748923hfhjfew32847hw43879=
}
</code>```

Trying to return both the value and innerText of Angular select option

Basically this is what I want to be able to do

http://jsfiddle.net/5bzkfwrt/

答:
you need to change this:

```<code> (change)="doSomething($event,test.value)"
</code>```

in .ts

```<code>doSomething(event,value) {
      console.log(value);

}
</code>```

Body:
Here is an example of my payload

    0: { category: “BRAINS”,
        description: "test 1234124”,
        userNumber: “789456123”,
        accountType: “WOW”,
        balance: {amount: 12.34, currency: “USD”},
        uniqueId: “47823748923hfhjfew32847hw43879=” },

1: { category: “DIET”,
        description: "test 1234124”, userNumber: “123456789”,
        accountType: “WOW”,
        balance: {amount: 43.21, currency: “GBP”},
        uniqueId: “47823748923hfhjfew32847hw43879=” },

    2: { category: “MEAT”,
        description: "test 1234124”,
        userNumber: “951234679”,
        accountType: “WOW”,
        balance: {amount: 26.56, currency: “EUR”},
        uniqueId: “47823748923hfhjfew32847hw43879=” },

I want to return both the value and the inner text of the select option,
so both the value ‘uniqueId’ and the inner text ‘userNumber’

My HTML

<select #category="ngModel" name=“user” id=“user” class="form-control" #test [(ngModel)]="model.user” (change)="doSomething(test.value)">
    <option *ngFor="let user of users” [value]=“user.uniqueId”>
       {{user.userNumber}}
    </option>
</select>

My .ts file

doSomething(value) {
      console.log(value);
      // returns the value 47823748923hfhjfew32847hw43879=
}

    onAddValue() {
          console.log('yoyoyoy', this.model);
         // returns {value: undefined, uniqueId: "47823748923hfhjfew32847hw43879="}
          console.log('accountNumber', this.model.user); //returns 47823748923hfhjfew32847hw43879=
}

Trying to return both the value and innerText of Angular select option

Basically this is what I want to be able to do

http://jsfiddle.net/5bzkfwrt/

Body:
you need to change this:

 (change)="doSomething($event,test.value)"

in .ts

doSomething(event,value) {
      console.log(value);

}


问:
Make Jackson more friendly for input JSON
Do I have a way to make Jackson less exacting to the input JSON. E.g. JSONObject provides following allowances:

The constructors are more forgiving in the texts they will accept:

An extra , (comma) may appear just before the closing brace.

Strings may be quoted with ' (single quote).

Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.*

Keys can be followed by = or => as well as by :.

Values can be followed by ; (semicolon) as well as by , (comma).

Numbers may have the 0x- (hex) prefix.

The most interesting for me is 3rd point. It allows to following conversion:

```<code>new JSONObject("{A : 1}");
</code>```

... but for jackson I will get an error with the same input json:

```<code>new ObjectMapper().readTree("{ A : 1}"); // throws an exception
</code>```

Exception:

```<code>org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): was expecting double-quote to start field name
   at [Source: java.io.StringReader@26d4f1; line: 1, column: 4]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:943)
at org.codehaus.jackson.impl.JsonParserBase._reportError(JsonParserBase.java:636)
at org.codehaus.jackson.impl.JsonParserBase._reportUnexpectedChar(JsonParserBase.java:569)
at org.codehaus.jackson.impl.ReaderBasedParser._handleUnusualFieldName(ReaderBasedParser.java:342)
at org.codehaus.jackson.impl.ReaderBasedParser._parseFieldName(ReaderBasedParser.java:235)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:125)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:180)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeAny(JsonNodeDeserializer.java:210)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:52)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:13)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1130)
</code>```

答:
List of extensions for non-standard JSON (i.e. stuff that is NOT JSON, but is close enough that it can be supported) can be found from: http://wiki.fasterxml.com/JacksonFeaturesNonStandard

From your list, (2) and (3) can be done (plus couple of other things not listed, like commnets). Others are not supported; and although project has added support for some extensions that are commonly used, there are limits to what will be considered. It is always possible to ask for new features of course; features are added based on request, use cases.

In my personal opinion one should either follow the standard, or define new formats -- HTML is a good example of rat holes one gets to when trying to support things that are "almost but not quite" valid. There is no end to tweaks, and interoperability suffers: since there is no standard, all implementations support some non-compatible subsets of features and constructs.

Body:
Do I have a way to make Jackson less exacting to the input JSON. E.g. JSONObject provides following allowances:

The constructors are more forgiving in the texts they will accept:

An extra , (comma) may appear just before the closing brace.

Strings may be quoted with ' (single quote).

Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.*

Keys can be followed by = or => as well as by :.

Values can be followed by ; (semicolon) as well as by , (comma).

Numbers may have the 0x- (hex) prefix.

The most interesting for me is 3rd point. It allows to following conversion:

new JSONObject("{A : 1}");

... but for jackson I will get an error with the same input json:

new ObjectMapper().readTree("{ A : 1}"); // throws an exception

Exception:

org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): was expecting double-quote to start field name
   at [Source: java.io.StringReader@26d4f1; line: 1, column: 4]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:943)
at org.codehaus.jackson.impl.JsonParserBase._reportError(JsonParserBase.java:636)
at org.codehaus.jackson.impl.JsonParserBase._reportUnexpectedChar(JsonParserBase.java:569)
at org.codehaus.jackson.impl.ReaderBasedParser._handleUnusualFieldName(ReaderBasedParser.java:342)
at org.codehaus.jackson.impl.ReaderBasedParser._parseFieldName(ReaderBasedParser.java:235)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:125)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:180)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeAny(JsonNodeDeserializer.java:210)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:52)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:13)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1130)


问:
i am getting a deprecated API error in my project
I have been getting an error while creating a WebView in android studio, the error says the API is deprecated. I'm adding the code of my file. I think it would be easy to find, but I have no experience in android so I'm not able to find the error.

I have read about the updates of the android / java but could not find this

```<code>import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
private WebView MywebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MywebView = (WebView) findViewById(R.id.view2);
    WebSettings webSettings = MywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    MywebView.loadUrl("http://www.ynaps.com");

    MywebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel:")) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }else{
                return false;
            }
        }
    });

}

@Override
public void onBackPressed() {
    if (MywebView.canGoBack()) {
        MywebView.goBack();
    } else {
        super.onBackPressed();
    }
}
 }
</code>```

I should not get this error:

```<code> E:\APP\pro\sdddd-
 dunia\app\src\main\java\com\business\ynaps_app\MainActivity.java:
  uses or overrides a deprecated API.
  Recompile with -Xlint:deprecation for details.
</code>```

答:
Error is fairly self explanatory. Your class have deprected method shouldOverrideUrlLoading. If you're not aware what does this mean either of the following link will help you understand.
Is it wrong to use Deprecated methods or classes in Java?
What does it mean for a method to be deprecated?

Some of the suggested solutions:

Essentially, you might just get over this error by adding jvm argument specified in error -Xlint:deprecation.

If that does does not help you can indicate JVM explicitly instructing method is deprecated with @Deprecated annotation.

Lower the jdk/jre (Jvm) to the version in which method is not yet deprecated

Correct solution is to update you code with removing usage of deprecated method and replace it with associated alternative method.

Body:
I have been getting an error while creating a WebView in android studio, the error says the API is deprecated. I'm adding the code of my file. I think it would be easy to find, but I have no experience in android so I'm not able to find the error.

I have read about the updates of the android / java but could not find this

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
private WebView MywebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MywebView = (WebView) findViewById(R.id.view2);
    WebSettings webSettings = MywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    MywebView.loadUrl("http://www.ynaps.com");

    MywebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("tel:")) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }else{
                return false;
            }
        }
    });

}

@Override
public void onBackPressed() {
    if (MywebView.canGoBack()) {
        MywebView.goBack();
    } else {
        super.onBackPressed();
    }
}
 }

I should not get this error:

 E:\APP\pro\sdddd-
 dunia\app\src\main\java\com\business\ynaps_app\MainActivity.java:
  uses or overrides a deprecated API.
  Recompile with -Xlint:deprecation for details.


问:
R Loop To Make New Vectors
```<code>data = data.frame("id"=c(1,2,3,4,5,6,7,8,9,10),
                  "group"=c(1,1,2,1,2,2,2,2,1,2),
                  "type"=c(1,1,2,3,2,2,3,3,3,1),
                  "score1"=c(sample(1:4,10,r=T)),
                  "score2"=c(sample(1:4,10,r=T)),
                  "score3"=c(sample(1:4,10,r=T)),
                  "score4"=c(sample(1:4,10,r=T)),
                  "score5"=c(sample(1:4,10,r=T)),
                  "weight1"=c(173,109,136,189,186,146,173,102,178,174),
                  "weight2"=c(147,187,125,126,120,165,142,129,144,197),
                  "weight3"=c(103,192,102,159,128,179,195,193,135,145),
                  "weight4"=c(114,182,199,101,111,116,198,123,119,181),
                  "weight5"=c(159,125,104,171,166,154,197,124,180,154))
</code>```

That is a sample of my data. I want population-weighted counts of the score variable like so:

```<code>count(data, score1, wt = weight1)
count(data, score2, wt = weight2)
count(data, score3, wt = weight3)
count(data, score4, wt = weight4)
count(data, score5, wt = weight5)
</code>```

However I aim to make a loop of a type such that, I can do this for every combination of 'group' and 'type' for scores1-5 and store these in separate vectors such that

```<code>vec1 = weighted score variable for scores1-5 for group = 1 and type = 1
vec2 = weighted score variable for scores1-5 for group = 1 and type = 2
vec3 = weighted score variable for scores1-5 for group = 1 and type = 3
</code>```

and so on and so forth.

答:
I am not sure to understand exactly what is your expected output but you might want to try something like this :</p>

```<code>for (i in 1:max(data[["group"]])) { #looping through groups
  weighted_score <- ... ## create your wheighted score for group i here

  name <- paste("vec",i,sep="")
  assign(name,weighted_score)

}
</code>```

Title: R Loop To Make New Vectors

Body:
data = data.frame("id"=c(1,2,3,4,5,6,7,8,9,10),
                  "group"=c(1,1,2,1,2,2,2,2,1,2),
                  "type"=c(1,1,2,3,2,2,3,3,3,1),
                  "score1"=c(sample(1:4,10,r=T)),
                  "score2"=c(sample(1:4,10,r=T)),
                  "score3"=c(sample(1:4,10,r=T)),
                  "score4"=c(sample(1:4,10,r=T)),
                  "score5"=c(sample(1:4,10,r=T)),
                  "weight1"=c(173,109,136,189,186,146,173,102,178,174),
                  "weight2"=c(147,187,125,126,120,165,142,129,144,197),
                  "weight3"=c(103,192,102,159,128,179,195,193,135,145),
                  "weight4"=c(114,182,199,101,111,116,198,123,119,181),
                  "weight5"=c(159,125,104,171,166,154,197,124,180,154))

That is a sample of my data. I want population-weighted counts of the score variable like so:

count(data, score1, wt = weight1)
count(data, score2, wt = weight2)
count(data, score3, wt = weight3)
count(data, score4, wt = weight4)
count(data, score5, wt = weight5)

However I aim to make a loop of a type such that, I can do this for every combination of 'group' and 'type' for scores1-5 and store these in separate vectors such that

vec1 = weighted score variable for scores1-5 for group = 1 and type = 1
vec2 = weighted score variable for scores1-5 for group = 1 and type = 2
vec3 = weighted score variable for scores1-5 for group = 1 and type = 3

and so on and so forth.

Body:
I am not sure to understand exactly what is your expected output but you might want to try something like this :

for (i in 1:max(data[["group"]])) { #looping through groups
  weighted_score <- ... ## create your wheighted score for group i here

  name <- paste("vec",i,sep="")
  assign(name,weighted_score)

}


问:
thymeleaf Cannot aggregate on iterable containing nulls
I am trying to use thymeleaf aggregate utility to find sum of salary from list as below

```<code>th:text="${#aggregates.sum(myList.![salary])}"
</code>```

here myList is list of MyObjct as below

```<code>List<MyObject> myList;

public class MyObject{

private String name;
private double salary;
//getter setter
}
</code>```

Everything works fine until salary is null on each item of list. On that case i am getting error
java.lang.IllegalArgumentException: Cannot aggregate on iterable containing nulls

How can i check if all items of list are null to prevent this error.

答:
Use collection selection first to eliminate entries with a null salary.

```<code>${#aggregates.sum(myList.?[salary != null].![salary])}
</code>```

Collection selection creates a new list where each element satisfies the condition.  In this case, I'm creating a new list from myList where each item in the list has a non-null salary (salary != null).

Body:
I am trying to use thymeleaf aggregate utility to find sum of salary from list as below

th:text="${#aggregates.sum(myList.![salary])}"

here myList is list of MyObjct as below

List<MyObject> myList;

public class MyObject{

private String name;
private double salary;
//getter setter
}

Everything works fine until salary is null on each item of list. On that case i am getting error
java.lang.IllegalArgumentException: Cannot aggregate on iterable containing nulls

How can i check if all items of list are null to prevent this error.

Body:
Use collection selection first to eliminate entries with a null salary.

${#aggregates.sum(myList.?[salary != null].![salary])}

Collection selection creates a new list where each element satisfies the condition.  In this case, I'm creating a new list from myList where each item in the list has a non-null salary (salary != null).


答:
I think you can solve your issue with using "withRouter" wrapper component which react-router provide to wrap your Nav component.

https://reacttraining.com/react-router/web/api/withRouter

Title: How can I render a component in React to 2 different components?


问:
What is the best way to get the result through Java8 function?
I need to filter elements and then sort based on certain column. Post that I would need to find the unique entries based on combination of columns. Since it is file processing, pipe(|) is used as delimiter to denote the column value.

```<code>String s1= "12|Thor|Asgaurd|1000000|Avenger|Active"
String s2= "234|Iron man|New York|9999999|Avenger|Active"
String s3= "420|Loki|Asgaurd|||Inactive"
String s4= "12|Thor|Asgaurd Bank|1000000|Avenger HQ|Active"
</code>```

Data first needs to be filtered based on the Active/Inactive status. Then it needs to be sorted based on 4th column. Lastly, the uniqueness needs to be maintained by combining column 1,2,3.

Expected Output =

```<code>"234|Iron man|New York|9999999|Avenger|Active"
"12|Thor|Asgaurd|1000000|Avenger|Active"
</code>```

答:
Creating a model class and parsing the string is the way to go, but if for some reaseon you don't want to do that you can do it this way:</p>

```<code>import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

List<String> result = Stream.of(s1, s2, s3, s4)
            .filter(s -> s.split("\\|")[5].equals("Active"))
            .sorted(Comparator.comparing(e -> e.split("\\|")[4]))
            .collect(Collectors.toList());
</code>```

Body:
I need to filter elements and then sort based on certain column. Post that I would need to find the unique entries based on combination of columns. Since it is file processing, pipe(|) is used as delimiter to denote the column value.

String s1= "12|Thor|Asgaurd|1000000|Avenger|Active"
String s2= "234|Iron man|New York|9999999|Avenger|Active"
String s3= "420|Loki|Asgaurd|||Inactive"
String s4= "12|Thor|Asgaurd Bank|1000000|Avenger HQ|Active"

Data first needs to be filtered based on the Active/Inactive status. Then it needs to be sorted based on 4th column. Lastly, the uniqueness needs to be maintained by combining column 1,2,3.

Expected Output =

"234|Iron man|New York|9999999|Avenger|Active"
"12|Thor|Asgaurd|1000000|Avenger|Active"

Body:
Creating a model class and parsing the string is the way to go, but if for some reaseon you don't want to do that you can do it this way:

import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

List<String> result = Stream.of(s1, s2, s3, s4)
            .filter(s -> s.split("\\|")[5].equals("Active"))
            .sorted(Comparator.comparing(e -> e.split("\\|")[4]))
            .collect(Collectors.toList());


问:
How to create a custom EditText layout?
I want to create an EditText like  the Image below.

This is what I want to achieve

This is my code (in the xml file of the layout):

<EditText
            android:id="@+id/newThoughtThoughtText"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:background="@drawable/lines"
            android:gravity="top"
            android:hint="@string/thought_first_text"
            android:inputType="textMultiLine"
            android:maxLines="15"
            android:textColor="@color/color_gray"   />
```

<p>I have created a custom drawable layout file. But this only enables me to have one line at the end, and I need several lines inside the EditText.
How can I do this?</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <stroke
            android:width="1dp"
            android:color="@color/color_gray" />
        </shape>
    </item>
</layer-list>
</code>```

Thanks in advance!

答:
I managed to solve the problem and to design the editText as wished.

This topic helped me:

Android - How to make all lines in an edittext underlined?

I created my own custom EditText:

```<code>package com.example.appsiety.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;

import com.example.appsiety.R;

public class EditTextThought extends android.support.v7.widget.AppCompatEditText {
    private Paint mPaint = new Paint();
    private Context context;

    public EditTextThought(Context context) {
        super(context);
        this.context = context;
        initPaint();
    }

    public EditTextThought(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initPaint();
    }

    public EditTextThought(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        initPaint();
    }

    private void initPaint() {
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(ContextCompat.getColor(context, R.color.color_gray));
    }

    @Override protected void onDraw(Canvas canvas) {
        int left = getLeft();
        int right = getRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int height = getHeight();
        int lineHeight = getLineHeight();
        int count = (height-paddingTop-paddingBottom) / lineHeight;

        for (int i = 0; i < count*2; i++) {
            int baseline = lineHeight * (i+1) + paddingTop;
            canvas.drawLine(left+paddingLeft, baseline, right-paddingRight, baseline, mPaint);
        }

        super.onDraw(canvas);
    }
}
</code>```

and then in my layout file i used it:

```<code><view
class="com.example.appsiety.utils.EditTextThought"
            android:id="@+id/newThoughtSituationText"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:scrollbars="vertical"
            android:fadingEdge="vertical"
            android:gravity="top"
            android:textSize="18sp"
            android:fontFamily="@font/opensans_light"
            android:textColorHint="@color/color_gray"
            android:textColor="@color/color_gray"
            android:hint="@string/situation_first_text"
            android:background="@android:color/transparent"
            android:inputType="textMultiLine|textVisiblePassword"
            />
</code>```

Title: How to create a custom EditText layout?

Body:
I want to create an EditText like  the Image below.

This is what I want to achieve

This is my code (in the xml file of the layout):

<EditText
            android:id="@+id/newThoughtThoughtText"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:background="@drawable/lines"
            android:gravity="top"
            android:hint="@string/thought_first_text"
            android:inputType="textMultiLine"
            android:maxLines="15"
            android:textColor="@color/color_gray"   />

I have created a custom drawable layout file. But this only enables me to have one line at the end, and I need several lines inside the EditText.
How can I do this?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <stroke
            android:width="1dp"
            android:color="@color/color_gray" />
        </shape>
    </item>
</layer-list>

Thanks in advance!

Body:
I managed to solve the problem and to design the editText as wished.

This topic helped me:

Android - How to make all lines in an edittext underlined?

I created my own custom EditText:

package com.example.appsiety.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;

import com.example.appsiety.R;

public class EditTextThought extends android.support.v7.widget.AppCompatEditText {
    private Paint mPaint = new Paint();
    private Context context;

    public EditTextThought(Context context) {
        super(context);
        this.context = context;
        initPaint();
    }

    public EditTextThought(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initPaint();
    }

    public EditTextThought(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        initPaint();
    }

    private void initPaint() {
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(ContextCompat.getColor(context, R.color.color_gray));
    }

    @Override protected void onDraw(Canvas canvas) {
        int left = getLeft();
        int right = getRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int height = getHeight();
        int lineHeight = getLineHeight();
        int count = (height-paddingTop-paddingBottom) / lineHeight;

        for (int i = 0; i < count*2; i++) {
            int baseline = lineHeight * (i+1) + paddingTop;
            canvas.drawLine(left+paddingLeft, baseline, right-paddingRight, baseline, mPaint);
        }

        super.onDraw(canvas);
    }
}

and then in my layout file i used it:

<view
class="com.example.appsiety.utils.EditTextThought"
            android:id="@+id/newThoughtSituationText"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:scrollbars="vertical"
            android:fadingEdge="vertical"
            android:gravity="top"
            android:textSize="18sp"
            android:fontFamily="@font/opensans_light"
            android:textColorHint="@color/color_gray"
            android:textColor="@color/color_gray"
            android:hint="@string/situation_first_text"
            android:background="@android:color/transparent"
            android:inputType="textMultiLine|textVisiblePassword"
            />


问:
Convert PNG to SVG using python
Is there way to convert a png file into SVG file using only pure python or a python module such as wand?

To be more precise, I want to convert a png into a real vector graphics, I don't want to embed a bitmap inside the svg, I want to convert into graphics code.

I know this is possible with Illustrator or Inkscape, but I need an automated process.

Thank you !

答:
I would suggest using potrace for python.

Use this link: https://pypi.org/project/pypotrace/

Here is the documentation: https://pythonhosted.org/pypotrace/ref.html#

Like This:

```<code>from potrace import Bitmap

# Initialize data, for example convert a PIL image to a numpy array
# [...]

bitmap = Bitmap(data)
path = bitmap.trace()
</code>```

Title: Convert PNG to SVG using python

Body:
I would suggest using potrace for python.

Use this link: https://pypi.org/project/pypotrace/

Here is the documentation: https://pythonhosted.org/pypotrace/ref.html#

Like This:

from potrace import Bitmap

# Initialize data, for example convert a PIL image to a numpy array
# [...]

bitmap = Bitmap(data)
path = bitmap.trace()


问:
Host does not start
For some reason, the host stopped running.

Previously, the console wrote that everything was OK and the application was running on a specific IP, but now nothing is written and API methods are not available:

There was an error connecting to
  http://localhost:20019/api/User/Authorize)

At the same time, no exceptions. The only thing that I recently changed is the password in the account. If something was not enough, it should have been a timeout. What could be the problem?

```<code> var host = new WebHostBuilder()
        .CaptureStartupErrors(false)
        .UseConfiguration(config)
        .UseHttpSys(options =>
        {
            options.Authentication.Schemes =
                AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
            options.UrlPrefixes.Add("http://*:20019");
            options.MaxRequestBodySize = config.GetValue<long?>("maxRequestBodySize");

        })
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .Build();
    var initializer = host.Services.GetService<IRepositoryInitializer>();
    initializer.Init();
    host.Run();
</code>```

答:
After an hour of waiting, the message appeared and the API started working.

All the following launches of the application began to be performed instantly.

Magick...

Title: Host does not start

Body:
For some reason, the host stopped running.

Previously, the console wrote that everything was OK and the application was running on a specific IP, but now nothing is written and API methods are not available:

There was an error connecting to
  http://localhost:20019/api/User/Authorize)

At the same time, no exceptions. The only thing that I recently changed is the password in the account. If something was not enough, it should have been a timeout. What could be the problem?

 var host = new WebHostBuilder()
        .CaptureStartupErrors(false)
        .UseConfiguration(config)
        .UseHttpSys(options =>
        {
            options.Authentication.Schemes =
                AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
            options.UrlPrefixes.Add("http://*:20019");
            options.MaxRequestBodySize = config.GetValue<long?>("maxRequestBodySize");

        })
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .Build();
    var initializer = host.Services.GetService<IRepositoryInitializer>();
    initializer.Init();
    host.Run();


问:
In-memory vs persistent state stores in Kafka Streams?
I've read the stateful stream processing overview and if I understand correctly, one of the main reasons why the RocksDB is being used as a default implementation of the key value store is a fact, that unlike in-memory collections, it can handle data larger than the available memory, because it can flush to disk. Both types of stores can survive application restarts, because the data is backed up as a Kafka topic.

But are there other differences? For example, I've noticed that my persistent state store creates some .log files for each topic partition, but they're all empty.

In short, I'm wondering what are the performance benefits and possible risks of replacing persistent stores with in-memory ones.

答:
I don't see any real reason to swap current RocksDB store. In fact RocksDB one of the fastest k,v store:
Percona benchmarks (based on RocksDB)

with in-memory ones - RocksDB already acts as in-memory with some LRU algorithms involved:

RocksDB architecture

The three basic constructs of RocksDB are memtable, sstfile and logfile. The memtable is an in-memory data structure - new writes are inserted into the memtable and are optionally written to the logfile.

But there is one more noticeable reason for choosing this implementation:

RocksDB source code

If you will look at source code ratio - there are a lot of Java api exposed from C++ code. So, it's much simpler to integrate this product in existing Java - based Kafka ecosystem with comprehensive control over store, using exposed api.


问:
Linux command to know the number of active db connections at any point of time in postgres?
Is there any postgresql command or linux command that can be run as cron job to know the number of active connections at any point of time? I have a flask application running which is integrated with gps logging in every 15 minutes via the mobile app built using Ionic framework. </p>

答:
Query pg_stat_activity:

```<code>psql -c "select count(*) from pg_stat_activity" -t
</code>```

Add any necessary connection params (-h, -U, etc). Auth is a little trickier - if you trust the environment, you can use a .pgpass file.

Other notes -

The -t limits output to the tuple itself

You can get some other useful info with different groupings or predicates. For example: select datname, count(*) from pg_stat_activity group by datname

Hope that helps.

Body:
Query pg_stat_activity:

psql -c "select count(*) from pg_stat_activity" -t

Add any necessary connection params (-h, -U, etc). Auth is a little trickier - if you trust the environment, you can use a .pgpass file.

Other notes -

The -t limits output to the tuple itself

You can get some other useful info with different groupings or predicates. For example: select datname, count(*) from pg_stat_activity group by datname

Hope that helps.


问:
Require a field if other field has value
I have 3 field which is bank_name, account_name and account_number. How can I  require other two fields if one of them has value? my validation for now looks like this:

```<code>validate = [
    'account_name' => ['sometimes','nullable', 'max:50'],
    'bank_name' => ['sometimes','nullable', 'max:50'],
    'account_number' => ['sometimes','nullable', 'max:50'],
];
</code>```

How can I possibly attain this one?

答:
You can use required_with:

```<code>$validate = [
    'account_name' => ['sometimes','nullable', 'max:50', 'required_with:bank_name,account_number'],
    'bank_name' => ['sometimes','nullable', 'max:50', 'required_with:account_name,account_number'],
    'account_number' => ['sometimes','nullable', 'max:50', 'required_with:account_name,bank_name'],
];
</code>```

With the rules above, when one of the 3 fields has a value, the two other ones would be required.

For more information: https://laravel.com/docs/5.8/validation#rule-required-with

Body:
I have 3 field which is bank_name, account_name and account_number. How can I  require other two fields if one of them has value? my validation for now looks like this:

validate = [
    'account_name' => ['sometimes','nullable', 'max:50'],
    'bank_name' => ['sometimes','nullable', 'max:50'],
    'account_number' => ['sometimes','nullable', 'max:50'],
];

How can I possibly attain this one?

Body:
You can use required_with:

$validate = [
    'account_name' => ['sometimes','nullable', 'max:50', 'required_with:bank_name,account_number'],
    'bank_name' => ['sometimes','nullable', 'max:50', 'required_with:account_name,account_number'],
    'account_number' => ['sometimes','nullable', 'max:50', 'required_with:account_name,bank_name'],
];

With the rules above, when one of the 3 fields has a value, the two other ones would be required.

For more information: https://laravel.com/docs/5.8/validation#rule-required-with


问:
Is there any method like __init_subclass__() before python 3.6
When I read Python Cookbook 3rd Edition recipe 9.18, I ran into a class definition with parent Class and some optional argument, and I looked it up. I know that Python 3.6 added a new feature __init_subclass__() method for parent class, but the book is written based on Python 3.3, so what method will take these arguments other than a metaclass?

The class definition is here:

```<code>class Spam(Base, debug=True, typecheck=False):
    ...
</code>```

I know that metaclass can accept other optional arguments in its' __prepare__, __new__, __init__ method, but Base is a parent class, where do these arguments go?

答:
The __init_subclass__ is an addition to Python 3.6 to reduce the need for custom metaclasses, as many of its uses are "overkill".
The idea is that each subclass that is created for a (normal, non-meta) base-class that contains an __init_subclass__ method, it willbe called, with the new subclass as first parameter:

```<code>class Base:
   def __init_subclass__(subclass, debug=None, typecheck=None, **kwargs):
        # do stuff with the optional debug and typecheck arguments
        # Pass possible arguments not consumed here to superclasses, if any:
        super().__init_subclass__(**kwargs)
</code>```

And there is no need for a metaclass at all - the __prepare__, __init__ and __new__ of the default metaclass - type - will ignore any named argument passed in this way. But the default __init_subclass__ in object will raise if unknown named arguments reach it - the pattern above will consume these arguments, removing them from kwargs. If you are dealing with unknown named arguments, just process kwargs like a normal dictionary - no need for explicit named parameters in the __init_subclass__.

Body:
When I read Python Cookbook 3rd Edition recipe 9.18, I ran into a class definition with parent Class and some optional argument, and I looked it up. I know that Python 3.6 added a new feature __init_subclass__() method for parent class, but the book is written based on Python 3.3, so what method will take these arguments other than a metaclass?

The class definition is here:

class Spam(Base, debug=True, typecheck=False):
    ...

I know that metaclass can accept other optional arguments in its' __prepare__, __new__, __init__ method, but Base is a parent class, where do these arguments go?

Body:
The __init_subclass__ is an addition to Python 3.6 to reduce the need for custom metaclasses, as many of its uses are "overkill".
The idea is that each subclass that is created for a (normal, non-meta) base-class that contains an __init_subclass__ method, it willbe called, with the new subclass as first parameter:

class Base:
   def __init_subclass__(subclass, debug=None, typecheck=None, **kwargs):
        # do stuff with the optional debug and typecheck arguments
        # Pass possible arguments not consumed here to superclasses, if any:
        super().__init_subclass__(**kwargs)

And there is no need for a metaclass at all - the __prepare__, __init__ and __new__ of the default metaclass - type - will ignore any named argument passed in this way. But the default __init_subclass__ in object will raise if unknown named arguments reach it - the pattern above will consume these arguments, removing them from kwargs. If you are dealing with unknown named arguments, just process kwargs like a normal dictionary - no need for explicit named parameters in the __init_subclass__.


问:
How to understand the method inEventLoop in Interface EventExecutor?
I am reading the source code of netty4.0. And I found that there are code like below in many places.How to understand it throughly? The following is a segment of class AbstractChannel.</p>

```<code>if (eventLoop.inEventLoop()) {
    register0(promise);
} else {
    try {
        eventLoop.execute(new Runnable() {
            @Override
            public void run() {
                register0(promise);
            }
        });
    } catch (Throwable t) {
        logger.warn(
            "Force-closing a channel whose registration task was not accepted by an event loop: {}",
            AbstractChannel.this, t);
        closeForcibly();
        closeFuture.setClosed();
        safeSetFailure(promise, t);
    }
}
</code>```

答: Basically it is an "optimisation" that will directly invoke the code if the current Thread is the same that is tied to the EventExecutor. If not it needs to allocate a Runnable and pass it over for execution.

Body:
I am reading the source code of netty4.0. And I found that there are code like below in many places.How to understand it throughly? The following is a segment of class AbstractChannel.

if (eventLoop.inEventLoop()) {
    register0(promise);
} else {
    try {
        eventLoop.execute(new Runnable() {
            @Override
            public void run() {
                register0(promise);
            }
        });
    } catch (Throwable t) {
        logger.warn(
            "Force-closing a channel whose registration task was not accepted by an event loop: {}",
            AbstractChannel.this, t);
        closeForcibly();
        closeFuture.setClosed();
        safeSetFailure(promise, t);
    }
}


问:
How to set oracle_home in linux with ansible playbook
Am trying to set oracle_home by using below

```<code>---
- name: setting up the ORACLE_HOME
  hosts: localhost
  become: yes
  environment:
    ORACLE_BASE: "/u01/app/oracle/"
    ORACLE_HOME: $ORACLE_BASE/product/12.1.0.2/cl_100
    PATH: $PATH:$HOME/bin:$ORACLE_HOME/bin:$ORACLE_HOME/OPatch
</code>```

script executing but not setting up please help

答:
I would go with the following:</p>

```<code>  vars:
    ORACLE_BASE: "/u01/app/oracle"
    ORACLE_HOME: "{{ORACLE_BASE}}/product/12.1.0.2/cl_100"
    ADD_PATH: "{{ORACLE_HOME}}/bin:{{ORACLE_HOME}}/OPatch"
  environment:
    ORACLE_BASE: "{{ORACLE_BASE}}"
    ORACLE_HOME: "{{ORACLE_HOME}}"
    PATH: "{{ansible_env.PATH}}:{{ansible_env.HOME}}/bin:{{ADD_PATH}}"
</code>```

Body:
Am trying to set oracle_home by using below

---
- name: setting up the ORACLE_HOME
  hosts: localhost
  become: yes
  environment:
    ORACLE_BASE: "/u01/app/oracle/"
    ORACLE_HOME: $ORACLE_BASE/product/12.1.0.2/cl_100
    PATH: $PATH:$HOME/bin:$ORACLE_HOME/bin:$ORACLE_HOME/OPatch

script executing but not setting up please help

Body:
I would go with the following:

  vars:
    ORACLE_BASE: "/u01/app/oracle"
    ORACLE_HOME: "{{ORACLE_BASE}}/product/12.1.0.2/cl_100"
    ADD_PATH: "{{ORACLE_HOME}}/bin:{{ORACLE_HOME}}/OPatch"
  environment:
    ORACLE_BASE: "{{ORACLE_BASE}}"
    ORACLE_HOME: "{{ORACLE_HOME}}"
    PATH: "{{ansible_env.PATH}}:{{ansible_env.HOME}}/bin:{{ADD_PATH}}"