问:
searching in n 2-dimensional arrays
Help with how to implement searching on n 2-dimenssional arrays. To be more specific:
If I have 6 tables and I am putting these into a 2-dimensional array.I will provide a value say 10 like how val=0 here. I need to search from these tables all the combination values that make up 10. The value will be computed taking values from all these tables.</p>

```<code>public static int Main() {
  int[] a = {2,1,4,7};
  int[] b = {3,-3,-8,0};
  int[] c = {-1,-4,-7,6};
  int sum;
  int i; int j;  int k;
  int val = 0;
  for(i = 0; i < 4; i++) {
    for(j = 0;j<4;j++) {
      for(k = 0;k<4;k++) {
        sum = a[i]* b[j]* c[k];

        if(sum == val)
          System.out.printf("%d  %d  %d\n",a[i],b[j],c[k]);
      }
    }
  }
}
</code>```

答:
You can consider a table as list of values. Then, if you have N tables, your problem is to find lists of N integers (each one taken from one of the N tables) whose product is equal to a value p. You can solve the problem recursively:

given a non-empty list of tables {t1, t2, t3, ...}

given a product value p that you look for

for every value v in t1 you must look for solutions of the sub-problem with a product value p / v and and tables {t2, t3, ...} (this assumes that p % v == 0, because we're dealing with integers

etc.

Some java code below:

```<code>public class SO6026472 {

    public static void main(String[] args) {
        // define individual tables
        Integer[] t1 = new Integer[] {2,-2,4,7};
        Integer[] t2 = new Integer[] {3,-3,-8,0};
        Integer[] t3 = new Integer[] {-1,-4,-7,6};
        Integer[] t4 = new Integer[] {1,5};
        // build list of tables
        List<List<Integer>> tables = new ArrayList<List<Integer>>();
        tables.add(Arrays.asList(t1));
        tables.add(Arrays.asList(t2));
        tables.add(Arrays.asList(t3));
        tables.add(Arrays.asList(t4));
        // find solutions
        SO6026472 c = new SO6026472();
        List<List<Integer>> solutions = c.find(36, tables);
        for (List<Integer> solution : solutions) {
            System.out.println(
                    Arrays.toString(solution.toArray(new Integer[0])));
        }
    }

    /**
     * Computes the ways of computing p as a product of elements taken from
     * every table in tables.
     *
     * @param p the target product value
     * @param tables the list of tables
     * @return the list of combinations of elements (one from each table) whose
     * product is equal to p
     */
    public List<List<Integer>> find(int p, List<List<Integer>> tables) {
        List<List<Integer>> solutions = new ArrayList<List<Integer>>();
        // if we have no tables, then we are done
        if (tables.size() == 0)
            return solutions;
        // if we have just one table, then we just have to check if it contains p
        if (tables.size() == 1) {
            if (tables.get(0).contains(p)) {
                List<Integer> solution = new ArrayList<Integer>();
                solution.add(p);
                solutions.add(solution);
                return solutions;
            } else
                return solutions;
        }
        // if we have several tables, then we take the first table T, and for
        // every value v in T we search for (p / v) in the rest of the tables;
        // we do this only if p % v is equal to 0, because we're dealing with
        // ints
        List<Integer> table = tables.remove(0);
        for (Integer value : table) {
            if (value != 0 && p % value == 0) {
                List<List<Integer>> subSolutions = find(p / value, tables);
                if (! subSolutions.isEmpty()) {
                    for (List<Integer> subSolution : subSolutions) {
                        subSolution.add(0, value);
                    }
                    solutions.addAll(subSolutions);
                }
            }
        }
        tables.add(0, table);
        return solutions;
    }

}
</code>```

The code prints solutions for a slightly modified version of your example:

```<code>[2, 3, 6, 1]
[-2, -3, 6, 1]
</code>```

The solutions work for any number of tables. There are ways to improve the algorithm, for example by using memoization and dynamic programming. But I think that the recursive solution is more clear.

Title: searching in n 2-dimensional arrays

Body:
Help with how to implement searching on n 2-dimenssional arrays. To be more specific:
If I have 6 tables and I am putting these into a 2-dimensional array.I will provide a value say 10 like how val=0 here. I need to search from these tables all the combination values that make up 10. The value will be computed taking values from all these tables.

public static int Main() {
  int[] a = {2,1,4,7};
  int[] b = {3,-3,-8,0};
  int[] c = {-1,-4,-7,6};
  int sum;
  int i; int j;  int k;
  int val = 0;
  for(i = 0; i < 4; i++) {
    for(j = 0;j<4;j++) {
      for(k = 0;k<4;k++) {
        sum = a[i]* b[j]* c[k];

        if(sum == val)
          System.out.printf("%d  %d  %d\n",a[i],b[j],c[k]);
      }
    }
  }
}

Body:
You can consider a table as list of values. Then, if you have N tables, your problem is to find lists of N integers (each one taken from one of the N tables) whose product is equal to a value p. You can solve the problem recursively:

given a non-empty list of tables {t1, t2, t3, ...}

given a product value p that you look for

for every value v in t1 you must look for solutions of the sub-problem with a product value p / v and and tables {t2, t3, ...} (this assumes that p % v == 0, because we're dealing with integers

etc.

Some java code below:

public class SO6026472 {

    public static void main(String[] args) {
        // define individual tables
        Integer[] t1 = new Integer[] {2,-2,4,7};
        Integer[] t2 = new Integer[] {3,-3,-8,0};
        Integer[] t3 = new Integer[] {-1,-4,-7,6};
        Integer[] t4 = new Integer[] {1,5};
        // build list of tables
        List<List<Integer>> tables = new ArrayList<List<Integer>>();
        tables.add(Arrays.asList(t1));
        tables.add(Arrays.asList(t2));
        tables.add(Arrays.asList(t3));
        tables.add(Arrays.asList(t4));
        // find solutions
        SO6026472 c = new SO6026472();
        List<List<Integer>> solutions = c.find(36, tables);
        for (List<Integer> solution : solutions) {
            System.out.println(
                    Arrays.toString(solution.toArray(new Integer[0])));
        }
    }

    /**
     * Computes the ways of computing p as a product of elements taken from
     * every table in tables.
     *
     * @param p the target product value
     * @param tables the list of tables
     * @return the list of combinations of elements (one from each table) whose
     * product is equal to p
     */
    public List<List<Integer>> find(int p, List<List<Integer>> tables) {
        List<List<Integer>> solutions = new ArrayList<List<Integer>>();
        // if we have no tables, then we are done
        if (tables.size() == 0)
            return solutions;
        // if we have just one table, then we just have to check if it contains p
        if (tables.size() == 1) {
            if (tables.get(0).contains(p)) {
                List<Integer> solution = new ArrayList<Integer>();
                solution.add(p);
                solutions.add(solution);
                return solutions;
            } else
                return solutions;
        }
        // if we have several tables, then we take the first table T, and for
        // every value v in T we search for (p / v) in the rest of the tables;
        // we do this only if p % v is equal to 0, because we're dealing with
        // ints
        List<Integer> table = tables.remove(0);
        for (Integer value : table) {
            if (value != 0 && p % value == 0) {
                List<List<Integer>> subSolutions = find(p / value, tables);
                if (! subSolutions.isEmpty()) {
                    for (List<Integer> subSolution : subSolutions) {
                        subSolution.add(0, value);
                    }
                    solutions.addAll(subSolutions);
                }
            }
        }
        tables.add(0, table);
        return solutions;
    }

}

The code prints solutions for a slightly modified version of your example:

[2, 3, 6, 1]
[-2, -3, 6, 1]

The solutions work for any number of tables. There are ways to improve the algorithm, for example by using memoization and dynamic programming. But I think that the recursive solution is more clear.


来源: stackexchange

问:
How do I get executor related info from a sparkcontext?
Spark version is 2.3.3.
I am trying to find total/used memory along with active/total tasks and other executor specific info.

In my driver :-

```<code>sc.statusTracker.getExecutorInfos.foreach{
      x=>
        x.numRunningTasks()
    }
</code>```

I can get the number of running tasks. But I also need total/used memory from these executors as well. I have thousands of job running on a Yarn cluster. The idea is to get actual usage vs allocated memory so that these can be optimized further.

Update:
http://:8088/proxy//api/v1/applications//executors provides all the information available on UI. Except memory used during computation. Which is what I am looking for majorly.

答:
Have a look for sc.getExecutorMemoryStatus

It return a map from the slave to the max memory available for caching and the remaining memory available for caching.

```<code>sc.getExecutorMemoryStatus.foreach {
  m => {
    println(s"Slave= ${m._1}")
    println(s"Max Memory Available= ${m._2._1}")
    println(s"Remaining Memory Available= ${m._2._2}")
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Spark version is 2.3.3.
I am trying to find total/used memory along with active/total tasks and other executor specific info.

In my driver :-

sc.statusTracker.getExecutorInfos.foreach{
      x=>
        x.numRunningTasks()
    }

I can get the number of running tasks. But I also need total/used memory from these executors as well. I have thousands of job running on a Yarn cluster. The idea is to get actual usage vs allocated memory so that these can be optimized further.

Update:
http://:8088/proxy//api/v1/applications//executors provides all the information available on UI. Except memory used during computation. Which is what I am looking for majorly.

Body:
Have a look for sc.getExecutorMemoryStatus

It return a map from the slave to the max memory available for caching and the remaining memory available for caching.

sc.getExecutorMemoryStatus.foreach {
  m => {
    println(s"Slave= ${m._1}")
    println(s"Max Memory Available= ${m._2._1}")
    println(s"Remaining Memory Available= ${m._2._2}")
  }
}


问:
Reshaping dataframe / multiple 'n' plots in python
I have a dataframe, which has different rates for multiple 'N' currencies over a time period.

```<code>dataframe
Dates      AUD     CAD    CHF    GBP    EUR
20/05/2019 0.11   -0.25  -0.98   0.63   0.96
21/05/2019 0.14   -0.35  -0.92   1.92   0.92
...
02/01/2020 0.135  -0.99  -1.4    0.93   0.83
</code>```

Firstly, I would like to reshape the dataframe table to look like the below as I would like to join another table which would be in a similar format:

```<code>dataframe
Dates      Pairs   Rates
20/05/2019 AUD     0.11
20/05/2019 CAD    -0.25
20/05/2019 CHF    -0.98
...

...
02/01/2020 AUD    0.135
02/01/2020 CAD    -0.99
02/01/2020 CHF    -1.4
</code>```

Then, for every N currency, I would like to plot a histogram . So with the above, it would be 5 separate histograms based off each N ccy.
I assume I would need to get this in some sort of loop, but not sure on the easiest way to approach.
Thanks

Body:
I have a dataframe, which has different rates for multiple 'N' currencies over a time period.

dataframe
Dates      AUD     CAD    CHF    GBP    EUR
20/05/2019 0.11   -0.25  -0.98   0.63   0.96
21/05/2019 0.14   -0.35  -0.92   1.92   0.92
...
02/01/2020 0.135  -0.99  -1.4    0.93   0.83

Firstly, I would like to reshape the dataframe table to look like the below as I would like to join another table which would be in a similar format:

dataframe
Dates      Pairs   Rates
20/05/2019 AUD     0.11
20/05/2019 CAD    -0.25
20/05/2019 CHF    -0.98
...

...
02/01/2020 AUD    0.135
02/01/2020 CAD    -0.99
02/01/2020 CHF    -1.4

Then, for every N currency, I would like to plot a histogram . So with the above, it would be 5 separate histograms based off each N ccy.
I assume I would need to get this in some sort of loop, but not sure on the easiest way to approach.
Thanks

Body:
Use DataFrame.melt first:

df['Dates'] = pd.to_datetime(df['Dates'], dayfirst=True)

df = df.melt('Dates', var_name='Pairs', value_name='Rates')
print (df)
        Dates Pairs  Rates
0  2019-05-20   AUD  0.110
1  2019-05-21   AUD  0.140
2  2020-01-02   AUD  0.135
3  2019-05-20   CAD -0.250
4  2019-05-21   CAD -0.350
5  2020-01-02   CAD -0.990
6  2019-05-20   CHF -0.980
7  2019-05-21   CHF -0.920
8  2020-01-02   CHF -1.400
9  2019-05-20   GBP  0.630
10 2019-05-21   GBP  1.920
11 2020-01-02   GBP  0.930
12 2019-05-20   EUR  0.960
13 2019-05-21   EUR  0.920
14 2020-01-02   EUR  0.830

And then DataFrameGroupBy.hist:

df.groupby('Pairs').hist()


问:
G-Suite - Upload data to the same Google Drive from Multiple User Accounts - Error 403 User rate limit exceeded
So forgive me if this is a silly question but i am having problems using multiple accounts and uploading data to the same google drive

Setup

Google Drive being used below to User01

Linux:

rclone remote setup to connect to Google Drive with api credentials and encrypted along the way. ** THIS WORKS AS IT SHOULD

Setup another user on my G-Suite (User02) and create a new remote using the api credentials for User02 but the connection token for User01. I believe this is the method to firstly use User02 upload quota (specifying cred key and secret) then uploading data to google drive using token from User02

Firstly is my assumption correct?

When i do the above and attempt to copy data to google drive i get error 403 user rate exceeded. I have checked the quotas and they are no way being reached so i am at a loss as to what is going on.

Anyone done this before and got it working?

答:
If you use the token of User01 then you are actually using your app as the User01.

I think that for your case you shouldn't be using Domain wide delegation to impersonate the User02 or whoever you want in your domain.

Your quota could be to try to upload files too big, or too many request to the server. Maybe post more information/source code/message error to try to debug it.


问:
How to offset Directions route Polyline to the side of the map canvas?
Currently I'm working on a direction based project and I want to push my direction to the right side when rendered.
This is what I'm getting.

I don't want to get directions behind the panel.
This is what I want to get.

Direction between two point to the right side.

My code to render directions between two points is as follows

```<code>renderDirections(): void {
    var placeID = this.destinationPlaceId.getPlace();
    console.log(placeID.place_id);
    this.destinationPlaceId = placeID.place_id;
    let directionsService = new google.maps.DirectionsService;

    let directionsRenderer = new google.maps.DirectionsRenderer({
        preserveViewport: false
    });
    initMap();
    directionsRenderer.setMap(map);

    placeID = this.startPlaceID.getPlace();
    console.log(placeID.place_id);
    this.originPlaceId = placeID.place_id;
    directionsService.route(
        {
            origin: { 'placeId': this.originPlaceId },
            destination: { 'placeId': this.destinationPlaceId },
            travelMode: google.maps.TravelMode[this.travelMode]
        },
        function (response, status) {
            if (status === 'OK') {
                directionsRenderer.setDirections(response);

            } else {
                window.alert('Directions request failed due to ' + status);
                window.location.reload();
            }
        });
}
</code>```

答:
There is no ready-made function to achieve this but it is feasible, as long as you know the width (and position) of your top layer.

Here is how you can do it:

Plot a route on the map and listen for the map idle event before starting with the offset process.

Check the leftmost point of the route bounds to see if it falls behind the overlay. This makes use of the fromLatLngToPoint() method to translate from lat/lng coordinates to a point on the map projection.

Check how much you can offset the route by comparing the leftmost and rightmost points of the route with the available space on the map. Offset the map until both points fit on the available canvas space.

If both points cannot fit within the map canvas, zoom out and start the same process again.

The script must be aware of the width of the overlay and you should apply some margins so that it always fits well.

Working code snippet:

var directionsDisplay;
var directionsService;
var start, end;
var map;
var routeBounds = false;
var overlayWidth = 200; // Width of the overlay DIV
var leftMargin = 30; // Grace margin to avoid too close fits on the edge of the overlay
var rightMargin = 80; // Grace margin to avoid too close fits on the right and leave space for the controls

overlayWidth += leftMargin;

function initialize() {

    directionsService = new google.maps.DirectionsService();
    start = new google.maps.LatLng(48.857380, 2.351717);
    end = new google.maps.LatLng(50.108814, 8.672309);

    var btn1 = document.getElementById('calcRoute');
    btn1.addEventListener('click', calcRoute);

    var btn2 = document.getElementById('offsetMap');
    btn2.addEventListener('click', offsetMap);

    var btn3 = document.getElementById('fitAndOffsetMap');
    btn3.addEventListener('click', fitAndOffsetMap);

    var btn4 = document.getElementById('fitMap');
    btn4.addEventListener('click', fitMap);

    directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: true
    });

    var mapOptions = {
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: start,
        panControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        zoomControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        }
    };

    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    directionsDisplay.setMap(map);
}

function offsetMap() {

    if (routeBounds !== false) {

        // Clear listener defined in directions results
        google.maps.event.clearListeners(map, 'idle');

        // Top right corner
        var topRightCorner = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getNorthEast().lng());

        // Top right point
        var topRightPoint = fromLatLngToPoint(topRightCorner).x;

        // Get pixel position of leftmost and rightmost points
        var leftCoords = routeBounds.getSouthWest();
        var leftMost = fromLatLngToPoint(leftCoords).x;
        var rightMost = fromLatLngToPoint(routeBounds.getNorthEast()).x;

        // Calculate left and right offsets
        var leftOffset = (overlayWidth - leftMost);
        var rightOffset = ((topRightPoint - rightMargin) - rightMost);

        // Only if left offset is needed
        if (leftOffset >= 0) {

            if (leftOffset < rightOffset) {

                var mapOffset = Math.round((rightOffset - leftOffset) / 2);

                // Pan the map by the offset calculated on the x axis
                map.panBy(-mapOffset, 0);

                // Get the new left point after pan
                var newLeftPoint = fromLatLngToPoint(leftCoords).x;

                if (newLeftPoint <= overlayWidth) {

                    // Leftmost point is still under the overlay
                    // Offset map again
                    offsetMap();
                }

            } else {

                // Cannot offset map at this zoom level otherwise both leftmost and rightmost points will not fit
                // Zoom out and offset map again
                map.setZoom(map.getZoom() - 1);
                offsetMap();
            }
        }
    }
}

function fromLatLngToPoint(latLng) {

    var scale = Math.pow(2, map.getZoom());
    var nw = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getSouthWest().lng());
    var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
    var worldCoordinate = map.getProjection().fromLatLngToPoint(latLng);

    return new google.maps.Point(Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale));
}

function calcRoute() {

    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function (response, status) {

        if (status == google.maps.DirectionsStatus.OK) {

            directionsDisplay.setDirections(response);

            // Define route bounds for use in offsetMap function
            routeBounds = response.routes[0].bounds;

            // Write directions steps
            writeDirectionsSteps(response.routes[0].legs[0].steps);

            // Wait for map to be idle before calling offsetMap function
            google.maps.event.addListener(map, 'idle', function () {

                // Offset map
                offsetMap();
            });

            // Listen for directions changes to update bounds and reapply offset
            google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {

                // Get the updated route directions response
                var updatedResponse = directionsDisplay.getDirections();

                // Update route bounds
                routeBounds = updatedResponse.routes[0].bounds;

                // Fit updated bounds
                map.fitBounds(routeBounds);

                // Write directions steps
                writeDirectionsSteps(updatedResponse.routes[0].legs[0].steps);

                // Offset map
                offsetMap();
            });
        }
    });
}

function writeDirectionsSteps(steps) {

    var overlayContent = document.getElementById("overlayContent");
    overlayContent.innerHTML = '';

    for (var i = 0; i < steps.length; i++) {

        overlayContent.innerHTML += '
' + steps[i].instructions + '
' + steps[i].distance.text + '';
    }
}

function fitMap() {

    if (routeBounds !== false) {

        map.fitBounds(routeBounds);
    }
}

function fitAndOffsetMap() {

    if (routeBounds !== false) {

        map.fitBounds(routeBounds);
        offsetMap();
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 0;
    padding: 0;
    font-family: Arial, Helvetica, sans-serif;
}
#map-canvas {
    height: 160px;
}
#overlay {
    position: absolute;
    width: 200px;
    height: 160px;
    background: black;
    opacity: 0.8;
    top: 0;
    left: 0;
    overflow: auto;
}
#overlayContent {
    color: white;
    padding: 10px 20px;
}
#overlayContent p {
    font-size: 12px;
    margin: 6px 0;
}
small {
    font-size: 9px;
}
#overlayContent small {
    display: block;
    text-align: right;
    font-style: italic;
}
i {
    color: lightblue;
}
h1 {
    font-size: 20px;
}
h5 {
    font-size: 12px;
}
button {
    margin: 20px 0 0 20px;
}</code>```

DIV OVERLAY

Routes should not be drawn below this element.

Click the Calc route button to draw the directions route.

Map offset will be applied automatically.

Drag the route to see how it is applied.

Click the Offset map button to reapply the offset.

Click the Fit only button to only fit route bounds.

Click the Fit and offset map button to fit to route bounds and reapply offset.

<button id="calcRoute">Calc route</button>
<button id="offsetMap">Offset map</button>
<button id="fitMap">Fit only</button>
<button id="fitAndOffsetMap">Fit and offset map</button>

```

Working fiddle:

You can play with it on JSFiddle as it is easier to see the behavior, resize the window, etc.

Body:
Currently I'm working on a direction based project and I want to push my direction to the right side when rendered.
This is what I'm getting.

I don't want to get directions behind the panel.
This is what I want to get.

Direction between two point to the right side.

My code to render directions between two points is as follows

renderDirections(): void {
    var placeID = this.destinationPlaceId.getPlace();
    console.log(placeID.place_id);
    this.destinationPlaceId = placeID.place_id;
    let directionsService = new google.maps.DirectionsService;

    let directionsRenderer = new google.maps.DirectionsRenderer({
        preserveViewport: false
    });
    initMap();
    directionsRenderer.setMap(map);

    placeID = this.startPlaceID.getPlace();
    console.log(placeID.place_id);
    this.originPlaceId = placeID.place_id;
    directionsService.route(
        {
            origin: { 'placeId': this.originPlaceId },
            destination: { 'placeId': this.destinationPlaceId },
            travelMode: google.maps.TravelMode[this.travelMode]
        },
        function (response, status) {
            if (status === 'OK') {
                directionsRenderer.setDirections(response);

            } else {
                window.alert('Directions request failed due to ' + status);
                window.location.reload();
            }
        });
}

Body:
There is no ready-made function to achieve this but it is feasible, as long as you know the width (and position) of your top layer.

Here is how you can do it:

Plot a route on the map and listen for the map idle event before starting with the offset process.

Check the leftmost point of the route bounds to see if it falls behind the overlay. This makes use of the fromLatLngToPoint() method to translate from lat/lng coordinates to a point on the map projection.

Check how much you can offset the route by comparing the leftmost and rightmost points of the route with the available space on the map. Offset the map until both points fit on the available canvas space.

If both points cannot fit within the map canvas, zoom out and start the same process again.

The script must be aware of the width of the overlay and you should apply some margins so that it always fits well.

Working code snippet:

var directionsDisplay;
var directionsService;
var start, end;
var map;
var routeBounds = false;
var overlayWidth = 200; // Width of the overlay DIV
var leftMargin = 30; // Grace margin to avoid too close fits on the edge of the overlay
var rightMargin = 80; // Grace margin to avoid too close fits on the right and leave space for the controls

overlayWidth += leftMargin;

function initialize() {

    directionsService = new google.maps.DirectionsService();
    start = new google.maps.LatLng(48.857380, 2.351717);
    end = new google.maps.LatLng(50.108814, 8.672309);

    var btn1 = document.getElementById('calcRoute');
    btn1.addEventListener('click', calcRoute);

    var btn2 = document.getElementById('offsetMap');
    btn2.addEventListener('click', offsetMap);

    var btn3 = document.getElementById('fitAndOffsetMap');
    btn3.addEventListener('click', fitAndOffsetMap);

    var btn4 = document.getElementById('fitMap');
    btn4.addEventListener('click', fitMap);

    directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: true
    });

    var mapOptions = {
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: start,
        panControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        zoomControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        }
    };

    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    directionsDisplay.setMap(map);
}

function offsetMap() {

    if (routeBounds !== false) {

        // Clear listener defined in directions results
        google.maps.event.clearListeners(map, 'idle');

        // Top right corner
        var topRightCorner = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getNorthEast().lng());

        // Top right point
        var topRightPoint = fromLatLngToPoint(topRightCorner).x;

        // Get pixel position of leftmost and rightmost points
        var leftCoords = routeBounds.getSouthWest();
        var leftMost = fromLatLngToPoint(leftCoords).x;
        var rightMost = fromLatLngToPoint(routeBounds.getNorthEast()).x;

        // Calculate left and right offsets
        var leftOffset = (overlayWidth - leftMost);
        var rightOffset = ((topRightPoint - rightMargin) - rightMost);

        // Only if left offset is needed
        if (leftOffset >= 0) {

            if (leftOffset < rightOffset) {

                var mapOffset = Math.round((rightOffset - leftOffset) / 2);

                // Pan the map by the offset calculated on the x axis
                map.panBy(-mapOffset, 0);

                // Get the new left point after pan
                var newLeftPoint = fromLatLngToPoint(leftCoords).x;

                if (newLeftPoint <= overlayWidth) {

                    // Leftmost point is still under the overlay
                    // Offset map again
                    offsetMap();
                }

            } else {

                // Cannot offset map at this zoom level otherwise both leftmost and rightmost points will not fit
                // Zoom out and offset map again
                map.setZoom(map.getZoom() - 1);
                offsetMap();
            }
        }
    }
}

function fromLatLngToPoint(latLng) {

    var scale = Math.pow(2, map.getZoom());
    var nw = new google.maps.LatLng(map.getBounds().getNorthEast().lat(), map.getBounds().getSouthWest().lng());
    var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
    var worldCoordinate = map.getProjection().fromLatLngToPoint(latLng);

    return new google.maps.Point(Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale), Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale));
}

function calcRoute() {

    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function (response, status) {

        if (status == google.maps.DirectionsStatus.OK) {

            directionsDisplay.setDirections(response);

            // Define route bounds for use in offsetMap function
            routeBounds = response.routes[0].bounds;

            // Write directions steps
            writeDirectionsSteps(response.routes[0].legs[0].steps);

            // Wait for map to be idle before calling offsetMap function
            google.maps.event.addListener(map, 'idle', function () {

                // Offset map
                offsetMap();
            });

            // Listen for directions changes to update bounds and reapply offset
            google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {

                // Get the updated route directions response
                var updatedResponse = directionsDisplay.getDirections();

                // Update route bounds
                routeBounds = updatedResponse.routes[0].bounds;

                // Fit updated bounds
                map.fitBounds(routeBounds);

                // Write directions steps
                writeDirectionsSteps(updatedResponse.routes[0].legs[0].steps);

                // Offset map
                offsetMap();
            });
        }
    });
}

function writeDirectionsSteps(steps) {

    var overlayContent = document.getElementById("overlayContent");
    overlayContent.innerHTML = '';

    for (var i = 0; i < steps.length; i++) {

        overlayContent.innerHTML += '<p>' + steps[i].instructions + '</p><small>' + steps[i].distance.text + '</small>';
    }
}

function fitMap() {

    if (routeBounds !== false) {

        map.fitBounds(routeBounds);
    }
}

function fitAndOffsetMap() {

    if (routeBounds !== false) {

        map.fitBounds(routeBounds);
        offsetMap();
    }
}

body {
    margin: 0;
    padding: 0;
    font-family: Arial, Helvetica, sans-serif;
}
#map-canvas {
    height: 160px;
}
#overlay {
    position: absolute;
    width: 200px;
    height: 160px;
    background: black;
    opacity: 0.8;
    top: 0;
    left: 0;
    overflow: auto;
}
#overlayContent {
    color: white;
    padding: 10px 20px;
}
#overlayContent p {
    font-size: 12px;
    margin: 6px 0;
}
small {
    font-size: 9px;
}
#overlayContent small {
    display: block;
    text-align: right;
    font-style: italic;
}
i {
    color: lightblue;
}
h1 {
    font-size: 20px;
}
h5 {
    font-size: 12px;
}
button {
    margin: 20px 0 0 20px;
}

<div id="map-canvas"></div>
<div id="overlay">
    <div id="overlayContent">
         <h1>DIV OVERLAY</h1>

         <h5>Routes should not be drawn below this element.</h5>

         <h5>Click the <i>Calc route</i> button to draw the directions route.</h5>

         <h5><i>Map offset</i> will be applied automatically.</h5>

         <h5><i>Drag the route</i> to see how it is applied.</h5>

         <h5>Click the <i>Offset map</i> button to reapply the offset.</h5>

         <h5>Click the <i>Fit only</i> button to only fit route bounds.</h5>

         <h5>Click the <i>Fit and offset map</i> button to fit to route bounds and reapply offset.</h5>

    </div>
</div>
<button id="calcRoute">Calc route</button>
<button id="offsetMap">Offset map</button>
<button id="fitMap">Fit only</button>
<button id="fitAndOffsetMap">Fit and offset map</button>

<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize">
</script>

Working fiddle:

You can play with it on JSFiddle as it is easier to see the behavior, resize the window, etc.


问:
BACnet segmentation-not-supported on mobile
I'm implementing a bacnet library to read and write some object instances.
But I don't understand, why with a PC and with an application like Yabe if I ask to a common controller to read more than 300 objects, the segmentation is supported, instead with a mobile phone and on the same request to the same controller the segmentation is not supported.
Both the PC and the smartphone are in the same network on Wifi.
So what is the problem/difference?</p>

答: Segmentation is used for APDUs (responses) that are too large to fit in one frame on the datalink. If both devices support segmentation, then great. If one of the device does not support segmentation, and the APDU does not fit, then "Segmentation not supported" error is issued. (and you have to then retry a smaller request).</p>


问:
How should the libqmi be linked?
I've tried to use libqmi but I can't get through the linker. It keeps saying "undefined reference" on libqmi functions. Any suggestions what is needed?

Paths and libraries are available for gcc, the symbols are inside libqmi-glib, looks like everything is in place.

The code is the simplest possible, I think.

```<code>int main(int argc, char **argv)
{
    GFile *qmi = g_file_new_for_path("/dev/cdc-wdm0");
    printf("%li\r\n", (long int)(qmi));
    g_object_unref(qmi);
    return 0;
}
</code>```

And the build goes like this:

```<code>gcc -I/usr/local/include/libqmi-glib/ -I/usr/include/glib-2.0/ -I/usr/lib/x86_64-linux-gnu/glib-2.0/include/ whatever.c -L/usr/local/lib/ -L/usr/lib/x86_64-linux-gnu/ -lqmi-glib -lglib-2.0
</code>```

答:
You're missing the link to libgobject-2 and libgio-2.

Anyway, the best way to compile a program using libqmi is to use pkg-config as that knows all the cflags and ldflags you should be using; e.g. you could probably do this, assuming you installed libqmi in /usr/local:

```<code>PKG_CONFIG_PATH=/usr/local/lib/pkgconfig gcc $(pkg-config --cflags qmi-glib) whatever.c $(pkg-config --libs qmi-glib)
</code>```

Title: How should the libqmi be linked?

Body:
I've tried to use libqmi but I can't get through the linker. It keeps saying "undefined reference" on libqmi functions. Any suggestions what is needed?

Paths and libraries are available for gcc, the symbols are inside libqmi-glib, looks like everything is in place.

The code is the simplest possible, I think.

int main(int argc, char **argv)
{
    GFile *qmi = g_file_new_for_path("/dev/cdc-wdm0");
    printf("%li\r\n", (long int)(qmi));
    g_object_unref(qmi);
    return 0;
}

And the build goes like this:

gcc -I/usr/local/include/libqmi-glib/ -I/usr/include/glib-2.0/ -I/usr/lib/x86_64-linux-gnu/glib-2.0/include/ whatever.c -L/usr/local/lib/ -L/usr/lib/x86_64-linux-gnu/ -lqmi-glib -lglib-2.0

Body:
You're missing the link to libgobject-2 and libgio-2.

Anyway, the best way to compile a program using libqmi is to use pkg-config as that knows all the cflags and ldflags you should be using; e.g. you could probably do this, assuming you installed libqmi in /usr/local:

PKG_CONFIG_PATH=/usr/local/lib/pkgconfig gcc $(pkg-config --cflags qmi-glib) whatever.c $(pkg-config --libs qmi-glib)


问:
Aero: How to draw solid (opaque) colors on glass?
Using GDI+ to draw various colors:

```<code>brush = new SolidBrush(color);
graphics.FillRectangle(brush, x, y, width, height);
</code>```

You'll notice that no opaque color shows properly on glass:

How do i draw solid colors on glass?

You'll also notice that a fully opaque color is handled differently depending on what color it is:

opaque black: fully transparent

opaque color: partially transparent

opaque white: fully opaque

Can anyone point me to the documentation on the desktop compositor that explains how different colors are handled?

Update 3

You'll also notice that FillRectangle behaves differently than FillEllipse:

FillEllipse with an opaque color draws an opaque color

FillRectangle with an opaque color draws partially (or fully) transparent

Explanation for non-sensical behavior please.

Update 4

Alwayslearning suggested i change the compositing mode. From MSDN:

CompositingMode Enumeration

The CompositingMode enumeration specifies how rendered colors are combined with background colors. This enumeration is used by the Graphics::GetCompositingMode and 'Graphics::SetCompositingMode' methods of the Graphics class.

```<code>CompositingModeSourceOver
</code>```

Specifies that when a color is rendered, it is blended with the background color. The blend is determined by the alpha component of the color being rendered.

```<code>CompositingModeSourceCopy
</code>```

Specifies that when a color is rendered, it overwrites the background color. This mode cannot be used along with TextRenderingHintClearTypeGridFit.

From the description of CompositingModeSourceCopy, it sounds like it's not the option i want. From the limitations it imposes, it sounds like the option i want. And with composition, or transparency disabled it isn't the option i want, since it performs a SourceCopy, rather than SourceBlend:

Fortunately it's not an evil i have to contemplate because it doesn't solve my actual issue. After constructing my graphics object, i tried changed the compositing mode:

```<code>graphics = new Graphics(hDC);
graphics.SetCompositingMode(CompositingModeSourceCopy); //CompositingModeSourceCopy = 1
</code>```

The result has no effect on the output:

Notes

Win32 native

not .NET (i.e. native)

not Winforms (i.e. native)

GDI+ (i.e. native)

See also

Aero: How to draw ClearType text on glass?

Windows Aero: What color to paint to make “glass” appear?

Vista/7: How to get glass color?

答:
I met the same issue with GDI.

GDI uses zero alpha channel value, so the simpliest solution is to fix alpha channel like this code does:

```<code>void fix_alpha_channel()
{
    std::vector<COLORREF> pixels(cx * cy);

    BITMAPINFOHEADER bmpInfo = {0};
    bmpInfo.biSize = sizeof(bmpInfo);
    bmpInfo.biWidth = cx;
    bmpInfo.biHeight = -int(cy);
    bmpInfo.biPlanes = 1;
    bmpInfo.biBitCount = 32;
    bmpInfo.biCompression = BI_RGB;

    GetDIBits(memDc, hBmp, 0, cy, &pixels[0], (LPBITMAPINFO)&bmpInfo, DIB_RGB_COLORS);

    std::for_each(pixels.begin(), pixels.end(), [](COLORREF& pixel){
        if(pixel != 0) // black pixels stay transparent
            pixel |= 0xFF000000; // set alpha channel to 100%
    });

    SetDIBits(memDc, hBmp, 0, cy, &pixels[0], (LPBITMAPINFO)&bmpInfo, DIB_RGB_COLORS);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Using GDI+ to draw various colors:

brush = new SolidBrush(color);
graphics.FillRectangle(brush, x, y, width, height);

You'll notice that no opaque color shows properly on glass:

How do i draw solid colors on glass?

You'll also notice that a fully opaque color is handled differently depending on what color it is:

opaque black: fully transparent

opaque color: partially transparent

opaque white: fully opaque

Can anyone point me to the documentation on the desktop compositor that explains how different colors are handled?

Update 3

You'll also notice that FillRectangle behaves differently than FillEllipse:

FillEllipse with an opaque color draws an opaque color

FillRectangle with an opaque color draws partially (or fully) transparent

Explanation for non-sensical behavior please.

Update 4

Alwayslearning suggested i change the compositing mode. From MSDN:

CompositingMode Enumeration

The CompositingMode enumeration specifies how rendered colors are combined with background colors. This enumeration is used by the Graphics::GetCompositingMode and 'Graphics::SetCompositingMode' methods of the Graphics class.

CompositingModeSourceOver

Specifies that when a color is rendered, it is blended with the background color. The blend is determined by the alpha component of the color being rendered.

CompositingModeSourceCopy

Specifies that when a color is rendered, it overwrites the background color. This mode cannot be used along with TextRenderingHintClearTypeGridFit.

From the description of CompositingModeSourceCopy, it sounds like it's not the option i want. From the limitations it imposes, it sounds like the option i want. And with composition, or transparency disabled it isn't the option i want, since it performs a SourceCopy, rather than SourceBlend:

Fortunately it's not an evil i have to contemplate because it doesn't solve my actual issue. After constructing my graphics object, i tried changed the compositing mode:

graphics = new Graphics(hDC);
graphics.SetCompositingMode(CompositingModeSourceCopy); //CompositingModeSourceCopy = 1

The result has no effect on the output:

Notes

Win32 native

not .NET (i.e. native)

not Winforms (i.e. native)

GDI+ (i.e. native)

See also

Aero: How to draw ClearType text on glass?

Windows Aero: What color to paint to make “glass” appear?

Vista/7: How to get glass color?

Body:
I met the same issue with GDI.

GDI uses zero alpha channel value, so the simpliest solution is to fix alpha channel like this code does:

void fix_alpha_channel()
{
    std::vector<COLORREF> pixels(cx * cy);

    BITMAPINFOHEADER bmpInfo = {0};
    bmpInfo.biSize = sizeof(bmpInfo);
    bmpInfo.biWidth = cx;
    bmpInfo.biHeight = -int(cy);
    bmpInfo.biPlanes = 1;
    bmpInfo.biBitCount = 32;
    bmpInfo.biCompression = BI_RGB;

    GetDIBits(memDc, hBmp, 0, cy, &pixels[0], (LPBITMAPINFO)&bmpInfo, DIB_RGB_COLORS);

    std::for_each(pixels.begin(), pixels.end(), [](COLORREF& pixel){
        if(pixel != 0) // black pixels stay transparent
            pixel |= 0xFF000000; // set alpha channel to 100%
    });

    SetDIBits(memDc, hBmp, 0, cy, &pixels[0], (LPBITMAPINFO)&bmpInfo, DIB_RGB_COLORS);
}

ContentLicense: CC BY-SA 3.0


问:
match multiple OR conditions in python 3 regex findall
In python 3:

This is the Office of Foreign Asset Control list where individuals' assets should be monitored

https://www.treasury.gov/ofac/downloads/sdn.csv

a lot of their data of births (the very last column, comma delimited) are like

```<code>DOB 23 Jun 1959; alt. DOB 23 Jun 1958
</code>```

or

```<code>DOB 1959; alt. DOB 1958
</code>```

I am trying to capture all the birthdates after the keyword "DOB" AND "alt. DOB" with the following codes:

```<code>   if len(x.split(';')) > 0:
        if len(re.findall('DOB (.*)', x.split(';')[0])) > 0:
            new = re.findall('DOB | alt. DOB (.*)', x.split(';')[0])[0]
            print(new)

            try:
                print(datetime.strptime(new, '%d %b %Y'))
                return datetime.strptime(new, '%d %b %Y')
            except:
                return None
</code>```

But the codes only get the birthdate right after "DOB", but not include the date of birth after "alt. DOB". Wonder how could i do it? Thank you.

答:
You could match DOB and use a capturing group for the date part. For the date part, the number of days and the month can be optional followed by matching 4 digits.

The date part pattern does not validate the date itself, it makes the match a bit more specific.

```<code>\bDOB ((?:(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+ )?\d{4})\b
</code>```

Explanation

\bDOB  Match literally preceded by a word boundary

( Capture group 1

(?: Non capture group

(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+  Match a digit 1-31 and 1+ chars A-Za-z

)? Close group and make it optional

\d{4} Match 4 digits

)\b Close group 1 followed by a word boundary

Regex demo | Python demo

For example:

```<code>import re

regex = r"\bDOB ((?:(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+ )?\d{4})\b"
test_str = ("DOB 23 Jun 1959; alt. DOB 23 Jun 1958\n"
    "DOB 1959; alt. DOB 1958")

print(re.findall(regex, test_str))
</code>```

Output

```<code>['23 Jun 1959', '23 Jun 1958', '1959', '1958']
</code>```

Body:
In python 3:

This is the Office of Foreign Asset Control list where individuals' assets should be monitored

https://www.treasury.gov/ofac/downloads/sdn.csv

a lot of their data of births (the very last column, comma delimited) are like

DOB 23 Jun 1959; alt. DOB 23 Jun 1958

or

DOB 1959; alt. DOB 1958

I am trying to capture all the birthdates after the keyword "DOB" AND "alt. DOB" with the following codes:

   if len(x.split(';')) > 0:
        if len(re.findall('DOB (.*)', x.split(';')[0])) > 0:
            new = re.findall('DOB | alt. DOB (.*)', x.split(';')[0])[0]
            print(new)

            try:
                print(datetime.strptime(new, '%d %b %Y'))
                return datetime.strptime(new, '%d %b %Y')
            except:
                return None

But the codes only get the birthdate right after "DOB", but not include the date of birth after "alt. DOB". Wonder how could i do it? Thank you.

Body:
You could match DOB and use a capturing group for the date part. For the date part, the number of days and the month can be optional followed by matching 4 digits.

The date part pattern does not validate the date itself, it makes the match a bit more specific.

\bDOB ((?:(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+ )?\d{4})\b

Explanation

\bDOB  Match literally preceded by a word boundary

( Capture group 1

(?: Non capture group

(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+  Match a digit 1-31 and 1+ chars A-Za-z

)? Close group and make it optional

\d{4} Match 4 digits

)\b Close group 1 followed by a word boundary

Regex demo | Python demo

For example:

import re

regex = r"\bDOB ((?:(?:3[01]|[12][0-9]|0?[1-9]) [A-Za-z]+ )?\d{4})\b"
test_str = ("DOB 23 Jun 1959; alt. DOB 23 Jun 1958\n"
    "DOB 1959; alt. DOB 1958")

print(re.findall(regex, test_str))

Output

['23 Jun 1959', '23 Jun 1958', '1959', '1958']


问:
SAPUI5 Table Items Duplicate IDs
I have a SAPUI5 application where you first choose a object and then a new table is build up which is showing some data to this selected object. I am creating list items with some input fields with unique ids. If a user goes back to select a new object, the table is built new the same way but has erros because it tries to create new ids which are already in use (duplicate ids) Is there a way in SAPUI5 to delete this ids or destroy the items? I tried it with table.destroyItems() and table.destroy() but i had no success. Did somebody of you already faced a problem like this?</p>

答:
Set data of model as empty array as per your requirement,

var oModel = new sap.ui.model.json.JSONModel();
  oModel.setData({results: []});```
</div>
</div>
</p>

<p>OR</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var oModel = new sap.ui.model.json.JSONModel();
  oModel.setData([]);</code>```

Title: SAPUI5 Table Items Duplicate IDs

Body:
Set data of model as empty array as per your requirement,

var oModel = new sap.ui.model.json.JSONModel();
  oModel.setData({results: []});

OR

var oModel = new sap.ui.model.json.JSONModel();
  oModel.setData([]);


问:
Using bindingsource stored in the ifs
Is there any possible way to create a serviceprogramm (crtsqlrpgi OBJTYPE(*SRVPGM)) using a .bnd file stored in the ifs as bindingsource?</p>

答: Ok, i solved it. I created my program with crtsqlrpgi ... objtype(*module) and then created the srvpgm. </p>

Title: Using bindingsource stored in the ifs


问:
Slow performance when querying remote db - is this normal?
I am doing some loading from an oracle db, using ODP.NET.

In its current implementation the code does something along the lines of:

```<code>query entityIds to load based on criteria
    foreach entityId
        load attributes
        query geometries that exist
        foreach geometry that exists
            load geometry
        next
    next
</code>```

when the DB is on the local network criteria which load 133 entities takes a couple of seconds to load all 133 entities.

When the db is a remote db hosted on a VM in a data center on the other side of the world this takes about 3.5 mins to load them all.

The particularly slow bit seems to be the querying the geometry.  In initial testing (in TOAD - not in the service loading code) it seems to take about 2 secs to load the geometry for a single entity using the remote machine.  If we change the query to load all the geometries in a single go, it still seems to take 2 secs.  This sort of implies that it isn't the network overhead (as the amount of data being returned is much more for the query which returns all the geometries, but the time is the same).

Is this sort of performance overhead for a remote db vs local expected?  Why does doing each query separately take so much longer than doing them all in one go?  Is there anything we can do to mitigate this (apart from do all the queries in one go)?

答:
You're probably coming up on the distinction between bandwidth and latency.

Latency is the time taken for a single round-trip, whereas bandwidth is the amount of data that can flow through over a given time period (eg 1 second).

If you're running 200 queries (from client-side code, not from a stored proc), then no matter how much data goes in each query, you will get 200 round-trips

Normal latency for the other end of the world is around half a second I believe - so for 200 entities retrieved separately, about 100 seconds.

Those numbers don't quite match yours, so there may be even higher latency (depends on all sorts of network factors). I would normally look for query/lookup overhead on the database server (assuming there is an indexing issue), but you've already mentioned that locally there is no significant overhead (presumably with the same data?).

Body:
I am doing some loading from an oracle db, using ODP.NET.

In its current implementation the code does something along the lines of:

query entityIds to load based on criteria
    foreach entityId
        load attributes
        query geometries that exist
        foreach geometry that exists
            load geometry
        next
    next

when the DB is on the local network criteria which load 133 entities takes a couple of seconds to load all 133 entities.

When the db is a remote db hosted on a VM in a data center on the other side of the world this takes about 3.5 mins to load them all.

The particularly slow bit seems to be the querying the geometry.  In initial testing (in TOAD - not in the service loading code) it seems to take about 2 secs to load the geometry for a single entity using the remote machine.  If we change the query to load all the geometries in a single go, it still seems to take 2 secs.  This sort of implies that it isn't the network overhead (as the amount of data being returned is much more for the query which returns all the geometries, but the time is the same).

Is this sort of performance overhead for a remote db vs local expected?  Why does doing each query separately take so much longer than doing them all in one go?  Is there anything we can do to mitigate this (apart from do all the queries in one go)?


问:
is there a way to remove UndefinedError in this code?
I am trying to display results of the most trending topics from twitter to my webpage but when i run the application it return jinja2.exceptions.UndefinedError: 'trends' is undefined. I suspect that i am not using  try/except how its supposed to.

```<code>@app.route('/')
def index():
    try:
        location = request.args.get('location')
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        return render_template('index.html',trends=trends)
    except tweepy.error.TweepError:
        return render_template('index.html')
</code>```

I also think there is an issue in my template code.

```<code><div class="column">
        <form  method="GET" action="{{url_for('index')}}">
            <div class="form-group">
                <p>See whats tending in your area.</p>
                <label for="">Enter location name</label>
                <input type="text" name="location" class="form-control" id="exampleInput" placeholder="example london " required>
                <input type="submit" value="Search" class="btn btn-primary">
            </div>
        </form>
    </div>

    <div class="column">
        <h4>Top Trending</h4>
        <ul class="list-group">
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
          </ul>
    </div>
</code>```

答:
Better to reorganize things something like this, to not query things if there is no location entered, and to not try to access trends if it's not set:

```<code>@app.route("/")
def index():
    location = request.args.get("location")
    trends = None
    if location:  # Only query if there is a location
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        # the above will throw an error if the place is invalid, that's fine
    return render_template("index.html", trends=trends, location=location)
</code>```

and

    <form method="GET">

See whats trending in your area.

            Enter location name
            <input type="text" name="location" value="{{ location|default("") }}" class="form-control" id="exampleInput" placeholder="example london " required>
            <input type="submit" value="Search" class="btn btn-primary">

    </form>

    {% if trends %}

Top Trending

        {% for trend in trends[0]["trends"]%}
            {{trend.name}}
        {% endfor %}

    {% endif %}

```

Body:
I am trying to display results of the most trending topics from twitter to my webpage but when i run the application it return jinja2.exceptions.UndefinedError: 'trends' is undefined. I suspect that i am not using  try/except how its supposed to.

@app.route('/')
def index():
    try:
        location = request.args.get('location')
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        return render_template('index.html',trends=trends)
    except tweepy.error.TweepError:
        return render_template('index.html')

I also think there is an issue in my template code.

        <form  method="GET" action="{{url_for('index')}}">

See whats tending in your area.

                Enter location name
                <input type="text" name="location" class="form-control" id="exampleInput" placeholder="example london " required>
                <input type="submit" value="Search" class="btn btn-primary">

        </form>

Top Trending

            {% for trend in trends[0]["trends"]%}
                {{trend.name}}
            {% endfor %}

Body:
Better to reorganize things something like this, to not query things if there is no location entered, and to not try to access trends if it's not set:

@app.route("/")
def index():
    location = request.args.get("location")
    trends = None
    if location:  # Only query if there is a location
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        # the above will throw an error if the place is invalid, that's fine
    return render_template("index.html", trends=trends, location=location)

and

<div class="column">
    <form method="GET">
        <div class="form-group">
            <p>See whats trending in your area.</p>
            <label for="">Enter location name</label>
            <input type="text" name="location" value="{{ location|default("") }}" class="form-control" id="exampleInput" placeholder="example london " required>
            <input type="submit" value="Search" class="btn btn-primary">
        </div>
    </form>
</div>

<div class="column">
    {% if trends %}
    <h4>Top Trending</h4>
    <ul class="list-group">
        {% for trend in trends[0]["trends"]%}
            <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
        {% endfor %}
      </ul>
    {% endif %}
</div>


问:
How to get System date formate
I have an application in Vuejs (Typescript) that get date from User, I am facing two issues for the time being.

Every time the User enter date of birth system decreases one.

If user enter 03/05/1981 and the System date formate is MM/dd/yyyy it store 5th of March.

I can't tell every person to change format to dd/MM/yyyy, or is there a way around.

Thanks

答:
By the details you have provided I assume everything happens in the browser.

Please check your browser localization settings even if your computer localization is setup as US if the browser has a different setting then it will be overwritten.

If you are sending the information to a different server please check how are you formatting the date in your request and which are the server side settings about localization.

Hope this helps.

Title: How to get System date formate


问:
Catch error server response with @nuxtjs/auth
I'm trying to catch the error response for @nuxtjs/auth but it doesn't seem to return anything but undefined.

It refuses to login if I include the user so I want to know why it's returning undefined.

CONFIG:

```<code>auth: {
    strategies: {
        local: {
            endpoints: {
                login: {
                    url: 'http://127.0.0.1:80/api/login',
                    method: 'post',
                    propertyName: 'token'
                },
                logout: false,
                user: {
                    url: 'http://127.0.0.1:80/api/me',
                    method: 'get',
                    propertyName: undefined
                }
            },
            tokenRequired: true,
            tokenType: 'bearer',
        }
    },
    plugins: [
        '@/plugins/auth.js'
    ]
},
</code>```

PLUGIN:

```<code>export default function ({ app }) {
    app.$auth.onError((error, name, endpoint) => {
        console.error(name, error)
    });
}
</code>```

VIEW FUNCTION:
- both handleSuccess and handleFailure returns undefined.

```<code>login() {
    this.toggleProcessing(0);

    let payload = {
        username: 'admin',
        password: 'admin123'
    }

    let handleSuccess = response => {
        console.log(response);
        this.toggleProcessing(0);
    }

    let handleFailure = error => {
        console.log(error);
        this.toggleProcessing(0);
    }

    this.$auth.loginWith('local', { data: payload }).then(handleSuccess).catch(handleFailure);
},
</code>```

答:
I fell into the same problem and after spending some time i found out a very good way to catch the response. The solution is to use the axios interceptor. Just replace your plugin file code with the following</p>

```<code>export default function ({$axios, $auth}){

  $axios.interceptors.response.use(function (response) {
    // Do something with response data

    return response;
  }, function (error) {
    // Do something with response error

    return Promise.reject(error);
  });
}
</code>```

Body:
I'm trying to catch the error response for @nuxtjs/auth but it doesn't seem to return anything but undefined.

It refuses to login if I include the user so I want to know why it's returning undefined.

CONFIG:

auth: {
    strategies: {
        local: {
            endpoints: {
                login: {
                    url: 'http://127.0.0.1:80/api/login',
                    method: 'post',
                    propertyName: 'token'
                },
                logout: false,
                user: {
                    url: 'http://127.0.0.1:80/api/me',
                    method: 'get',
                    propertyName: undefined
                }
            },
            tokenRequired: true,
            tokenType: 'bearer',
        }
    },
    plugins: [
        '@/plugins/auth.js'
    ]
},

PLUGIN:

export default function ({ app }) {
    app.$auth.onError((error, name, endpoint) => {
        console.error(name, error)
    });
}

VIEW FUNCTION:
- both handleSuccess and handleFailure returns undefined.

login() {
    this.toggleProcessing(0);

    let payload = {
        username: 'admin',
        password: 'admin123'
    }

    let handleSuccess = response => {
        console.log(response);
        this.toggleProcessing(0);
    }

    let handleFailure = error => {
        console.log(error);
        this.toggleProcessing(0);
    }

    this.$auth.loginWith('local', { data: payload }).then(handleSuccess).catch(handleFailure);
},

Body:
I fell into the same problem and after spending some time i found out a very good way to catch the response. The solution is to use the axios interceptor. Just replace your plugin file code with the following

export default function ({$axios, $auth}){

  $axios.interceptors.response.use(function (response) {
    // Do something with response data

    return response;
  }, function (error) {
    // Do something with response error

    return Promise.reject(error);
  });
}


问:
What is the best practice for adding constants in laravel? (Long List)
I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel.
I know the .env method that we use to add the constants.
Also I have made one constants file to use them for my project.
For example:

```<code>define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);
</code>```

And so on. It can reach upto 100 or more records. So What should be the best approach to write the constants. The .env method. Or adding the constant.php file?

Thanks

答:
You can define constants at the top of the web.php file located in routes and can be access the constants anywhere in project  with just constant name</p>

```<code>define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);
</code>```

Body:
I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel.
I know the .env method that we use to add the constants.
Also I have made one constants file to use them for my project.
For example:

define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);

And so on. It can reach upto 100 or more records. So What should be the best approach to write the constants. The .env method. Or adding the constant.php file?

Thanks

Body:
You can define constants at the top of the web.php file located in routes and can be access the constants anywhere in project  with just constant name

define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);


问:
How to construct an NHibernate query based on the following schema?
I'm trying to construct an NHibernate query to get a list of countries that a Share Class is available for sale (AFS) in.

This is the definition of the AFS table:

```<code>CREATE TABLE [MStar].[AFS](
    [AFS_ShareClassId] [int] NOT NULL,
    [AFS_CountryId] [int] NOT NULL,
 CONSTRAINT [PK_AFS] PRIMARY KEY CLUSTERED
(
    [AFS_ShareClassId] ASC,
    [AFS_CountryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [MStar].[AFS]  WITH CHECK ADD  CONSTRAINT [FK_AFS_Country] FOREIGN KEY([AFS_CountryId])
REFERENCES [MStar].[Country] ([Country_Id])
GO

ALTER TABLE [MStar].[AFS] CHECK CONSTRAINT [FK_AFS_Country]
</code>```

and this is the definition of the Country table:

```<code>CREATE TABLE [MStar].[Country](
    [Country_Id] [int] NOT NULL,
    [Country_ShortCode] [char](2) NULL,
    [Country_LongCode] [char](3) NOT NULL,
    [Country_RegionId] [char](3) NOT NULL,
    [Country_Name] [varchar](128) NOT NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED
(
    [Country_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [MStar].[Country]  WITH CHECK ADD  CONSTRAINT [FK_Country_Region] FOREIGN KEY([Country_RegionId])
REFERENCES [MStar].[Region] ([Region_Id])
GO

ALTER TABLE [MStar].[Country] CHECK CONSTRAINT [FK_Country_Region]
</code>```

At first, I'm I'm trying to make this query as simple as possible, as follows:

```<code>var afs = _session.CreateCriteria<AFS>().List<AFS>();
</code>```

This is always returning nothing, even though I know there's (tons of) stuff in the AFS & Country tables, which is suggesting to me that there's something wrong with my mapping files.

This is the AFS mapping:

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="FTMS.Domain"
                   namespace="FTMS.Domain.Entities">

    <class mutable="false" name="AFS" table="AFS" schema="MStar">
        <composite-id >
            <key-many-to-one name="ShareClass" column="AFS_ShareClassId" type="FTMS.Domain.Entities.ShareClass"></key-many-to-one>
        <key-many-to-one name="Country" column="AFS_CountryId" type="FTMS.Domain.Entities.Country"></key-many-to-one>
        </composite-id>

        <set name="Countries"
             inverse="true"
             lazy="true"
             cascade="save-update">
            <key column="Country_Id"></key>
            <one-to-many class="Country"/>
        </set>
    </class>
</hibernate-mapping>
</code>```

and this is the Country mapping:

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="FTMS.Domain"
                   namespace="FTMS.Domain.Entities">

  <class mutable="false" name="Country" table="Country" schema="MStar">

    <id name="Id" column="Country_Id">
      <generator class="native"></generator>
    </id>

    <property name="ShortCode" column="Country_ShortCode" />
    <property name="LongCode" column="Country_LongCode" />
    <property name="Name" column="Country_Name" />

      <set name="Funds" lazy="true">
            <key column="Fund_DomicileId"></key>
            <one-to-many class="Fund"/>
      </set>
  </class>
</hibernate-mapping>
</code>```

... and with all this, I'm getting the following error message:

```<code>The 'type' attribute is not declared.
</code>```

Ideally, the result would be an AFS object that contains a List<Country>. Is there something obvious I'm doing wrong?

答:
Okay, here's what I think's wrong...

Your mappings shou;d have the full assembly qualified type name as the name attribtue in the class element.

Your property elements should have the full assembly qualified type name for the type they map to. (this is probably what it's complaining about since it mentions 'type'.

Here's an example from our application...

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
  <class xmlns="urn:nhibernate-mapping-2.2" mutable="false" name="Civica.Common.Services.Web.Authorization.Model.Operation, Civica.Common.Services.Web, Version=1.0.4140.18095, Culture=neutral, PublicKeyToken=537c3450b3658434" table="`Operation`">
    <id name="Id" type="System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Id" />
      <generator class="hilo">
        <param name="max_lo">10000</param>
      </generator>
    </id>
    <property name="Name" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Name" length="50" unique="true" />
    </property>
    <property name="TypeName" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="TypeName" length="255" unique="true" />
    </property>
    <property name="Usage" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Usage" length="255" not-null="false" />
    </property>
    <property name="GroupingName" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="GroupingName" length="50" not-null="false" />
    </property>
  </class>
</hibernate-mapping>
</code>```

Note: this mapping was generated using the Fluent NHibernate API. It might include some optional elements that you don't need but I don't know because I don't do "manual" mapping.

Body:
I'm trying to construct an NHibernate query to get a list of countries that a Share Class is available for sale (AFS) in.

This is the definition of the AFS table:

CREATE TABLE [MStar].[AFS](
    [AFS_ShareClassId] [int] NOT NULL,
    [AFS_CountryId] [int] NOT NULL,
 CONSTRAINT [PK_AFS] PRIMARY KEY CLUSTERED
(
    [AFS_ShareClassId] ASC,
    [AFS_CountryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [MStar].[AFS]  WITH CHECK ADD  CONSTRAINT [FK_AFS_Country] FOREIGN KEY([AFS_CountryId])
REFERENCES [MStar].[Country] ([Country_Id])
GO

ALTER TABLE [MStar].[AFS] CHECK CONSTRAINT [FK_AFS_Country]

and this is the definition of the Country table:

CREATE TABLE [MStar].[Country](
    [Country_Id] [int] NOT NULL,
    [Country_ShortCode] [char](2) NULL,
    [Country_LongCode] [char](3) NOT NULL,
    [Country_RegionId] [char](3) NOT NULL,
    [Country_Name] [varchar](128) NOT NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED
(
    [Country_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [MStar].[Country]  WITH CHECK ADD  CONSTRAINT [FK_Country_Region] FOREIGN KEY([Country_RegionId])
REFERENCES [MStar].[Region] ([Region_Id])
GO

ALTER TABLE [MStar].[Country] CHECK CONSTRAINT [FK_Country_Region]

At first, I'm I'm trying to make this query as simple as possible, as follows:

var afs = _session.CreateCriteria<AFS>().List<AFS>();

This is always returning nothing, even though I know there's (tons of) stuff in the AFS & Country tables, which is suggesting to me that there's something wrong with my mapping files.

This is the AFS mapping:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="FTMS.Domain"
                   namespace="FTMS.Domain.Entities">

    <class mutable="false" name="AFS" table="AFS" schema="MStar">
        <composite-id >
            <key-many-to-one name="ShareClass" column="AFS_ShareClassId" type="FTMS.Domain.Entities.ShareClass"></key-many-to-one>
        <key-many-to-one name="Country" column="AFS_CountryId" type="FTMS.Domain.Entities.Country"></key-many-to-one>
        </composite-id>

        <set name="Countries"
             inverse="true"
             lazy="true"
             cascade="save-update">
            <key column="Country_Id"></key>
            <one-to-many class="Country"/>
        </set>
    </class>
</hibernate-mapping>

and this is the Country mapping:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="FTMS.Domain"
                   namespace="FTMS.Domain.Entities">

  <class mutable="false" name="Country" table="Country" schema="MStar">

    <id name="Id" column="Country_Id">
      <generator class="native"></generator>
    </id>

    <property name="ShortCode" column="Country_ShortCode" />
    <property name="LongCode" column="Country_LongCode" />
    <property name="Name" column="Country_Name" />

      <set name="Funds" lazy="true">
            <key column="Fund_DomicileId"></key>
            <one-to-many class="Fund"/>
      </set>
  </class>
</hibernate-mapping>

... and with all this, I'm getting the following error message:

The 'type' attribute is not declared.

Ideally, the result would be an AFS object that contains a List<Country>. Is there something obvious I'm doing wrong?

Body:
Okay, here's what I think's wrong...

Your mappings shou;d have the full assembly qualified type name as the name attribtue in the class element.

Your property elements should have the full assembly qualified type name for the type they map to. (this is probably what it's complaining about since it mentions 'type'.

Here's an example from our application...

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
  <class xmlns="urn:nhibernate-mapping-2.2" mutable="false" name="Civica.Common.Services.Web.Authorization.Model.Operation, Civica.Common.Services.Web, Version=1.0.4140.18095, Culture=neutral, PublicKeyToken=537c3450b3658434" table="`Operation`">
    <id name="Id" type="System.Int64, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Id" />
      <generator class="hilo">
        <param name="max_lo">10000</param>
      </generator>
    </id>
    <property name="Name" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Name" length="50" unique="true" />
    </property>
    <property name="TypeName" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="TypeName" length="255" unique="true" />
    </property>
    <property name="Usage" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="Usage" length="255" not-null="false" />
    </property>
    <property name="GroupingName" type="System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <column name="GroupingName" length="50" not-null="false" />
    </property>
  </class>
</hibernate-mapping>

Note: this mapping was generated using the Fluent NHibernate API. It might include some optional elements that you don't need but I don't know because I don't do "manual" mapping.


问:
Use of multiple <router-outlet> under Angular Material (8) is not working
Attempting to redefine the problem since I have some more information.

I am working with Angular Material (8) - along with the MDBootstrap package.
I have 2 areas. One is an area that deals with logins/authorizations (AUTH) and the other is a "dashboard" area (that is to be accessed after login) (DASHBOARD).

Here is the code that is working with AUTH and MYDASHBOARD - AUTH is being interpreted by Angular as being the primary. I named the second router-outlet definition mydashboard

app.component.html

```<code><router-outlet></router-outlet>
<router-outlet name="mydashboard"></router-outlet>
</code>```

app-routing.module.ts

```<code>const routes: Routes = [
  { path: 'auth', loadChildren: './kdc/authorization/authorization.module#AuthorizationModule' },
  { path: 'dashboard', loadChildren: './kdc/dashboard/dashboard.module#DashboardModule'  },
  { path: '**' , component: PageNotFoundComponent }

];
</code>```

authorization-routing.module.ts

```<code>export const routesAuth : Routes = [
    { path: 'login' , component: LoginComponent },
    { path: 'register' , component: RegisterComponent },
    { path: 'forgot-pass' , component: ForgotPasswordComponent },
];
</code>```

NOTE: EVERYTHING FOR (AUTH) IS WORKING - THERE IS NOTHING WRONG WITH THIS PART. THE PROBLEM IS WITH (DASHBOARD)

After logging in, the processing goes to the dashboard. I used the code below to send it to the dashboard

login.component.ts

```<code>onLoginSubmit() {
[... snip ...]
        if (this.in_results.count == 0)
          this.errorMsg = 'EMail/Login ID not found';
        else
          // go ahead and navigate to the HOME page
          this.router.navigate(['/dashboard']);
[... snip ...]
}
</code>```

dashboard-routing.module.ts

```<code>const dashboardroutes: Routes = [
    { path: 'clients', component: ClientsComponent, outlet: 'contentarea'  },
    { path: '', component: HomeComponent, outlet:'mydashboard' },
];
</code>```

NOTE: EVERYTHING EXECUTES FINE HERE, THE DASHBOARD DOES COME UP AND IT IS STORED IN <router-outlet name="mydashboard"></router-outlet> THE PROBLEM COMES WITH USING THE MENU.

When clicking on the "Clients" area, my expectation is that the "Client Information" will be placed into <router-outlet name="contentarea"> </router-outlet>  because of how home.component.html was defined.

home.component.html

```<code>[... snip ...]
                       <!-- Collapsible link -->
                            <mdb-accordion-item-body>
                                <ul>
                                    <li>  <a [routerLink]="[{ outlets: { primary: 'mydashboard', contentarea : 'clients' }}]" mdbWavesEffect> Press for clients</a></li>
                                    <li><a href="#" mdbWavesEffect>Link 2</a></li>
                                </ul>
                            </mdb-accordion-item-body>
                        </mdb-accordion-item>

[... snip ...]
<!--Main Layout-->
<main>
    <div class="container-fluid mt-5">
        <router-outlet name="contentarea"> </router-outlet>
    </div>
</main>
<!--/Main layout-->

[... snip ...]
</code>```

NOTE:
The processing does not go to: <router-outlet name="contentarea"> </router-outlet>

INSTEAD

It goes to: <router-outlet></router-outlet> located on page: app.component.html

QUESTION: Why does it do this? Am I doing it properly? Is there a better way?

I have looked at the following pieces of documentation

```<code>https://stackoverflow.com/questions/53702674/children-routing-not-working-and-application-redirects-to-the-404-page
https://www.tektutorialshub.com/angular/angular-child-routes-nested-routes/
https://stackoverflow.com/questions/52824639/nested-router-outlet-with-name-not-working
https://www.techiediaries.com/angular-router-multiple-outlets/
https://angular.io/guide/router
</code>```

but have not found anything as of yet.

Any information or ideas would be greatly appreciated.

TIA

答: Did you add <router-outlet></router-outlet> in your parent html component?

Body:
Attempting to redefine the problem since I have some more information.

I am working with Angular Material (8) - along with the MDBootstrap package.
I have 2 areas. One is an area that deals with logins/authorizations (AUTH) and the other is a "dashboard" area (that is to be accessed after login) (DASHBOARD).

Here is the code that is working with AUTH and MYDASHBOARD - AUTH is being interpreted by Angular as being the primary. I named the second router-outlet definition mydashboard

app.component.html

<router-outlet></router-outlet>
<router-outlet name="mydashboard"></router-outlet>

app-routing.module.ts

const routes: Routes = [
  { path: 'auth', loadChildren: './kdc/authorization/authorization.module#AuthorizationModule' },
  { path: 'dashboard', loadChildren: './kdc/dashboard/dashboard.module#DashboardModule'  },
  { path: '**' , component: PageNotFoundComponent }

];

authorization-routing.module.ts

export const routesAuth : Routes = [
    { path: 'login' , component: LoginComponent },
    { path: 'register' , component: RegisterComponent },
    { path: 'forgot-pass' , component: ForgotPasswordComponent },
];

NOTE: EVERYTHING FOR (AUTH) IS WORKING - THERE IS NOTHING WRONG WITH THIS PART. THE PROBLEM IS WITH (DASHBOARD)

After logging in, the processing goes to the dashboard. I used the code below to send it to the dashboard

login.component.ts

onLoginSubmit() {
[... snip ...]
        if (this.in_results.count == 0)
          this.errorMsg = 'EMail/Login ID not found';
        else
          // go ahead and navigate to the HOME page
          this.router.navigate(['/dashboard']);
[... snip ...]
}

dashboard-routing.module.ts

const dashboardroutes: Routes = [
    { path: 'clients', component: ClientsComponent, outlet: 'contentarea'  },
    { path: '', component: HomeComponent, outlet:'mydashboard' },
];

NOTE: EVERYTHING EXECUTES FINE HERE, THE DASHBOARD DOES COME UP AND IT IS STORED IN <router-outlet name="mydashboard"></router-outlet> THE PROBLEM COMES WITH USING THE MENU.

When clicking on the "Clients" area, my expectation is that the "Client Information" will be placed into <router-outlet name="contentarea"> </router-outlet>  because of how home.component.html was defined.

home.component.html

[... snip ...]

                            <mdb-accordion-item-body>

   Press for clients

Link 2

                            </mdb-accordion-item-body>
                        </mdb-accordion-item>

[... snip ...]

        <router-outlet name="contentarea"> </router-outlet>

[... snip ...]

NOTE:
The processing does not go to: <router-outlet name="contentarea"> </router-outlet>

INSTEAD

It goes to: <router-outlet></router-outlet> located on page: app.component.html

QUESTION: Why does it do this? Am I doing it properly? Is there a better way?

I have looked at the following pieces of documentation

https://stackoverflow.com/questions/53702674/children-routing-not-working-and-application-redirects-to-the-404-page
https://www.tektutorialshub.com/angular/angular-child-routes-nested-routes/
https://stackoverflow.com/questions/52824639/nested-router-outlet-with-name-not-working
https://www.techiediaries.com/angular-router-multiple-outlets/
https://angular.io/guide/router

but have not found anything as of yet.

Any information or ideas would be greatly appreciated.

TIA


问:
rename bigquery tablename
How to rename table name in bigquery table?

答: Here in a bigquery we need to copy table with new name and then you can delete existing table

Title: rename bigquery tablename


问:
height in vh (viewport) and max-height in px (pixels)
Is it possible to define height of element where CSS3 tells:

```<code>if viewport >= 1000px then
      element height: 300px (in pixels)
else if viewport < 1000px
      element height: 30vh (30% of viewport height)
</code>```

So all I want is to have an element that has 30% of viewport but not more than 300px. Is it possible?

This is what I've tested but didn't work:

```<code>div {
    height: 30vh;
    max-height: 300px;
}
</code>```

答:
You probably want something like this:
JSfiddle</p>

```<code><p>test content</p>

p {
  height: 30vh;
  background-color: blue;
}

@media only screen and (max-width: 1000px) {
  p {
    height: 300px;
    background-color: red;
  }
}
</code>```

Body:
Is it possible to define height of element where CSS3 tells:

if viewport >= 1000px then
      element height: 300px (in pixels)
else if viewport < 1000px
      element height: 30vh (30% of viewport height)

So all I want is to have an element that has 30% of viewport but not more than 300px. Is it possible?

This is what I've tested but didn't work:

div {
    height: 30vh;
    max-height: 300px;
}

Body:
You probably want something like this:
JSfiddle

<p>test content</p>

p {
  height: 30vh;
  background-color: blue;
}

@media only screen and (max-width: 1000px) {
  p {
    height: 300px;
    background-color: red;
  }
}


问:
Android Problem on Widget ImageButton click
I'm new in Android development, and my English is awfull.

I have an application with a homescreen widget.

When I start application, in main activity, I can select options for widget (these options are saved to a DB).

Then, I add a Widget, that it have an ImageButton on it, to the homescreen. The click on ImageButton works fine.

If I kill the application activity with some Task Manager, delete the widget, and add it again. The click on ImageButton crash.

Is this normally?

Here you have the error:

```<code>java.lang.RuntimeException: Unable to start service cat.aat.quoteswidget.Widget$UpdateService@45d1b188 with Intent { cmp=cat.aat.quoteswidget/.Widget$UpdateService }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3282)
at android.app.ActivityThread.access$3600(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2211)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at cat.aat.quoteswidget.Widget$UpdateService.buildUpdate(Widget.java:130)
at cat.aat.quoteswidget.Widget$UpdateService.onStart(Widget.java:90)
at android.app.Service.onStartCommand(Service.java:420)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3267)
... 10 more
</code>```

Thanks!

答: You have a NullPointerException on line 130 of your Widget.java file, in the buildUpdate() method of your UpdateService.

Body:
I'm new in Android development, and my English is awfull.

I have an application with a homescreen widget.

When I start application, in main activity, I can select options for widget (these options are saved to a DB).

Then, I add a Widget, that it have an ImageButton on it, to the homescreen. The click on ImageButton works fine.

If I kill the application activity with some Task Manager, delete the widget, and add it again. The click on ImageButton crash.

Is this normally?

Here you have the error:

java.lang.RuntimeException: Unable to start service cat.aat.quoteswidget.Widget$UpdateService@45d1b188 with Intent { cmp=cat.aat.quoteswidget/.Widget$UpdateService }: java.lang.NullPointerException
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3282)
at android.app.ActivityThread.access$3600(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2211)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at cat.aat.quoteswidget.Widget$UpdateService.buildUpdate(Widget.java:130)
at cat.aat.quoteswidget.Widget$UpdateService.onStart(Widget.java:90)
at android.app.Service.onStartCommand(Service.java:420)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3267)
... 10 more

Thanks!


问:
Multiple object tracking using radar data and extended kalman filter
thanks in advance.
I am new to the multiple object tracking field. So, I have been working on this for a couple of days. I have developed my first version of a single object tracker using an extended Kalman filter. I am estimating position, velocity by assuming a constant acceleration model. Now my question is how can I convert the existing model for multiple objects tracking. The main problem is I am using radar data. So, I am not able to get the references for developing the tracker. So, One good example or steps to achieve can help me in understanding the concept.</p>

答:
The answer to this question depends on a lot of things. For example, how much control and knowledge do you have over the whole system? If you know how many targets you need to track you can add all of them to the Kalman Filter state and for every measurement you perform data association to find out to which object a given measurement belongs. An easy association metric would be nearest neighbor.

If you don't know how many targets there will be you will want to implement a track management where each target you are tracking represents a track and you can model birth and death probabilities of targets.

Multi Target Tracking is a vast field and if you want to have an in-depth mathematical introduction I would recommend the 2015 survey paper "Multitarget Tracking" by Ba-Ngu Vo et al. You should be able to find a preprint pdf online.

If you are looking more for a lightweight tutorial I would assume it should be possible to find some tutorial or example code online where to start. As mentioned in the first paragraph, nearest neighbor association for a fixed amount of objects might be a good first step.


问:
dns_get_mx, dns_get_record and checkdnsrr don't work with MX (work with A though)
I'm trying to validate whether an MX record exists for a given domain, and nothing works.

```<code>// prepare the hostname
$hostname = 'gmail.com';
$hostname = idn_to_ascii($hostname);//php.net/manual/function.checkdnsrr.php#113537
$hostname = sprintf('%s.', $hostname);//php.net/manual/function.checkdnsrr.php#119969
// perform the checks
dns_get_mx($hostname, $dns_get_mx); // a.k.a. getmxrr()
$dns_get_record = dns_get_record($hostname, DNS_MX);
$checkdnsrr = checkdnsrr($hostname, 'MX');
// output the result
var_dump(array(
    'hostname' => $hostname,
    'dns_get_mx' => $dns_get_mx,
    'dns_get_record' => $dns_get_record,
    'checkdnsrr' => $checkdnsrr,
));
</code>```

Here's what I'm getting (for both gmail.com. and gmail.com, tried separately):

```<code>Warning: dns_get_record(): A temporary server error occurred. in /var/www/html/example.php
array (size=4)
  'hostname' => string 'gmail.com.' (length=10)
  'dns_get_mx' =>
    array (size=0)
      empty
  'dns_get_record' => boolean false
  'checkdnsrr' => boolean false
</code>```

If I replace MX with A, dns_get_record() returns a correct IP address, and checkdnsrr() returns true.

There's nothing in the logs (except for the above warning), and googling didn't help. How do I debug this?

UPD The issue appears in my local VirtualBox environment (PHP 5.6.39); everything actually works on the production server (PHP 7.3.11)

答:
VirtualBox seems to be overwriting /etc/resolv.conf, and that messes up the DNS on the guest machine.

My fix for now is:

```<code>echo "nameserver 1.1.1.1" > /etc/resolv.conf
</code>```

More info

Body:
I'm trying to validate whether an MX record exists for a given domain, and nothing works.

// prepare the hostname
$hostname = 'gmail.com';
$hostname = idn_to_ascii($hostname);//php.net/manual/function.checkdnsrr.php#113537
$hostname = sprintf('%s.', $hostname);//php.net/manual/function.checkdnsrr.php#119969
// perform the checks
dns_get_mx($hostname, $dns_get_mx); // a.k.a. getmxrr()
$dns_get_record = dns_get_record($hostname, DNS_MX);
$checkdnsrr = checkdnsrr($hostname, 'MX');
// output the result
var_dump(array(
    'hostname' => $hostname,
    'dns_get_mx' => $dns_get_mx,
    'dns_get_record' => $dns_get_record,
    'checkdnsrr' => $checkdnsrr,
));

Here's what I'm getting (for both gmail.com. and gmail.com, tried separately):

Warning: dns_get_record(): A temporary server error occurred. in /var/www/html/example.php
array (size=4)
  'hostname' => string 'gmail.com.' (length=10)
  'dns_get_mx' =>
    array (size=0)
      empty
  'dns_get_record' => boolean false
  'checkdnsrr' => boolean false

If I replace MX with A, dns_get_record() returns a correct IP address, and checkdnsrr() returns true.

There's nothing in the logs (except for the above warning), and googling didn't help. How do I debug this?

UPD The issue appears in my local VirtualBox environment (PHP 5.6.39); everything actually works on the production server (PHP 7.3.11)

Body:
VirtualBox seems to be overwriting /etc/resolv.conf, and that messes up the DNS on the guest machine.

My fix for now is:

echo "nameserver 1.1.1.1" > /etc/resolv.conf

More info


问:
How to convert a directory to a ZIP?
I wanted to know how to convert a file (x) directly to a ZIP (x.zip), and convert it back into a normal file, using python (3.7)

答:
For zipping and Unzipping without password protected:

For zipping the File, You can use pyminizip module

```<code>import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("/home/paulsteven/src.txt",'src', "dst.zip", None, compression_level)
</code>```

For Unzipping the File, Use Zipfile module

```<code>from zipfile import ZipFile
with ZipFile('/home/paulsteven/dst.zip') as zf:
    zf.extractall()
</code>```

For zipping and Unzipping with password protected:

For ZIP:

```<code>import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("/home/paulsteven/src.txt",'src', "dst.zip", "password", compression_level)
</code>```

For UNZIP:

```<code>from zipfile import ZipFile

with ZipFile('/home/paulsteven/dst.zip') as zf:
    zf.extractall(pwd=b'password')
</code>```

Title: How to convert a directory to a ZIP?

Body:
For zipping and Unzipping without password protected:

For zipping the File, You can use pyminizip module

import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("/home/paulsteven/src.txt",'src', "dst.zip", None, compression_level)

For Unzipping the File, Use Zipfile module

from zipfile import ZipFile
with ZipFile('/home/paulsteven/dst.zip') as zf:
    zf.extractall()

For zipping and Unzipping with password protected:

For ZIP:

import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("/home/paulsteven/src.txt",'src', "dst.zip", "password", compression_level)

For UNZIP:

from zipfile import ZipFile

with ZipFile('/home/paulsteven/dst.zip') as zf:
    zf.extractall(pwd=b'password')


答:
You're noticing network latency.

There needs to be at least one round-trip with the server each time you make a query.

If the server is "far", i.e. 500ms ping, that means at minimum one second of latency per query. This is uncompressible - even if the query returns no rows, that 1s hit will happen.

The bandwidth of the network is an unrelated characteristic. If your bandwidth is high, you wont notice a big difference between transferring a large dataset and a small one. But both will still suffer the latency hit in exactly the same way.

I found this article has interesting (if dated) information: It's the latency, Stupid.

Title: Slow performance when querying remote db - is this normal?