问:
Expected BEGIN_ARRAY but was BEGIN_OBJECT after retrofit call
I know this was asked a lot before but i cannot find a solution in my case.
I am requesting for a json response about a list of POJO (Movie)

While this is my first time using retrofit i have the problem in the title. The url i am building is right and below is a sample of the response:

```<code>{
   "page":1,
   "total_results":19850,
   "total_pages":993,
   "results":[
      {
         "vote_count":855,
         "id":420817,
         "video":false,
         "vote_average":7.2,
         "title":"Aladdin",
         "popularity":445.349,
         "poster_path":"\/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
         "original_language":"en",
         "original_title":"Aladdin",
         "genre_ids":[
            12,
            14,
            10749,
            35,
            10751
         ],
         "backdrop_path":"\/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
         "adult":false,
         "overview":"A kindhearted street urchin named Aladdin embarks on a magical adventure after finding a lamp that releases a wisecracking genie while a power-hungry Grand Vizier vies for the same lamp that has the power to make their deepest wishes come true.",
         "release_date":"2019-05-22"
      },
      {
         "vote_count":5224,
         "id":299537,
         "video":false,
         "vote_average":7.1,
         "title":"Captain Marvel",
         "popularity":399.859,
         "poster_path":"\/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg",
         "original_language":"en",
         "original_title":"Captain Marvel",
         "genre_ids":[
            28,
            12,
            878
         ],
         "backdrop_path":"\/w2PMyoyLU22YvrGK3smVM9fW1jj.jpg",
         "adult":false,
         "overview":"The story follows Carol Danvers as she becomes one of the universe’s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.",
         "release_date":"2019-03-06"
      },
</code>```

This is my model

```<code>public class Movie implements Parcelable {

@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String releaseDate;
private String moviePoster;
private String avgVote;
private String plot;
private String movieId;
private String movieGenre;

@Ignore
public Movie(String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;
}

public Movie(int id, String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.id = id;
    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;

}

public String getMovieGenre() {
    return movieGenre;
}

public void setMovieGenre(String movieGenre) {
    this.movieGenre = movieGenre;
}

public int getId() {
    return id;
}

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

public String getTitle() {
    return title;
}

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

public String getReleaseDate() {
    return releaseDate;
}

public void setReleaseDate(String releaseDate) {
    this.releaseDate = releaseDate;
}

public String getMoviePoster() {
    return moviePoster;
}

public void setMoviePoster(String moviePoster) {
    this.moviePoster = moviePoster;
}

public String getAvgVote() {
    return avgVote;
}

public void setAvgVote(String avgVote) {
    this.avgVote = avgVote;
}

public String getPlot() {
    return plot;
}

public void setPlot(String plot) {
    this.plot = plot;
}

public String getMovieId() {
    return movieId;
}

public void setMovieId(String movieId) {
    this.movieId = movieId;
}

protected Movie(Parcel in) {
    title = in.readString();
    releaseDate = in.readString();
    moviePoster = in.readString();
    avgVote = in.readString();
    plot = in.readString();
    movieId = in.readString();
    movieGenre = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(title);
    dest.writeString(releaseDate);
    dest.writeString(moviePoster);
    dest.writeString(avgVote);
    dest.writeString(plot);
    dest.writeString(movieId);
    dest.writeString(movieGenre);
}

@SuppressWarnings("unused")
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
    @Override
    public Movie createFromParcel(Parcel in) {
        return new Movie(in);
    }

    @Override
    public Movie[] newArray(int size) {
        return new Movie[size];
    }
};
</code>```

}

My @GET

```<code>public interface JsonPlaceHolderApi {

    @GET("popular")
    Call<List<Movie>> getMovies(@Query("api_key") String api_key);
}
</code>```

my data request class

```<code>private static final String LOG_TAG = DataRequest.class.getSimpleName();

    ArrayList<Movie> mMovies = null;
    String jsonResponse = "";

    private DataInterface mListener;

    public DataRequest() {
        super();
    }

    public void  getData(String url)  {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_MOVIE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
        Call<List<Movie>> call = jsonPlaceHolderApi.getMovies(Constants.API_KEY);

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {

               if(response!=null && response.body()!=null && mListener!=null){

                   mListener.responseData(response.body());
               }
            }
            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d(LOG_TAG, "response code throwable " + t);
            }
        });
    }

    public void setOnDataListener(DataInterface listener) {
        mListener = listener;
    }

    public interface DataInterface {
        void responseData( List<Movie> myResponse );
    }
}
</code>```

And finally what im trying to do in my mainactivity

```<code>prefSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                userOption = prefSpinner.getSelectedItem().toString();
                Log.d(LOG_TAG, "user option is "+ userOption);
                if (userOption.contentEquals("Most Popular") || userOption.contentEquals("Highest Rated")) {

                    DataRequest dataRequest = new DataRequest();
                    dataRequest.setOnDataListener(new DataRequest.DataInterface() {
                        @Override
                        public void responseData(List<Movie> myResponse) {
                            mMoviesList = myResponse;
                        }
                    });
                            dataRequest.getData(userOption);
                    movieRecycleViewAdapter.swapData(mMoviesList);

                } else if(userOption.contentEquals("Favorites")) {
                    setUpViewModel();
                    movieRecycleViewAdapter.notifyDataSetChanged();
                }
            }
</code>```

答:
I am requesting for a json response about a list of POJO (Movie)

No, you are not. If you look at your JSON output, it is a JSON object, not a JSON array. It contains a JSON array in its results property.

You need to:

Create a Java class that matches the JSON object structure (which will include a List<Movie> results field)

Change Retrofit to return Call<...> where ... is whatever you call the Java class that you created in the preceding bullet

Body:
I know this was asked a lot before but i cannot find a solution in my case.
I am requesting for a json response about a list of POJO (Movie)

While this is my first time using retrofit i have the problem in the title. The url i am building is right and below is a sample of the response:

{
   "page":1,
   "total_results":19850,
   "total_pages":993,
   "results":[
      {
         "vote_count":855,
         "id":420817,
         "video":false,
         "vote_average":7.2,
         "title":"Aladdin",
         "popularity":445.349,
         "poster_path":"\/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
         "original_language":"en",
         "original_title":"Aladdin",
         "genre_ids":[
            12,
            14,
            10749,
            35,
            10751
         ],
         "backdrop_path":"\/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
         "adult":false,
         "overview":"A kindhearted street urchin named Aladdin embarks on a magical adventure after finding a lamp that releases a wisecracking genie while a power-hungry Grand Vizier vies for the same lamp that has the power to make their deepest wishes come true.",
         "release_date":"2019-05-22"
      },
      {
         "vote_count":5224,
         "id":299537,
         "video":false,
         "vote_average":7.1,
         "title":"Captain Marvel",
         "popularity":399.859,
         "poster_path":"\/AtsgWhDnHTq68L0lLsUrCnM7TjG.jpg",
         "original_language":"en",
         "original_title":"Captain Marvel",
         "genre_ids":[
            28,
            12,
            878
         ],
         "backdrop_path":"\/w2PMyoyLU22YvrGK3smVM9fW1jj.jpg",
         "adult":false,
         "overview":"The story follows Carol Danvers as she becomes one of the universe’s most powerful heroes when Earth is caught in the middle of a galactic war between two alien races. Set in the 1990s, Captain Marvel is an all-new adventure from a previously unseen period in the history of the Marvel Cinematic Universe.",
         "release_date":"2019-03-06"
      },

This is my model

public class Movie implements Parcelable {

@PrimaryKey(autoGenerate = true)
private int id;
private String title;
private String releaseDate;
private String moviePoster;
private String avgVote;
private String plot;
private String movieId;
private String movieGenre;

@Ignore
public Movie(String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;
}

public Movie(int id, String title, String releaseDate, String moviePoster, String avgVote, String plot, String movieId, String movieGenre) {

    this.id = id;
    this.title = title;
    this.releaseDate = releaseDate;
    this.moviePoster = moviePoster;
    this.avgVote = avgVote;
    this.plot = plot;
    this.movieId = movieId;
    this.movieGenre = movieGenre;

}

public String getMovieGenre() {
    return movieGenre;
}

public void setMovieGenre(String movieGenre) {
    this.movieGenre = movieGenre;
}

public int getId() {
    return id;
}

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

public String getTitle() {
    return title;
}

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

public String getReleaseDate() {
    return releaseDate;
}

public void setReleaseDate(String releaseDate) {
    this.releaseDate = releaseDate;
}

public String getMoviePoster() {
    return moviePoster;
}

public void setMoviePoster(String moviePoster) {
    this.moviePoster = moviePoster;
}

public String getAvgVote() {
    return avgVote;
}

public void setAvgVote(String avgVote) {
    this.avgVote = avgVote;
}

public String getPlot() {
    return plot;
}

public void setPlot(String plot) {
    this.plot = plot;
}

public String getMovieId() {
    return movieId;
}

public void setMovieId(String movieId) {
    this.movieId = movieId;
}

protected Movie(Parcel in) {
    title = in.readString();
    releaseDate = in.readString();
    moviePoster = in.readString();
    avgVote = in.readString();
    plot = in.readString();
    movieId = in.readString();
    movieGenre = in.readString();
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(title);
    dest.writeString(releaseDate);
    dest.writeString(moviePoster);
    dest.writeString(avgVote);
    dest.writeString(plot);
    dest.writeString(movieId);
    dest.writeString(movieGenre);
}

@SuppressWarnings("unused")
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
    @Override
    public Movie createFromParcel(Parcel in) {
        return new Movie(in);
    }

    @Override
    public Movie[] newArray(int size) {
        return new Movie[size];
    }
};

}

My @GET

public interface JsonPlaceHolderApi {

    @GET("popular")
    Call<List<Movie>> getMovies(@Query("api_key") String api_key);
}

my data request class

private static final String LOG_TAG = DataRequest.class.getSimpleName();

    ArrayList<Movie> mMovies = null;
    String jsonResponse = "";

    private DataInterface mListener;

    public DataRequest() {
        super();
    }

    public void  getData(String url)  {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_MOVIE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
        Call<List<Movie>> call = jsonPlaceHolderApi.getMovies(Constants.API_KEY);

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {

               if(response!=null && response.body()!=null && mListener!=null){

                   mListener.responseData(response.body());
               }
            }
            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d(LOG_TAG, "response code throwable " + t);
            }
        });
    }

    public void setOnDataListener(DataInterface listener) {
        mListener = listener;
    }

    public interface DataInterface {
        void responseData( List<Movie> myResponse );
    }
}

And finally what im trying to do in my mainactivity

prefSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                userOption = prefSpinner.getSelectedItem().toString();
                Log.d(LOG_TAG, "user option is "+ userOption);
                if (userOption.contentEquals("Most Popular") || userOption.contentEquals("Highest Rated")) {

                    DataRequest dataRequest = new DataRequest();
                    dataRequest.setOnDataListener(new DataRequest.DataInterface() {
                        @Override
                        public void responseData(List<Movie> myResponse) {
                            mMoviesList = myResponse;
                        }
                    });
                            dataRequest.getData(userOption);
                    movieRecycleViewAdapter.swapData(mMoviesList);

                } else if(userOption.contentEquals("Favorites")) {
                    setUpViewModel();
                    movieRecycleViewAdapter.notifyDataSetChanged();
                }
            }


来源: stackexchange

问:
Javascript mouseenter event only fires if cursor is moving fast enough
I'm creating a custom cursor "trailer" (see fiddle: https://jsfiddle.net/alexdlf/hx6yzu4w/)

Normally, the circle (.cursor) should trail the cursor. While hovering the red box (.cl), the circle should move and stick to the tiny blue point (.ct) within the red box. This is triggered by a mouseenter listener. However, if the cursor is moved into the red box too slowly, it seems the event is not firing and the effect is not taking place (it works fine if the cursor enters the red box at a normal/faster speed).

Is there something wrong with my implementation? Or is there something fundamental about mouseenter that I'm missing?

答:
The "cursor" is covering the red box. Having a transparent background doesn't prevent this. It "works" if you move your mouse faster than the "cursor" can keep up.

Add pointer-events: none to the CSS of the "cursor".

ContentLicense: CC BY-SA 4.0


问:
What's the difference between streams and datagrams in network programming?
What's the difference between sockets (stream) and sockets (datagrams)?

Why use one over the other?

答:
If it is the network programming I think starting from sockets would be a good start.

socket = ip + port

there are three types of sockets

stream (TCP, order and delivery guaranteed,no duplication,no length or char boundaries for data,connection-oriented,reliable, concurrency)

datagram(UDP,packet-based, connectionless, datagram size limit, data can be lost or duplicated, order not guaranteed,not reliable)

raw (direct access to lower layer protocols IP,ICMP)

I do not see any strict rule for transport protocol type as to what socket has to use what transport protocol and reliability should not be mistaken because UDP is realiable in case both ends are active.

Reliability refers  to more like reliability of delivery since there are sequence number checks by using TCP as transport protocol which do not exist in UDP.It is better using network protocol analyzer like wireshark tcpdump etc to see what your software is exactly doing; kind of verification or merging theory on the paper with your work in action.


问:
Simple jQuery page not working
```<code>  …
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <div id ="iAmNew">id="iAmNew"</div>
  <script>
    $(#iAmNew).style("border", "4px dotted blue");
  </script>
  …
</code>```

答:
The style() method doesn't exist, you're looking for css(). You also need to put the selector in quotes like so:

```<code>$("#iAmNew").css("border", "4px dotted blue");
</code>```

ContentLicense: CC BY-SA 3.0

Title: Simple jQuery page not working

Body:
  …

id="iAmNew"

  …

Body:
The style() method doesn't exist, you're looking for css(). You also need to put the selector in quotes like so:

$("#iAmNew").css("border", "4px dotted blue");


问:
How to fix function is undefined in JS
Porting a Chrome extension to Firefox.

```<code>// Changes extension icon on tab switch
browser.tabs.onActivated.addListener(async function (change) {
  var status = await currentStatus();
  browser.tabs.get(info.tabId, function (change) {
    if (!(status) || info.url.match(/https:\/\/url.com\/*/) == null) {
      browser.browserAction.setIcon({
        path: 'images/icon-19-disabled.png'
      });
    } else {
      browser.browserAction.setIcon({
        path: 'images/icon-19.png'
      });
    }
  });
});

// Changes extension icon on tab URL switch
browser.tabs.onUpdated.addListener(async function (change, tab) {
  var status = await currentStatus();
  if (tab.url == undefined) {
    return;
  }

  if (!(status) || tab.url.match(/https:\/\/url.com\/*/) == null) {
    browser.browserAction.setIcon({
      path: 'images/icon-19-disabled.png'
    });
  } else {
    browser.browserAction.setIcon({
      path: 'images/icon-19.png'
    });
  }
});
</code>```

Debugger is spitting out 'change is undefined'

I've tried changing the function name to info, but the debugger throws out the same error.

答:
Well if your js parser is telling you change is undefined

then thats exactly the problem. change is undefined.
renaming it to info doesn't change a thing, unless you also have an object info,
that you can acsess.

So the parser is exactly telling you whats wrong, is inside this line:

```<code>browser.tabs.get(info.tabId, function(change) {
if (!(status) || info.url.match(/https:\/\/url.com\/*/) == null) {
</code>```

It tells you that info === undefined and of course you can't do something like undefined.tabId or undefined.url.match(). because there is no such Object variables or methods inside an undefined

Title: How to fix function is undefined in JS

Body:
Porting a Chrome extension to Firefox.

// Changes extension icon on tab switch
browser.tabs.onActivated.addListener(async function (change) {
  var status = await currentStatus();
  browser.tabs.get(info.tabId, function (change) {
    if (!(status) || info.url.match(/https:\/\/url.com\/*/) == null) {
      browser.browserAction.setIcon({
        path: 'images/icon-19-disabled.png'
      });
    } else {
      browser.browserAction.setIcon({
        path: 'images/icon-19.png'
      });
    }
  });
});

// Changes extension icon on tab URL switch
browser.tabs.onUpdated.addListener(async function (change, tab) {
  var status = await currentStatus();
  if (tab.url == undefined) {
    return;
  }

  if (!(status) || tab.url.match(/https:\/\/url.com\/*/) == null) {
    browser.browserAction.setIcon({
      path: 'images/icon-19-disabled.png'
    });
  } else {
    browser.browserAction.setIcon({
      path: 'images/icon-19.png'
    });
  }
});

Debugger is spitting out 'change is undefined'

I've tried changing the function name to info, but the debugger throws out the same error.

Body:
Well if your js parser is telling you change is undefined

then thats exactly the problem. change is undefined.
renaming it to info doesn't change a thing, unless you also have an object info,
that you can acsess.

So the parser is exactly telling you whats wrong, is inside this line:

browser.tabs.get(info.tabId, function(change) {
if (!(status) || info.url.match(/https:\/\/url.com\/*/) == null) {

It tells you that info === undefined and of course you can't do something like undefined.tabId or undefined.url.match(). because there is no such Object variables or methods inside an undefined


问:
Excel - Line Chart Ignore #N/A Series Value
I have data such as follows:

The date extends till 14-02-2024

The Cost column contents are derived using:

=IF($Q2=TODAY(),$I$2,NA())

I have following formula:

=OFFSET(Funds!$R$2,0,0,COUNTA(Funds!$R:$R)-1)

And I use this formula as a Series in the Line Chart. And the Horizontal Axis is:

=Funds!$Q$2:$Q$1721

Now, the line chart looks like this:

This is because only the initial dates have values, whereas the future dates have #N/A
How can these future dates with #N/A values be ignored?

I want the chart to display the values from past to only current date, not after today's date.

答:
The solution was to have #N/A in Date column for future dates.

I added an extra column (P) with all dates, past and future.

Then, I added to the date column:

=IF($P2<=TODAY(),$P2,NA())

So only dates till today will have date values and all future dates will have #N/A

The Line Chart will not display data for #N/A dates.


问:
Docker Wordpress super slow
I have Wordpress running inside Docker, for local development, and it's super slow. My docker-compose.yml looks like this:

```<code>version: '3.3'

services:
  db:
    image: mysql:5.7
    volumes:
      - ./db_data:/var/lib/mysql
      - ./dbconfig.cnf:/etc/mysql/conf.d/custom.cnf
    restart: always
    ports:
      - "3308:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: wp_database
      MYSQL_USER: db_user
      MYSQL_PASSWORD: some_secure_password

  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - "80:80"
      - "443:443"
    restart: always
    volumes:
      - ./wp-content:/var/www/html/wp-content
      - ./.htaccess:/var/www/html/.htaccess
      - ./wp-config.php:/var/www/html/wp-config.php
      - ./logs/debug.log:/var/www/html/wp-content/debug.log
volumes:
  db_data: {}
  wp_content: {}
</code>```

As far as I read online, it might be the reason I am mounting the wp-content volume, which causes super slow page loading (takes like half a second to load each file, e.g. a jquery file, and it has to load a ton of files for one page).

Is there a solution for this? I read about NFS, but it didn't work for me to configure NFS with docker-compose, somehow I keep getting "permission errors". On the other hand, the Docker interface of macOS already shows me a "Shared folder" tab but I don't know whether I am using those shared folders at the moment or just mounting them again.

Any help is appreciated.

答:
TL;DR
Mount to temporary folder on container, sync that folder with Bindfs to public server folder.
Serving WP site with direct mount is slow because container has to access Host files one by one, which is a heavy process. Serving from public folder while files being part directly of container is much faster.

I've encountered exactly the same problem with local WordPress on Docker Compose development. It doesn't matter how fast your computer might be, it'll still be slow when mounting the folders in the containers.

I also tried solutions like NFS and other recommendations like properly excluding the project in the antivirus, adding .dockerignore, etc. which at best improve just slightly the performance.

While browsing for a similar speed improvement I came across this Dockerfile at the WordPress Starter repository https://github.com/visiblevc/wordpress-starter/blob/cd7a3c4dc1dacdfb247fa6a86001cf6909734c87/Dockerfile.
If you look at this file you'll see that the way they intialize and mount the project in the container is by mounting it not to, let's say, /var/www/html/ directly, but a temporary folder instead. Then they sync this temporary folder to /var/www/html/ through bindfs. This way every time you load a WordPress page in the browser it'll be lightning fast because it won't have to access and read the Host files on every request. The WordPress files are part of the Linux container. When you make changes to your code those changes will reflect on the container temporary folder and bindfs will instantly sync those changes over to the public container folder, and same the other way around. All changes made on the public folder will be synced over to the temp folder, and from there to your Host project files.

Title: Docker Wordpress super slow

Body:
I have Wordpress running inside Docker, for local development, and it's super slow. My docker-compose.yml looks like this:

version: '3.3'

services:
  db:
    image: mysql:5.7
    volumes:
      - ./db_data:/var/lib/mysql
      - ./dbconfig.cnf:/etc/mysql/conf.d/custom.cnf
    restart: always
    ports:
      - "3308:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: wp_database
      MYSQL_USER: db_user
      MYSQL_PASSWORD: some_secure_password

  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - "80:80"
      - "443:443"
    restart: always
    volumes:
      - ./wp-content:/var/www/html/wp-content
      - ./.htaccess:/var/www/html/.htaccess
      - ./wp-config.php:/var/www/html/wp-config.php
      - ./logs/debug.log:/var/www/html/wp-content/debug.log
volumes:
  db_data: {}
  wp_content: {}

As far as I read online, it might be the reason I am mounting the wp-content volume, which causes super slow page loading (takes like half a second to load each file, e.g. a jquery file, and it has to load a ton of files for one page).

Is there a solution for this? I read about NFS, but it didn't work for me to configure NFS with docker-compose, somehow I keep getting "permission errors". On the other hand, the Docker interface of macOS already shows me a "Shared folder" tab but I don't know whether I am using those shared folders at the moment or just mounting them again.

Any help is appreciated.


问:
How to deserialize an api response given dynamic column list? C# .NET Core 2.2
Say you have an endpoint that returns a JSON response with a dynamic list of indexed columns, in the following format:

```<code>"columnNames": [
  "date",
  "value",
  "someOtherValue"
],
"data": [
  [
    "2019-05-29",
    1.23,
    2.34
  ],
  [
    "2019-05-28",
    0.20,
    1.34
  ],
  [
    "2019-05-27,
    2.99,
    1.94
  ]
]
</code>```

What would be the most optimal way to deserialize such a response? I could try mapping it to some class which would contain both the columnNames and the data and afterwards just map it out, more or less like this (pseudo code):

```<code>var apiResponseContent = await response.Content.ReadAsAsync<ApiResponse>();
foreach(var responseData in apiResponseContent.data) {
  var model = new Model();
  model.date = responseData[apiResponseContent.columnNames.First(v => v == "date").index]
  ..
}
</code>```

But this seems to be such typical scenario, that there should be a more efficient alternative that is not prone to break if the endpoint response changes. Of course I could use reflection and create an extension method to automatically map out the columns to classes but it seems odd for me to do it.

答:
I decided to go for the reflection solution but slightly adjusted. I am using AutoMapper on the project so to maintain architectural consistency I wrote a ValueResolver that essentially wraps around your approach, just with a few adjustments:

```<code>public class VariableColumnConverter : ITypeConverter<ApiResponse, List<AssetPrice>>
{
    public List<AssetPrice> Convert(ApiResponse source, List<AssetPrice> destination, ResolutionContext context)
    {
        var properties = typeof(AssetPrice).GetProperties();
        destination = new List<AssetPrice>();

        foreach (var dataItem in source.data)
        {
            var price = new AssetPrice();

            foreach (var column in source.columnNames.Select((value, i) => (value, i)))
            {
                var property = properties.SingleOrDefault(p => p.Name.Equals(column.value, StringComparison.InvariantCultureIgnoreCase));

                if (property != null)
                {
                    property.SetValue(price, System.Convert.ChangeType(dataItem[column.i], property.PropertyType));
                }
            }
            destination.Add(price);
        }

        return destination;
    }
}
</code>```

Thanks @DavidG, I removed the generic since I only have one endpoint like that. I will tag your answer as correct since my end approach is a little opinionated and the root uses your approach.

Regardless, there are some small issues with your code which make it not compile, Root would actually be ApiResponse, also since IEnumerable does not contain a definition of indexation methods, you cannot use the [] operator. Would be great if you could please adjust it. Also, I would personally suggest using Decimal type for floating point numbers.

Body:
Say you have an endpoint that returns a JSON response with a dynamic list of indexed columns, in the following format:

"columnNames": [
  "date",
  "value",
  "someOtherValue"
],
"data": [
  [
    "2019-05-29",
    1.23,
    2.34
  ],
  [
    "2019-05-28",
    0.20,
    1.34
  ],
  [
    "2019-05-27,
    2.99,
    1.94
  ]
]

What would be the most optimal way to deserialize such a response? I could try mapping it to some class which would contain both the columnNames and the data and afterwards just map it out, more or less like this (pseudo code):

var apiResponseContent = await response.Content.ReadAsAsync<ApiResponse>();
foreach(var responseData in apiResponseContent.data) {
  var model = new Model();
  model.date = responseData[apiResponseContent.columnNames.First(v => v == "date").index]
  ..
}

But this seems to be such typical scenario, that there should be a more efficient alternative that is not prone to break if the endpoint response changes. Of course I could use reflection and create an extension method to automatically map out the columns to classes but it seems odd for me to do it.

Body:
I decided to go for the reflection solution but slightly adjusted. I am using AutoMapper on the project so to maintain architectural consistency I wrote a ValueResolver that essentially wraps around your approach, just with a few adjustments:

public class VariableColumnConverter : ITypeConverter<ApiResponse, List<AssetPrice>>
{
    public List<AssetPrice> Convert(ApiResponse source, List<AssetPrice> destination, ResolutionContext context)
    {
        var properties = typeof(AssetPrice).GetProperties();
        destination = new List<AssetPrice>();

        foreach (var dataItem in source.data)
        {
            var price = new AssetPrice();

            foreach (var column in source.columnNames.Select((value, i) => (value, i)))
            {
                var property = properties.SingleOrDefault(p => p.Name.Equals(column.value, StringComparison.InvariantCultureIgnoreCase));

                if (property != null)
                {
                    property.SetValue(price, System.Convert.ChangeType(dataItem[column.i], property.PropertyType));
                }
            }
            destination.Add(price);
        }

        return destination;
    }
}

Thanks @DavidG, I removed the generic since I only have one endpoint like that. I will tag your answer as correct since my end approach is a little opinionated and the root uses your approach.

Regardless, there are some small issues with your code which make it not compile, Root would actually be ApiResponse, also since IEnumerable does not contain a definition of indexation methods, you cannot use the [] operator. Would be great if you could please adjust it. Also, I would personally suggest using Decimal type for floating point numbers.


问:
Correct name for non-COM, non-.NET DLL?
In the Windows world, what is the correct name for a good. old-fashioned C++ DLL with exported functions? Not a COM DLL, not a .NET DLL. The kind of DLL that we used to invoke by calling LoadLibrary() and GetProcAddress()?

I've always called them "flat DLLs" because the caller cannot instantiate objects from the DLL, but what is the correct name?

EDIT

Thanks for the answers.

Just "DLL" may be technically correct, but where I work everyone assumes that "DLL" means COM, or maybe at a push .NET, so I need a term that distinguishes exactly what I mean.

答: A .dll? All those other things use the basic functionality provided by a .dll to do their respective thing. Maybe a raw .dll if you want to be pedantic, but .dll should be fine.</p>

OwnerDisplayName: Peter May

ContentLicense: CC BY-SA 2.5

Title: Correct name for non-COM, non-.NET DLL?

LastEditorDisplayName: Peter May

OwnerDisplayName: MSN


问:
How do I call a SOAP based Web Service from within a .asmx page?
I am trying to create a sort of "bootstrap" web service using a classic .net C# .asmx page and not WCF.  (The business requirements for this project are specific and do not want a WCF service).

Basically, I am trying to do this:

Create a new web service (I have no problem doing this)

That service needs to make a SOAP based call to a Sharepoint Web Service

I need to consume that service

I need to add additional pieces of information for my web service to the SOAP result (No problem here either)

The issue I have having is with point #2 and #3.  I have found plenty of articles using WCF to consume SOAP based Web Services or using "Linq" to connect to sharepoint etc., but that's not what I'm looking for.

What I am looking for is simply a step by step process of what I need to do to push me in the right direction.

Example:

add a web service reference??

add this line(s) of code to create a new SOAP request??

add this line(s) of code to parse and consume the service??

Thank you very much in advance!!!

Sample code would be greatly appreciated as well!

答:
There's nothing magical about the fact that it's a web service. Just use "Add Service Reference" and then treat it like any other piece of code referencing a web service.

Also, are those who wrote the requirements aware that a WCF service can expose a basicHttpBinding endpoint that looks exactly like an ASMX web service endpoint? It would also have the benefit of all of the features of WCF, in addition to not using what Microsoft considers a "legacy technology".


问:
Wait for foreach to complete NodeJS
So, I am creating an API in NodeJS. In one API, I have to call for loop within mongoose query.

How do I wait for the forEach to complete before executing res.send()? I have attached my code below.

```<code>router.post("/getResult", function (req, res) {
    const lottery_id = req.body.lottery_id;
    const prizeQuery = Prize.find({"lotid": lottery_id});

    let response = [];

    prizeQuery.exec(function (err, prizes) {
        console.log(prizes.length);
        if (err) return res.send({success: 0, data: err});
        else {
            prizes.forEach(prize => {
                let prizeData = {};
                const winnerQuery = Winner.find({"id": prize._id});
                winnerQuery.exec(function (err, winners) {
                    if (err) return res.send({success: 0, data: err});
                    else {
                        prizeData = {
                            prize: prize,
                            winners: winners
                        };
                        response.push(prizeData);
                    }
                });
            });
        }
    });
    return res.send({success:1, data: response});
});
</code>```

In the code above, return is called before forEach is completed.

答:
Because you are running asynchronous code inside the forEach and forEach will not wait until the asynchronous code finish, to do so, you must wrap your async code with a waiting primitive.

Also the code you provided will call send twice in case of failure, because the return inside the forEach will not actually end the enclosing function.

```<code>try {
    await Promise.all(prizes.map(async (prize) => {
        const winners = await Winner.find({"id": prize._id});
        response.push({prize, winners});
    }))
    res.send({success:1, data: response});
} catch (err) {
    res.send({success: 0, data: err});
}
</code>```

Title: Wait for foreach to complete NodeJS

Body:
So, I am creating an API in NodeJS. In one API, I have to call for loop within mongoose query.

How do I wait for the forEach to complete before executing res.send()? I have attached my code below.

router.post("/getResult", function (req, res) {
    const lottery_id = req.body.lottery_id;
    const prizeQuery = Prize.find({"lotid": lottery_id});

    let response = [];

    prizeQuery.exec(function (err, prizes) {
        console.log(prizes.length);
        if (err) return res.send({success: 0, data: err});
        else {
            prizes.forEach(prize => {
                let prizeData = {};
                const winnerQuery = Winner.find({"id": prize._id});
                winnerQuery.exec(function (err, winners) {
                    if (err) return res.send({success: 0, data: err});
                    else {
                        prizeData = {
                            prize: prize,
                            winners: winners
                        };
                        response.push(prizeData);
                    }
                });
            });
        }
    });
    return res.send({success:1, data: response});
});

In the code above, return is called before forEach is completed.

Body:
Because you are running asynchronous code inside the forEach and forEach will not wait until the asynchronous code finish, to do so, you must wrap your async code with a waiting primitive.

Also the code you provided will call send twice in case of failure, because the return inside the forEach will not actually end the enclosing function.

try {
    await Promise.all(prizes.map(async (prize) => {
        const winners = await Winner.find({"id": prize._id});
        response.push({prize, winners});
    }))
    res.send({success:1, data: response});
} catch (err) {
    res.send({success: 0, data: err});
}


问:
Table view - empty background space while delete items
While I delete a row from tableview it renders content in a strange way with empty space below and above - see video record and bug image:
deformed table view after call deletion

Probably, it may be caused by constraints changes (top view expanding / collapsing), or incorrect delete operations.

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let contentOffSetY = scrollView.contentOffset.y
    switch true {

    case contentOffSetY < 0 && searchViewIsHidden && !topMainViewIsHidden:
        changeSearchVisibility(false)

    case contentOffSetY > 0 && !searchViewIsHidden && !topMainViewIsHidden:
        changeSearchVisibility(true)

    case contentOffSetY > maxHeaderHeight && searchViewIsHidden && !topMainViewIsHidden:
        transformTopView(toBig: false)

    case self.contentOffSetY <= 0 && searchViewIsHidden && topMainViewIsHidden:
        transformTopView(toBig: true)

    default:
        break
    }
}

// Indexes of items that should be changed from Realm Observer
func updateTableView(_ deletions: [Int],
    _ insertions: [Int], _ modifications: [Int]) {
    tableView.beginUpdates()
    tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
                                     with: .none)
    tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
                                     with: .none)
    tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
                                     with: .none)
    tableView.endUpdates()
}
</code>```

答:
Maybe not a perfect solution but you could try redrawing the entire tableview after deleting a row. With reloadData()

Let me know if this works for you.

Body:
While I delete a row from tableview it renders content in a strange way with empty space below and above - see video record and bug image:
deformed table view after call deletion

Probably, it may be caused by constraints changes (top view expanding / collapsing), or incorrect delete operations.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let contentOffSetY = scrollView.contentOffset.y
    switch true {

    case contentOffSetY < 0 && searchViewIsHidden && !topMainViewIsHidden:
        changeSearchVisibility(false)

    case contentOffSetY > 0 && !searchViewIsHidden && !topMainViewIsHidden:
        changeSearchVisibility(true)

    case contentOffSetY > maxHeaderHeight && searchViewIsHidden && !topMainViewIsHidden:
        transformTopView(toBig: false)

    case self.contentOffSetY <= 0 && searchViewIsHidden && topMainViewIsHidden:
        transformTopView(toBig: true)

    default:
        break
    }
}

// Indexes of items that should be changed from Realm Observer
func updateTableView(_ deletions: [Int],
    _ insertions: [Int], _ modifications: [Int]) {
    tableView.beginUpdates()
    tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
                                     with: .none)
    tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
                                     with: .none)
    tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
                                     with: .none)
    tableView.endUpdates()
}


问:
Toggle Back And Forth Between Styles onClick() - Switch Case
On this page:

http://javascript.drawyourpets.com/

I'm trying to toggle back and forth between styles every time a user clicks the button.

I'm using a switch case as per the code from this solution:

function changeColor() {
  let theToggle = document.getElementById("change-color");
  theToggle.toggleStatus = "on";
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}</code>```

  <button id="change-color" onclick="changeColor()">Change Color</button>

```

This changes the background color the first time, but it only works once - it should be changing on every click.

I'm not very familiar with switch-cases, maybe something's wrong with it?

答:
It's not the switch case issue.

First of all, toggleStatus is not a property.

And second, Every time the function runs theToggle.toggleStatus = "on"; is always set the property on, so that's why switch case is running only for 'on'

you can do something like this:

var  toggleStatus = "on";

function changeColor() {
  let theToggle = document.getElementById("change-color");
  switch (toggleStatus) {
    case "on":
      toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}</code>```

  <button id="change-color" onclick="changeColor()">Change Color</button>

```
</div>
</div>
</p>

<p>One easy way to do all this is simple toggle a class</p>

<p>example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function changeColor() {
  let theToggle = document.getElementById("change-color");
  theToggle.classList.toggle('active')
}</code>```

#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}

#change-color.active {
  color: purple;
  background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="column">
  <button id="change-color" onclick="changeColor()">Change Color</button>
</div></code>```

Body:
On this page:

http://javascript.drawyourpets.com/

I'm trying to toggle back and forth between styles every time a user clicks the button.

I'm using a switch case as per the code from this solution:

function changeColor() {
  let theToggle = document.getElementById("change-color");
  theToggle.toggleStatus = "on";
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}

#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}

  <button id="change-color" onclick="changeColor()">Change Color</button>

This changes the background color the first time, but it only works once - it should be changing on every click.

I'm not very familiar with switch-cases, maybe something's wrong with it?

Body:
It's not the switch case issue.

First of all, toggleStatus is not a property.

And second, Every time the function runs theToggle.toggleStatus = "on"; is always set the property on, so that's why switch case is running only for 'on'

you can do something like this:

var  toggleStatus = "on";

function changeColor() {
  let theToggle = document.getElementById("change-color");
  switch (toggleStatus) {
    case "on":
      toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}

#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}

<div class="column">
  <button id="change-color" onclick="changeColor()">Change Color</button>
</div>

One easy way to do all this is simple toggle a class

example:

function changeColor() {
  let theToggle = document.getElementById("change-color");
  theToggle.classList.toggle('active')
}

#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}

#change-color.active {
  color: purple;
  background-color: yellow;
}

<div class="column">
  <button id="change-color" onclick="changeColor()">Change Color</button>
</div>


问:
Angular Nested-Form builder giving "Cannot find control with path" error
I have an Angular nested Form which is divided into Tabs, and each tab has multiple input elements as in this stackblitz.

Please help me resolve below issue:

```<code>Error: Cannot find control with path: 'averageBos -> sip5xx -> SIP500 -> avg'
</code>```

答:
I've corrected your errors:

use formGroupName for a div tag and formControlName for an input tag

```<code><my-tabs>
  <my-tab [tabTitle]="'Tab 1'">
    <form [formGroup]="MyGroup">
      <label>Average MOS</label>
      <div formGroupName="averageMos">
        <input type="text" formControlName="critical">
      </div>
    </form>
  </my-tab>
  <my-tab tabTitle="Tab 2">
    <form [formGroup]="MyGroup">
      <label>Average BOS</label>
   <div formGroupName="averageBos">
     <div formGroupName="sip5xx">
       <div formGroupName="SIP500">
         <input type="text" formControlName="critical">
         <input type="text" formControlName="warning">
       </div>
     <div formGroupName="SIP501">
       <input type="text" formControlName="critical">
       <input type="text" formControlName="warning">
     </div>
    </div>
  </div>
     </form>
  </my-tab>

 </my-tabs>
</code>```

Try this stackblitz demo.

if you want to do: formControlName="avg" then you have to find that control in the class file.

Body:
I have an Angular nested Form which is divided into Tabs, and each tab has multiple input elements as in this stackblitz.

Please help me resolve below issue:

Error: Cannot find control with path: 'averageBos -> sip5xx -> SIP500 -> avg'

Body:
I've corrected your errors:

use formGroupName for a div tag and formControlName for an input tag

<my-tabs>
  <my-tab [tabTitle]="'Tab 1'">
    <form [formGroup]="MyGroup">
      <label>Average MOS</label>
      <div formGroupName="averageMos">
        <input type="text" formControlName="critical">
      </div>
    </form>
  </my-tab>
  <my-tab tabTitle="Tab 2">
    <form [formGroup]="MyGroup">
      <label>Average BOS</label>
   <div formGroupName="averageBos">
     <div formGroupName="sip5xx">
       <div formGroupName="SIP500">
         <input type="text" formControlName="critical">
         <input type="text" formControlName="warning">
       </div>
     <div formGroupName="SIP501">
       <input type="text" formControlName="critical">
       <input type="text" formControlName="warning">
     </div>
    </div>
  </div>
     </form>
  </my-tab>

 </my-tabs>

Try this stackblitz demo.

if you want to do: formControlName="avg" then you have to find that control in the class file.


答:
It should be </p>

```<code>$('#iAmNew').css("border", "4px dotted blue");
</code>```

Title: Simple jQuery page not working

Body:
  …

id="iAmNew"

  …

Body:
It should be

$('#iAmNew').css("border", "4px dotted blue");


问:
How to solve this error 'Warning: Use of undefined constant asDollars - assumed 'asDollars' (this will throw an Error in a future version of PHP) '
I'm currently working on a project to build a website. What should I do to remove this error?

This is newer version of PHP.

```<code>if(!function_exists(asDollars)){
    function asDollars($value){
        return '$' .number_format((double)$value,8);
    }
}

$pricetotal = asDollars("%10.2n", $pricetotal);
// Dynamic Checkout Btn Assembly
$x = $i + 1;
$pp_checkout_btn .= '<input type="hidden" name="item_name_' .
$x . '" value="' . $product_name . '">
    <input type="hidden" name="amount_' . $x . '" value="' . $price . '">
    <input type="hidden" name="quantity_' . $x . '" value="' .
    $each_item['quantity'] . '">  ';
</code>```

Error message:

Warning: Use of undefined constant asDollars - assumed 'asDollars' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\MyOnlineStore\cart.php on line 124

答:
You need to put quotes around the string:

```<code>if (!function_exists('asDollars')) {
</code>```

However, the function you're defining in this case doesn't seem to match the way you're calling it later. You call it with two arguments, a format string and a value, but your definition only takes a value.

It's not clear why you think you need to define the function here conditionally. Is there some reason you can't ensure that the library that defines asDollars is properly loaded?

Body:
I'm currently working on a project to build a website. What should I do to remove this error?

This is newer version of PHP.

if(!function_exists(asDollars)){
    function asDollars($value){
        return '$' .number_format((double)$value,8);
    }
}

$pricetotal = asDollars("%10.2n", $pricetotal);
// Dynamic Checkout Btn Assembly
$x = $i + 1;
$pp_checkout_btn .= '<input type="hidden" name="item_name_' .
$x . '" value="' . $product_name . '">
    <input type="hidden" name="amount_' . $x . '" value="' . $price . '">
    <input type="hidden" name="quantity_' . $x . '" value="' .
    $each_item['quantity'] . '">  ';

Error message:

Warning: Use of undefined constant asDollars - assumed 'asDollars' (this will throw an Error in a future version of PHP) in C:\xampp\htdocs\MyOnlineStore\cart.php on line 124

Body:
You need to put quotes around the string:

if (!function_exists('asDollars')) {

However, the function you're defining in this case doesn't seem to match the way you're calling it later. You call it with two arguments, a format string and a value, but your definition only takes a value.

It's not clear why you think you need to define the function here conditionally. Is there some reason you can't ensure that the library that defines asDollars is properly loaded?


问:
I Can not use Cross Compiler
I want to compile my Go code in windows 10 for Linux (Ubuntu).

I use the commands:

```<code>SET GOOS=linux
SET GOARCH=amd64
go build .\main.go
</code>```

but the compiler creates an .exe file.

How to cross-compile this code for linux?

答: Try this like a one line command in the terminal: GOOS=linux GOARCH=amd64 go build .\main.go

Title: I Can not use Cross Compiler

Body:
I want to compile my Go code in windows 10 for Linux (Ubuntu).

I use the commands:

SET GOOS=linux
SET GOARCH=amd64
go build .\main.go

but the compiler creates an .exe file.

How to cross-compile this code for linux?


问:
Number of threads created by GCD?
Is there any good documention on how many threads are created by GCD?
At WWDC, they told us it's modeled around CPU cores. However, if I call this example:

```<code>for (int i=1; i<30000; i++) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:100000];
    });
}
</code>```

it opens 66 threads, even on an iPad1. (It also opens 66 threads when called on Lion natively). Why 66?

答:
Number of busy threads is equal to CPU cores. Blocked threads (you block them with sleepForTimeInterval) are not counted.

If you change your code to this (Swift):

```<code>for _ in 1..<30000 {
    DispatchQueue.global().async {
        while true {}
     }
}
</code>```

you'll see that there are just 2 threads created (on iPhone SE):

There is a thread limit so that your app is not killed because of big memory consumption if you have problem with blocked threads (usually because of deadlock).

Never block threads and you'll have them as much as your cores.

Title: Number of threads created by GCD?

Body:
Is there any good documention on how many threads are created by GCD?
At WWDC, they told us it's modeled around CPU cores. However, if I call this example:

for (int i=1; i<30000; i++) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:100000];
    });
}

it opens 66 threads, even on an iPad1. (It also opens 66 threads when called on Lion natively). Why 66?

Body:
Number of busy threads is equal to CPU cores. Blocked threads (you block them with sleepForTimeInterval) are not counted.

If you change your code to this (Swift):

for _ in 1..<30000 {
    DispatchQueue.global().async {
        while true {}
     }
}

you'll see that there are just 2 threads created (on iPhone SE):

There is a thread limit so that your app is not killed because of big memory consumption if you have problem with blocked threads (usually because of deadlock).

Never block threads and you'll have them as much as your cores.


答:
Since toggleStatus is not a 'real' property of the DOM element #change-color, every time you set the property within the function: changeColor() to "on" it is being treated as a new instance- and therefore inherits no previous history or properties of the last call.

you can fix this by declaring the property outside of this function like so:

```<code>const theToggle = document.getElementById("change-color");
theToggle.toggleStatus = "on";

function changeColor() {
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}
</code>```

This way, your custom property is 'held on' within the browser, and can be changed and inherited by the DOM when set.

example:

const theToggle = document.getElementById("change-color");
theToggle.toggleStatus = "on";

function changeColor() {
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}</code>```

  <button id="change-color" data-status="on" onclick="changeColor()">Change Color</button>

```

Title: Toggle Back And Forth Between Styles onClick() - Switch Case

Body:
Since toggleStatus is not a 'real' property of the DOM element #change-color, every time you set the property within the function: changeColor() to "on" it is being treated as a new instance- and therefore inherits no previous history or properties of the last call.

you can fix this by declaring the property outside of this function like so:

const theToggle = document.getElementById("change-color");
theToggle.toggleStatus = "on";

function changeColor() {
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}

This way, your custom property is 'held on' within the browser, and can be changed and inherited by the DOM when set.

example:

const theToggle = document.getElementById("change-color");
theToggle.toggleStatus = "on";

function changeColor() {
  switch (theToggle.toggleStatus) {
    case "on":
      theToggle.toggleStatus = "off";
      theToggle.style.color = "purple";
      theToggle.style.backgroundColor = "yellow";
      break;
    case "off":
      theToggle.toggleStatus = "on";
      theToggle.style.color = "yellow";
      theToggle.style.backgroundColor = "purple";
      break;
  }
}

#change-color {
  width: 100px;
  height: 100px;
  color: yellow;
  background-color: purple
}

<div class="column">
  <button id="change-color" data-status="on" onclick="changeColor()">Change Color</button>
</div>


问:
How to change a boolean value in JavaScript?
I want when my site first loads for a value to be false but when a button is clicked I want it to update the value to make it true.

What I've tried so far:

For the HTML

```<code><button onclick="button1()"></button>
</code>```

For the JavaScript

```<code>let button1pressed = false;

function button1(){
  button1pressed = true;
}
</code>```

But the problem with this is that afterwards I have an if statement

```<code>if(button1pressed === true) {
console.log('The value is now true');
}
</code>```

However the message doesn't log to the console.

How do I solve this problem?

答:
You can get the value in the log, try this:

let button1pressed = false;

function button1(){
button1pressed = true;

    console.log("The value is now: "+ button1pressed);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="button1()">click</button></code>```

Body:
I want when my site first loads for a value to be false but when a button is clicked I want it to update the value to make it true.

What I've tried so far:

For the HTML

<button onclick="button1()"></button>

For the JavaScript

let button1pressed = false;

function button1(){
  button1pressed = true;
}

But the problem with this is that afterwards I have an if statement

if(button1pressed === true) {
console.log('The value is now true');
}

However the message doesn't log to the console.

How do I solve this problem?

Body:
You can get the value in the log, try this:

let button1pressed = false;

function button1(){
button1pressed = true;

    console.log("The value is now: "+ button1pressed);
}

<button onclick="button1()">click</button>


问:
Does the string <!-FTCACHE-1-> in a PDF file mean anything?
My program downloads a PDF file from a source location every day. When I see the binary text of the PDF file in Notepad, I find that sometimes the PDF file has the string <!-FTCACHE-1-> at the end. Sometimes this word is missing from the PDF file.

My program downloads this PDF daily and compares it with the previous day's PDF file using the Windiff binary comparison.

99% of the time, Windiff reports differences in the PDF file just because one PDF contains the string <!-FTCACHE-1-> at the end.

Does anyone knows what the reason behind this is?

Thanks,
Praveen

答: The application that generates the PDF file has a bug, the FTCACHE tag should not be there, it is not a valid PDF construct. Its presence actually damages the PDF file, it invalidates the FastWebView feature in the PDF file, as you have seen it. It is safe to remove it before comparing the files.</p>

LastEditorDisplayName: Eddie


问:
node.js http module request or response object has a on (addlistener) method but its not inside that object or that proto and constructor object
when i make a http.get() request (or post or create server) i can use some mothod of that parameter of callback function (for here 'response') so it's ok i can call response.on('data',callback) method, but when i want to see this method inside the 'resonse object' i cant, even i try to console.log from proto of this object but this method is not inside object, but i can call 'addListener' and 'on' method !!!
i'm confused</p>

```<code>http.get('address',(res)=>{
*/
console.log(res); // return a object that dont have on or addListener method
and or console.log(res.__proto__); console.log(res.__proto__.constructor);
*/

*/
but when i console that method, i can see them
console.log(res.on) // return on function
or console.log(res.addListener)
*/

})
</code>```

答:
i find it, when i give a log with using 'in' operator or using Reflect.has(res,'addListener') this resault was true becuse its note in one step of proto object and for finding this should use the 4 step nested of proto object :

```<code>console.log(res.__proto__.__proto__.__proto__.__proto__)
</code>```

Body:
when i make a http.get() request (or post or create server) i can use some mothod of that parameter of callback function (for here 'response') so it's ok i can call response.on('data',callback) method, but when i want to see this method inside the 'resonse object' i cant, even i try to console.log from proto of this object but this method is not inside object, but i can call 'addListener' and 'on' method !!!
i'm confused

http.get('address',(res)=>{
*/
console.log(res); // return a object that dont have on or addListener method
and or console.log(res.__proto__); console.log(res.__proto__.constructor);
*/

*/
but when i console that method, i can see them
console.log(res.on) // return on function
or console.log(res.addListener)
*/

})

Body:
i find it, when i give a log with using 'in' operator or using Reflect.has(res,'addListener') this resault was true becuse its note in one step of proto object and for finding this should use the 4 step nested of proto object :

console.log(res.__proto__.__proto__.__proto__.__proto__)


问:
How to delete data in MySQL with date range
I have a MySQL database. I wanted to delete all unverified users from the beginning until a specific date (May 31,2019). I have a column for date_created (datetime in MySQL). How can I do it? I don't want to do it manually or one by one.

答:
Dates are an ordinal data type. You can use a < operator:

```<code>DELETE
FROM   mytable
WHERE  date_created < STR_TO_DATE('2019-05-01', '%Y-%m-%d');
</code>```

Body:
Dates are an ordinal data type. You can use a < operator:

DELETE
FROM   mytable
WHERE  date_created < STR_TO_DATE('2019-05-01', '%Y-%m-%d');


问:
What does Cassandra return to client on dropped mutations?
When there are "dropped mutations" on Cassandra side, does it return corresponding failure to calling client? Or It's always success response to calling client which invoked the transaction even though the corresponding mutations are dropped at server side and resulting in data loss?

In one particular instance we observed lots of dropped mutations (around 6k dropped mutations per sec) when we had TPS around 80K/sec and increased latency of 4000+ ms. The cluster is 6 node cluster. Don't node/cassandra yaml config with me now. In general, how to trouble shoot this "dropped mutations".
Strangely, we couldn't reproduce this bahavior even with at later point.

答:
On writes, if enough replicas respond within write_request_timeout_in_ms (2 seconds by default) you will see successful responses at the client.

So consider that case where you are writing with consistency QUORUM with a replication factor of 3.  When a write is sent from a client to the coordinator, the coordinator sends a write request to all three replicas simultaneously.  If 2 replicas are able to respond within write_request_timeout_in_ms, the coordinator will then send a successful response back to the client.  Meanwhile, if the third replica is not able to begin processing the write mutation within write_request_timeout_in_ms it will drop the mutation.

In this scenario, the fact that the mutation was dropped is not visible to the client, but that's OK from the client perspective!  All you asked for was a quorum of nodes to acknowledge the write.

From an operational perspective however, this is a cause for concern.  You have replicas that aren't even able to start working on processing the mutation until the timeout would have elapsed, that's not good!

There are multiple possible causes for this, garbage collection thrashing, hardware issues, or maybe your cluster is simply under-provisioned.  Monitoring for dropped mutations to identify these situations is a good step towards understanding what is happening.

If you are worried about consistency issues between replicas, cassandra employs multiple anti-entropy mechanisms to get into a consistent state.  If inconsistencies are identified while reading data, read repair will get replicas into a consistent state on those nodes by applying the cells with the highest timestamp.  Even if data does match between required replicas, a read repair may still be triggered based on table's configured read repair chance to ensure consistent data among all replicas.  You should also run scheduled repairs as well.

One last note, in the  case that not enough replicas respond to meet your consistency level, you will see WriteTimeoutExceptions surfaced to the client.  This could mean that your replicas are dropping mutations, but that isn't necessarily the case.  They could have begun processing the mutation, but not completed processing within the timeout.  In this case, the write will be applied on those replicas.


问:
Why should port number be converted to Network Byte Order when binding a socket?
I came across this snippet of code which appeared in the guts of setting up a socket:

```<code>#define PORT xxxx

struct sockaddr_in self;
self.sin_family = PF_INET;
self.sin_port = htons(PORT);
</code>```

I understand that we need to convert byte order of the data that we are transmitting over a network to Network Byte Order but I don't get why we need to convert port number to that as well when setting up a socket. I mean, when we do bind, isn't it a "local" thing? Say the port we intend to be bound is 1 and the machine actually uses little endian; now since we converted it into Network Byte Order, wouldn't we be binding a totally different port to the socket?

答:
Are you asking why you the application programmer does it instead of the library doing it internally?  If so, the only technical advantage I can think of is that it allows the application to do the conversion once and cache it and use it many times without requiring many conversions.

On TCP you only need to use it once per connection and typically won't make millions of connections.  But on UDP you use it every time you send a packet, and it's reasonable to assume you'd make millions or billions of such calls.

Then, for myriad calls to say sendto() for UDP, or what have you, the re-ordered-if-necessary address is supplied to the OS which can copy it as-is directly into outgoing network packets.

The alternative of doing it in the kernel would require every call to sendto() to take what the app knows as the same address over and over, and reconvert it every time.

Since sendto() benefits from this, that was perhaps sufficient reason for them to have the rest of the API work the same way.

Body:
I came across this snippet of code which appeared in the guts of setting up a socket:

#define PORT xxxx

struct sockaddr_in self;
self.sin_family = PF_INET;
self.sin_port = htons(PORT);

I understand that we need to convert byte order of the data that we are transmitting over a network to Network Byte Order but I don't get why we need to convert port number to that as well when setting up a socket. I mean, when we do bind, isn't it a "local" thing? Say the port we intend to be bound is 1 and the machine actually uses little endian; now since we converted it into Network Byte Order, wouldn't we be binding a totally different port to the socket?


问:
JQuery select a variable by passing a text string of its name
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

```<code>var test = "xxx";
</code>```

I'm thinking I could do something like this, but it won't work:

```<code>  alert($("#test"));
</code>```

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..

答: Not sure, but maybe you are looking for eval function.</p>

Body:
I'd like to use a JQuery selector to return a variable by passing a text string of the variable name:

ex.

var test = "xxx";

I'm thinking I could do something like this, but it won't work:

  alert($("#test"));

Edit:  People are getting confused.  Think of it as a reflective way to get the contents of var test.  Preferrably with a JQuery selector, but I'll take any way one can come up with it..


问:
Nested loop to pull JSON database elements
I am attempting to create a dynamic group within a select2 field while I pull my data from a JSON file. I'm using a nested loop to first loop through the states, then loop through the colleges in that state. The <optgroup> label should be the state and the <option> should be the college.

What you see below is my current code, representing what I've tried.

JSON file with database info:

```<code>var collegeData = [
    {
    'Ohio':
        [
            {name: 'Colllege of Wooster', value: 'cow'},
            {name: 'Ohio State University', value: 'osu'}
        ],
    'Arizona': [
            {name: 'Arizona State University', value: 'asu'}
        ]
    }
];
</code>```

Select2 with ejs loops:

```<code><select class="single-select" id="college" name="college">
  <option value="default"></option>
    <% for(var i = 0; i < college.length; i++) {%>
      <optgroup label="<%=college[i] %>">
        <% for(var j = 0; j < college[i][j].length; j++) {%>
         <option value="<%=college[i][j].value %>">
         <%=college[i][j].name %></option>
      <%}%>
    </optgroup>
  <%}%>
</select>
</code>```

Controller:

```<code>var mongodb = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/collegeApp';

app.get('/', function(rep, res){
    mongodb.connect(url, (error, database) => {
        const db = database.db('collegesApp');

        if (error) return process.exit(1);
        console.log('Connection is linked');

        const collection = db.collection('colleges');
        collection.find({}).toArray(function(err, results){
            if (err) throw err;
            res.render('index', {  nav, college: results });
        });
    });
});
</code>```

Ideal output in HTML:

```<code><select class="single-select" id="college" name="college">
  <option value="default"></option>
      <optgroup label="Ohio">
         <option value="cow"> College of Wooster</option>
         <option value="osu"> Ohio State University</option>
      </optgroup>
      <optgroup label="Arizona">
         <option value="asu"> Arizona State University</option>
      </optgroup>
</select>
</code>```

The error I receive is a Cannot read 'length' of undefined, so I know there is something wrong. My thought is that it is something to do with my syntax, but if you have other thoughts I would be happy to hear.

I've also already taken a look at W3Schools JSON Arrays article, as well as a codeburst article on JSON arrays. Neither was as specific as I needed.

Thank you!

答:
Try the following:

1. Execute this query in your controller to exclude _id from the result.

```<code>collection.find({}, { _id: 0 }).toArray(function(err, results){
...
</code>```

2.Try the following loop in your ejs file.

```<code><select class="single-select" id="college" name="college">
  <option value="default"></option>
  <% college.forEach((coll) => { %>
    <% Object.entries(coll).forEach(([key, value]) => { %>
      <optgroup label="<%= key %>" >
        <% Object.entries(value).forEach(([cKey, cValue]) => { %>
           <option value="<%= cValue.value %>"> <%= cValue.name %> </option>
        <% }); %>
      </optgroup>
    <% }); %>
  <% }); %>
</select>
</code>```

Hope it works.

Body:
I am attempting to create a dynamic group within a select2 field while I pull my data from a JSON file. I'm using a nested loop to first loop through the states, then loop through the colleges in that state. The <optgroup> label should be the state and the <option> should be the college.

What you see below is my current code, representing what I've tried.

JSON file with database info:

var collegeData = [
    {
    'Ohio':
        [
            {name: 'Colllege of Wooster', value: 'cow'},
            {name: 'Ohio State University', value: 'osu'}
        ],
    'Arizona': [
            {name: 'Arizona State University', value: 'asu'}
        ]
    }
];

Select2 with ejs loops:

<select class="single-select" id="college" name="college">
  <option value="default"></option>
    <% for(var i = 0; i < college.length; i++) {%>
      <optgroup label="<%=college[i] %>">
        <% for(var j = 0; j < college[i][j].length; j++) {%>
         <option value="<%=college[i][j].value %>">
         <%=college[i][j].name %></option>
      <%}%>
    </optgroup>
  <%}%>
</select>

Controller:

var mongodb = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/collegeApp';

app.get('/', function(rep, res){
    mongodb.connect(url, (error, database) => {
        const db = database.db('collegesApp');

        if (error) return process.exit(1);
        console.log('Connection is linked');

        const collection = db.collection('colleges');
        collection.find({}).toArray(function(err, results){
            if (err) throw err;
            res.render('index', {  nav, college: results });
        });
    });
});

Ideal output in HTML:

<select class="single-select" id="college" name="college">
  <option value="default"></option>
      <optgroup label="Ohio">
         <option value="cow"> College of Wooster</option>
         <option value="osu"> Ohio State University</option>
      </optgroup>
      <optgroup label="Arizona">
         <option value="asu"> Arizona State University</option>
      </optgroup>
</select>

The error I receive is a Cannot read 'length' of undefined, so I know there is something wrong. My thought is that it is something to do with my syntax, but if you have other thoughts I would be happy to hear.

I've also already taken a look at W3Schools JSON Arrays article, as well as a codeburst article on JSON arrays. Neither was as specific as I needed.

Thank you!

Body:
Try the following:

1. Execute this query in your controller to exclude _id from the result.

collection.find({}, { _id: 0 }).toArray(function(err, results){
...

2.Try the following loop in your ejs file.

<select class="single-select" id="college" name="college">
  <option value="default"></option>
  <% college.forEach((coll) => { %>
    <% Object.entries(coll).forEach(([key, value]) => { %>
      <optgroup label="<%= key %>" >
        <% Object.entries(value).forEach(([cKey, cValue]) => { %>
           <option value="<%= cValue.value %>"> <%= cValue.name %> </option>
        <% }); %>
      </optgroup>
    <% }); %>
  <% }); %>
</select>

Hope it works.


问:
How to do git hub configuration?
I am a new user to git hub. I just wanted to configure my GitHub account from the git bash. What is the command that should be used to configure username? Please help me to solve this question. </p>

答:
You can use git config command to that

```<code>$ git config --global user.name "P.Mihiran"
</code>```

From the above command, it sets the user name as you mentioned. If you want to check the username you can use the following command to check user name

```<code>git config --global user.name
</code>```

For more details visit
https://help.github.com/en/articles/setting-your-username-in-git

Title: How to do git hub configuration?

Body:
You can use git config command to that

$ git config --global user.name "P.Mihiran"

From the above command, it sets the user name as you mentioned. If you want to check the username you can use the following command to check user name

git config --global user.name

For more details visit
https://help.github.com/en/articles/setting-your-username-in-git


问:
how do I ensure all package.json dependencies go to the same version
I have a problem with path-to-regexp, I want to ensure if possible all dependencies go through 3.0.0.

I have ran

npm i path-to-regexp it adds this to my package.json:

```<code>"path-to-regexp": "^3.0.0",
</code>```

But when I run

npm ls path-to-regexp

I get:

```<code>├── path-to-regexp@3.0.0
├─┬ react-router-dom@5.0.0
│ └─┬ react-router@5.0.0
│   └── path-to-regexp@1.7.0
└─┬ react-scripts@3.0.1
  └─┬ webpack-dev-server@3.2.1
    └─┬ express@4.17.0
      └── path-to-regexp@0.1.7
</code>```

I want react-router-dom use 3.0.0.

Is this possible?

答:
Different modules are released by different teams, on different schedules, with independent version numbers. It makes no sense to force "all dependencies" to the same version.

How to override a specific dependency version, in your case react-router-dom, is explained here:
https://stackoverflow.com/a/17423915/11451509

Body:
I have a problem with path-to-regexp, I want to ensure if possible all dependencies go through 3.0.0.

I have ran

npm i path-to-regexp it adds this to my package.json:

"path-to-regexp": "^3.0.0",

But when I run

npm ls path-to-regexp

I get:

├── path-to-regexp@3.0.0
├─┬ react-router-dom@5.0.0
│ └─┬ react-router@5.0.0
│   └── path-to-regexp@1.7.0
└─┬ react-scripts@3.0.1
  └─┬ webpack-dev-server@3.2.1
    └─┬ express@4.17.0
      └── path-to-regexp@0.1.7

I want react-router-dom use 3.0.0.

Is this possible?


问:
How do undefined components work in Vue.js - Vue.js + Pug
I was just going through some Vue.js code right HERE. And came across the following Vue.js + PUG code , basically its just PUG templating:

```<code>menu-dropdown.task-dropdown(
  v-if="!isRunningYesterdailies",
  :right="task.type === 'reward'",
  ref="taskDropdown",
  v-b-tooltip.hover.top="$t('options')"
)
</code>```

Now when something like below is in PUG i understand that a div with the classes will be outputted.

```<code>.d-flex.justify-content-between
</code>```

But what about when something is not preceded by a . ? What does it mean ?

Like what exactly is menu-dropdown , I was thinking its a component but when i look to the bottom of the file , i see no component named .menu-dropdown , IE i see only the following components loaded:

```<code>components: {
  approvalFooter,
  approvalHeader,
  MenuDropdown,
},
</code>```

So where is .menu-dropdown coming from and what exactly is it ?

答:
It looks like without the leading dot, pug renders a component

```<code><menu-dropdown class="task-dropdown" ...more data here../ ></menu-dropdown>
</code>```

Vue internally automatically creates an alias from user-name to UserName, and vice versa, so you can use whatever you like. It’s generally best to use UserName in the JavaScript, and user-name in the template.

Body:
I was just going through some Vue.js code right HERE. And came across the following Vue.js + PUG code , basically its just PUG templating:

menu-dropdown.task-dropdown(
  v-if="!isRunningYesterdailies",
  :right="task.type === 'reward'",
  ref="taskDropdown",
  v-b-tooltip.hover.top="$t('options')"
)

Now when something like below is in PUG i understand that a div with the classes will be outputted.

.d-flex.justify-content-between

But what about when something is not preceded by a . ? What does it mean ?

Like what exactly is menu-dropdown , I was thinking its a component but when i look to the bottom of the file , i see no component named .menu-dropdown , IE i see only the following components loaded:

components: {
  approvalFooter,
  approvalHeader,
  MenuDropdown,
},

So where is .menu-dropdown coming from and what exactly is it ?

Body:
It looks like without the leading dot, pug renders a component

<menu-dropdown class="task-dropdown" ...more data here../ ></menu-dropdown>

Vue internally automatically creates an alias from user-name to UserName, and vice versa, so you can use whatever you like. It’s generally best to use UserName in the JavaScript, and user-name in the template.


问:
Disable CodeLens in specific files
How to disable CodeLens in specific file(s) in Visual Studio 2019, like tool-generated one?

Our project is using some extra long tool-generated code (about 400k lines...Well, lets say its the burden of the past and we cant get rid of it, its doing really useful work :) ) and when i (almost always accidentaly) open them, Visual studio slow down to crawl. When we used ReSharper, disabling CodeAnalytic for this specific file(s) really helped, so disabling CodeLens should help too... I gues...

Maybe this is duplicate, i tried google, but its really cluttered with "Disable reference count" or "Disable whole CodeLens".

答:
As an alternative to hiding Code Lens, you could hide the source files to avoid opening them on accident.

In your project file, you can set the InProject metadata on the files to false to prevent them from showing up in Solution Explorer.  They are still part of the project during compilation, but that way it's much harder to open them on accident in VS.

```<code>  <ItemGroup>
    <Compile Include="Hidden.cs">
      <InProject>false</InProject>
    </Compile>
  </ItemGroup>
</code>```

This will make it harder to open these files on the rare occasions that you do want to.
 You can still open the files with File -> Open, or using code navigation like Go to Definition, but they won't appear in the Solution Explorer tree.

This property only seems to work for non-SDK style projects.

Title: Disable CodeLens in specific files

Body:
As an alternative to hiding Code Lens, you could hide the source files to avoid opening them on accident.

In your project file, you can set the InProject metadata on the files to false to prevent them from showing up in Solution Explorer.  They are still part of the project during compilation, but that way it's much harder to open them on accident in VS.

  <ItemGroup>
    <Compile Include="Hidden.cs">
      <InProject>false</InProject>
    </Compile>
  </ItemGroup>

This will make it harder to open these files on the rare occasions that you do want to.
 You can still open the files with File -> Open, or using code navigation like Go to Definition, but they won't appear in the Solution Explorer tree.

This property only seems to work for non-SDK style projects.


问:
How do I contribute to other's code in GitHub?
I would like to contribute to a certain project in GitHub. Should I fork it? Branch it? What is recommended and how to do it?

答:
Technical workflow

I would suggest the following workflow:

Fork the repository (via GitHub web interface: "Fork" button)

In your forked repository, copy the URL

Clone (in the command line)

git clone <url-from-your-workspace>

Enter the directory, that just got created, and create a branch

cd <directory>
git checkout -b <branchname>

Now make your changes

You can create one or more commits after each change:

git add .;
git commit

When done, push your changes

git push origin <branch>

In your command line, you should see a URL to create the PR. Visit the URL and click the button to create a PR.

If not, visit the repository in the browser and it will offer you a button for creating the pull request

That's it.

So, basically, you forked the repository to your workspace, created a new branch and pushed that new branch.

If you later make more PR from the same cloned repo, you should synchronize (get the latest changes from the original repository) before you create another branch for another PR:

```<code>git checkout master
git remote add upstream <url-of-original-repo>
git pull upstream master
</code>```

Other considerations:

the project may have Contribution Guidelines: Look for a file CONTRIBUTING.rst or .md

you may want to follow the coding guidelines for the project

you may want to outline your idea as issue first

you may want to look at the Pull Requests tab for the project and check if there are open PR, merged PR

These suggestions are here to save you from the trouble of putting work into a PR that will not get merged. If there is activity in the project and PR get merged, this is a good sign. If there are Contribution Guidelines, follow them.

Always be courteous. Remember, the maintainers of the project are in no way obligated to merge your PR. Do you have something valuable to add to the project?

Body:
Technical workflow

I would suggest the following workflow:

Fork the repository (via GitHub web interface: "Fork" button)

In your forked repository, copy the URL

Clone (in the command line)

git clone <url-from-your-workspace>

Enter the directory, that just got created, and create a branch

cd <directory>
git checkout -b <branchname>

Now make your changes

You can create one or more commits after each change:

git add .;
git commit

When done, push your changes

git push origin <branch>

In your command line, you should see a URL to create the PR. Visit the URL and click the button to create a PR.

If not, visit the repository in the browser and it will offer you a button for creating the pull request

That's it.

So, basically, you forked the repository to your workspace, created a new branch and pushed that new branch.

If you later make more PR from the same cloned repo, you should synchronize (get the latest changes from the original repository) before you create another branch for another PR:

git checkout master
git remote add upstream <url-of-original-repo>
git pull upstream master

Other considerations:

the project may have Contribution Guidelines: Look for a file CONTRIBUTING.rst or .md

you may want to follow the coding guidelines for the project

you may want to outline your idea as issue first

you may want to look at the Pull Requests tab for the project and check if there are open PR, merged PR

These suggestions are here to save you from the trouble of putting work into a PR that will not get merged. If there is activity in the project and PR get merged, this is a good sign. If there are Contribution Guidelines, follow them.

Always be courteous. Remember, the maintainers of the project are in no way obligated to merge your PR. Do you have something valuable to add to the project?


问:
how to add a jquery script tag in pug?
Not sure about it failed at adding script tag or it's because the jquery library. But it failed when I aa the jquery script tag to my pug file. It works perfectly without the script tag.

```<code>html
head
    title !{comp}
    link(rel='stylesheet', href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css')
script(src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js')
body
    table
        tr
            th Session
            th Num.
            th Couple
            th Age
            th Division
            th Dance Studio
            th Heat
        each event in events
            tr
                td=event.Session
                td=event.CoupleID
                td=event.Couple
                td=event.Age
                td=event.Division
                td=event.DanceStudio
                td=event.Heat
</code>```

I got a 404 not found after I add the jquery script tag and I'm not sure why.

Any help will be appreciated!

答:
Your script tag is between the head tag and the body tag, which is not valid HTML.

The standard place to put scripts is in the body tag, at the end of it, after the visible UI tags.

Title: how to add a jquery script tag in pug?

Body:
Not sure about it failed at adding script tag or it's because the jquery library. But it failed when I aa the jquery script tag to my pug file. It works perfectly without the script tag.

html
head
    title !{comp}
    link(rel='stylesheet', href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css')
script(src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js')
body
    table
        tr
            th Session
            th Num.
            th Couple
            th Age
            th Division
            th Dance Studio
            th Heat
        each event in events
            tr
                td=event.Session
                td=event.CoupleID
                td=event.Couple
                td=event.Age
                td=event.Division
                td=event.DanceStudio
                td=event.Heat

I got a 404 not found after I add the jquery script tag and I'm not sure why.

Any help will be appreciated!


问:
What is name of this component in Android?
I'm building a form like below. What is name of this component, and how can I make it?

Form:

After I click on the down arrow icon ╲╱ it's expanded:

答:
Actually, this can be done by using only a LinearLayout with 2 EditTexts in which you make it visible or not, programmatically.

To animate when opening, you can set this in your parent layout:

```<code>android:animateLayoutChanges="true"
</code>```

Arrow OnClick method example:

```<code>LinearLayout llExtraFields = findViewById(R.id.llExtraFields);
if (llExtraFields.getVisibility() == View.VISIBLE) {
    llExtraFields.setVisibility(View.GONE);
} else {
    llExtraFields.setVisibility(View.VISIBLE);
}
</code>```

Body:
Actually, this can be done by using only a LinearLayout with 2 EditTexts in which you make it visible or not, programmatically.

To animate when opening, you can set this in your parent layout:

android:animateLayoutChanges="true"

Arrow OnClick method example:

LinearLayout llExtraFields = findViewById(R.id.llExtraFields);
if (llExtraFields.getVisibility() == View.VISIBLE) {
    llExtraFields.setVisibility(View.GONE);
} else {
    llExtraFields.setVisibility(View.VISIBLE);
}


问:
Constrained weighted linear regression in R
I am trying to set up a contrained weighted linear regression. That is to say, that I have a dataset of i observations and three different x values. Each observations has a weight. I want to perform a weighted multiple linear regression using the restrictions that the weighted mean of each x value has to be zero and the weighted standard deviation should be one.

Since I am new and have no reputation yet, I can‘t post images with latex formulas. So I have to write them down this way.

First restriction $\sum_{i} w_{i} X_{i,k} = 0$ for k = 1,2,3.

Second one: $\sum_{i} w_{i} X_{i,k}^2 = 1$ for k = 1,2,3.

This is an example dataset:

```<code>y <- rnorm(10)
w <- rep(0.1, 10)
x1 <- rnorm(10)
x2 <- rnorm(10)
x3 <- rnorm(10)
data <- cbind(y, x1, x2, x3, w)
lm(y ~ x1 + x2 + x3, data = data, weigths = data$w)
</code>```

The weights do not have to be equal for each observation but have to add up to one.
I would like to include these restrictions into the regression. Is there a way to do that?

答:
You could perhaps use the Generalised Linear Model:

```<code>glm(y ~ x1 + x2 + x3, weights = w, data=data)
</code>```

Data needs to be a data.frame(...).

Body:
I am trying to set up a contrained weighted linear regression. That is to say, that I have a dataset of i observations and three different x values. Each observations has a weight. I want to perform a weighted multiple linear regression using the restrictions that the weighted mean of each x value has to be zero and the weighted standard deviation should be one.

Since I am new and have no reputation yet, I can‘t post images with latex formulas. So I have to write them down this way.

First restriction $\sum_{i} w_{i} X_{i,k} = 0$ for k = 1,2,3.

Second one: $\sum_{i} w_{i} X_{i,k}^2 = 1$ for k = 1,2,3.

This is an example dataset:

y <- rnorm(10)
w <- rep(0.1, 10)
x1 <- rnorm(10)
x2 <- rnorm(10)
x3 <- rnorm(10)
data <- cbind(y, x1, x2, x3, w)
lm(y ~ x1 + x2 + x3, data = data, weigths = data$w)

The weights do not have to be equal for each observation but have to add up to one.
I would like to include these restrictions into the regression. Is there a way to do that?

Body:
You could perhaps use the Generalised Linear Model:

glm(y ~ x1 + x2 + x3, weights = w, data=data)

Data needs to be a data.frame(...).