text:
Q: Retrieve Data from Json (Serialized form) for android (JAVA) Here is the json array i want to retrieve data from.I am making a app of live score upadtes so will be using the api to get live score and show it on app. Here is the whole api.
{
   "status":"ok",
   "post":{
      "id":1168,
      "type":"sp_event",
      "slug":"match-20-haryana-steelers-vs-u-mumba",
      "url":"http:\/\/fantasy-arena.com\/event\/match-20-haryana-steelers-vs-u-mumba\/",
      "status":"publish",
      "title":"Match 20, Haryana Steelers vs U Mumba",
      "title_plain":"Match 20, Haryana Steelers vs U Mumba",
      "content":"",
      "excerpt":"<p>Match 20, Haryana Steelers vs U Mumba<\/p>\n",
      "date":"2018-10-17 21:00:03",
      "modified":"2018-10-19 16:47:50",
      "categories":[

      ],
      "tags":[

      ],
      "author":{
         "id":1,
         "slug":"admin",
         "name":"Sports Master",
         "first_name":"",
         "last_name":"",
         "nickname":"Sports Master",
         "url":"",
         "description":""
      },
      "comments":[

      ],
      "attachments":[

      ],
      "comment_count":0,
      "comment_status":"closed",
      "custom_fields":{
         "sp_status":[
            "ok"
         ],
         "sp_format":[
            "league"
         ],
         "sp_mode":[
            "team"
         ],
         "sp_day":[
            ""
         ],
         "sp_minutes":[
            ""
         ],
         "sp_results":[
            "a:2:{i:688;a:4:{s:9:\"firsthalf\";s:2:\"13\";s:10:\"secondhalf\";s:2:\"19\";s:6:\"points\";s:2:\"32\";s:7:\"outcome\";a:1:{i:0;s:4:\"loss\";}}i:691;a:4:{s:9:\"firsthalf\";s:2:\"24\";s:10:\"secondhalf\";s:2:\"18\";s:6:\"points\";s:2:\"42\";s:7:\"outcome\";a:1:{i:0;s:3:\"win\";}}}"
         ],
         "sp_result_columns":[
            "a:2:{i:0;s:9:\"firsthalf\";i:1;s:6:\"points\";}"
         ],
         "sp_players":[
            "a:2:{i:688;a:11:{i:0;a:6:{s:3:\"pts\";s:0:\"\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:0:\"\";}i:764;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"190\";}s:3:\"pts\";s:2:\"15\";s:10:\"totalraids\";s:2:\"21\";s:8:\"touchpts\";s:2:\"11\";s:8:\"bonuspts\";s:1:\"4\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:1:\"1\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:765;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"190\";}s:3:\"pts\";s:1:\"4\";s:10:\"totalraids\";s:2:\"12\";s:8:\"touchpts\";s:1:\"2\";s:8:\"bonuspts\";s:1:\"2\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:0:\"\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:770;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:0:\"\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:1:\"4\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:1102;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:1:\"2\";s:10:\"totalraids\";s:1:\"1\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"2\";s:12:\"totaltackles\";s:1:\"7\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:1115;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"192\";}s:3:\"pts\";s:1:\"2\";s:10:\"totalraids\";s:1:\"2\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"2\";s:12:\"totaltackles\";s:1:\"5\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:1142;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"190\";}s:3:\"pts\";s:1:\"2\";s:10:\"totalraids\";s:1:\"7\";s:8:\"touchpts\";s:1:\"2\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:1:\"5\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:1166;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:0:\"\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:1:\"2\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:763;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"190\";}s:3:\"pts\";s:1:\"1\";s:10:\"totalraids\";s:1:\"1\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:0:\"\";s:6:\"status\";s:3:\"sub\";s:3:\"sub\";s:1:\"0\";}i:774;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"192\";}s:3:\"pts\";s:1:\"1\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"1\";s:12:\"totaltackles\";s:1:\"2\";s:6:\"status\";s:3:\"sub\";s:3:\"sub\";s:1:\"0\";}i:1165;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:1:\"4\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"4\";s:12:\"totaltackles\";s:1:\"4\";s:6:\"status\";s:3:\"sub\";s:3:\"sub\";s:1:\"0\";}}i:691;a:9:{i:0;a:6:{s:3:\"pts\";s:0:\"\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:0:\"\";}i:811;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"190\";}s:3:\"pts\";s:1:\"5\";s:10:\"totalraids\";s:2:\"11\";s:8:\"touchpts\";s:1:\"4\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"1\";s:12:\"totaltackles\";s:1:\"1\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:816;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"190\";}s:3:\"pts\";s:1:\"7\";s:10:\"totalraids\";s:2:\"11\";s:8:\"touchpts\";s:1:\"6\";s:8:\"bonuspts\";s:1:\"1\";s:9:\"tacklepts\";s:1:\"0\";s:12:\"totaltackles\";s:1:\"0\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:817;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"190\";}s:3:\"pts\";s:2:\"15\";s:10:\"totalraids\";s:2:\"18\";s:8:\"touchpts\";s:2:\"13\";s:8:\"bonuspts\";s:1:\"2\";s:9:\"tacklepts\";s:0:\"\";s:12:\"totaltackles\";s:0:\"\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:820;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:1:\"2\";s:10:\"totalraids\";s:1:\"1\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"2\";s:12:\"totaltackles\";s:1:\"4\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:821;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:1:\"2\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"2\";s:12:\"totaltackles\";s:1:\"6\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:822;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:1:\"1\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"1\";s:12:\"totaltackles\";s:1:\"3\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:1090;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:1:\"3\";s:10:\"totalraids\";s:0:\"\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:0:\"\";s:9:\"tacklepts\";s:1:\"3\";s:12:\"totaltackles\";s:2:\"10\";s:6:\"status\";s:6:\"lineup\";s:3:\"sub\";s:1:\"0\";}i:805;a:10:{s:6:\"number\";s:0:\"\";s:8:\"position\";a:1:{i:0;s:3:\"193\";}s:3:\"pts\";s:1:\"3\";s:10:\"totalraids\";s:1:\"4\";s:8:\"touchpts\";s:0:\"\";s:8:\"bonuspts\";s:1:\"1\";s:9:\"tacklepts\";s:1:\"2\";s:12:\"totaltackles\";s:1:\"2\";s:6:\"status\";s:3:\"sub\";s:3:\"sub\";s:1:\"0\";}}}"
         ],
         "sp_order":[
            "a:0:{}"
         ],
         "sp_timeline":[
            "a:2:{i:688;a:10:{i:764;a:1:{s:3:\"sub\";a:1:{i:0;s:0:  \"\";}}i:765;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:770;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:1102;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:1115;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:1142;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:1166;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:763;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:774;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:1165;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}}i:691;a:8:{i:811;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:816;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:817;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:820;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:821;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:822;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:1090;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}i:805;a:1:{s:3:\"sub\";a:1:{i:0;s:0:\"\";}}}}"
         ],
         "sp_stars":[
            "a:1:{i:817;s:1:\"1\";}"
         ],
         "sp_specs":[
            "a:1:{s:4:\"zone\";s:1:\"A\";}"
         ],
         "sp_video":[
            ""
         ],
         "sp_team":[
            "688",
            "691"
         ],
         "sp_player":[
            "0",
            "763",
            "764",
            "765",
            "770",
            "774",
            "1102",
            "1115",
            "1142",
            "1165",
            "1166",
            "0",
            "805",
            "811",
            "816",
            "817",
            "820",
            "821",
            "822",
            "1090"
         ],
         "sp_staff":[
            "0",
            "0"
         ]
      }
   },
   "previous_url":"http:\/\/fantasy-arena.com\/event\/match-19-bengaluru-bulls-vs-tamil-thalaivas\/",
   "next_url":"http:\/\/fantasy-arena.com\/event\/match-21-haryana-steelers-vs-dabang-delhi-k-c\/"
}

A: YOu can use JSON String Escape to remove useless slashes() from you JSON.
Then use jsonschema2pojo to Create model class. Then you can get any data from you JSON
Add GSON dependency in you build.gradle
  dependencies {
      implementation 'com.google.code.gson:gson:2.8.5'
    }

After putting your JSON in JsonSchema2Pojo i got these classes, YOu can use these Models to get any data you need.
MyData.java (Main Model Class)
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MyData {
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("post")
    @Expose
    private Post post;
    @SerializedName("previous_url")
    @Expose
    private String previousUrl;
    @SerializedName("next_url")
    @Expose
    private String nextUrl;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    public String getPreviousUrl() {
        return previousUrl;
    }

    public void setPreviousUrl(String previousUrl) {
        this.previousUrl = previousUrl;
    }

    public String getNextUrl() {
        return nextUrl;
    }

    public void setNextUrl(String nextUrl) {
        this.nextUrl = nextUrl;
    }

}

Author.java
public class Author {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("first_name")
    @Expose
    private String firstName;
    @SerializedName("last_name")
    @Expose
    private String lastName;
    @SerializedName("nickname")
    @Expose
    private String nickname;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("description")
    @Expose
    private String description;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

CustomFields.java
public class CustomFields {

    @SerializedName("sp_status")
    @Expose
    private List<String> spStatus = null;
    @SerializedName("sp_format")
    @Expose
    private List<String> spFormat = null;
    @SerializedName("sp_mode")
    @Expose
    private List<String> spMode = null;
    @SerializedName("sp_day")
    @Expose
    private List<String> spDay = null;
    @SerializedName("sp_minutes")
    @Expose
    private List<String> spMinutes = null;
    @SerializedName("sp_results")
    @Expose
    private List<String> spResults = null;
    @SerializedName("sp_result_columns")
    @Expose
    private List<String> spResultColumns = null;
    @SerializedName("sp_players")
    @Expose
    private List<String> spPlayers = null;
    @SerializedName("sp_order")
    @Expose
    private List<String> spOrder = null;
    @SerializedName("sp_timeline")
    @Expose
    private List<String> spTimeline = null;
    @SerializedName("sp_stars")
    @Expose
    private List<String> spStars = null;
    @SerializedName("sp_specs")
    @Expose
    private List<String> spSpecs = null;
    @SerializedName("sp_video")
    @Expose
    private List<String> spVideo = null;
    @SerializedName("sp_team")
    @Expose
    private List<String> spTeam = null;
    @SerializedName("sp_player")
    @Expose
    private List<String> spPlayer = null;
    @SerializedName("sp_staff")
    @Expose
    private List<String> spStaff = null;

    public List<String> getSpStatus() {
        return spStatus;
    }

    public void setSpStatus(List<String> spStatus) {
        this.spStatus = spStatus;
    }

    public List<String> getSpFormat() {
        return spFormat;
    }

    public void setSpFormat(List<String> spFormat) {
        this.spFormat = spFormat;
    }

    public List<String> getSpMode() {
        return spMode;
    }

    public void setSpMode(List<String> spMode) {
        this.spMode = spMode;
    }

    public List<String> getSpDay() {
        return spDay;
    }

    public void setSpDay(List<String> spDay) {
        this.spDay = spDay;
    }

    public List<String> getSpMinutes() {
        return spMinutes;
    }

    public void setSpMinutes(List<String> spMinutes) {
        this.spMinutes = spMinutes;
    }

    public List<String> getSpResults() {
        return spResults;
    }

    public void setSpResults(List<String> spResults) {
        this.spResults = spResults;
    }

    public List<String> getSpResultColumns() {
        return spResultColumns;
    }

    public void setSpResultColumns(List<String> spResultColumns) {
        this.spResultColumns = spResultColumns;
    }

    public List<String> getSpPlayers() {
        return spPlayers;
    }

    public void setSpPlayers(List<String> spPlayers) {
        this.spPlayers = spPlayers;
    }

    public List<String> getSpOrder() {
        return spOrder;
    }

    public void setSpOrder(List<String> spOrder) {
        this.spOrder = spOrder;
    }

    public List<String> getSpTimeline() {
        return spTimeline;
    }

    public void setSpTimeline(List<String> spTimeline) {
        this.spTimeline = spTimeline;
    }

    public List<String> getSpStars() {
        return spStars;
    }

    public void setSpStars(List<String> spStars) {
        this.spStars = spStars;
    }

    public List<String> getSpSpecs() {
        return spSpecs;
    }

    public void setSpSpecs(List<String> spSpecs) {
        this.spSpecs = spSpecs;
    }

    public List<String> getSpVideo() {
        return spVideo;
    }

    public void setSpVideo(List<String> spVideo) {
        this.spVideo = spVideo;
    }

    public List<String> getSpTeam() {
        return spTeam;
    }

    public void setSpTeam(List<String> spTeam) {
        this.spTeam = spTeam;
    }

    public List<String> getSpPlayer() {
        return spPlayer;
    }

    public void setSpPlayer(List<String> spPlayer) {
        this.spPlayer = spPlayer;
    }

    public List<String> getSpStaff() {
        return spStaff;
    }

    public void setSpStaff(List<String> spStaff) {
        this.spStaff = spStaff;
    }

}

Post.java
public class Post {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("url")
    @Expose
    private String url;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("title_plain")
    @Expose
    private String titlePlain;
    @SerializedName("content")
    @Expose
    private String content;
    @SerializedName("excerpt")
    @Expose
    private String excerpt;
    @SerializedName("date")
    @Expose
    private String date;
    @SerializedName("modified")
    @Expose
    private String modified;
    @SerializedName("categories")
    @Expose
    private List<Object> categories = null;
    @SerializedName("tags")
    @Expose
    private List<Object> tags = null;
    @SerializedName("author")
    @Expose
    private Author author;
    @SerializedName("comments")
    @Expose
    private List<Object> comments = null;
    @SerializedName("attachments")
    @Expose
    private List<Object> attachments = null;
    @SerializedName("comment_count")
    @Expose
    private Integer commentCount;
    @SerializedName("comment_status")
    @Expose
    private String commentStatus;
    @SerializedName("custom_fields")
    @Expose
    private CustomFields customFields;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitlePlain() {
        return titlePlain;
    }

    public void setTitlePlain(String titlePlain) {
        this.titlePlain = titlePlain;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getExcerpt() {
        return excerpt;
    }

    public void setExcerpt(String excerpt) {
        this.excerpt = excerpt;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getModified() {
        return modified;
    }

    public void setModified(String modified) {
        this.modified = modified;
    }

    public List<Object> getCategories() {
        return categories;
    }

    public void setCategories(List<Object> categories) {
        this.categories = categories;
    }

    public List<Object> getTags() {
        return tags;
    }

    public void setTags(List<Object> tags) {
        this.tags = tags;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    public List<Object> getComments() {
        return comments;
    }

    public void setComments(List<Object> comments) {
        this.comments = comments;
    }

    public List<Object> getAttachments() {
        return attachments;
    }

    public void setAttachments(List<Object> attachments) {
        this.attachments = attachments;
    }

    public Integer getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(Integer commentCount) {
        this.commentCount = commentCount;
    }

    public String getCommentStatus() {
        return commentStatus;
    }

    public void setCommentStatus(String commentStatus) {
        this.commentStatus = commentStatus;
    }

    public CustomFields getCustomFields() {
        return customFields;
    }

    public void setCustomFields(CustomFields customFields) {
        this.customFields = customFields;
    }
}

A: There are two options

*

*Use plain JSONObject to parse the data manually

*Use some library (i.e Gson) to map your data to Java object fields automatically


text:
Q: How to move flutter bin file I was working with flutter and for some reason the bat file was removed. Now flutter as been moved into another directory. How do I move it back, as my android studio project wont run and delete the unused files. Tried to earlier but it wont delete the bin file.
Pic 1 - Old flutter path
Pic 2 -  Where bat file used to be
Pic 3 - New bat file location
Pic 4 - Flutter doc error

A: You can relocate the flutter SDK path in Android studio.
For Windows
Go to File-> Settings -> Under languages & framework section choose flutter
For MAC
Click on Android Studio-> Preferences -> Under languages & framework section choose flutter
You will now see an option for flutter SDK path. From here you can relocate your SDK path.
Try restarting Android studio if that doesn't solve your problem immediately.

redpajama_set_name: RedPajamaStackExchange


text:
Q: If I compare conditions within two preexisting groups is that a quasi-experimental design? I have two groups of participants, one group of psychosis patients and one group of controls. All of the participants complete a computer task that has three different conditions.
So, I want to make both within- and between-groups comparisons. Since the differentiating factor between the groups is illness condition (something that can't be manipulated), I figured I run a mixed design ANOVA (split-plot ANOVA). Thus, labeling psychosis and healthy as two independent variables. Is this analysis right?
If it is right, what do I call this type of design? Would it be appropriate to call it "Quasi-experimental independent groups repeated measures design"?


text:
Q: Typing 'python' in terminal runs a python script and spits error I'm taking a python course, I save exercise scripts in /this/is/where/I save/exercises/exercise.py.
Now whenever I type python in terminal it immediately gives me this:
IOError: [Errno 2] No such file or directory: '/this/is/where/I save/exercises/exercise.py'
I know it's not found since I deleted the file. But why is python running that script whenever it runs? It's annoying.
INFO
Linux OS
Python2 and Python3 both show same error

A: Thanks, @JoranBeasley, @barunsthakur, @PadraicCunningham, and all.
I had PYTHONSTARTUP set in .bashrc.
May help forgetful people in the future.

A: If you're on UNIX-like system, like Linux or Mac, I suspect you might have an alias or mis-configured PATH. Start investigating by running:
which python  # which program is run when you type in python?

And
alias         # what are the aliases for the shell?

A: Python has a special script that is run on startup. On my platform it is located at /usr/lib/python2.5/site-packages/sitecustomize.py IIRC. You may want to check that file for any script calls to that directory. Also, if you are on a linux machine you could check /etc/bashrc or /etc/profile.d. If that doesn't help, try to update your question with more specific information.


text:
Q: std::map in class : trade off between execution speed and memory usage My question concerns the trade off between execution speed and memory usage when designing a class that will be instantiated thousands or millions of times and used differently in different contexts.
So I have a class that contains a bunch of numerical properties (stored in int and double). A simple example would be
class MyObject
{
  public:
    double property1;
    double property2;
    ...
    double property14
    int property15;
    int property16;
    ...
    int property25;
    MyObject();
    ~MyObject();
};

This class is used by different programs that instantiate
std::vector<MyObject> SetOfMyObjects;

that may contain as much as a few millions of elements. The thing is that depending on the context, some or many properties may remain unused (we do not need to compute them in this given context), implying that the memory for millions of useless int and double is allocated. As I said, the usefulness and uselessness of the properties depend on the context, and I would like to avoid writing a different class for each specific contexts.
So I was thinking about using std::maps to assign memory only for the properties I use. For example
class MyObject
{
  public:
    std::map<std::string, double> properties_double;
    std::map<std::string, int> properties_int;
    MyObject();
    ~MyObject();
};

such that if "property1" has to be computed, it would stored as
MyObject myobject;
myobject.properties_double["property1"] = the_value;

Obviously, I would define proper "set" and "get" methods.
I understand that accessing elements in a std::map goes as the logarithm of its size, but since the number of properties is quite small (about 25), I suppose that this should not slow down the execution of the code too much.
Am I overthinking this too much? Do you think using std::map is a good idea? Any suggestion from more seasoned programmers would be appreciated.

A: TL;DR: it's not worth it.
From carpenters we get: measure twice, cut once. Apply it.

Your 25 int and double will occupy on a x86_64 processor:

*

*14 double: 112 bytes (14 * 8)

*11 int: 44 bytes (11 * 4)

for a total of 156 bytes.

A std::pair<std::string, double> will, on most implementation, consume:

*

*24 bytes for the string

*8 bytes for the double

and a node in the std::map<std::string, double> will add at least 3 pointers (1 parent, 2 children) and a red-black flag for another 24 bytes.
That's at least 56 bytes per property.
Even with a 0-overhead allocator, any time you store 3 elements or more in this map you use more than 156 bytes...

A compressed (type, property) pair will occupy:

*

*8 bytes for the property (double is the worst case)

*8 bytes for the type (you can choose a smaller type, but alignment kicks in)

for a total of 16 bytes per pair. Much better than map.
Stored in a vector, this will mean:

*

*24 bytes of overhead for the vector

*16 bytes per property

Even with a 0-overhead allocator, any time you store 9 elements or more in this vector you use more than 156 bytes.

You know the solution: split that object.

A: You're looking up objects by name that you know will be there. So look them up by name.

I understand that accessing elements in a std::map goes as the logarithm of its size, but since the number of properties is quite small (about 25), I suppose that this should not slow down the execution of the code too much.

You will slow down your program by more than one order of magnitude. Lookup of a map may be O(logN) but it's O(LogN) * C. C will be huge compared to direct access of properties (thousands of times slower).

implying that the memory for millions of useless int and double is allocated

A std::string is at least 24 bytes on all the implementations I can think of - assuming you keen the names of properties short (google 'short string optimisation' for details).
Unless 60% of your properties are unpopulated there is no saving using a map keyed by string at all.

A: With so many objects and small map object in each you may hit another problem - memory fragmentation. It could be usable to have std::vector with std::pair<key,value> in it instead and do lookup (I think binary search should be sufficient, but it depends on your situation, it could be cheaper to do linear lookup but not to sort the vector). For property key I would use enum instead of string, unless later is dictated by interface (which you did not show).

A: Just an idea (not compiled/tested):
struct property_type
{
  enum { kind_int, kind_double } k;
  union { int i; double d; };
};

enum prop : unsigned char { height, widht, };

typedef std::map< std::pair< int/*data index*/, prop/*property index*/ >, property_type > map_type;

class data_type
{
  map_type m;

public:

  double& get_double( int i, prop p )
  {
    // invariants...
    return m[ std::pair<int,prop>(i,p) ].d;
  }

};

A: Millions of ints and doubles is still only hundreds of megabytes of data. On a modern computer that may not be a huge issue.
The map route looks like it will be a waste of time but there is an alternative you could use that saves memory while retaining decent performance characteristics: store the details in a separate vector and store an index into this vector (or -1 for unassigned) in your main data type. Unfortunately, your description doesn't really indicate how the property usage actually looks but I'm going to guess you can sub-divide into properties that are always, or usually, set together and some that are needed for every node. Let's say you subdivide into four sets: A, B, C and D. The As are needed for every node whereas B, C and D are rarely set but all elements are typically modified together, then modify the struct you're storing like so:
struct myData {
  int A1;
  double A2;
  int B_lookup = -1;
  int C_lookup = -1;
  int D_lookup = -1;
};

struct myData_B {
  int B1;
  double B2;
  //etc.
};

// and for C and D

and then store 4 vectors in your main class. When a property in the Bs in accessed you add a new myData_B to the vector of Bs (actually a deque might be a better choice, retaining fast access but without the same memory fragmentation issues) and set the B_lookup value in the original myData to the index of the new myData_B. And the same for Cs and Ds.
Whether this is worth doing depends on how few of the properties you actually access and how you access them to together but you should be able to modify the idea to your tastes.

A: I don't think this is your best option, for 25 elements, you will not benefit that much from using a map in terms of lookup performance. Also, it depends on what kinds of properties are you going to have, if it is a fixed set of properties as in your example, then string lookup would be a waste of memory and CPU cycles, you could go for an enum  of all properties or just an integer and use a sequential container for the properties each element has. For such a small number of possible properties, lookup time will be lower than a map because of cache friendliness and integer comparisons, and memory usage will be lower too. For such a small set of properties this solution is marginally better.
Then there is the problem that an int is usually twice as small as a double. And they are different types. So it is not directly possible to store both in a single container, but you could have enough space for a double in each element, and either use a union or just read/write an int from/to the address of the double if the property "index" is larger than 14.
So you can have something as simple as:
struct Property {
   int type;
   union {
       int d_int;
       double d_double;
   };
};

class MyObject {
    std::vector<Property> properties;
};

And for type 1 - 14 you read the d_double field, for type 15 - 25 the d_int field.
BENCHMARKS!!!
Out of curiosity I did some testing, creating 250k objects, each with 5 int and 5 double properties, using a vector, a map and a hash for the properties, and measured memory usage and time taken to set and get the properties, ran each test 3 times in a row to see impact on caching, calculate checksum for getters to verify consistency, and here are the results:
vector | iteration | memory usage MB | time msec | checksum
setting 0 32 54
setting 1 32 13
setting 2 32 13
getting 0 32 77 3750000
getting 1 32 77 3750000
getting 2 32 77 3750000

map | iteration | memory usage MB | time msec | checksum
setting 0 132 872
setting 1 132 800
setting 2 132 800
getting 0 132 800 3750000
getting 1 132 799 3750000
getting 2 132 799 3750000

hash | iteration | memory usage MB | time msec | checksum
setting 0 155 797
setting 1 155 702
setting 2 155 702
getting 0 155 705 3750000
getting 1 155 705 3750000
getting 2 155 706 3750000

As expected, the vector solution is by far the fastest and most efficient, although it is most influenced by cold cache, even running cold it is way faster than a map or hash implementation.
On a cold run, the vector implementation is 16.15 times faster than map and 14.75 times faster than hash. On a warm run it is even faster - 61 times faster and 54 times faster respectively.
As for memory usage, the vector solution is far more efficient as well, using over 4 times less memory than the map solution and almost 5 times less than the hash solution.
As I said, it is marginally better.
To clarify, the "cold run" is not only the first run but also the one inserting the actual values in the properties, so it is fairly illustrative of the insert operations overhead. None of the containers used preallocation so they used their default policies of expanding. As for the memory usage, it is possible it doesn't accurately reflect actual memory usage 100% accurately, since I use the entire working set for the executable, and there is usually some preallocation taking place on OS level as well, it will most likely be more conservative as the working set increases. Last but not least, the map and hash solutions are implemented using a string lookup as the OP originally intended, which is why they are so inefficient. Using integers as keys in the map and hash produces far more competitive results:
vector | iteration | memory usage MB | time msec | checksum
setting 0 32 55
setting 1 32 13
setting 2 32 13
getting 0 32 77 3750000
getting 1 32 77 3750000
getting 2 32 77 3750000

map | iteration | memory usage MB | time msec | checksum
setting 0 47 95
setting 1 47 11
setting 2 47 11
getting 0 47 12 3750000
getting 1 47 12 3750000
getting 2 47 12 3750000

hash | iteration | memory usage MB | time msec | checksum
setting 0 68 98
setting 1 68 19
setting 2 68 19
getting 0 68 21 3750000
getting 1 68 21 3750000
getting 2 68 21 3750000

Memory usage is much lower for hash and map, while still higher than vector, but in terms of performance the tables are turned, while the vector solution sill wins at inserts, at reading and writing the map solution takes the trophy. So there's the trade-off.
As for how much memory is saved compared to having all the properties as object members, by just a rough calculation, it would take about 80 MB of RAM to have 250k such objects in a sequential container. So you save like 50 MB for the vector solution and almost nothing for the hash solution. And it goes without saying - direct member access would be much faster.


text:
Q: Create an event with insert into I have this table:
CREATE TABLE myT(
    p1  float(6,2),
    p2  float(6,2),
    p3  float(6,2),
    date timestamp not null DEFAULT CURRENT_TIMESTAMP,
    primary key(date)
);

I create this event:
CREATE EVENT insert_new ON SCHEDULE EVERY 1 MINUTE
DO
   INSERT INTO myT(p1,p2,p3, date) VALUES (1.00,2.00,3.00, CURRENT_TIMESTAMP);

With this event I expect that every minute MySQL insert automatically e new record
with the timestamp as primary key. But this event doesn't work

A: Try
delimiter //
CREATE EVENT insert_new
   ON SCHEDULE EVERY 1 MINUTE
   STARTS  '2014-10-03 00:00:00'
   ON COMPLETION PRESERVE ENABLE
DO
    insert into myT(p1,p2,p3, date)
    values(1.00,2.00,3.00, CURRENT_TIMESTAMP);
//


text:
Q: Nested IF statement not working with Vendor Email Template - PHP Laravel 5.6 Can you please help me see what I am doing wrong here?
When I cancel a booking and choose the option to refund the amount paid for some reason the BookingCancelled email blade template is not kicking off to the customer. Below is the full code of the email template.

<!doctype html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ __('emails.booking_cancelled_subject', ['booking_id' => $booking->id]) }}</title>

{{ __('emails.greeting') }}  {{ $booking->first_name }} {{ $booking->last_name }}!

{{ __('emails.booking_cancelled_message', ['booking_id' => $booking->id]) }}

@if($refund_status)
@if(!$booking->invoice->is_partial == 1 && $booking->invoice->is_paid == 0)
    Your payment of ${{ $booking->invoice->is_partial ? $booking->invoice->amount_paid : }} was refunded via {{ $booking->invoice->payment_method }}. If you have any questions, please contact
    us.

@else

    Your payment of ${{ $booking->invoice->amount_paid }} was not refundable. If you have any questions, please contact
    us.

@endif
@endif

{{ __('emails.greeting') }}  {{ $booking->first_name }} {{ $booking->last_name }}!

{{ __('emails.booking_cancelled_message', ['booking_id' => $booking->id]) }}

@if($refund_status)
@if(!$booking->invoice->is_paid == 1 && $booking->invoice->is_partial == 0)

    Your payment of ${{ $booking->invoice->is_paid ? $booking->invoice->amount : }} was refunded via {{ $booking->invoice->payment_method }}. If you have any questions, please contact
    us.

@else

    Your payment of ${{ $booking->invoice->amount }} was not refundable. If you have any questions, please contact
    us.

@endif
@endif

                    @if(config('settings.facebook_link'))

@endif

                    @if(config('settings.twitter_link'))

@endif

                    @if(config('settings.instagram_link'))

@endif

                    @if(config('settings.google_plus_link'))

@endif

{{ __('emails.spam_notice') }}

{{ __('auth.copyrights') }}. © {{ date('Y') }}. {{ __('auth.rights_reserved') }} {{ config('settings.business_name', 'Bookify') }}.

This is the code with the nested IF statements:

{{ __('emails.greeting') }}  {{ $booking->first_name }} {{ $booking->last_name }}!

{{ __('emails.booking_cancelled_message', ['booking_id' => $booking->id]) }}

@if($refund_status)
@if(!$booking->invoice->is_partial == 1 && $booking->invoice->is_paid == 0)
    Your payment of ${{ $booking->invoice->is_partial ? $booking->invoice->amount_paid : }} was refunded via {{ $booking->invoice->payment_method }}. If you have any questions, please contact
    us.

@else

    Your payment of ${{ $booking->invoice->amount_paid }} was not refundable. If you have any questions, please contact
    us.

@endif
@endif

{{ __('emails.greeting') }}  {{ $booking->first_name }} {{ $booking->last_name }}!

{{ __('emails.booking_cancelled_message', ['booking_id' => $booking->id]) }}

@if($refund_status)
@if(!$booking->invoice->is_paid == 1 && $booking->invoice->is_partial == 0)

    Your payment of ${{ $booking->invoice->is_paid ? $booking->invoice->amount : }} was refunded via {{ $booking->invoice->payment_method }}. If you have any questions, please contact
    us.

@else

    Your payment of ${{ $booking->invoice->amount }} was not refundable. If you have any questions, please contact
    us.

@endif
@endif


text:
Q: Copying a datatable to another datatable while changing the format of a column I have a DataTable that I want to copy to another DataTable.. but the catch if that I want to change one of the columns to Short Date format (which is of type String in the original Datatable). I am able to add the columns from the original Datatable to the new one but when I try to set column format to Date type, it sets it to Datetime format. This causes a problem when copying data over from the original Datatable as the dates are not set correctly in the new table (i.e. 10/03/2018 00:00:00 changes to 10/01/2018 00:03:00).
Any idea how I can resolve this issue? Or maybe there is a better way of doing this?
    Dim sColumn As String
    Dim dRow As DataRow

    For Each dC as DataColumn In dT.Columns
        dTRet.Columns.Add (dC.ColumnName)
    Next
    dTRet.Columns(ColName).DataType = GetType(Date)

    For Each row As DataRow in dT.Rows
        dRow = dTRet.NewRow
        For iC As Integer = 0 To dT.Columns.Count - 1
            sColumn = dT.Columns(iC).ColumnName

            If sColumn = ColName Then
                dRow(sColumn) = Date.ParseExact(row.Item(sColumn), DateFormat,
                                    System.Globalization.DateTimeFormatInfo.InvariantInfo,
                                    Globalization.DateTimeStyles.None)
            Else
                dRow(sColumn) = row.Item(sColumn)
            End If
        Next iC

        dTRet.Rows.Add (dRow)
    Next Row

ColName: holds the name of the column to change
dT: is the original Datatable
dTRet: is the new Datatable
Thanks in advance


text:
Q: PowerShell: populate column A null rows with data from previous column A row data, if Column B value is "X" I have an oddly formatted csv file that I need to adjust and I could use some help using powershell. I usually have a pretty good idea where to start, but I am at a bit of a loss with this one on how to iterate data from column A from the previous row to the next row based on Column B having "sales order" and only doing it if the Column A field is Null and then using the next row that is populated to continue down the line.
Here is what the csv looks like as a picture:

Here is the actual data:
,Type,Date,Due Date,Num
Inventory,,,,
2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid),,,,
,Sales Order,7/23/2021,7/23/2021,12834
Total 2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid),,,,
Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,9/23/2021,9/23/2021,13304
Total Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,7/23/2021,7/23/2021,12841
Total Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,4/1/2021,4/1/2021,11807
Total Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,6/9/2021,6/9/2021,12457
Total Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer)),,,,
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,,,,
,Sales Order,6/7/2021,6/7/2021,12425
,Sales Order,8/3/2021,8/3/2021,12939
,Sales Order,9/14/2021,9/14/2021,13218
Total Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,,,,
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...,,,,
,Sales Order,6/8/2021,6/8/2021,12454
,Sales Order,8/24/2021,8/24/2021,13102
,Sales Order,9/14/2021,9/14/2021,13220
,Sales Order,10/8/2021,10/8/2021,13415

I need to fill the blank lines in Column A that have "Sales Order" in column B with the line from above. (i hate quickbooks report formatting) so it looks like this: (added lines are highlighted in Yellow)

Data looks like this:
,Type,Date,Due Date,Num
Inventory,,,,
2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid),,,,
2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid),Sales Order,7/23/2021,7/23/2021,12834
Total 2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid),,,,
Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer)),Sales Order,9/23/2021,9/23/2021,13304
Total Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer)),Sales Order,7/23/2021,7/23/2021,12841
Total Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer)),Sales Order,4/1/2021,4/1/2021,11807
Total Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer)),Sales Order,6/9/2021,6/9/2021,12457
Total Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer)),,,,
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,,,,
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,Sales Order,6/7/2021,6/7/2021,12425
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,Sales Order,8/3/2021,8/3/2021,12939
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,Sales Order,9/14/2021,9/14/2021,13218
Total Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,,,,
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...,,,,
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...,Sales Order,6/8/2021,6/8/2021,12454
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...,Sales Order,8/24/2021,8/24/2021,13102
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...,Sales Order,9/14/2021,9/14/2021,13220
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...,Sales Order,10/8/2021,10/8/2021,13415

as a side note, if anyone knows how to display Quickbooks desktop report for "open sales orders by item" to display in a better format that would do that, that would also be great.

A: $Data = ConvertFrom-Csv @'
,Type,Date,Due Date,Num
Inventory,,,,
2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid),,,,
,Sales Order,7/23/2021,7/23/2021,12834
Total 2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid),,,,
Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,9/23/2021,9/23/2021,13304
Total Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,7/23/2021,7/23/2021,12841
Total Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,4/1/2021,4/1/2021,11807
Total Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer)),,,,
Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer)),,,,
,Sales Order,6/9/2021,6/9/2021,12457
Total Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer)),,,,
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,,,,
,Sales Order,6/7/2021,6/7/2021,12425
,Sales Order,8/3/2021,8/3/2021,12939
,Sales Order,9/14/2021,9/14/2021,13218
Total Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...,,,,
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...,,,,
,Sales Order,6/8/2021,6/8/2021,12454
,Sales Order,8/24/2021,8/24/2021,13102
,Sales Order,9/14/2021,9/14/2021,13220
,Sales Order,10/8/2021,10/8/2021,13415
'@

WARNING: One or more headers were not specified. Default names starting with "H" have been used in place of any missing headers.

$Data |ForEach-Object { $H1 = '' } {
    If ($_.H1) { $H1 = $_.H1 }
    If ($_.Type -eq 'Sales Order') { $_.H1 = $H1 }
    $_
} |Format-Table

Result:
H1                                                                                Type        Date      Due Date  Num
--                                                                                ----        ----      --------  ---
Inventory
2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid)
2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid)                      Sales Order 7/23/2021 7/23/2021 12834
Total 2.25 Gal Cast Iron KettlewLid (2.25 Gallon Cast Iron Kettle with Lid)
Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer))
Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer))           Sales Order 9/23/2021 9/23/2021 13304
Total Antika Chestnut Brown (Antika Chestnut Brown (87 sqft/pallet - 9.67 sqft/layer))
Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer))
Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer))                   Sales Order 7/23/2021 7/23/2021 12841
Total Antika Onyx Black (Antika Onyx Black (87 sqft/pallet - 9.67 sqft/layer))
Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer))
Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer))                   Sales Order 4/1/2021  4/1/2021  11807
Total Antika Sandlewood (Antika Sandlewood (87 sqft/pallet - 9.67 sqft/layer))
Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer))
Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer))                   Sales Order 6/9/2021  6/9/2021  12457
Total Antika Shale Grey (Antika Shale Grey (87 sqft/pallet - 9.67 sqft/layer))
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...       Sales Order 6/7/2021  6/7/2021  12425
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...       Sales Order 8/3/2021  8/3/2021  12939
Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...       Sales Order 9/14/2021 9/14/2021 13218
Total Architect Cap Champlain Grey (Architectural Cap Champlain Grey (66 linft/pallet -...
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...       Sales Order 6/8/2021  6/8/2021  12454
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...       Sales Order 8/24/2021 8/24/2021 13102
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...       Sales Order 9/14/2021 9/14/2021 13220
Architect Cap Chestnut Brown (Architectural Cap Chestnut Brown (66 linft/pallet -...       Sales Order 10/8/2021 10/8/2021 13415

Explanation

*

*ConvertFrom-Csv causes a warning because the first column is empty. As the warning implies, the property H1 is used for this related property

*ForEach-Object supports multiple scriptblocks as input. When two scriptblocks are supplied, the first one is assign to the -Begin parameter and the later to the -Proces parameter.

*The begin block ({ $H1 = '' }) just makes sure the $H1 variable isn't set.

*If ($_.H1) { $H1 = $_.H1 } captures the H1 (first cell) from the current row

*If ($_.Type -eq 'Sales Order') { $_.H1 = $H1 } set the H1 (first cell) at the current row which might have been captured in a prior iteration

*$_ emits the current (modified) object


text:
Q: Is applying a jQuery plugin inside a each loop worse for performance than applying it the traditional way? Is applying a plugin this way:
        $('.zoom').zoom({
            on: 'grab',
            url: 'http://i.imgur.com/giJudUh.jpg'
        });

any worse for performance than this way:
        $('.zoom').each(function() {
            $(this).zoom({
                on: 'grab',
                url: $(this).data('zoom-url')
            });
        });

I need to do it the 2nd way since the zoom url has to be different for each ".zoom" element. And doing it the 2nd way allows me to grab the unique url from a data attribute on the element itself.
Just wondering if doing it the 2nd way is bad for performance in any way.

A: No, in this case they do literally the same thing: https://github.com/jackmoore/zoom/blob/master/jquery.zoom.js#L85
$.fn.zoom = function (options) {
    return this.each(function () {

Maybe the only difference is $('.zoom').each(... would require $.fn.each to be ran twice.


text:
Q: Changing the Title Bar style on Windows 10 applications Applications in Windows 10 have a title bar in one of two styles.
The style that is present for "normal" desktop applications:

And the style that appears in UWP applications:

I'm wondering if it is somehow possible to change an attribute of a running application, or change some registry key, like in this question, to make it so that my "normal" desktop applications automatically have the new updated UWP title bar. I know it's possible to create / compile a new application with the updated title bar, but is it possible to force an older application to have the new UWP titlebar without recompiling it?
(A good answer for this question will demonstrate how to do so or include a technical explanation why this isn't possible.)


text:
Q: Code shows the segmentation fault but I am not able to find it out When I was working on the linked list in a program the adds two polynomials using linked list and when I compiled it in my laptop it printed an infinite loop but online compilation showed segmentation fault I have checked all the pointers but I was not able to find it out, can you help me with that ?
my input polynomials are:
-polynomial 1= x^8 +5x^4 -7x^2 +6x
-polynomial 2= x^9 +7x^5 -3x^4 +2x^3

*

*create_list program creates the list

*insert program inserts the node at given position

*add_polynomials prog. adds two polynomials

struct node {
    float cofficient;
    int exponent;
    struct  node *next;
};
struct node *create_list()
{
    struct node *head,*newnode,*temp;
    printf("enter the number of terms:\n");
    int n;
    scanf("%d",&n);
    if(n==0){
        printf("creating empty list\n");
        struct node *head=NULL;
        return head;
    }
    int i=1;
    newnode=(struct node *)malloc(sizeof(struct node));
    printf("enter the cofficient and expression of term %d:\n",i);
    scanf("%f%d",&newnode->cofficient,&newnode->exponent);
    newnode->next=NULL;
    head=newnode;
    temp=head;
    for(i=2;i<=n;i++){
        newnode=(struct node *)malloc(sizeof(struct node));
        printf("enter the cofficient and expression of term %d:\n",i);
        scanf("%f%d",&newnode->cofficient,&newnode->exponent);
        newnode->next=NULL;
        temp->next=newnode;
        temp=newnode;
    }
    return head;
}

void display(struct node *start)
{
    if(start==NULL){
        printf("nothing to display\n");
    }
    struct node *p=start;
    int i=1;
    while(p != NULL){
        //printf("for term %d:\n",i++);
        printf("%.1fx^(%d)  ",p->cofficient,p->exponent);
        if(p->next->cofficient  >0)
        printf("+");
        p=p->next;
    }
}
struct node *insert(struct node *start,float coff,int expo)
{
    struct node *newnode=(struct node *)malloc(sizeof(struct node ));
    newnode->cofficient=coff;
    newnode->exponent=expo;
    newnode->next=NULL;
    if(start ==NULL){
        printf("inserting in the empty list...\n");
        start=newnode;
        return start;
    }
    if(newnode->exponent > start->exponent){
        newnode->next=start;
        start=newnode;
        return start;
    }
    struct node *temp,*p=start;
    while(p->next != NULL){
        temp=p->next;
        if(temp->exponent <= newnode->exponent){
        p->next=newnode;
        newnode->next=temp;
        return start;
        }
        p=p->next;
    }
    if(newnode->exponent < p->exponent){
        p->next=newnode;
        newnode->next=NULL;
        return start;
    }
}
struct node *add_polynomials(struct node *start1,struct node *start2)
{
    struct node *p1,*p2;
    p1=start1;
    p2=start2;
    //struct node *newnode;
    struct node *p3_start=(struct node *)malloc(sizeof(struct node ));
    //p3_start=NULL;
    while(p1 != NULL && p2 != NULL){
        if(p1->exponent > p2->exponent){
            p3_start=insert(p3_start,p1->cofficient,p1->exponent);
            p1=p1->next;
            //continue;
        }
        else if(p1->exponent < p2->exponent){
            p3_start=insert(p3_start,p2->cofficient,p2->exponent);
            p2=p2->next;
            //continue;

        }
        else if(p1->exponent == p2->exponent){
            p3_start=insert(p3_start,p1->cofficient +p2->cofficient,p1->exponent);
            p1=p1->next;
            p2=p2->next;
        }
    }
    while(p1 != NULL){

        p3_start=insert(p3_start,p1->cofficient,p1->exponent);
        p1=p1->next;
    }
    while(p2 != NULL){

        p3_start=insert(p3_start,p2->cofficient,p2->exponent);
        p2=p2->next;
    }
    return p3_start;
}

int main ()
{
    struct node *p1_head,*p2_head,*p3_head;
    p1_head=(struct node *)malloc(sizeof(struct node ));
    p1_head=create_list();
    p2_head=(struct node *)malloc(sizeof(struct node ));
    p2_head=create_list();
    p3_head=(struct node *)malloc(sizeof(struct node ));
    p3_head=add_polynomials(p1_head,p2_head);
    display(p3_head);
    return 0;
}

A: When testing this I needed to change in function display
if(p->next->cofficient  >0)
    printf("+");

to
if(p->next != NULL)
    if(p->next->cofficient  >0)
        printf("+");

Else you try to dereference the pointer p->next which is null.
If you learn how to run the code in a debugger these types of errors are trivial to find.


text:
Q: TypeError while template matching in opencv python Part of my code is :
import pyscreenshot as ImageGrab
img=ImageGrab.grab()
img = img.load()
img = np.array(img)
template = cv2.imread('s2_5.jpg',0)
res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF)

I'm getting the following error message:
Traceback (most recent call last):
  File "E:\python\opencv\template_matching.py", line 20, in <module>
  res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF)
TypeError: image data type = 17 is not supported

A: You get that error because img and template are not of the same type, and more importantly, as the error messages says, img's type is not supported by cv2.matchTemplate().
On line 20 of your code, ImageGrab.grab() returns a PIL/Pillow image. So you need to convert img to a numpy array before using it as an input of cv2.matchTemplate().


text:
Q: How can I set a cookie's expiration in NodeJS? I'm writing my own cookies as part of a webserver I'm making using NodeJS (i.e. not using any packages). I've been able to do this just fine using something like:
response.writeHead(200, {
  'Set-Cookie':'sesh=wakadoo'
});

However, I'd like to make my cookies more persistent than they currently are (which is to say not at all). I've tried doing something like this:
var curdate = new Date();
response.writeHead(200, {
   'Set-Cookie':'sesh=wakadoo; expires='+curdate.toUTCString()
});

but alas this doesn't seem to work. chrome just ignores the expiration i set, and firefox never loads the page. My current goal is to simply give my cookie an expiration date that can be interpreted by the browser... does anybody know how to do this?
Best,Sami

A: Try giving the expires some lead time, like an day. The client/server may not read it because it's expired when you submit it.
response.writeHead(200, {
    'Set-Cookie':'sesh=wakadoo; expires='+new Date(new Date().getTime()+86409000).toUTCString()
});


text:
Q: Computer Modern Bright font and blackboard bold symbols I am trying to match the sans serif math font provided by cmbright with proper blackboard bold symbols (also sans serif). I found that the fourier and stix (xits?) fonts provide such symbols. But how can I use cmbright and import only the blackboard bold symbols in LuaLaTeX/XeLaTeX?

A: Getting the definition of the font from fourier is easy; with a little trial and error one can also get the right magnification factor.
\documentclass{article}
\usepackage{cmbright}

%%% taken from fourier.sty
\DeclareFontFamily{U}{futm}{}
\DeclareFontShape{U}{futm}{m}{n}{
  <-> s * [.97534] fourier-bb % but changing the magnification factor
  }{}
\DeclareMathAlphabet{\mathbb}{U}{futm}{m}{n}

\begin{document}
$-3\in\mathbb{Z}\subseteq\mathbb{Q}\ne Q$

\texttt{\sbox0{$Q$}\the\ht0}

\texttt{\sbox0{$\mathbb{Q}$}\the\ht0}

\end{document}

The last two lines show that the heights match (up to 0.00001pt).

For the STIX fonts the procedure is similar.
\documentclass{article}
\usepackage{cmbright}

%% taken from the STIX font distribution
\DeclareFontEncoding{LS1}{}{}
\DeclareFontSubstitution{LS1}{stix}{m}{n}
\DeclareFontFamily{LS1}{stixbb}{\skewchar\font127 }
\DeclareFontShape{LS1}{stixbb}{m}{n} {<-> s*[1.032631] stix-mathbb}{}
\DeclareFontShape{LS1}{stixbb}{b}{n} {<-> s*[1.032631] stix-mathbb-bold}{}
\DeclareMathAlphabet{\mathbb}{LS1}{stixbb}{m}{n}
\SetMathAlphabet{\mathbb}{bold}{LS1}{stixbb}{b}{n}

\begin{document}
$-3\in\mathbb{Z}\subseteq\mathbb{Q}\ne Q$

\texttt{\sbox0{$Q$}\the\ht0}

\texttt{\sbox0{$\mathbb{Q}$}\the\ht0}

\end{document}

A: The mathalfa package makes this kind of changes quite easy!
For fourier:
\usepackage{cmbright}
\usepackage[bb=fourier]{mathalfa} % esstix math bb font

For stix (resp. esstix):
\usepackage{cmbright}
\usepackage[bb=esstix]{mathalfa} % fourier math bb font


text:
Q: Aggregate sql resultset into HashBytes value Is there an equivalent of
CHECKSUM_AGG(CHECKSUM(*))

for HashBytes?
I know you can do
SELECT
    HashBytes('MD5',
        CONVERT(VARCHAR,Field1) + '|'
      + CONVERT(VARCHAR,Field2) + '|'
      + CONVERT(VARCHAR,field3) + '|'
    )
FROM MyTable

But I am not sure how to aggregate all calculated hashbyte records into a single value inside of SQL.
One reason I would want to do this is to determine if data has changed in the source table since the previous load before moving the data into my system.

A: If you want to check if a given row has changed I strongly recomend you to use a "timestamp" column.
The value is automatically updated by Sql Server in every row modification.
Then if a row is changed, the value will be diferent after modification and you could notice it without implementing logic or querying the whole table.
But if you want to know if at least one row has been updated I recomend you to use:
DECLARE @Tablename sysname = 'MyTable';

SELECT modify_date FROM sys.tables WHERE name = @Tablename;

(If you are using .Net in your business layer it might be interesting for you to take a look on SqlDependency)

A: You can loop through all records and combine hashes to one
declare @c cursor;
declare @data varchar(max);
declare @hash varchar(400) = '';

set @c = cursor fast_forward for
    select cast(SomeINTData as varchar(50)) + SomeTextData
    from TFact
    where Year = @year
        and Month = @month;

open @c
fetch next from @c into @data
while @@FETCH_STATUS = 0 begin
    set @hash = HASHBYTES('sha1', @hash + @data)

    fetch next from @c into @data
end

select @hash Ha

A: You can nest hashbytes, using a varbinary variable to accrue each row's inner hash results for the final outer hash.
My example below takes ~24 seconds against 870k rows on a mid-range Xeon. More columns and lots of null values will increase crunch time.
The Order by clause is essential to guaranteeing repeatable results.
Declare @TableHash varbinary(max) = 0x00;

Select @TableHash =
    hashbytes('MD5', @TableHash +
        hashbytes('MD5',
            isnull(convert(nvarchar(max),Col1_int),'null') +
            isnull(convert(nvarchar(max),Col2_int),'null') +
            isnull(convert(nvarchar(max),Col3_int),'null') +
            isnull(convert(nvarchar(max),Col4_int),'null') +
            isnull(convert(nvarchar(max),Col5_nvmax),'null'))

    )
From MyTable
Order by Col2_int,Col1_int;

Print convert(varchar(max), @TableHash, 1) +
    Case @TableHash When 0x00 Then ' (Table has no data)' Else '' End;

Output:
0x2AF0A66411F23B67D3819AC407D3B8BD

A: With newer versions of SQL Server, you can use a combination of CONCAT and STRING_AGG to bung everything together, then hash the whole result.
SELECT
    HASHBYTES('SHA2_512',
      STRING_AGG(
        CONCAT(
          CAST(Field1 AS varchar(max)),  -- at least one max
          Field2,
          field3
        ), ''
      )
    )
FROM MyTable;

Note that MD5 is deprecated, and would probably be at risk of hash collisions even in this case. You should use SHA2_512 or SHA2_256 instead.


text:
Q: Extract domain or subdomain PHP I need to extract either domain or 1st level subdomain from the link with regex
www.google.com -> google.com
www.maps.google.com -> maps.google.com
www.dev.maps.google.com - > maps.google.com
www.dev.maps.google.com/show/maps - > maps.google.com

I know how to do extract just the domain, but I'm struggling to write an expression that would detect if there are subdomains and get only the first one
Could someone show me the right expression?

A: I couldn't come up with a regex that does what you want, but as this question is only tagged with php here is some php code that does what you want.
This code will split your input by ".", extract the tld from the last part and shift everything up to 3 elements from the splitted string while ignoring a possible "www" part. Finally, it will combine the maximum 3 remaining parts, which gives you your desired domain with possibly one subdomain.
<?php
$domain = 'www.dev.maps.google.com/asd/fgh';
$parts = explode('.', $domain);

// extract tld
preg_match('/([a-z]+)[^a-z]/', $parts[count($parts)-1], $tldMatches);
$parts[count($parts)-1] = (isset($tldMatches[1]))
    ? $tldMatches[1]
    : $parts[count($parts)-1];

// remove www if present
if ('www' === $parts[0]) {
    array_shift($parts);
}

// define how many parts we have to ignore
$splitHere = (count($parts) > 3)
    ? count($parts) - 3
    : 0;

// output the desired parts combined with "."
echo implode('.', array_slice($parts, $splitHere)) . PHP_EOL;

This code will not work with umlaut-domains.

A: Using regex-based methods to manipulate url strings is generally not recommended.  The first order of business is to prepare the string for parse_url(), then you will have a solid foundation to start from.
After generating a standardized host string, I use explode() and array functions to extract the desired result.
Code: (Demo)
$array=['google.com', // -> google.com
        'www.google.com', // -> google.com
        'www.maps.google.com', // -> maps.google.com
        'www.dev.maps.google.com', // - > maps.google.com
        'www.dev.maps.google.com/show/maps', // - > maps.google.com
        'www.dev.maps.google.com?key=value', // - > maps.google.com
];

foreach($array as $url){
    $host=parse_url("http://$url")['host'];        // reliable way to isolate host component only
    $bits=explode('.',$host);                      // split string on dots
    if($bits[0]==='www'){                          // check for www in first element
        unset($bits[0]);                           // remove first element
    }
    echo implode('.',array_slice($bits,-3)),"\n";  // extract maximum of 3 elements from end, rejoin with dots
}

Output:
google.com
google.com
maps.google.com
maps.google.com
maps.google.com
maps.google.com

This code is not written to validate the input string as a valid url.  It assumes you will be feeding valid domains to it.  If you know that the only substring to move after www. will be dev. then an approach can be written far more literally.


text:
Q: How to split the numbers and characters in to two strings in objective c? I want to split the string like FG12344 in to FG and 12344 using Objective C. I don't how to do this, please help me in this issue?

A: For the characters:
NSString *characters = [@"FG12344" stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];

For the numbers:
NSString *numbers = [@"FG12344" stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]];

A: you can use NSPredicate for similar cases.


text:
Q: Firebase/Firestore Testing Pattern: mock fake data without code duplication (DRY) This is a question about programming style and patterns when it comes to writing tests for complex systems written in Firebase/Firestore. I'm writing a web app using Firebase, Typescript, Angular, Firestore, etc...
Objective:
I have written basic security rules tests to test my users collection. I'll also be testing the function that writes the document, and e2e testing that the document is written when a new user signs up. So far so good.
The tests are clean so far - I manually define a few user objects, write it to the database before the tests with beforeEach() and run the tests. The tests depend on me knowing what data I wrote in the first place - what were the document ids, what were the field values etc... and then I check for certain operations to pass, certain operations to fail, depending on the custom claims provided. Similarly, with functions tests and e2e tests, I'll be checking if correct data was written, generated, etc...
The next step would be to test the chat functionality. Here's where I run into code duplication issues.
Issue:
So let's say I want to test the chat functionality or the transaction functionality. For these modules to be tested, the database needs to have fake user data, transaction data, test data etc... and, furthermore, within the tests, I need to have access to the fields, document Ids, etc.. that were written to the database, so I can access the documents for tests, etc...
For example, whether or not a chat message can be written to firestore depends on whether certain fields exist on the user document.
This would require me to manually define all the objects I plan to write to the database in the same file as the tests themselves, so I have access to what I wrote. As I test more complex and dependent modules of the system, since each test for each module is in a separate file, I either have to manually write out each object, or require it from another test file and write it. Each document has its payload and its Id that I need to keep track of, and even the fake user token objects I have to pass to firestore (or actual auth user records I have to import for online testing). This would mean a whole bunch of boilerplate code and duplication simply writing objects as such in all of my files:
const fakeUserPayload: User = {
  handle: 'username',
  email: faker.internet.email(),
  ...etc
}
// And so on and on for all test users, chat docs, transaction docs, etc...

Potential Solution: so there are a few potential solutions I came up with, but none seem to solve the problem.
For example, I thought I would write a module that simply populates the firestore database at the start of each test. The module would have a userPayloadFactory and other loops (using faker module) to automatically populate the Db with fake data.
Problem: If I did this, I wouldn't have access to the document Ids and field data in my tests, since it's automatically generated. I thought, maybe I could populate firestore with fake data, and then use an administrative db connection to read the fake user documents and their Ids back into the tests, and then use this data to conduct the tests. For example, I would find the user id and then generate a chat document and test for correct data / success. Except it seems incredibly messy to write data in one module and then read it back in another, especially since most tests require a specific document to be written to test for certain cases/scenarios. Which makes auto-populated mock data useless - so we're back to square one, where I have to manually define and write out a large number of fake objects in order to test rules, functions and functionality.
Potential Solution: I could maybe keep auth and firestore data in a JSON backup file, (so they remain static) and import them into the database with a shell command before each test suite. However, this has its own issues as it's not easy to dynamically generate new test cases or edge cases, and also difficult to continually re-export and update the JSON backup files as the project grows.
What is a better way to structure and write my tests so that I can automatically generate the documents and payloads I need, while having control and access over what gets written?
I'm hoping there's some kind of factory or pattern that can make this easier, scalable and more consistent and robust.

A: You're asking a really huge question, writing tests for big environments is a complex task and even more when it's coupled to database state. I will try to answer to the best of my knowledge so take my words with a grain of salt.
I believe you're dealing with two similar yet different concerns, automatic creation of mock data and edge-cases that require very specific document setup. These two are tightly coupled within the tests itself as you need both kinds of data to run them, however the requirements differ one another and therefore their creation should take that in account. Let's talk about your potential solutions from that perspective.
The JSON backup provides a static and consistent dataset that allows to repeat the tests over time being sure the environment hasn't changed and it's a good candidate to address the edge-case problem. It's downsides are that is hardly maintainable because any object modification to accommodate changes in TestA may break the expectations of TestB that also relies on it, it's almost assured you will loss the track of these nuances at some point; You can add new objects to accommodate code and test changes but this could lead to a combinatoric explosion of the objects you need to take care of as your project grows. Finally JSON files are not the way to go if you are going to require dynamically generated data.
The factory method is a great option to deal with the creation of arbitrary mock data since there are less restrictions placed on it, so writing a generator seems a good idea. You disliked this based on the fact that you need to know your data while running the tests but I think that's solvable. Your test might load the Factory module, then create the data and store it in-memory/HDD in addition to commit this changes to Firestore, there's no need to read the data from the database.
Your other other concern were the corner case documents which is trickier because you need very specifically shaped data. You might handcraft the documents yourself but then you got a poorly scalable solution. The alternative is trying to look for constraints/invariants in the shape of edge-case documents that you can abstract into factory methods. The worst scenario here is that when some edge-cases do not share any similarity with the rest you will need to write a whole method for each of these. I won't consider this a downside as it improves the modularity and maintainability of the Factory .
Overall, I would stick with the Factory pattern because it already offers techniques to follow the DRY principle by the means of isolating the creation of distinct objects, decoupling data creation from test execution and facilities to avoid disruptive breaks as the tests evolve with the project.
With that being said a little research got me to this page about the Builder Pattern that you may find interesting. Also this thread about code duplication in tests might be of interest. And finally just to comment out that Firebase has some testing functionality that can be found here.
Hope this helps.


text:
Q: "vector subscript out of range" I have a strange issue with 2 arrays of "pointer to pointer to objects" (by looking a te the code am i getting this right?)
I did read A LOT to try and grasp as much knowledge about what I'm trying to do but this error is getting overwhelming and I really wanna find out why is this happening.
For what I can see from the error that pops on this line:
vec_cliente[i] = new Cliente(nombre,apellido,carne,fecha); //this pops the error

is that I am trying to put the a new Cliente at vec_cliente[i] (0) and that doesn't exist.
however... this
vec_solicitudes[i] = new Casa_Profesor(carne, fecha_sol, costo_mant, costo_alquiler, cant_p,salon);

runs fine o.0
Principal.h has this:
#pragma once
#include string>
#include vector>
#include "Cliente.h"
#include "Persona.h"
#include "Casa_Profesor.h"
using namespace std;

class Principal{

private:
    Cliente ** vec_cliente;
    Casa_Profesor ** vec_solicitudes;

public:
    static string  info [];
    static string  miembros [];

    Principal(void);
    void cargar(void);
    void calular_mayor_solicitudes(Cliente* vec_cliente, Casa_Profesor* vec_solicitudes);
    void mayor_costo(void);
    void ingreso_total(void);
    void espacio_mayor_uso(void);
    virtual ~Principal(void);

};

Principal.cpp has this:
#include "StdAfx.h"
#include "Principal.h"
#include iostream>
#include string>
#include sstream>
#include vector>
#include iterator>

using namespace std;

string Principal::info[] = {"623 25-05-2010 625.00 850.50 190 1"

                                ,"199 24-01-2009 300 900.5 180 1"
                ,"199 24-01-2010 300.50 900 175 2"
                ,"201 24-01-2009 300 900.5 180 3"
                ,"201 24-01-2010 300.50 900 175 3"
                ,"201 24-01-2009 30 900.5 180 3"
                ,"201 24-01-2010 300.50 900 175 3"
                ,"404 24-01-2009 300 900.5 180 3"
                ,"404 24-01-2010 300.50 900 175 2"
                ,"404 24-01-2009 30 900.5 180 3"
                ,"404 24-01-2010 300.50 900 175 2"
                ,"404 24-01-2009 300 90.5 180 3"
                ,"505 24-01-2010 300.50 900 175 2"
                ,"505 24-01-2009 300 900.5 180 3"
                ,"505 24-01-2010 300.50 900 175 2"
                ,"505 24-01-2009 300 90.5 180 1"
                ,"505 24-01-2010 300.50 900 175 1"
                ,"505 24-01-2009 300 900.5 180 3"
                ,"505 24-01-2010 1300.50 900 175 2"
                ,"106 24-01-2009 300 900.5 180 3"
                ,"106 24-01-2010 300.50 900 175 3"
                ,"106 24-01-2009 300 900.5 180 3"
                ,"106 24-01-2010 300.50 900 175 3"};

string Principal::miembros[] = {"Jaime Perez 623 22 12 1998"

                ,"Maria Perez 199 02 12 1988"
                ,"Jose Castro 201 3 11 2008"
                ,"Juan Caceres 404 21 1 2007"
                ,"Carla Vivas 505 18 09 1990"
                ,"Daniela Ochoa 106 02 01 2010"};

Principal::Principal(void)
{

}

void Principal::cargar(){

int i = 0, carne = 0, cant_p = 0, salon = 0;
string nombre, apellido, fecha, aux, fecha_sol;
double costo_mant, costo_alquiler;

vec_solicitudes = new  Casa_Profesor * [(sizeof(info)/sizeof(string))*sizeof(Casa_Profesor)];

    for (i = 0; i < (sizeof(info)/sizeof(string)); i++){
        istringstream stream(info[i],ios_base::in);

        stream >> aux;
        carne = atoi(aux.c_str());
        stream >> fecha_sol;
        stream >> aux;
        costo_mant = atof(aux.c_str());
        stream >> aux;
        costo_alquiler = atof(aux.c_str());
        stream >> aux;
        cant_p = atoi(aux.c_str());
        stream >> aux;
        salon = atoi(aux.c_str());

        vec_solicitudes[i] = new Casa_Profesor(carne, fecha_sol, costo_mant, costo_alquiler, cant_p,salon);  //THIS runs fine
    }

vec_cliente = new  Cliente * [(sizeof(miembros)/sizeof(string))*sizeof(Cliente)];

    for (i = 0; i < (sizeof(miembros)/sizeof(string)); i++){
        istringstream stream(miembros[i],ios_base::in);

        stream >> nombre;
        stream >> apellido;
        stream >> aux;
        carne = atoi(aux.c_str());
        stream >> fecha;
        fecha.append(" ");
        stream >> aux;
        fecha.append(aux);
        fecha.append(" ");
        stream >> aux;
        fecha.append(aux);

        vec_cliente[i] = new Cliente(nombre,apellido,carne,fecha);  //THIS trows the exception
    }

}

/* the only difference between Casa_Profesor and Cliente is that Cliente inherits from a class Persona and Casa_Profesor doesn't.
  as for why is this code so weird: it's a practice for programing but feel free to point out any other programming mistakes I'm making in this code (specially on the sizeof stuff)
 ALSO, I could edit and post all the code for the clases and all that but I wanted to first see if someoe could point me into an obvious newbie mistake I might be making...
thanks in advance for any help */

A: I am not sure why you get "vector subscript out of range" when you aren't using any vectors, just raw pointers and arrays. I'll assume that you didn't tell us something!
So I'll just make some random comments on your code:
vec_solicitudes = new  Casa_Profesor * [(sizeof(info)/sizeof(string))*sizeof(Casa_Profesor)];

Are you trying to create 1 Casa_Profesor * in vec_solicitudes for each string in info? If so, you want:
vec_solicitudes = new  Casa_Profesor * [sizeof(info)/sizeof(string)];

This will allocate enough memory for (sizeof(info)/sizeof(string)) (Casa_Profesor *).
Likewise:
vec_cliente = new  Cliente * [sizeof(miembros)/sizeof(string)];

However, your allocations are too big, rather than too small, so they are not the cause of the exception. I suggest instead that you look at the Casa_Profesor and Cliente constructors - they are where the exception probably originates.


text:
Q: How to link documents on mongoose I am new to express development and i am trying to build a blog. I have built two models, one for posts and one for uses. On users schema i have an attribute posts to save the post when a user creates a post. On the controller, before i create a post first i am taking the user's id from the req.params and after that i retrive the user by findbyid function and try to save the post on user's posts attribute, but with no succeful.
const mongoose = require("mongoose");

UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    posts: [{type: mongoose.Schema.Types.ObjectId, ref: "Post"}]
})

module.exports = mongoose.model("User", UserSchema);

const Post = require("../model/post");
const User = require("../model/user");

module.exports = {
    new: (req, res) => {
        res.render("new_post");
    },
    post_new: (req, res) => {
        const title = req.body.title;
        const article = req.body.article;
        const id = req.params.id;

        const post = new Post({
            title: title,
            article: article,
        })

        User.findById(id)
        .then(user => {
            user.posts.push(post);
        })

        //post.created_by.push(id);

        post.save()
        .then(result => {
            console.log("Post has created");
            res.redirect("/");
        });
    }
};

A: I see a few problems.
You user schema should not have array of posts. Instead, your post schema should have a field named user/userId to store user ID.
Example:
const PostSchema = new mongoose.Schema({
  title: { type: String },
  ....,
  userId: {type: mongoose.Schema.Types.ObjectId, ref: "User"}
});

Now your post_new function should be like this.
post_new: async (req, res) => {
  const title = req.body.title;
  const article = req.body.article;
  const id = req.params.id;

  const post = await Post.create({
      title: title,
      article: article,
      userId: id
  });

  console.log("Post has created");
  res.redirect("/");
}

If you want to stick with your way then the create_new function should be like this.
post_new: async (req, res) => {
  const title = req.body.title;
  const article = req.body.article;
  const id = req.params.id;

  const post = new Post({
      title: title,
      article: article,
  });

  const {_id} = await post.save();

  const user = await User.findById(id);
  user.posts.push(_id);
  await user.save();

  console.log("Post has created");
  res.redirect("/");
}


text:
Q: Set http link for text cell in Google Sheets Java Api I want to insert in Google sheets cell text with hyperlink:

I tried this Java code:
values.add(new CellData()
                .setUserEnteredValue(new ExtendedValue()
                    .setStringValue(get.getTitle())).setHyperlink(get.getUrl())

But I get only text without hyperlink.
How I can implement this?

A: In Documentation

A hyperlink this cell points to, if any. This field is read-only. (To set it, use a =HYPERLINK formula in the userEnteredValue.formulaValue field.)

You can't set multiple properties for an ExtendedValue object it only accepts single property to set. All properties point a value for Cell but only difference is those setters determines the type of cell value (bool, string, formula, number, error), so you can't set multiple value for Single Cell thats why you get the error( (oneof), oneof field 'value' is already set ).
Here is the new code, you can add hyperlink like this:
values.add(
    new CellData()
        .setUserEnteredValue(new ExtendedValue()
        .setFormulaValue("=HYPERLINK(\"http://stackoverflow.com\",\"SO label\")")
);


text:
Q: Compare two nested lists in Python I have two lists:
list_a = [["the", "ball", "is", "red", "and", "the", "car", "is", "red"],
          ["the", "boy", "is", "tall", "and", "the", "man", "is", "tall"]]
list_b = [["the", 0], ["ball", 0], ["is", 0], ["red", 0], ["and", 0], ["car", 0]],
          ["The", 0], ["boy", 0], ["is", 0], ["and", 0], ["man", 0], ["tall", 0]]

Goals:
Iterate over list_b, pick up the specific string and check if it is in list_a and if so, increase the specific int by 1.
Important in that context is that I will only compare list_a[0] with list_b[0] and list_a[1] with list_b[1].
When finished it should look like that:
list_a = [["the", "ball", "is", "red", "and", "the", "car", "is", "red"],
          ["the", "boy", "is", "tall", "and", "the", "man", "is", "tall"]]
list_b = [["the", 2], ["ball", 1], ["is", 2], ["red", 2], ["and", 1], ["car", 1]],
          ["the", 2], ["boy", 1], ["is", 2], ["and", 1], ["man", 1], ["tall", 2]]

for loops give me massive problems and it seems that this approach is wrong and not suitable for this task, so I am open and thankful for different solutions.

A: You can use enumerate and find the index of each row in list_b and base row_index, Use collections.Counter for list_a and update value in each sublist of each row in list_b.
from collections import Counter

for row, lst_b in enumerate(list_b):
    cnt_list_a = Counter(list_a[row])
    for lst in lst_b:
        lst[1] = cnt_list_a[lst[0].lower()]

print(list_b)

Output:
[
    [['the', 2], ['ball', 1], ['is', 2], ['red', 2], ['and', 1], ['car', 1]],
    [['The', 2], ['boy', 1], ['is', 2], ['and', 1], ['man', 1], ['tall', 2]]
]


text:
Q: Call method after ActionResult in .NET Core I'm new to MVC stuff, so my thinking might be completely wrong, but I would like to achieve when I call an action in a controller, as soon as it returns a result, another method will be invoked.
Currently my code is working on this way:
[HttpGet("/api/compile/{*path}")]
public IActionResult Compile(string path)
{
    this.Queue.QueueBackgroundWorkItem(async token =>
    {
        await cp.Compile()
                .ContinueWith((compilation) =>
                    Console.WriteLine(compilation.Result), token);
    });

    return new ContentResult
    {
        Content = "
Compilation requested...
",
        ContentType = "text/html"
    };
}

It's working as expected, a background job has been enqueued and the contentresult will be returned.
My problem is that if I check the console log, of course because of a reasonable reason, the background job starts logging in the console earlier than the contentresult has been returned, so what I see:
backgroundjob log...1
backgroundjob log...2
[compilation.Result]
backgroundjob log...3
backgroundjob log...4
...

But I would like to reach, that the background job will be enqueued strictly after the return of the result.
[compilation.Result]
backgroundjob log...1
backgroundjob log...2
backgroundjob log...3
backgroundjob log...4
...

Maybe I can add a Thread.Sleep inside the background job anonymous method, but of course it's not consistent and fine-logic way but currently I don't know how I can solve this.
Thank you for your help!


text:
Q: link not loading properly in android N webview I want open this link (http://e-sign-poc.s3-website-us-west-2.amazonaws.com/) like mobile browser using webview
mWebview = (WebView) findViewById(R.id.wb_sample);
WebSettings webSettings = mWebview.getSettings(); webSettings.setJavaScriptEnabled(true);
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebViewClient(new WebViewClient());
mWebview.loadUrl("http://e-sign-poc.s3-website-us-west-2.amazonaws.com/");

This link not loading properly in webview, but this link works perfectly in telegram webview

A: Wait for some time after you load URL to WebView
It will work perfectly in my device
or
Try with this code
 url = "http://e-sign-poc.s3-website-us-west-2.amazonaws.com/" +
            "";
    linearLayout.setVisibility(View.GONE);
    webView.setVisibility(View.VISIBLE);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setSupportZoom(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.loadUrl(url);

A: Try with it -
 webView = (WebView) findViewById(R.id.wvTest);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                progressBar.setProgress(view.getProgress());
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);
            }
        });
        webView.loadUrl("https://www.example.com");


text:
Q: Is it mandatory to check if realloc worked? In C is it mandatory to check if the realloc function made it?
void *tmp = realloc(data, new_size);
if (tmp == NULL) return 1;
data = tmp;

A:
In C is it mandatory to check if the realloc function made it?

The quick answer is: NO! checking for failure is not mandatory. If realloc fails, it returns a null pointer, storing it into the original pointer overwrites the previous value, potentially making the block unreachable for later freeing. Dereferencing this null pointer has undefined behavior, a crash on architectures with protected virtual memory.  In practice, on these systems with virtual memory, unless you pass an insanely large number for the new size, the call will not fail so you wont get hit by this sloppy code:
data = realloc(data, new_size); // assume realloc succeeds

If you care to be friendly to the next guy trying to debug the program in more stressed environments, you could add:
data = realloc(data, new_size); // assume realloc succeeds
assert(data);

The long answer is: YES you should check for realloc failure in a reliable production program and handle the failure gracefully.
Obviously realloc can fail if you the requested amount of memory is too large for the heap to honor, but it can also fail for internal reasons for requests for smaller amounts, even amounts smaller than the size of the allocated block passed as an argument, even in the absence of heap corruption caused by undefined behavior. There is just no reason to assume that realloc() will always succeed.
If you know the current size allocated for the object you mean to realloc, you can ignore a realloc failure to shrink the object.
For other requests, you should handle handle the error gracefully.  If the error causes the function to abort its operation, any memory allocated for the current task should be free'd to avoid memory leaks if the calling program continues.  This is a recommendation to avoid memory or resource leaks and allow the program to run reliably for a long time, but depending on your local constraints, you may get away with slack.

To summarize: depending on local constraints (from quick and dirty throw away code to reliable sturdy production code running indefinitely in a life support system), you might not care about the potential improbable failures or it could be mandatory for you to detect, handle and document any unexpected situations.
Detecting and reporting less improbable errors such as fopen() failure to open files, fgets() failure at end of file or scanf() conversion errors from invalid user input is recommended to avoid wasting hours trying to make sense of unexpected behavior, or worse relying on corrupted data that did not produce obviously incorrect results.

A:
Is it mandatory to check if realloc worked?

Yes, or at least, as mandatory as is to check any other success/failure return.
realloc can certainly fail, just as malloc can.  In fact, realloc can fail even if you're trying to make a block smaller.
Now, if you're working on the assumption that malloc on a virtual memory system can never fail, and if you're not checking the return value from malloc, either, then no, with the same justification, you could skip checking realloc's return value also.  (It'd be silly to check realloc's return value but not malloc's.)
In practice, the question of whether to check for memory allocation failure (malloc and/or realloc) on a modern, virtual-memory system is the subject of some debate.  There are plenty of programmers who believe that checking the return values is a waste of time, since "malloc never fails".  Me, I always check (except in the very most rushed, throwaway code), because even after all these years, the number of times I've said "I'm getting so tired of typing if( … != NULL) all the time!" is still zero, while the number of times that a checked and caught NULL return has alerted me promptly to a bug in my code, and saved me hours of pointless debugging, is countless.
So in summary, and at the risk of repeating myself, I'd say that, yes, it's mandatory.  See also Always check malloc'ed memory?

A: It is a return value from a library function. The language has no knowledge of the semantics of any function and it is not syntactically mandatory to check or use any return value.  That is to say it will compile.
However it may be a semantic error not to check, and an unchecked failure may cause unintended runtime behaviour - i.e. a bug.  The language does not prevent you from writing bugs.
It may be "mandatory" in a "local" sense, in cases where development is subjected a coding standard that makes it so.  Any reasonable coding standard would likely impose such a requirement, and that might be enforced by static analysis tools or peer review used by the development team. But not universally mandatory.  You are free to write bad code if such standards are not applied to your project.

A: If you use realloc() on a pointer that has not been initialized with either malloc() or calloc(), as far as I know there's no retrospective way to check realloc()'s return value since it will throw an error:
realloc(): invalid pointer
Aborted (core dumped)
Example:
int myint = 10;
int * ptr = &myint;
ptr = (int*) realloc(ptr,(2 * sizeof(int)));


text:
Q: How to return multiple objects from a Java Method which are stored in an ArrayList? I am trying to return all items with the same category name within a list I made myself.
But it is returning only one category item when there are more items with the same category name.
What can I do to return all of them?
I did this method in my item class :
public static String findCategory(List<item>items ,String cat ) {

    for (int i =0 ; i < items.size() ; i++) {

        if(items.get(i).getcategory().equals(cat))
        {
            return items.get(i).toString();
        }

    }
    return "Invalid Category!" ;
}

I am calling this method in my main as :
System.out.println("Enter category name : ");
String categ = input.next() ;
System.out.println(item.findCategory(itemDatabase, categ)) ;

A:
I am trying to return all items with the same category name within a list

Using Stream it's pretty easy:
public static List<item> findCategory(List<item> items, String cat) {
    return items.stream()
      .filter(item -> item.getcategory().equals(cat))
      .collect(Collectors.toList());
}

A: It is important to realize that java exits the function after the First return call which is why you encountered the problem where it only returns one category.
You need to, within the function, create a new list and store the items with the same category name within said list.  Only once that list is full, you can return it.
Be sure to adjust the function header to accommodate the new return type
public static List<item> findCategory(List<item> items, String cat)

So to put what I said into code:
Create the new list before the for loop:
List<item> out = new ArrayList<item>();

And within your for loop simply append to the list if you have a match:
out.add( items.get(i).toString() );

Then at the end of the function return this list
return out;

Edit: Here is how it looks put together:
public static List<item> findCategory(List<item>items ,String cat ) {

    List<item> out = new ArrayList<item>();

    for (int i =0 ; i < items.size() ; i++) {

        if(items.get(i).getcategory().equals(cat))
        {
            out.add( items.get(i).toString() );
        }
    }

    return out;

}