问:
Calculate bounding box for OpenStreetMap
Is possible to get bounding box from coordinates (latitude, longitude), zoom level and size (screen)? I found only calculating bounding box from tile. I need it, because OpenStreetMap accept only bbox in export mode. I dont have any experience with this, so I will be glad for any advice. Thanks.

Edit:

Sorry, I was describe it wrong. I write something like this:

(pseudocode)
`

```<code>x = getX(longitude, zoom); //X Tile - return 41870
y = getY(latitude, zoom); //Y Tile - return 22226
north = getXToLongitude(x, zoom); //return 49.998779
south = getXToLongitude(x + 1, zoom); //return 50.004272
west = getYToLatitude(y, zoom); //return 49.997078
east = getYToLatitude(y + 1, zoom); //return 50.000609
</code>```

`

But this is very inaccurate and and shifts the center of the 100 m.

答:
I tried to implement Angular component for OSM embedding, based on code samples from OSM. It turned out to be pretty hard. :(

Here is the code I have so far:

```<code>import { Component, Input, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-osm',
  templateUrl: './osm.component.html',
  styleUrls: ['./osm.component.scss']
})
export class OsmComponent implements OnInit {
  @Input() latitude: number;
  @Input() longitude: number;
  @Input() zoom: number;

  public iframeSrc;
  public extMapSrc;

  constructor(
    private sanitizer: DomSanitizer
  ) { }

  ngOnInit(): void {
    const bbox = this.boundaryBox(this.latitude, this.longitude, 1100, 400, 16);
    this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(
      `https://www.openstreetmap.org/export/embed.html` +
      `?bbox=${bbox.join(',')}` +
      `&layer=mapnik` +
      `&marker=${this.latitude},${this.longitude}`
    );
    this.extMapSrc = this.sanitizer.bypassSecurityTrustUrl(
      `https://www.openstreetmap.org/` +
      `?mlat=${this.latitude}&mlon=${this.longitude}` +
      `#map=17/${this.latitude}/${this.longitude}`
    );
  }

  lonToTile(lon: number, zoom: number): number {
    return (Math.floor((lon + 180) / 360 * Math.pow(2, zoom)));
  }

  latToTile(lat: number, zoom: number): number {
    return Math.floor(
      (1 - Math.log(
        Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)
      ) / Math.PI) / 2 * Math.pow(2, zoom)
    );
  }

  tileToLon(x: number, zoom: number): number {
    return (x / Math.pow(2, zoom) * 360 - 180);
  }

  tileToLat(y: number, zoom: number): number {
    const n = Math.PI - 2 * Math.PI * y / Math.pow(2, zoom);
    return (180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))));
  }

  boundaryBox(
    lat: number,
    lon: number,
    width: number = 1110,
    height: number = 400,
    zoom: number = 17,
  ) {
    const tileSize = 256;

    const lonTile = this.lonToTile(lon, zoom);
    const latTile = this.latToTile(lat, zoom);

    const minLonTile = (lonTile * tileSize - width / 2) / tileSize;
    const minLatTile = (latTile * tileSize - height / 2) / tileSize;
    const maxLonTile = (lonTile * tileSize + width / 2) / tileSize;
    const maxLatTile = (latTile * tileSize + height / 2) / tileSize;

    const minLon = this.tileToLon(minLonTile, zoom);
    const minLat = this.tileToLat(minLatTile, zoom);
    const maxLon = this.tileToLon(maxLonTile, zoom);
    const maxLat = this.tileToLat(maxLatTile, zoom);

    return [minLon, minLat, maxLon, maxLat];
  }

}
</code>```

It (kind of) works, though map positioning for some reason is not exactly correct.

Body:
Is possible to get bounding box from coordinates (latitude, longitude), zoom level and size (screen)? I found only calculating bounding box from tile. I need it, because OpenStreetMap accept only bbox in export mode. I dont have any experience with this, so I will be glad for any advice. Thanks.

Edit:

Sorry, I was describe it wrong. I write something like this:

(pseudocode)
`

x = getX(longitude, zoom); //X Tile - return 41870
y = getY(latitude, zoom); //Y Tile - return 22226
north = getXToLongitude(x, zoom); //return 49.998779
south = getXToLongitude(x + 1, zoom); //return 50.004272
west = getYToLatitude(y, zoom); //return 49.997078
east = getYToLatitude(y + 1, zoom); //return 50.000609

`

But this is very inaccurate and and shifts the center of the 100 m.

Body:
I tried to implement Angular component for OSM embedding, based on code samples from OSM. It turned out to be pretty hard. :(

Here is the code I have so far:

import { Component, Input, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-osm',
  templateUrl: './osm.component.html',
  styleUrls: ['./osm.component.scss']
})
export class OsmComponent implements OnInit {
  @Input() latitude: number;
  @Input() longitude: number;
  @Input() zoom: number;

  public iframeSrc;
  public extMapSrc;

  constructor(
    private sanitizer: DomSanitizer
  ) { }

  ngOnInit(): void {
    const bbox = this.boundaryBox(this.latitude, this.longitude, 1100, 400, 16);
    this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(
      `https://www.openstreetmap.org/export/embed.html` +
      `?bbox=${bbox.join(',')}` +
      `&layer=mapnik` +
      `&marker=${this.latitude},${this.longitude}`
    );
    this.extMapSrc = this.sanitizer.bypassSecurityTrustUrl(
      `https://www.openstreetmap.org/` +
      `?mlat=${this.latitude}&mlon=${this.longitude}` +
      `#map=17/${this.latitude}/${this.longitude}`
    );
  }

  lonToTile(lon: number, zoom: number): number {
    return (Math.floor((lon + 180) / 360 * Math.pow(2, zoom)));
  }

  latToTile(lat: number, zoom: number): number {
    return Math.floor(
      (1 - Math.log(
        Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)
      ) / Math.PI) / 2 * Math.pow(2, zoom)
    );
  }

  tileToLon(x: number, zoom: number): number {
    return (x / Math.pow(2, zoom) * 360 - 180);
  }

  tileToLat(y: number, zoom: number): number {
    const n = Math.PI - 2 * Math.PI * y / Math.pow(2, zoom);
    return (180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))));
  }

  boundaryBox(
    lat: number,
    lon: number,
    width: number = 1110,
    height: number = 400,
    zoom: number = 17,
  ) {
    const tileSize = 256;

    const lonTile = this.lonToTile(lon, zoom);
    const latTile = this.latToTile(lat, zoom);

    const minLonTile = (lonTile * tileSize - width / 2) / tileSize;
    const minLatTile = (latTile * tileSize - height / 2) / tileSize;
    const maxLonTile = (lonTile * tileSize + width / 2) / tileSize;
    const maxLatTile = (latTile * tileSize + height / 2) / tileSize;

    const minLon = this.tileToLon(minLonTile, zoom);
    const minLat = this.tileToLat(minLatTile, zoom);
    const maxLon = this.tileToLon(maxLonTile, zoom);
    const maxLat = this.tileToLat(maxLatTile, zoom);

    return [minLon, minLat, maxLon, maxLat];
  }

}

It (kind of) works, though map positioning for some reason is not exactly correct.


来源: stackexchange

问:
Raspbian update independent of Motioneyeos update?
I have installed Motioneyeos on a Pi Zero and on a Pi2, and it works like a charm in both of them. The control of the 2 systems can be unified on the web server of any one of them. The web interface is clear and allows to customize hundreds aspects of the program. Anything perfect so far.

Trying to understand a little bit how does it work, I have logged to one of the 2 Pis through ssh and I have checked that the OS is kept to a bare minimum. uname -r returns 4.19.65.

On the web interface of the app it is possible to check if the last version of the program is the one running. I have checked, and yes, I have the last version.

My question is: does it make sense to upgrade the OS components used by the program (apt update, apt dist-upgrade) even if the last version of the program is the one running in my Pis? Apt is not even installed, so the first thing would be to bring it there and install it, but I am afraid that if I update the OS, the program may stop to work...

答: I answer myself thanks to the feedback received in another forum. Motioneyeos is an embedded software based on Buildroot and as such it is not possible to install any package on it. To be able to install a package on Motioneyeos, Motioneyeos has to be installed on an full OS as Raspbian following the instructions in Motioneyeos web ==>></p>

ContentLicense: CC BY-SA 4.0


问:
How to get substring between two strings in DART?
How can i achieve similar solution to: How to get a substring between two strings in PHP? but in DART

For example I have a String:

String data = "the quick brown fox jumps over the lazy dog"

I have two other Strings: quick and over

I want the data inside these two Strings and expecting result:

brown fox jumps

答:
```<code>final str = 'the quick brown fox jumps over the lazy dog';
final start = 'quick';
final end = 'over';

final startIndex = str.indexOf(start);
final endIndex = str.indexOf(end);
final result = str.substring(startIndex + start.length, endIndex).trim();
</code>```


问:
How to remove function from file on Linux?
We have in our project several files that contains implementation of functions, what I need is to find in one of the files:

The specific location where a function is declared

Remove the function - meaning- the line where it start and the following 4 lines.

How can it be done using bash commands?

答:
You can do this using sed. The exact command would depend on the function (and language) that you are trying to remove. In general, you can use sed -i '/STARTING_PATTERN/,/ENDING_PATTERN/d' file.ext to delete from STARTING_PATTERN to ENDING_PATTERN. Say you have a C function (obviously this is a dummy example):

```<code>double toDouble(int input) {
    double output = (double)input;
    return output;
}
</code>```

You could use sed -i '/^double toDouble(int input) {$/,/^}$/d' file.c. This will delete from a line that has only the signature of the function (double toDouble(int input) {) to the next line that has only a } on it. Obviously you will need to tailor your starting and ending patterns to whatever the function you are trying to match looks like. The ^ and $ match the beginning and end of a line.

Edit: fixing typo

Body:
You can do this using sed. The exact command would depend on the function (and language) that you are trying to remove. In general, you can use sed -i '/STARTING_PATTERN/,/ENDING_PATTERN/d' file.ext to delete from STARTING_PATTERN to ENDING_PATTERN. Say you have a C function (obviously this is a dummy example):

double toDouble(int input) {
    double output = (double)input;
    return output;
}

You could use sed -i '/^double toDouble(int input) {$/,/^}$/d' file.c. This will delete from a line that has only the signature of the function (double toDouble(int input) {) to the next line that has only a } on it. Obviously you will need to tailor your starting and ending patterns to whatever the function you are trying to match looks like. The ^ and $ match the beginning and end of a line.

Edit: fixing typo


问:
C#- Need to access JSON Data values from my Dynamic object
I have a json data as below -

```<code>{
    "request": {
        "type": "",
        "query": "",
        "language": "en",
        "unit": "m"
    },
    "location": {
        "name": "",
        "country": "",
        "region": "",
        "lat": "",
        "lon": "",
        "timezone_id": "Asia/Kolkata",
        "localtime": "2020-05-29 23:30",
        "localtime_epoch": 1590795000,
        "utc_offset": "5.50"
    },
    "current": {
        "observation_time": "06:00 PM",
        "temperature": 40,
        "weather_code": 116,
        "weather_icons": [
            ""
        ],
        "weather_descriptions": [
            "Partly cloudy"
        ],
        "wind_speed": 9,
        "wind_degree": 230,
        "wind_dir": "SW",
        "pressure": 1006,
        "precip": 0,
        "humidity": 26,
        "cloudcover": 25,
        "feelslike": 42,
        "uv_index": 1,
        "visibility": 6,
        "is_day": "no"
    },
    "forecast": {
        "2020-05-28": {
            "date": "2020-05-28",
            "date_epoch": 1590624000,
            "astro": {
                "sunrise": "05:41 AM",
                "sunset": "06:46 PM",
                "moonrise": "10:29 AM",
                "moonset": "11:48 PM",
                "moon_phase": "First Quarter",
                "moon_illumination": 39
            },
            "mintemp": 32,
            "maxtemp": 44,
            "avgtemp": 38,
            "totalsnow": 0,
            "sunhour": 13.1,
            "uv_index": 9
        }
    }
}
</code>```

First Three nodes("request","location","current") are binding properly but for "forecast" since the first node is a date time. I have written in the following way-

```<code>var dataObjects = JsonConvert.DeserializeObject<Location_Weather.Weather>(customerJsonString);
var dataObjects23 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>> (customerJsonString);
dynamic forecast_details = dataObjects23["forecast"];
</code>```

This is my Model->

```<code>public class New_Location_Weather
    {

        [JsonProperty("request")]
        public Request Request { get; set; }

        [JsonProperty("location")]
        public Location Location { get; set; }

        [JsonProperty("current")]
        public Current Current { get; set; }

        [JsonProperty("forecast")]
        public Forecast Forecast { get; set; }
    }

    public partial class Current
    {
        [JsonProperty("observation_time")]
        public string ObservationTime { get; set; }

        [JsonProperty("temperature")]
        public long Temperature { get; set; }

        [JsonProperty("weather_code")]
        public long WeatherCode { get; set; }

        [JsonProperty("weather_icons")]
        public Uri[] WeatherIcons { get; set; }

        [JsonProperty("weather_descriptions")]
        public string[] WeatherDescriptions { get; set; }

        [JsonProperty("wind_speed")]
        public long WindSpeed { get; set; }

        [JsonProperty("wind_degree")]
        public long WindDegree { get; set; }

        [JsonProperty("wind_dir")]
        public string WindDir { get; set; }

        [JsonProperty("pressure")]
        public long Pressure { get; set; }

        [JsonProperty("precip")]
        public long Precip { get; set; }

        [JsonProperty("humidity")]
        public long Humidity { get; set; }

        [JsonProperty("cloudcover")]
        public long Cloudcover { get; set; }

        [JsonProperty("feelslike")]
        public long Feelslike { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }

        [JsonProperty("visibility")]
        public long Visibility { get; set; }

        [JsonProperty("is_day")]
        public string IsDay { get; set; }
    }

    public partial class Forecast
    {
        [JsonProperty("2020-05-28")]
        public The20200528 The20200528 { get; set; }
    }

    public partial class The20200528
    {
        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }

        [JsonProperty("date_epoch")]
        public long DateEpoch { get; set; }

        [JsonProperty("astro")]
        public Astro Astro { get; set; }

        [JsonProperty("mintemp")]
        public long Mintemp { get; set; }

        [JsonProperty("maxtemp")]
        public long Maxtemp { get; set; }

        [JsonProperty("avgtemp")]
        public long Avgtemp { get; set; }

        [JsonProperty("totalsnow")]
        public long Totalsnow { get; set; }

        [JsonProperty("sunhour")]
        public double Sunhour { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }
    }

    public partial class Astro
    {
        [JsonProperty("sunrise")]
        public string Sunrise { get; set; }

        [JsonProperty("sunset")]
        public string Sunset { get; set; }

        [JsonProperty("moonrise")]
        public string Moonrise { get; set; }

        [JsonProperty("moonset")]
        public string Moonset { get; set; }

        [JsonProperty("moon_phase")]
        public string MoonPhase { get; set; }

        [JsonProperty("moon_illumination")]
        public long MoonIllumination { get; set; }
    }

    public partial class Location
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }

        [JsonProperty("region")]
        public string Region { get; set; }

        [JsonProperty("lat")]
        public string Lat { get; set; }

        [JsonProperty("lon")]
        public string Lon { get; set; }

        [JsonProperty("timezone_id")]
        public string TimezoneId { get; set; }

        [JsonProperty("localtime")]
        public string Localtime { get; set; }

        [JsonProperty("localtime_epoch")]
        public long LocaltimeEpoch { get; set; }

        [JsonProperty("utc_offset")]
        public string UtcOffset { get; set; }
    }

    public partial class Request
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("query")]
        public string Query { get; set; }

        [JsonProperty("language")]
        public string Language { get; set; }

        [JsonProperty("unit")]
        public string Unit { get; set; }
    }
</code>```

Now issue is I am not able to get the values. I need some guidance on how to get this values from the dynamic object which is forecast_details into my C# code.
Below is the screenshot of the values which I need to access them in my c# code

While debugging the dynamic object I found the values in my result view. But I am not sure how to access those values in my c# code.

Please do let me know on how to get these values from my C# dynamic object(forecast_details).

答:
This is what I figured it out. Hope it helps for others to.</p>

```<code>JObject obj = JObject.Parse(customerJsonString);
var forecast_details = obj.SelectToken("forecast").Children().OfType<JProperty>()
                                    .ToDictionary(p => p.Name, p => new
                                    {
                                        MaxTemp = (int)p.First()["maxtemp"],
                                        MinTemp = (int)p.First()["mintemp"]
                                    });
if(forecast_details.Count>0)
{
  int max_temp = forecast_details.Values.Select(x => x.MaxTemp).FirstOrDefault();
  int min_temp = forecast_details.Values.Select(x => x.MinTemp).FirstOrDefault();
}
</code>```

Body:
I have a json data as below -

{
    "request": {
        "type": "",
        "query": "",
        "language": "en",
        "unit": "m"
    },
    "location": {
        "name": "",
        "country": "",
        "region": "",
        "lat": "",
        "lon": "",
        "timezone_id": "Asia/Kolkata",
        "localtime": "2020-05-29 23:30",
        "localtime_epoch": 1590795000,
        "utc_offset": "5.50"
    },
    "current": {
        "observation_time": "06:00 PM",
        "temperature": 40,
        "weather_code": 116,
        "weather_icons": [
            ""
        ],
        "weather_descriptions": [
            "Partly cloudy"
        ],
        "wind_speed": 9,
        "wind_degree": 230,
        "wind_dir": "SW",
        "pressure": 1006,
        "precip": 0,
        "humidity": 26,
        "cloudcover": 25,
        "feelslike": 42,
        "uv_index": 1,
        "visibility": 6,
        "is_day": "no"
    },
    "forecast": {
        "2020-05-28": {
            "date": "2020-05-28",
            "date_epoch": 1590624000,
            "astro": {
                "sunrise": "05:41 AM",
                "sunset": "06:46 PM",
                "moonrise": "10:29 AM",
                "moonset": "11:48 PM",
                "moon_phase": "First Quarter",
                "moon_illumination": 39
            },
            "mintemp": 32,
            "maxtemp": 44,
            "avgtemp": 38,
            "totalsnow": 0,
            "sunhour": 13.1,
            "uv_index": 9
        }
    }
}

First Three nodes("request","location","current") are binding properly but for "forecast" since the first node is a date time. I have written in the following way-

var dataObjects = JsonConvert.DeserializeObject<Location_Weather.Weather>(customerJsonString);
var dataObjects23 = JsonConvert.DeserializeObject<Dictionary<string, dynamic>> (customerJsonString);
dynamic forecast_details = dataObjects23["forecast"];

This is my Model->

public class New_Location_Weather
    {

        [JsonProperty("request")]
        public Request Request { get; set; }

        [JsonProperty("location")]
        public Location Location { get; set; }

        [JsonProperty("current")]
        public Current Current { get; set; }

        [JsonProperty("forecast")]
        public Forecast Forecast { get; set; }
    }

    public partial class Current
    {
        [JsonProperty("observation_time")]
        public string ObservationTime { get; set; }

        [JsonProperty("temperature")]
        public long Temperature { get; set; }

        [JsonProperty("weather_code")]
        public long WeatherCode { get; set; }

        [JsonProperty("weather_icons")]
        public Uri[] WeatherIcons { get; set; }

        [JsonProperty("weather_descriptions")]
        public string[] WeatherDescriptions { get; set; }

        [JsonProperty("wind_speed")]
        public long WindSpeed { get; set; }

        [JsonProperty("wind_degree")]
        public long WindDegree { get; set; }

        [JsonProperty("wind_dir")]
        public string WindDir { get; set; }

        [JsonProperty("pressure")]
        public long Pressure { get; set; }

        [JsonProperty("precip")]
        public long Precip { get; set; }

        [JsonProperty("humidity")]
        public long Humidity { get; set; }

        [JsonProperty("cloudcover")]
        public long Cloudcover { get; set; }

        [JsonProperty("feelslike")]
        public long Feelslike { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }

        [JsonProperty("visibility")]
        public long Visibility { get; set; }

        [JsonProperty("is_day")]
        public string IsDay { get; set; }
    }

    public partial class Forecast
    {
        [JsonProperty("2020-05-28")]
        public The20200528 The20200528 { get; set; }
    }

    public partial class The20200528
    {
        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }

        [JsonProperty("date_epoch")]
        public long DateEpoch { get; set; }

        [JsonProperty("astro")]
        public Astro Astro { get; set; }

        [JsonProperty("mintemp")]
        public long Mintemp { get; set; }

        [JsonProperty("maxtemp")]
        public long Maxtemp { get; set; }

        [JsonProperty("avgtemp")]
        public long Avgtemp { get; set; }

        [JsonProperty("totalsnow")]
        public long Totalsnow { get; set; }

        [JsonProperty("sunhour")]
        public double Sunhour { get; set; }

        [JsonProperty("uv_index")]
        public long UvIndex { get; set; }
    }

    public partial class Astro
    {
        [JsonProperty("sunrise")]
        public string Sunrise { get; set; }

        [JsonProperty("sunset")]
        public string Sunset { get; set; }

        [JsonProperty("moonrise")]
        public string Moonrise { get; set; }

        [JsonProperty("moonset")]
        public string Moonset { get; set; }

        [JsonProperty("moon_phase")]
        public string MoonPhase { get; set; }

        [JsonProperty("moon_illumination")]
        public long MoonIllumination { get; set; }
    }

    public partial class Location
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }

        [JsonProperty("region")]
        public string Region { get; set; }

        [JsonProperty("lat")]
        public string Lat { get; set; }

        [JsonProperty("lon")]
        public string Lon { get; set; }

        [JsonProperty("timezone_id")]
        public string TimezoneId { get; set; }

        [JsonProperty("localtime")]
        public string Localtime { get; set; }

        [JsonProperty("localtime_epoch")]
        public long LocaltimeEpoch { get; set; }

        [JsonProperty("utc_offset")]
        public string UtcOffset { get; set; }
    }

    public partial class Request
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("query")]
        public string Query { get; set; }

        [JsonProperty("language")]
        public string Language { get; set; }

        [JsonProperty("unit")]
        public string Unit { get; set; }
    }

Now issue is I am not able to get the values. I need some guidance on how to get this values from the dynamic object which is forecast_details into my C# code.
Below is the screenshot of the values which I need to access them in my c# code

While debugging the dynamic object I found the values in my result view. But I am not sure how to access those values in my c# code.

Please do let me know on how to get these values from my C# dynamic object(forecast_details).

Body:
This is what I figured it out. Hope it helps for others to.

JObject obj = JObject.Parse(customerJsonString);
var forecast_details = obj.SelectToken("forecast").Children().OfType<JProperty>()
                                    .ToDictionary(p => p.Name, p => new
                                    {
                                        MaxTemp = (int)p.First()["maxtemp"],
                                        MinTemp = (int)p.First()["mintemp"]
                                    });
if(forecast_details.Count>0)
{
  int max_temp = forecast_details.Values.Select(x => x.MaxTemp).FirstOrDefault();
  int min_temp = forecast_details.Values.Select(x => x.MinTemp).FirstOrDefault();
}


问:
With equal heights constrain between two views, how do I decide which view shrinks/inflates?
Lets say I have a horizontal stack view, wherein 2 stack views are present (each internal stack view naturally represents a column). Every internal stackview has 2 labels. Now I set the equal with constraint and assert that the first constraint in the first internal stackview needs to have equal height to the first view in the second stack view. How do I decide, whether the first shrinks, or the second grows?

in this case the green view grew. How do I make the yellow view shrink?

答:
You can decide whether first view in the first stack view should shrink or the first view in the second stack view grows by setting Content Hugging Priority and Content Compression Resistance Priority for both.

If you want view in the first stack view shrinks then set Vertical Content Compression Resistance Priority for the first view in first stack view to be less than Vertical Content Hugging Priority of the first view in second stack view and vice versa for the opposite scenario.

For example set Vertical Content Compression Resistance Priority for the first view in first stack view to be 250 and Vertical Content Hugging Priority of the first view in second stack view should be 251. In this case view in first stack view will get shrink.


问:
Cannot find polygons within polygons using spatial LINQ queries
I loaded this (Quebec) OSM PBF file in my PostgreSQL database and from a .NET Core Web Api, I'm trying to do basic queries, like finding polygons within a specified area, but getting no results.

I have scaffolded a DbContext using this command:

```<code>Scaffold-DbContext "Host=52.0.0.0;Database=my-db;Username=postgres;Password=password" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models
</code>```

I got this error though:

Could not find type mapping for column 'public.planet_osm_polygon.way'
  with data type 'geometry(Geometry,3857)'. Skipping column. Unable to
  scaffold the index 'planet_osm_polygon_way_idx'. The following columns
  could not be scaffolded: way.

So I manually added this property to the PlanetOsmPolygon.cs that was produced by the command

```<code>public Geometry Way { get; set; }
</code>```

Weird thing is I do have Geometry available as I can declare a variable of that type and compile properly....

I think I have properly set up the context for PostgreSQL and PostGIS

```<code>services.AddDbContext<OSMContext>(x =>
{
        var connectionString = Configuration.GetValue<string>("SQL:Prod");
        x.UseNpgsql(connectionString, o =>
        {
            o.CommandTimeout(240);
            o.UseNetTopologySuite();

        });

}, ServiceLifetime.Scoped);
</code>```

Here's the API method code

```<code>GeometryFactory geometryFactory = new GeometryFactory();

//values are from query string
//north=45.5154045103725&south=45.4901382447544&west=-73.5854034422038&east=-73.5493545534017

Polygon space = geometryFactory.CreatePolygon(new Coordinate[] {
            new Coordinate(west, south),
            new Coordinate(east, south),
            new Coordinate(east, north),
            new Coordinate(west, north),
            new Coordinate(west, south) });

//var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.Covers(space)).ToList();
//var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.CoveredBy(space)).ToList();
//var polygons = OSMContext.PlanetOsmPolygon.Where(x => space.Covers(x.Way)).ToList();
//var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.Covers(space)).ToList();
var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.Within(space)).ToList();
</code>```

As you can see, I've tried a few way around this, with no results ever. space is valid (IsValid returns true).

Is it the values that I'm using for space that may be a problem ? Or that scaffold issue ?

答:
The OSM data is saved using CRS 3857.

The bounding box is created using WGS 84 (4326), but you haven't specified the CRS.

To fix it, you can specify the bounding box coordinates in 3857, or you can project the current 4326 box to 3857.

Body:
I loaded this (Quebec) OSM PBF file in my PostgreSQL database and from a .NET Core Web Api, I'm trying to do basic queries, like finding polygons within a specified area, but getting no results.

I have scaffolded a DbContext using this command:

Scaffold-DbContext "Host=52.0.0.0;Database=my-db;Username=postgres;Password=password" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models

I got this error though:

Could not find type mapping for column 'public.planet_osm_polygon.way'
  with data type 'geometry(Geometry,3857)'. Skipping column. Unable to
  scaffold the index 'planet_osm_polygon_way_idx'. The following columns
  could not be scaffolded: way.

So I manually added this property to the PlanetOsmPolygon.cs that was produced by the command

public Geometry Way { get; set; }

Weird thing is I do have Geometry available as I can declare a variable of that type and compile properly....

I think I have properly set up the context for PostgreSQL and PostGIS

services.AddDbContext<OSMContext>(x =>
{
        var connectionString = Configuration.GetValue<string>("SQL:Prod");
        x.UseNpgsql(connectionString, o =>
        {
            o.CommandTimeout(240);
            o.UseNetTopologySuite();

        });

}, ServiceLifetime.Scoped);

Here's the API method code

GeometryFactory geometryFactory = new GeometryFactory();

//values are from query string
//north=45.5154045103725&south=45.4901382447544&west=-73.5854034422038&east=-73.5493545534017

Polygon space = geometryFactory.CreatePolygon(new Coordinate[] {
            new Coordinate(west, south),
            new Coordinate(east, south),
            new Coordinate(east, north),
            new Coordinate(west, north),
            new Coordinate(west, south) });

//var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.Covers(space)).ToList();
//var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.CoveredBy(space)).ToList();
//var polygons = OSMContext.PlanetOsmPolygon.Where(x => space.Covers(x.Way)).ToList();
//var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.Covers(space)).ToList();
var polygons = OSMContext.PlanetOsmPolygon.Where(x => x.Way.Within(space)).ToList();

As you can see, I've tried a few way around this, with no results ever. space is valid (IsValid returns true).

Is it the values that I'm using for space that may be a problem ? Or that scaffold issue ?


问:
How to separate character string by a word and adding the word on both sides, using R?
I have a df that looks like this (dput()at the end of question):

```<code>id                                                                                leg_activity
1044                                          home, pt, work, adpt, home, adpt, work, adpt, home
1215                 home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home
1238                                                             home, work, leisure, adpt, home
1458                                          home, outside, pt, home, adpt, leisure, adpt, home
1569 home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home
1615                                          home, adpt, work, walk, work, walk, work, pt, home
</code>```

I want to separate the cells of leg_activity into multiple columns. The separation of the character string should occur as soon as , home occurs. The idea is to see what happens between two home entries. For the first row the desired result would look like this:

```<code>id      1                              2
1044    home, pt, work, adpt, home     home, adpt, work, adpt, home
</code>```

As you can see, I'd like to keep home in both new cells.

My approach so far can not do this, it simply deletes home but I need it to appear on both sides of the cut:

```<code>library(dplyr)

df  <- agents %>%
  mutate(n = row_number()) %>%
  separate_rows(leg_activity, sep = 'home, ') %>%
  group_by(n, id) %>%
  mutate(n2 = row_number()) %>%
  spread(n2, leg_activity) %>%
  select(-n)
</code>```

Thank you very much for your help in advance!

data to try the code:

```<code>structure(list(id = c(9L, 10L, 11L, 96L, 97L, 101L, 103L, 248L,
499L, 1044L, 1215L, 1238L, 1458L, 1569L, 1615L, 1626L, 1734L,
1735L, 1790L, 1912L, 9040L, 14858L, 14859L, 14967L, 15011L, 15012L,
15015L, 15045L, 15050L, 15058L, 15060L, 15086L, 15088L, 15094L,
15109L, 15113L, 15152L, 15157L, 15192L, 15193L, 15222L, 15230L,
15231L, 15234L, 15235L, 15237L, 15256L, 15257L, 15258L, 15269L
), leg_activity = c("home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home",
"home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home",
"home, work, adpt, home", "home, car, work, car, home, work, adpt, home",
"home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home",
"home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home",
"home, adpt, work, adpt, home, walk, other, pt, home", "home, adpt, work, walk, home, adpt, work, walk, home",
"home, adpt, leisure, adpt, home, bike, outside, bike, home",
"home, pt, work, adpt, home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home",
"home, work, leisure, adpt, home", "home, outside, pt, home, adpt, leisure, adpt, home",
"home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home",
"home, adpt, work, walk, work, walk, work, pt, home", "home, car, work, pt, leisure, adpt, work, car, home, car, home",
"home, adpt, other, adpt, home, car, home", "home, adpt, other, adpt, home",
"home, education, walk, shop, walk, education, pt, outside, home, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, adpt, work, pt, leisure, adpt, work, adpt, work, adpt, home, adpt, other, walk, home",
"home, adpt, work, adpt, home, adpt, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, outside, car_passenger, leisure, car_passenger, home, car_passenger, home",
"home, adpt, other, adpt, home, car, work, car, home", "home, adpt, education, adpt, leisure, adpt, home, walk, leisure, walk, home",
"home, car_passenger, other, pt, home, walk, other, walk, home, car_passenger, other, walk, home, adpt, other, adpt, home",
"home, work, pt, work, adpt, work, adpt, home", "home, adpt, leisure, adpt, home, car, shop, car, other, car, home",
"home, adpt, work, adpt, home, walk, other, adpt, home", "home, adpt, work, adpt, home, car_passenger, leisure, car_passenger, home",
"home, car, other, car, home, adpt, shop, adpt, home", "home, pt, work, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, walk, education, adpt, home, walk, education, walk, home, bike, leisure, bike, home",
"home, adpt, shop, adpt, home, car, home", "home, adpt, leisure, walk, leisure, walk, leisure, adpt, home",
"home, adpt, shop, pt, home, adpt, other, adpt, home", "home, adpt, other, adpt, home, car_passenger, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, shop, car_passenger, home",
"home, adpt, other, adpt, work, adpt, home", "home, adpt, work, adpt, home, adpt, other, walk, shop, walk, home, car, outside, car, outside, car, outside, car, home",
"home, adpt, other, adpt, home", "home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, pt, work, adpt, work, adpt, work, adpt, work, adpt, home, adpt, work, adpt, home",
"home, walk, other, car_passenger, education, walk, home, car_passenger, education, adpt, home",
"home, walk, shop, walk, home, walk, leisure, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, shop, walk, home, walk, leisure, walk, home, walk, home",
"home, adpt, leisure, adpt, home")), row.names = c(NA, 50L), class = "data.frame")
</code>```

答:
Base R version using a custom function.
split_by_home creates a list of legs, the final steps ensure all vectors have the same length so they can be combined to a data frame.

```<code>split_by_home <- apply(df["leg_activity"], 1, function(x) {
  splits <- strsplit(x, split = ", home,")[[1]]
  if(length(splits) >= 1) splits[1] <- paste0(splits[1], ", home")
  if(length(splits) > 2) {
    splits[2:(length(splits) - 1)] <- paste0("home,", splits[2:(length(splits) - 1)], ", home")
    splits[length(splits)] <- paste0("home,", splits[length(splits)])
  }
  if(length(splits) == 2){
    splits[length(splits)] <- paste0("home,", splits[length(splits)])
  }
  return(splits)
}
)

max_length <- max(unlist(lapply(split_by_home, length)))
split_by_home_na <- lapply(split_by_home, function(x) c(x, rep(NA, max_length - length(x))))
split_by_home_df <- as.data.frame(do.call(rbind, split_by_home_na))
final_table <- cbind(df$id, split_by_home_df)
</code>```

```<code>> final_table[1:10, ]
   df$id                                                                              V1
1      9                                           home, adpt, shop, car_passenger, home
2     10                                                     home, pt, outside, pt, home
3     11                                                    home, work, adpt, home, home
4     96                                                      home, car, work, car, home
5     97       home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home
6    101 home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home
7    103                                                    home, adpt, work, adpt, home
8    248                                                    home, adpt, work, walk, home
9    499                                                 home, adpt, leisure, adpt, home
10  1044                                                      home, pt, work, adpt, home
                                                                                V2                              V3   V4
1                                                                                home, adpt, work, adpt, home   home, work, outside, pt, home <NA>
2  home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home home, adpt, leisure, adpt, home <NA>
3                                                                                <NA>                            <NA> <NA>
4                                                                                home, work, adpt, home                            <NA> <NA>
5                                                  home, car_passenger, outside, car_passenger, outside, car_passenger, home                            <NA> <NA>
6                                                                                home, adpt, leisure, adpt, home home, bike, leisure, bike, home <NA>
7                                                                                home, walk, other, pt, home                            <NA> <NA>
8                                                                                home, adpt, work, walk, home                            <NA> <NA>
9                                                                                home, bike, outside, bike, home                            <NA> <NA>
10                                                                                home, adpt, work, adpt, home                            <NA> <NA>
</code>```

Body:
I have a df that looks like this (dput()at the end of question):

id                                                                                leg_activity
1044                                          home, pt, work, adpt, home, adpt, work, adpt, home
1215                 home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home
1238                                                             home, work, leisure, adpt, home
1458                                          home, outside, pt, home, adpt, leisure, adpt, home
1569 home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home
1615                                          home, adpt, work, walk, work, walk, work, pt, home

I want to separate the cells of leg_activity into multiple columns. The separation of the character string should occur as soon as , home occurs. The idea is to see what happens between two home entries. For the first row the desired result would look like this:

id      1                              2
1044    home, pt, work, adpt, home     home, adpt, work, adpt, home

As you can see, I'd like to keep home in both new cells.

My approach so far can not do this, it simply deletes home but I need it to appear on both sides of the cut:

library(dplyr)

df  <- agents %>%
  mutate(n = row_number()) %>%
  separate_rows(leg_activity, sep = 'home, ') %>%
  group_by(n, id) %>%
  mutate(n2 = row_number()) %>%
  spread(n2, leg_activity) %>%
  select(-n)

Thank you very much for your help in advance!

data to try the code:

structure(list(id = c(9L, 10L, 11L, 96L, 97L, 101L, 103L, 248L,
499L, 1044L, 1215L, 1238L, 1458L, 1569L, 1615L, 1626L, 1734L,
1735L, 1790L, 1912L, 9040L, 14858L, 14859L, 14967L, 15011L, 15012L,
15015L, 15045L, 15050L, 15058L, 15060L, 15086L, 15088L, 15094L,
15109L, 15113L, 15152L, 15157L, 15192L, 15193L, 15222L, 15230L,
15231L, 15234L, 15235L, 15237L, 15256L, 15257L, 15258L, 15269L
), leg_activity = c("home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home",
"home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home",
"home, work, adpt, home", "home, car, work, car, home, work, adpt, home",
"home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home",
"home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home",
"home, adpt, work, adpt, home, walk, other, pt, home", "home, adpt, work, walk, home, adpt, work, walk, home",
"home, adpt, leisure, adpt, home, bike, outside, bike, home",
"home, pt, work, adpt, home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home",
"home, work, leisure, adpt, home", "home, outside, pt, home, adpt, leisure, adpt, home",
"home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home",
"home, adpt, work, walk, work, walk, work, pt, home", "home, car, work, pt, leisure, adpt, work, car, home, car, home",
"home, adpt, other, adpt, home, car, home", "home, adpt, other, adpt, home",
"home, education, walk, shop, walk, education, pt, outside, home, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, adpt, work, pt, leisure, adpt, work, adpt, work, adpt, home, adpt, other, walk, home",
"home, adpt, work, adpt, home, adpt, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, outside, car_passenger, leisure, car_passenger, home, car_passenger, home",
"home, adpt, other, adpt, home, car, work, car, home", "home, adpt, education, adpt, leisure, adpt, home, walk, leisure, walk, home",
"home, car_passenger, other, pt, home, walk, other, walk, home, car_passenger, other, walk, home, adpt, other, adpt, home",
"home, work, pt, work, adpt, work, adpt, home", "home, adpt, leisure, adpt, home, car, shop, car, other, car, home",
"home, adpt, work, adpt, home, walk, other, adpt, home", "home, adpt, work, adpt, home, car_passenger, leisure, car_passenger, home",
"home, car, other, car, home, adpt, shop, adpt, home", "home, pt, work, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, walk, education, adpt, home, walk, education, walk, home, bike, leisure, bike, home",
"home, adpt, shop, adpt, home, car, home", "home, adpt, leisure, walk, leisure, walk, leisure, adpt, home",
"home, adpt, shop, pt, home, adpt, other, adpt, home", "home, adpt, other, adpt, home, car_passenger, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, shop, car_passenger, home",
"home, adpt, other, adpt, work, adpt, home", "home, adpt, work, adpt, home, adpt, other, walk, shop, walk, home, car, outside, car, outside, car, outside, car, home",
"home, adpt, other, adpt, home", "home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, pt, work, adpt, work, adpt, work, adpt, work, adpt, home, adpt, work, adpt, home",
"home, walk, other, car_passenger, education, walk, home, car_passenger, education, adpt, home",
"home, walk, shop, walk, home, walk, leisure, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, shop, walk, home, walk, leisure, walk, home, walk, home",
"home, adpt, leisure, adpt, home")), row.names = c(NA, 50L), class = "data.frame")

Body:
Base R version using a custom function.
split_by_home creates a list of legs, the final steps ensure all vectors have the same length so they can be combined to a data frame.

split_by_home <- apply(df["leg_activity"], 1, function(x) {
  splits <- strsplit(x, split = ", home,")[[1]]
  if(length(splits) >= 1) splits[1] <- paste0(splits[1], ", home")
  if(length(splits) > 2) {
    splits[2:(length(splits) - 1)] <- paste0("home,", splits[2:(length(splits) - 1)], ", home")
    splits[length(splits)] <- paste0("home,", splits[length(splits)])
  }
  if(length(splits) == 2){
    splits[length(splits)] <- paste0("home,", splits[length(splits)])
  }
  return(splits)
}
)

max_length <- max(unlist(lapply(split_by_home, length)))
split_by_home_na <- lapply(split_by_home, function(x) c(x, rep(NA, max_length - length(x))))
split_by_home_df <- as.data.frame(do.call(rbind, split_by_home_na))
final_table <- cbind(df$id, split_by_home_df)

> final_table[1:10, ]
   df$id                                                                              V1
1      9                                           home, adpt, shop, car_passenger, home
2     10                                                     home, pt, outside, pt, home
3     11                                                    home, work, adpt, home, home
4     96                                                      home, car, work, car, home
5     97       home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home
6    101 home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home
7    103                                                    home, adpt, work, adpt, home
8    248                                                    home, adpt, work, walk, home
9    499                                                 home, adpt, leisure, adpt, home
10  1044                                                      home, pt, work, adpt, home
                                                                                V2                              V3   V4
1                                                                                home, adpt, work, adpt, home   home, work, outside, pt, home <NA>
2  home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home home, adpt, leisure, adpt, home <NA>
3                                                                                <NA>                            <NA> <NA>
4                                                                                home, work, adpt, home                            <NA> <NA>
5                                                  home, car_passenger, outside, car_passenger, outside, car_passenger, home                            <NA> <NA>
6                                                                                home, adpt, leisure, adpt, home home, bike, leisure, bike, home <NA>
7                                                                                home, walk, other, pt, home                            <NA> <NA>
8                                                                                home, adpt, work, walk, home                            <NA> <NA>
9                                                                                home, bike, outside, bike, home                            <NA> <NA>
10                                                                                home, adpt, work, adpt, home                            <NA> <NA>


问:
NSArray becoming invalid after assignment
This is a strange problem, but two of my NSArrays are becoming invalid right after assignment. I went into debug and verified this during assignment. The screenshot shows it all. I must be missing a silly error somewhere - can someone please help!

Link to Screenshot

Thank You!

答:
You need to send the -retain message to the array on assignment, like this:

```<code>ivar = [[NSArray arrayWithObjects:@"a", @"b", @"c", nil] retain];
</code>```

The reason why they are going out of scope is because -arrayWithObjects: returns an autoreleased object. It is for this reason that you must send it the -retain message.

Also, don't forget to -release these objects in your -dealloc method.

ContentLicense: CC BY-SA 3.0

Body:
You need to send the -retain message to the array on assignment, like this:

ivar = [[NSArray arrayWithObjects:@"a", @"b", @"c", nil] retain];

The reason why they are going out of scope is because -arrayWithObjects: returns an autoreleased object. It is for this reason that you must send it the -retain message.

Also, don't forget to -release these objects in your -dealloc method.


问:
LZ77 optimization
I have a code for LZ77 compression algorithm. It works fine with small files. But if I want to compress 100 kB and bigger files, it takes a lot of time.

I think, it's all because of this part:

```<code>do { // searchin for longest mathcing
                j++;
                i++;
                if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                    do {
                        i++;
                        j++;
                        if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                        addJ++;
                    } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                }
            } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);
</code>```

This part searches the longest matching between search buffer and look-ahead buffer.

So, is there faster way to find this matching?

Full code for LZ77 compression:

```<code> void lz77(char *fileName, FILE *from, FILE *path, long long size) {

char *searchBuffer = (char*)malloc((searchLen) * sizeof(char)); // search array
memset(searchBuffer, 0x00, searchLen);

long i = 0, j = 0, length = 0, offset = 0, isMatching = 0, iForSearchBuff = 0, iForLookBuff = 0;
int isFirst = 1, n = 0;
unsigned char symbol;

while(!feof(from)) {
    isMatching = 0;
    length = 0;
    iForSearchBuff = 0;
    iForLookBuff = 0;
    offset = strlen(searchBuffer);
    if (isFirst) { // first symbol
        fread(searchBuffer, 1, 1, from);
        writeBit(0, 0, *searchBuffer, tmpFile); // writing(0, 0, symbol)
        isFirst = 0;
    } else {
        char *lookBuffer = (char*)malloc((lookLen) * sizeof(char)); // look array
        memset(lookBuffer, 0x00, lookLen);

        fread(lookBuffer, 1, 1, from);

        for (j = 0; j <= strlen(searchBuffer); j++) {

            i = 0;
            if (searchBuffer[j] == lookBuffer[i]) { // MATCHING
                isMatching = 1;
                long fixJ = j, fixI = i, addJ = 0;

                do { // searchin for longest mathcing
                    j++;
                    i++;
                    if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                    if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                        do {
                            i++;
                            j++;
                            if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                            addJ++;
                        } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                    }
                } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);

                if (((strlen(searchBuffer) - fixJ) <= offset) && ((i - fixI) >= length)) {
                    length = i - fixI;
                    offset = strlen(searchBuffer) - fixJ;
                    iForSearchBuff = fixI;
                    iForLookBuff = i;
                }

                j = fixJ;

            } else if (j >= (strlen(searchBuffer))) {
                if (isMatching) {
                    if (lookBuffer[iForLookBuff] == '\0') { writeBit(offset, length, ' ', tmpFile);}
                    else {
                        writeBit(offset, length, lookBuffer[iForLookBuff], tmpFile);
                        searchBuffer = insertIntoBuffer(searchBuffer, length + 1, &lookBuffer[iForSearchBuff]);
                    }

                    isMatching = 0;
                    break;
                } else {
                    writeBit(0, 0, lookBuffer[i], tmpFile);

                    searchBuffer = insertIntoBuffer(searchBuffer, 1, &lookBuffer[i]);
                    break;
                }
            }

        }
    }
}
</code>```

}

答: Keep a table indexed by the first 'n' bytes of each string in your window -- where 'n' is the minimum length match you want (probably 2).  You may have multiple strings starting with the same 'n' bytes, so the entries in this table are lists of strings and each one's offset in the window.  You may want to prefer longest match at smallest offset from the end of the window.  It can be worth dealing specially with strings that start with a long run of the same byte.  As you move the window forwards, you need to drop strings from the table and add new ones.</p>

Title: LZ77 optimization

Body:
I have a code for LZ77 compression algorithm. It works fine with small files. But if I want to compress 100 kB and bigger files, it takes a lot of time.

I think, it's all because of this part:

do { // searchin for longest mathcing
                j++;
                i++;
                if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                    do {
                        i++;
                        j++;
                        if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                        addJ++;
                    } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                }
            } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);

This part searches the longest matching between search buffer and look-ahead buffer.

So, is there faster way to find this matching?

Full code for LZ77 compression:

 void lz77(char *fileName, FILE *from, FILE *path, long long size) {

char *searchBuffer = (char*)malloc((searchLen) * sizeof(char)); // search array
memset(searchBuffer, 0x00, searchLen);

long i = 0, j = 0, length = 0, offset = 0, isMatching = 0, iForSearchBuff = 0, iForLookBuff = 0;
int isFirst = 1, n = 0;
unsigned char symbol;

while(!feof(from)) {
    isMatching = 0;
    length = 0;
    iForSearchBuff = 0;
    iForLookBuff = 0;
    offset = strlen(searchBuffer);
    if (isFirst) { // first symbol
        fread(searchBuffer, 1, 1, from);
        writeBit(0, 0, *searchBuffer, tmpFile); // writing(0, 0, symbol)
        isFirst = 0;
    } else {
        char *lookBuffer = (char*)malloc((lookLen) * sizeof(char)); // look array
        memset(lookBuffer, 0x00, lookLen);

        fread(lookBuffer, 1, 1, from);

        for (j = 0; j <= strlen(searchBuffer); j++) {

            i = 0;
            if (searchBuffer[j] == lookBuffer[i]) { // MATCHING
                isMatching = 1;
                long fixJ = j, fixI = i, addJ = 0;

                do { // searchin for longest mathcing
                    j++;
                    i++;
                    if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);

                    if (j == strlen(searchBuffer) && lookBuffer[addJ] == lookBuffer[i]) {
                        do {
                            i++;
                            j++;
                            if(!lookBuffer[i]) fread(&lookBuffer[i], 1, 1, from);
                            addJ++;
                        } while (lookBuffer[addJ] == lookBuffer[i] && i < lookLen);
                    }
                } while (searchBuffer[j] == lookBuffer[i] && i < lookLen);

                if (((strlen(searchBuffer) - fixJ) <= offset) && ((i - fixI) >= length)) {
                    length = i - fixI;
                    offset = strlen(searchBuffer) - fixJ;
                    iForSearchBuff = fixI;
                    iForLookBuff = i;
                }

                j = fixJ;

            } else if (j >= (strlen(searchBuffer))) {
                if (isMatching) {
                    if (lookBuffer[iForLookBuff] == '\0') { writeBit(offset, length, ' ', tmpFile);}
                    else {
                        writeBit(offset, length, lookBuffer[iForLookBuff], tmpFile);
                        searchBuffer = insertIntoBuffer(searchBuffer, length + 1, &lookBuffer[iForSearchBuff]);
                    }

                    isMatching = 0;
                    break;
                } else {
                    writeBit(0, 0, lookBuffer[i], tmpFile);

                    searchBuffer = insertIntoBuffer(searchBuffer, 1, &lookBuffer[i]);
                    break;
                }
            }

        }
    }
}

}


问:
time optimization: performance, accessing values in an list of list, list of array numpy
I have been trying to optimize my code.

I compared 4 possible coding choices for getting the value in one cell of a list of list ( or replace list with array).

```<code>M = 1000
my_list = [[] for i in range(M)]
for i in range(M):
    for j in range(M):
        my_list[i].append(0)
my_numpy_list = [ np.full(M,1) for i in range(M) ]
time1 = time.time()
for j in range(1000):
    for i in range(10000):
        my_list[0][0]
print( "1  ", time.time() - time1)

time1 = time.time()
for j in range(1000):
    test_list = my_list[0]
    for i in range(10000):
        test_list[0]
print("2 ",time.time() - time1)

for j in range(1000):
    for i in range(10000):
        my_numpy_list[0][0]
print("3 ", time.time() - time1)

for j in range(1000):
    my_numpy_test_list = my_numpy_list[0]
    for i in range(10000):
        my_numpy_test_list[0]
print( "4  ", time.time() - time1)
</code>```

on my computer, it gives the following times :

```<code>1   0.9008669853210449
2  0.7616724967956543
3  2.9174351692199707
4   4.883266925811768
</code>```

The question is, why is it longer to access values in a numpy array ? If it's longer, what about converting an array into a list in order to access data faster. In particular, I am very surprised that storing the array which was in a list ( case 4) is the slowest case. Shoudln't the time be :

4 < 2 < 3 < 1 ?

Cheers

答:
Because the goal of numpy is not to make your access to data faster.
Instead the goal of numpy is to allow you to write vectorized code and avoid loops.

Let's modify your example and make your code adding 1 to every element of your list/np.array

```<code>M = 1000
my_list = [[] for i in range(M)]
for i in range(M):
    for j in range(M):
        my_list[i].append(0)
my_numpy_array = np.array([ np.full(M,1) for i in range(M) ])
time1 = time.time()

time1 = time.time()
for j in range(1000):
    test_list = my_list[0]
    for i in range(10000):
        test_list[0]+1
print("list case addition",time.time() - time1)

time2 = time.time()
my_numpy_list = my_numpy_array+1
print("numpy case addition",time.time() - time2)
</code>```

The output is:

```<code>list case addition 0.7961978912353516
numpy case addition 0.0031096935272216797
</code>```

which is about 250 times faster

Body:
I have been trying to optimize my code.

I compared 4 possible coding choices for getting the value in one cell of a list of list ( or replace list with array).

M = 1000
my_list = [[] for i in range(M)]
for i in range(M):
    for j in range(M):
        my_list[i].append(0)
my_numpy_list = [ np.full(M,1) for i in range(M) ]
time1 = time.time()
for j in range(1000):
    for i in range(10000):
        my_list[0][0]
print( "1  ", time.time() - time1)

time1 = time.time()
for j in range(1000):
    test_list = my_list[0]
    for i in range(10000):
        test_list[0]
print("2 ",time.time() - time1)

for j in range(1000):
    for i in range(10000):
        my_numpy_list[0][0]
print("3 ", time.time() - time1)

for j in range(1000):
    my_numpy_test_list = my_numpy_list[0]
    for i in range(10000):
        my_numpy_test_list[0]
print( "4  ", time.time() - time1)

on my computer, it gives the following times :

1   0.9008669853210449
2  0.7616724967956543
3  2.9174351692199707
4   4.883266925811768

The question is, why is it longer to access values in a numpy array ? If it's longer, what about converting an array into a list in order to access data faster. In particular, I am very surprised that storing the array which was in a list ( case 4) is the slowest case. Shoudln't the time be :

4 < 2 < 3 < 1 ?

Cheers

Body:
Because the goal of numpy is not to make your access to data faster.
Instead the goal of numpy is to allow you to write vectorized code and avoid loops.

Let's modify your example and make your code adding 1 to every element of your list/np.array

M = 1000
my_list = [[] for i in range(M)]
for i in range(M):
    for j in range(M):
        my_list[i].append(0)
my_numpy_array = np.array([ np.full(M,1) for i in range(M) ])
time1 = time.time()

time1 = time.time()
for j in range(1000):
    test_list = my_list[0]
    for i in range(10000):
        test_list[0]+1
print("list case addition",time.time() - time1)

time2 = time.time()
my_numpy_list = my_numpy_array+1
print("numpy case addition",time.time() - time2)

The output is:

list case addition 0.7961978912353516
numpy case addition 0.0031096935272216797

which is about 250 times faster


问:
Qt Quick2 Creating qmlRegisterSingletonType for Singleton Class Type
I am trying to create a singleton property using qmlRegisterSingletonType but when I try to access the object in the QML I am getting below error in the console logs:

```<code>qrc:/qml/MyQml.qml:21 Element is not creatable.
</code>```

Below is my code:

// TestSingletonType.h Class

```<code>#include <QObject>
#include <QJsonObject>
#include <QVariantMap>
#include <QQmlEngine>

class TestSingletonType : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY(TestSingletonType)
    TestSingletonType(QObject *parent = nullptr) {}

public:

    // To maintain single object of the class
    static QObject *qmlInstance(QQmlEngine *engine, QJSEngine *scriptEngine)
    {
        Q_UNUSED(engine);
        Q_UNUSED(scriptEngine);

        if (theInstance == NULL)
            theInstance = new TestSingletonType();

        return theInstance;
    }

private:

    static QObject *theInstance; // I have set it to NULL in Cpp file
};

</code>```

// Main.cpp

```<code>int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    qmlRegisterSingletonType<TestSingletonType>("com.my.TestSingletonType", 1, 0, "TestSingletonType", &TestSingletonType::qmlInstance);

    // Rest of the code to load the QML

    return app.exec();
}
</code>```

// MyQml.qml file:

```<code>import QtQuick 2.0
import QtQuick.Controls 2.0
import com.my.TestSingletonType 1.0

Item {

    TestSingletonType {      <---- Getting error on this line
        id: mySingleClass
    }

    // Rest of my code which uses "mySingleClass"
}
</code>```

If I use qmlRegisterType then it works properly, but not with the qmlRegisterSingletonType.

I have referred the below answer and link:

How to implement a singleton provider for qmlRegisterSingletonType?

https://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterSingletonType

答:
The error is clear: A singleton is not created in QML since it was already created in the callback (qmlInstance method), you just have to access the properties of that method. The typeName ("TestSingletonType") is the id.</p>

```<code>Item {
    // binding property
    foo_property : TestSingletonType.foo_value
    // update singleton property
    onAnotherPropertyChanged: TestSingletonType.another_prop = anotherProperty
}

// listen singleton signal
Connections{
    target: TestSingletonType
    onBarChanged: bar_object.bar_property = bar
}
</code>```

Body:
I am trying to create a singleton property using qmlRegisterSingletonType but when I try to access the object in the QML I am getting below error in the console logs:

qrc:/qml/MyQml.qml:21 Element is not creatable.

Below is my code:

// TestSingletonType.h Class

#include <QObject>
#include <QJsonObject>
#include <QVariantMap>
#include <QQmlEngine>

class TestSingletonType : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY(TestSingletonType)
    TestSingletonType(QObject *parent = nullptr) {}

public:

    // To maintain single object of the class
    static QObject *qmlInstance(QQmlEngine *engine, QJSEngine *scriptEngine)
    {
        Q_UNUSED(engine);
        Q_UNUSED(scriptEngine);

        if (theInstance == NULL)
            theInstance = new TestSingletonType();

        return theInstance;
    }

private:

    static QObject *theInstance; // I have set it to NULL in Cpp file
};

// Main.cpp

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    qmlRegisterSingletonType<TestSingletonType>("com.my.TestSingletonType", 1, 0, "TestSingletonType", &TestSingletonType::qmlInstance);

    // Rest of the code to load the QML

    return app.exec();
}

// MyQml.qml file:

import QtQuick 2.0
import QtQuick.Controls 2.0
import com.my.TestSingletonType 1.0

Item {

    TestSingletonType {      <---- Getting error on this line
        id: mySingleClass
    }

    // Rest of my code which uses "mySingleClass"
}

If I use qmlRegisterType then it works properly, but not with the qmlRegisterSingletonType.

I have referred the below answer and link:

How to implement a singleton provider for qmlRegisterSingletonType?

https://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterSingletonType

Body:
The error is clear: A singleton is not created in QML since it was already created in the callback (qmlInstance method), you just have to access the properties of that method. The typeName ("TestSingletonType") is the id.

Item {
    // binding property
    foo_property : TestSingletonType.foo_value
    // update singleton property
    onAnotherPropertyChanged: TestSingletonType.another_prop = anotherProperty
}

// listen singleton signal
Connections{
    target: TestSingletonType
    onBarChanged: bar_object.bar_property = bar
}


问:
Generate TYPECASE with macro in Common Lisp
I have a list of two element sublists which will change and grow in the course of the program. I want to write a macro which takes a key and generates a case dynamically like:

```<code>;; This is the List for saving CASE clauses
(setf l '((number 2) (symbol 3)))

;; and i want to have the following expansion
(typecase 'y
  (number 2)
  (symbol 3))
</code>```

I could have a macro which only refers to the global l:

```<code>(defmacro m (x)
  `(typecase ,x ,@l))
</code>```

which would expand correctly

```<code>(m 'y)  ;expands to (TYPECASE 'Y (number 2) (symbol 3))
</code>```

But how can i write the macro with a parameter for the list l so that it would work with other lists as well?

```<code>;; A macro which should generate the case based on the above list
(defmacro m (x l)
  `(typecase ,x ,@l))
</code>```

This doesn't work since l in the arguments list i a symbol and a call to (m 'y l) will expand to (TYPECASE 'Y . L).

Wanting to adhere to typecase mechanism, my workaround was as follows:

```<code>(setf types-x '(((integer 0 *) 38)
                ((eql neli) "Neli in X")
                (symbol 39))
            )
(setf types-y '(((eql neli) "Neli in Y")
                ((array bit *) "A Bit Vector")))

(defmacro m (x types-id)
  (case types-id
    (:x `(typecase ,x ,@types-x))
    (:y `(etypecase ,x ,@types-y))))

(m 'neli :x)                ;"Neli in X"
(m 'neli :y)                ;"Neli in Y"
(m 'foo :x)             ;39
</code>```

Any hints and comments is appreciated.

答:
Macro expansion happens at compile time, not run time, thus if the case clause list changes over the course of the program, the macro expansion will not change to reflect it.
If you want to dynamically select an unevaluated but changeable value, you can use assoc in the expansion instead of case:

```<code>(defmacro m (x l)
  `(second (assoc ,x ,l)))
</code>```

Sample expansion:

```<code>(m x l)
->
(SECOND (ASSOC X L))
</code>```

Output of (assoc x l) with the value of l in your question and x = 'x:

```<code>(let ((x 'x))
  (m x l))
->
2
</code>```

However if you did decide to do it this way, you could simplify things and replace the macro with a function:

```<code>(defun m (x l)
  (second (assoc x l)))
</code>```

UPDATE FOR QUESTION EDIT:

Replace assoc as follows:

```<code>(defun m (x l)
  (second (assoc-if (lambda (type)
                     (typep x type))
                    l)))
</code>```

Body:
I have a list of two element sublists which will change and grow in the course of the program. I want to write a macro which takes a key and generates a case dynamically like:

;; This is the List for saving CASE clauses
(setf l '((number 2) (symbol 3)))

;; and i want to have the following expansion
(typecase 'y
  (number 2)
  (symbol 3))

I could have a macro which only refers to the global l:

(defmacro m (x)
  `(typecase ,x ,@l))

which would expand correctly

(m 'y)  ;expands to (TYPECASE 'Y (number 2) (symbol 3))

But how can i write the macro with a parameter for the list l so that it would work with other lists as well?

;; A macro which should generate the case based on the above list
(defmacro m (x l)
  `(typecase ,x ,@l))

This doesn't work since l in the arguments list i a symbol and a call to (m 'y l) will expand to (TYPECASE 'Y . L).

Wanting to adhere to typecase mechanism, my workaround was as follows:

(setf types-x '(((integer 0 *) 38)
                ((eql neli) "Neli in X")
                (symbol 39))
            )
(setf types-y '(((eql neli) "Neli in Y")
                ((array bit *) "A Bit Vector")))

(defmacro m (x types-id)
  (case types-id
    (:x `(typecase ,x ,@types-x))
    (:y `(etypecase ,x ,@types-y))))

(m 'neli :x)                ;"Neli in X"
(m 'neli :y)                ;"Neli in Y"
(m 'foo :x)             ;39

Any hints and comments is appreciated.

Body:
Macro expansion happens at compile time, not run time, thus if the case clause list changes over the course of the program, the macro expansion will not change to reflect it.
If you want to dynamically select an unevaluated but changeable value, you can use assoc in the expansion instead of case:

(defmacro m (x l)
  `(second (assoc ,x ,l)))

Sample expansion:

(m x l)
->
(SECOND (ASSOC X L))

Output of (assoc x l) with the value of l in your question and x = 'x:

(let ((x 'x))
  (m x l))
->
2

However if you did decide to do it this way, you could simplify things and replace the macro with a function:

(defun m (x l)
  (second (assoc x l)))

UPDATE FOR QUESTION EDIT:

Replace assoc as follows:

(defun m (x l)
  (second (assoc-if (lambda (type)
                     (typep x type))
                    l)))


问:
Append JavaScript Object in HTML without library
I have a object that looks like this:

```<code>var options1 = {
    container: 'carosello',
    fetchCard: function(chunksize) {
        //function that returns (chunkSize) card objects to be displayed in the carousel
        return {
            image: 'https://images.blablabla',
            title: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. ',
        };
    }
};
</code>```

And I want to be able to display each item in the object in HTML like this:

```<code><div id="carosello">
   <div class="caroselloCard">
      <img src=" image here " alt="">
      <p> title here </p>
    </div>
</div>
</code>```

All this only with javascript without the help of NO LIBRARY.

答:
document.querySelector is enough for this

var options1 = {
    container: 'carosello',
    fetchCard: function(chunksize) {
        //function that returns (chunkSize) card objects to be displayed in the carousel
        return {
            image: 'https://i.picsum.photos/id/688/100/100.jpg',
            title: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. ',
        };
    }
};

document.querySelector("p").textContent = options1.fetchCard().title;
document.querySelector("img").src = options1.fetchCard().image;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="carosello">
   <div class="caroselloCard">
      <img src="" alt="">
      <p></p>
    </div>
</div></code>```

Body:
I have a object that looks like this:

var options1 = {
    container: 'carosello',
    fetchCard: function(chunksize) {
        //function that returns (chunkSize) card objects to be displayed in the carousel
        return {
            image: 'https://images.blablabla',
            title: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. ',
        };
    }
};

And I want to be able to display each item in the object in HTML like this:

 title here

All this only with javascript without the help of NO LIBRARY.

Body:
document.querySelector is enough for this

var options1 = {
    container: 'carosello',
    fetchCard: function(chunksize) {
        //function that returns (chunkSize) card objects to be displayed in the carousel
        return {
            image: 'https://i.picsum.photos/id/688/100/100.jpg',
            title: 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. ',
        };
    }
};

document.querySelector("p").textContent = options1.fetchCard().title;
document.querySelector("img").src = options1.fetchCard().image;

<div id="carosello">
   <div class="caroselloCard">
      <img src="" alt="">
      <p></p>
    </div>
</div>


问:
Load a specific tfvars variables file in my Terraform Cloud workspace
I wish to specify which .tfvars file to load on my workspaces.

Managing variables with files is much easier compared to entering everything in the workspaces. I'll explain.

I have two Worspaces:

database-qa

database-prod

Repo for the workspaces looks like this:

```<code>├── database/
│   ├── main.tf
│   ├── main.qa.tfvars
│   ├── main.prod.tfvars
</code>```

I want to load main.qa.tfvars for the database-qa workspace, and main.prod.tfvars for the database-prod workspace, naturally.

I keep the secrets/passwords on the workspace variables for security, and use the tfvars for non-sensitive configurations such as names, versions, etc, for convenience. I find it much easier than adding all to the variables to the workspace in the cloud.

I checked the documentation but I can't find a way to do it.

There is the option to use *.auto.tfvars variable definitions for file names but it will end up loading qa and prod files and that won't work properly.

Is it possible to do it? What are the alternatives?

答:
After a lot of reading and help with this thread I found a solution/workaround.

First of all, Terraform Cloud does not support specifying the .tfvars file to be loaded in the workspace run, at this time. It is not clear if it is planned on the backlog or not.

Terraform CLI however supports it with the following command and it works fine if you create your pipeline, but risky to run it manually.

-var-file=<filename>.tfvars
```

<p>Since I'm using Terraform Cloud I ended up with the following configuration. It'll have to be copied to all workspaces (sigh) but it works.</p>

```variable "TFC_WORKSPACE_NAME" {
  type = string
}

locals {
  env = merge(
    yamldecode(file("env/${var.TFC_WORKSPACE_NAME}.yaml"))
  )
}

resource "azurerm_resource_group" "group" {
  name     = local.env.group
  location = local.env.location
}
```

Any one interested in the complete example might to my repo and play with it.

Body:
I wish to specify which .tfvars file to load on my workspaces.

Managing variables with files is much easier compared to entering everything in the workspaces. I'll explain.

I have two Worspaces:

database-qa

database-prod

Repo for the workspaces looks like this:

├── database/
│   ├── main.tf
│   ├── main.qa.tfvars
│   ├── main.prod.tfvars

I want to load main.qa.tfvars for the database-qa workspace, and main.prod.tfvars for the database-prod workspace, naturally.

I keep the secrets/passwords on the workspace variables for security, and use the tfvars for non-sensitive configurations such as names, versions, etc, for convenience. I find it much easier than adding all to the variables to the workspace in the cloud.

I checked the documentation but I can't find a way to do it.

There is the option to use *.auto.tfvars variable definitions for file names but it will end up loading qa and prod files and that won't work properly.

Is it possible to do it? What are the alternatives?

Body:
After a lot of reading and help with this thread I found a solution/workaround.

First of all, Terraform Cloud does not support specifying the .tfvars file to be loaded in the workspace run, at this time. It is not clear if it is planned on the backlog or not.

Terraform CLI however supports it with the following command and it works fine if you create your pipeline, but risky to run it manually.

-var-file=<filename>.tfvars

Since I'm using Terraform Cloud I ended up with the following configuration. It'll have to be copied to all workspaces (sigh) but it works.

variable "TFC_WORKSPACE_NAME" {
  type = string
}

locals {
  env = merge(
    yamldecode(file("env/${var.TFC_WORKSPACE_NAME}.yaml"))
  )
}

resource "azurerm_resource_group" "group" {
  name     = local.env.group
  location = local.env.location
}

Any one interested in the complete example might to my repo and play with it.


问:
Laravel Eloquent - Attach vs. SyncWithoutDetaching
What is the difference between syncWithoutDetaching and attach in Laravel?</p>

答:
Two things:

attach() will always add a new record to the pivot table, whereas syncWithoutDetaching() will only add a new record if one does not exist.

Let's say you have orders and items.

```<code>$order->items()->attach(1);
$order->items()->attach(1);

// $order->items()->count() === 2

$order2->items()->syncWithoutDetaching(1);
$order2->items()->syncWithoutDetaching(1);

// $order2->items()->count() === 1
</code>```

attach() returns null, whereas syncWithoutDetaching() returns an array showing what was attached/detached/updated.

Body:
Two things:

attach() will always add a new record to the pivot table, whereas syncWithoutDetaching() will only add a new record if one does not exist.

Let's say you have orders and items.

$order->items()->attach(1);
$order->items()->attach(1);

// $order->items()->count() === 2

$order2->items()->syncWithoutDetaching(1);
$order2->items()->syncWithoutDetaching(1);

// $order2->items()->count() === 1

attach() returns null, whereas syncWithoutDetaching() returns an array showing what was attached/detached/updated.


问:
Split Image into parts ionic
I want to divide the image into multiple parts dynamically based on dimensions in ionic 5.

let's say

3 piece

8 piece

any number

I tried css tricks to make white color line on image but that hides the image portion behind.

I read this two blocks but helped me

split base64 image into parts

Split image into parts

I want to show preview of selection.

reference image
Please help

答:
you can use something like this with some styles...

HTML:

```<code> <div class="image-holder">
    <img src="./assets/images/defaultCompanyPic.png">
    <div class="grid">
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
    </div>
  </div>
</code>```

CSS:

```<code>.image-holder {
  width: fit-content;
  height: fit-content;
  position: relative;
}

.image-holder img {
  width: 300px;
  height: 400px;
}

.image-holder .grid {
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: 1px gray solid;
}

.image-holder .grid .row {
  display: flex;
  flex-direction: row;
  flex-grow: 1;
}

.image-holder .grid .row .cell {
  flex-grow: 1;
  box-sizing: border-box;
  border: 1px gray solid;
}
</code>```

Good Luck!

Title: Split Image into parts ionic

Body:
you can use something like this with some styles...

HTML:

 <div class="image-holder">
    <img src="./assets/images/defaultCompanyPic.png">
    <div class="grid">
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
      <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
      </div>
    </div>
  </div>

CSS:

.image-holder {
  width: fit-content;
  height: fit-content;
  position: relative;
}

.image-holder img {
  width: 300px;
  height: 400px;
}

.image-holder .grid {
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  right: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: 1px gray solid;
}

.image-holder .grid .row {
  display: flex;
  flex-direction: row;
  flex-grow: 1;
}

.image-holder .grid .row .cell {
  flex-grow: 1;
  box-sizing: border-box;
  border: 1px gray solid;
}

Good Luck!


问:
the intent always return the default value
i have many activities and i need to move an integer data from one to another one >>
in the first activity i have this code

```<code> final Intent go_to_main = new Intent(getBaseContext() , MainActivity.class);
    go_to_main.putExtra("data" , i1) ;
</code>```

and the secound one
 Intent intent = getIntent() ;
        data = intent.getIntExtra("data",3) ;

bbut always return the default which is 3 here
i have tried the bundle but when i use it like that my app stoping when i click the button to move to the secound activity

```<code> Intent go_to_main = new Intent(getApplicationContext() , MainActivity.class);
            Bundle mBundle = new Bundle();
            mBundle.putInt("data", i1);
            go_to_main.putExtras(mBundle);
</code>```

and in the secound one i have this code

```<code>Intent intent = getIntent() ;
data =     intent.getExtras().getInt("data") ;
</code>```

the error in the logcat is :

```<code>2020-05-30 18:27:56.461 14976-15008/com.e.pluspath E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
</code>```

答:
Don't think you have to use bundle.
for go_to_main intent:

```<code>Intent go_to_main = new Intent(getApplicationContext() , MainActivity.class);
go_to_main.putExtra("data", i1);
</code>```

And for your receiving end:

```<code>Intent intent = getIntent() ;
data = intent.getIntExtra("data", 0);
</code>```

Body:
i have many activities and i need to move an integer data from one to another one >>
in the first activity i have this code

 final Intent go_to_main = new Intent(getBaseContext() , MainActivity.class);
    go_to_main.putExtra("data" , i1) ;

and the secound one
 Intent intent = getIntent() ;
        data = intent.getIntExtra("data",3) ;

bbut always return the default which is 3 here
i have tried the bundle but when i use it like that my app stoping when i click the button to move to the secound activity

 Intent go_to_main = new Intent(getApplicationContext() , MainActivity.class);
            Bundle mBundle = new Bundle();
            mBundle.putInt("data", i1);
            go_to_main.putExtras(mBundle);

and in the secound one i have this code

Intent intent = getIntent() ;
data =     intent.getExtras().getInt("data") ;

the error in the logcat is :

2020-05-30 18:27:56.461 14976-15008/com.e.pluspath E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1

Body:
Don't think you have to use bundle.
for go_to_main intent:

Intent go_to_main = new Intent(getApplicationContext() , MainActivity.class);
go_to_main.putExtra("data", i1);

And for your receiving end:

Intent intent = getIntent() ;
data = intent.getIntExtra("data", 0);


问:
How to debug with breakpoint when crash line is the App Delegate?
Ever since upgrading to the latest Xcode, I've experienced random/intermittent crashes on app launch that I can only reproduce by launching the app n times and waiting for it to return. The line that the app crashes on is the top of the App Delegate:

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {
</code>```

I don't know how I'd set a breakpoint here and what I could gather from it. The reported cause of the crash is an NSException error on Thread 1:

[_NSTaggedDate countByEnumeratingWithState:objects:count]: unrecognized selector sent to instance 0x8000000000000000

Backtrace:

```<code>* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x000000019b7c6d88 libsystem_kernel.dylib`__pthread_kill + 8
    frame #1: 0x000000019b6df1e8 libsystem_pthread.dylib`pthread_kill$VARIANT$mp + 136
    frame #2: 0x000000019b632934 libsystem_c.dylib`abort + 100
    frame #3: 0x000000019b79acc0 libc++abi.dylib`abort_message + 128
    frame #4: 0x000000019b78ce10 libc++abi.dylib`demangling_terminate_handler() + 296
    frame #5: 0x000000019b6f3e80 libobjc.A.dylib`_objc_terminate() + 124
    frame #6: 0x000000019b79a14c libc++abi.dylib`std::__terminate(void (*)()) + 16
    frame #7: 0x000000019b79a0e4 libc++abi.dylib`std::terminate() + 44
    frame #8: 0x000000019b6f3e04 libobjc.A.dylib`objc_terminate + 12
    frame #9: 0x0000000105e2b744 libdispatch.dylib`_dispatch_client_callout + 36
    frame #10: 0x0000000105e39710 libdispatch.dylib`_dispatch_main_queue_callback_4CF + 976
    frame #11: 0x000000019b94f7fc CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
    frame #12: 0x000000019b94a6d0 CoreFoundation`__CFRunLoopRun + 1724
    frame #13: 0x000000019b949ce8 CoreFoundation`CFRunLoopRunSpecific + 424
    frame #14: 0x00000001a5a9438c GraphicsServices`GSEventRunModal + 160
    frame #15: 0x000000019fa78444 UIKitCore`UIApplicationMain + 1932
    frame #16: 0x0000000100fc866c FXTracker`main at AppDelegate.swift:8:7
    frame #17: 0x000000019b7d18f0 libdyld.dylib`start + 4
</code>```

In the debug navigator window, it's opened to Thread 1 and there is a drop-down called Original Exception Backtrace which looks like this:

```<code>0 _exceptionPreprocess
9 Sequence<>.contains(_:)
10 closure #3 in closure #1 in closure #2 in FXEditorViewController.loadBadges()
19 UIApplicationMain
20 main
21 start
</code>```

Is it safe to say that the crash is caused by closure #3 in closure #1 in closure #2 in loadBadges()?

答:
In this case you can set exception breakpoints

here

and then here (in Exceptions -> All)

Body:
Ever since upgrading to the latest Xcode, I've experienced random/intermittent crashes on app launch that I can only reproduce by launching the app n times and waiting for it to return. The line that the app crashes on is the top of the App Delegate:

class AppDelegate: UIResponder, UIApplicationDelegate {

I don't know how I'd set a breakpoint here and what I could gather from it. The reported cause of the crash is an NSException error on Thread 1:

[_NSTaggedDate countByEnumeratingWithState:objects:count]: unrecognized selector sent to instance 0x8000000000000000

Backtrace:

* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x000000019b7c6d88 libsystem_kernel.dylib`__pthread_kill + 8
    frame #1: 0x000000019b6df1e8 libsystem_pthread.dylib`pthread_kill$VARIANT$mp + 136
    frame #2: 0x000000019b632934 libsystem_c.dylib`abort + 100
    frame #3: 0x000000019b79acc0 libc++abi.dylib`abort_message + 128
    frame #4: 0x000000019b78ce10 libc++abi.dylib`demangling_terminate_handler() + 296
    frame #5: 0x000000019b6f3e80 libobjc.A.dylib`_objc_terminate() + 124
    frame #6: 0x000000019b79a14c libc++abi.dylib`std::__terminate(void (*)()) + 16
    frame #7: 0x000000019b79a0e4 libc++abi.dylib`std::terminate() + 44
    frame #8: 0x000000019b6f3e04 libobjc.A.dylib`objc_terminate + 12
    frame #9: 0x0000000105e2b744 libdispatch.dylib`_dispatch_client_callout + 36
    frame #10: 0x0000000105e39710 libdispatch.dylib`_dispatch_main_queue_callback_4CF + 976
    frame #11: 0x000000019b94f7fc CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
    frame #12: 0x000000019b94a6d0 CoreFoundation`__CFRunLoopRun + 1724
    frame #13: 0x000000019b949ce8 CoreFoundation`CFRunLoopRunSpecific + 424
    frame #14: 0x00000001a5a9438c GraphicsServices`GSEventRunModal + 160
    frame #15: 0x000000019fa78444 UIKitCore`UIApplicationMain + 1932
    frame #16: 0x0000000100fc866c FXTracker`main at AppDelegate.swift:8:7
    frame #17: 0x000000019b7d18f0 libdyld.dylib`start + 4

In the debug navigator window, it's opened to Thread 1 and there is a drop-down called Original Exception Backtrace which looks like this:

0 _exceptionPreprocess
9 Sequence<>.contains(_:)
10 closure #3 in closure #1 in closure #2 in FXEditorViewController.loadBadges()
19 UIApplicationMain
20 main
21 start

Is it safe to say that the crash is caused by closure #3 in closure #1 in closure #2 in loadBadges()?


问:
ArrayIndexOutOfBoundsException in Java from CSV file
trying to read the inputs from the CSV file, but got this error. Can someone tell why?
trying to take three inputs from the user (name, id, GPA) all as a string (I know it is not a good practice)

答:
There is an inconsistency with your csv file that you are reading. Probably a missing , somewhere:

12345,Molly,2.5
 54321,Sally 3.5

Line 2 will cause an ArrayIndexOutOfBoundsException.


问:
Web scraping with R: web site has two drop down menus
I want to get grade data from the following web site using R's for loop function: https://www7.nau.edu/pair/reports/ClassDistribution

In order to get the table data I have to first choose year and then academic school. I need data for 2015-2019 and for all schools (ACC, ACM,...,WGS) within university. When I select year and school the url is not changing that is why I am getting no table data. I'd really appreciate your help and advice. I am able to create for loop, I just need to see how to pull first table.

I was using following code for a static web site:

```<code>library(XML)
library(RCurl)
url <- "https://www7.nau.edu/pair/reports/ClassDistribution"
url.parsed <- htmlParse(getURL(url), asText = TRUE)
tableNodes <- getNodeSet(url.parsed, '//*[@id="pp_table"]/table')
grade_data <- readHTMLTable(tableNodes[[1]], header=F, stringsAsFactors=F)
</code>```

答:
You're dealing with a simple form that you need to update and submit for each semester and subject. Selenium is fine, but I think it might be overkill here. rvest::html_session is good at this kind of thing:

library(tidyverse)
library(rvest)

# Start session, extract semesters from form and filter.
session <- html_session("https://www7.nau.edu/pair/reports/ClassDistribution")
form <- html_form(session)[[1]]
semesters <- form$fields[[5]]$options[-1]
semesters <- semesters[grep("201[5-9]", names(semesters))]

# Update form with semester info, submit, and extract subjects.
form <- set_values(form, 'ctl00$MainContent$TermList' = semesters[1])
session <- submit_form(session, form, "<unnamed>")
form <- html_form(session)[[1]]
subjects <- form$fields[[6]]$options

# Update form with subject, submit, and extract data frame(s).
form <- set_values(form, 'ctl00$MainContent$SubjectList' = subjects[1])
session <- submit_form(session, form, "ctl00$MainContent$Button1")

df_list <- html_table(session, T, T, T)
```

Two things to be aware of:

df_list returns a list of data frames that you'll need to combine. I recommend dplyr::bind_rows().

You'll need two loops: An outer loop for the semesters, and an inner loop for the subjects within each semester.

Body:
I want to get grade data from the following web site using R's for loop function: https://www7.nau.edu/pair/reports/ClassDistribution

In order to get the table data I have to first choose year and then academic school. I need data for 2015-2019 and for all schools (ACC, ACM,...,WGS) within university. When I select year and school the url is not changing that is why I am getting no table data. I'd really appreciate your help and advice. I am able to create for loop, I just need to see how to pull first table.

I was using following code for a static web site:

library(XML)
library(RCurl)
url <- "https://www7.nau.edu/pair/reports/ClassDistribution"
url.parsed <- htmlParse(getURL(url), asText = TRUE)
tableNodes <- getNodeSet(url.parsed, '//*[@id="pp_table"]/table')
grade_data <- readHTMLTable(tableNodes[[1]], header=F, stringsAsFactors=F)

Body:
You're dealing with a simple form that you need to update and submit for each semester and subject. Selenium is fine, but I think it might be overkill here. rvest::html_session is good at this kind of thing:

library(tidyverse)
library(rvest)

# Start session, extract semesters from form and filter.
session <- html_session("https://www7.nau.edu/pair/reports/ClassDistribution")
form <- html_form(session)[[1]]
semesters <- form$fields[[5]]$options[-1]
semesters <- semesters[grep("201[5-9]", names(semesters))]

# Update form with semester info, submit, and extract subjects.
form <- set_values(form, 'ctl00$MainContent$TermList' = semesters[1])
session <- submit_form(session, form, "<unnamed>")
form <- html_form(session)[[1]]
subjects <- form$fields[[6]]$options

# Update form with subject, submit, and extract data frame(s).
form <- set_values(form, 'ctl00$MainContent$SubjectList' = subjects[1])
session <- submit_form(session, form, "ctl00$MainContent$Button1")

df_list <- html_table(session, T, T, T)

Two things to be aware of:

df_list returns a list of data frames that you'll need to combine. I recommend dplyr::bind_rows().

You'll need two loops: An outer loop for the semesters, and an inner loop for the subjects within each semester.