问:
Getting null data on response body using retrofit2?
I am new to retrofit 2 and i am trying to get json array data but getting null, this is the url for getting the data.

But the funny thing is when i try to debug inside onResponse i am getting success message as well as response.body data. What is the problem here?

https://xenzet.com/GameCheat/viewgamesjson.php

this is json data

```<code>[
    {
        "gameid":"2",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/counter strike 1.6.png",
        "Games_Name":"1"
    },
    {
        "gameid":"3",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/gta.ico",
        "Games_Name":"vice city sucjlfsdrgefdsrhag"
    },
    {
        "gameid":"4",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/pubg.png",
        "Games_Name":"pubg"
    },
    {
    "gameid":"5",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/doom.png",
    "Games_Name":"Doom Enternal"
    },
    {
    "gameid":"6",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/for.png",
    "Games_Name":"Fornite"
    },
    {
    "gameid":"9",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/dota2.png",
    "Games_Name":"dota2"
    }
]
</code>```

this is the method which is trying to get data

```<code> public void fetch_information() {

        ApiInterface = ApiClient.getApiClient().create(Api.class);

        Call<List<Games>> call = ApiInterface.GetGames();

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

                    gameslist = response.body();
                    gamescounter = gameslist.size();
                    adapter = new GameRecyclerViewAdapter(GamesActivity.this, gameslist);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<List<Games>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }
</code>```

this is ApiClient

```<code>public class ApiClient {

    public static  String Base_URL ;

    public static Retrofit retrofit;

    public static Retrofit getApiClient()
    {
        if (retrofit == null)
        {
            Base_URL ="https://xenzet.com/GameCheat/";
            retrofit = new Retrofit.Builder().baseUrl(Base_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();

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

and Api

```<code>public interface Api {

    @GET("viewgamesjson.php")
    Call<List<Games>> GetGames();
}
</code>```

and in OnCreate i am calling fetch information method.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_games);
    gameslist = new ArrayList<Games>();
    RecyclerView recyclerView = findViewById(R.id.recyclerview_gameslist);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
     fetch_information();

    Toast.makeText(getApplicationContext(),"" +gamescounter, Toast.LENGTH_SHORT).show();

    adapter = new GameRecyclerViewAdapter(this, gameslist);

   recyclerView.setAdapter(adapter);
    adapter.setClickListener((GameRecyclerViewAdapter.ItemClickListener) this);
}
</code>```

trying to fill data of game list in recycler view but fails as it null.

this is logcat

```<code>2019-05-27 14:03:43.261 1261-1261/com.example.quizgames E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quizgames, PID: 1261
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
    at com.example.quizgames.GamesActivity$1.onResponse(GamesActivity.java:109)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6251)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
</code>```

This is class Games

```<code>public class Games {

    @SerializedName("gameid")
    @Expose
    private String gameid;
    @SerializedName("gameIcon")
    @Expose
    private String gameIcon;
    @SerializedName("Games_Name")
    @Expose
    private String gamesName;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGamesName() {
        return gamesName;
    }

    public void setGamesName(String gamesName) {
        this.gamesName = gamesName;
    }

//    public Games(String Gameid,String Gameicon,String GameName)
//    {
//      this.gameid = Gameid;
//      this.gameIcon = Gameicon;
//      this.gamesName = GameName;
//
//    }

}
</code>```

This is recycler view

```<code>class GameRecyclerViewAdapter extends RecyclerView.Adapter<GameRecyclerViewAdapter.ViewHolder> {

    private List<Games> mGames;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    GameRecyclerViewAdapter(Context context, List<Games> games) {
        this.mInflater = LayoutInflater.from(context);
        this.mGames = games;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.gameitem, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Games Game = mGames.get(position);
        String Gameid = Game.getGameid();
        String Gameicon = Game.getGameIcon();
        String Gamename = Game.getGamesName();
        holder.GameNameTxt.setText(Gamename);
        Glide.with(holder.GameIconImage.getContext()).load(Game.getGameIcon()).thumbnail(0.1f).
                placeholder(R.color.colorPrimary).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.GameIconImage);

    }

    // total number of rows
    @Override
    public int getItemCount() {

        return mGames == null ? 0 : mGames.size();

    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView GameNameTxt;
        ImageView GameIconImage;
        ViewHolder(View itemView) {
            super(itemView);
            GameNameTxt = itemView.findViewById(R.id.gamename);
            GameIconImage = itemView.findViewById(R.id.imageView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);

    }
}
</code>```

答:
Add data in your Adapter in side onResponse Method

add fetch_information() in oncreate

```<code>@Override
        public void onResponse(Call<List<Games>> call, Response<List<Games>> response) {
            if(response.isSuccessful()) {
                gameslist = response.body();
                adapter = new GameRecyclerViewAdapter(MainActivity.this, gameslist);
                //change your Activity name here insted of MainActivity
                recyclerView.setAdapter(adapter);
            }
        }
</code>```

Body:
I am new to retrofit 2 and i am trying to get json array data but getting null, this is the url for getting the data.

But the funny thing is when i try to debug inside onResponse i am getting success message as well as response.body data. What is the problem here?

https://xenzet.com/GameCheat/viewgamesjson.php

this is json data

[
    {
        "gameid":"2",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/counter strike 1.6.png",
        "Games_Name":"1"
    },
    {
        "gameid":"3",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/gta.ico",
        "Games_Name":"vice city sucjlfsdrgefdsrhag"
    },
    {
        "gameid":"4",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/pubg.png",
        "Games_Name":"pubg"
    },
    {
    "gameid":"5",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/doom.png",
    "Games_Name":"Doom Enternal"
    },
    {
    "gameid":"6",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/for.png",
    "Games_Name":"Fornite"
    },
    {
    "gameid":"9",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/dota2.png",
    "Games_Name":"dota2"
    }
]

this is the method which is trying to get data

 public void fetch_information() {

        ApiInterface = ApiClient.getApiClient().create(Api.class);

        Call<List<Games>> call = ApiInterface.GetGames();

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

                    gameslist = response.body();
                    gamescounter = gameslist.size();
                    adapter = new GameRecyclerViewAdapter(GamesActivity.this, gameslist);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<List<Games>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

this is ApiClient

public class ApiClient {

    public static  String Base_URL ;

    public static Retrofit retrofit;

    public static Retrofit getApiClient()
    {
        if (retrofit == null)
        {
            Base_URL ="https://xenzet.com/GameCheat/";
            retrofit = new Retrofit.Builder().baseUrl(Base_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();

        }
        return retrofit;
    }
}

and Api

public interface Api {

    @GET("viewgamesjson.php")
    Call<List<Games>> GetGames();
}

and in OnCreate i am calling fetch information method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_games);
    gameslist = new ArrayList<Games>();
    RecyclerView recyclerView = findViewById(R.id.recyclerview_gameslist);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
     fetch_information();

    Toast.makeText(getApplicationContext(),"" +gamescounter, Toast.LENGTH_SHORT).show();

    adapter = new GameRecyclerViewAdapter(this, gameslist);

   recyclerView.setAdapter(adapter);
    adapter.setClickListener((GameRecyclerViewAdapter.ItemClickListener) this);
}

trying to fill data of game list in recycler view but fails as it null.

this is logcat

2019-05-27 14:03:43.261 1261-1261/com.example.quizgames E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quizgames, PID: 1261
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
    at com.example.quizgames.GamesActivity$1.onResponse(GamesActivity.java:109)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6251)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

This is class Games

public class Games {

    @SerializedName("gameid")
    @Expose
    private String gameid;
    @SerializedName("gameIcon")
    @Expose
    private String gameIcon;
    @SerializedName("Games_Name")
    @Expose
    private String gamesName;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGamesName() {
        return gamesName;
    }

    public void setGamesName(String gamesName) {
        this.gamesName = gamesName;
    }

//    public Games(String Gameid,String Gameicon,String GameName)
//    {
//      this.gameid = Gameid;
//      this.gameIcon = Gameicon;
//      this.gamesName = GameName;
//
//    }

}

This is recycler view

class GameRecyclerViewAdapter extends RecyclerView.Adapter<GameRecyclerViewAdapter.ViewHolder> {

    private List<Games> mGames;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    GameRecyclerViewAdapter(Context context, List<Games> games) {
        this.mInflater = LayoutInflater.from(context);
        this.mGames = games;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.gameitem, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Games Game = mGames.get(position);
        String Gameid = Game.getGameid();
        String Gameicon = Game.getGameIcon();
        String Gamename = Game.getGamesName();
        holder.GameNameTxt.setText(Gamename);
        Glide.with(holder.GameIconImage.getContext()).load(Game.getGameIcon()).thumbnail(0.1f).
                placeholder(R.color.colorPrimary).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.GameIconImage);

    }

    // total number of rows
    @Override
    public int getItemCount() {

        return mGames == null ? 0 : mGames.size();

    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView GameNameTxt;
        ImageView GameIconImage;
        ViewHolder(View itemView) {
            super(itemView);
            GameNameTxt = itemView.findViewById(R.id.gamename);
            GameIconImage = itemView.findViewById(R.id.imageView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);

    }
}

Body:
Add data in your Adapter in side onResponse Method

add fetch_information() in oncreate

@Override
        public void onResponse(Call<List<Games>> call, Response<List<Games>> response) {
            if(response.isSuccessful()) {
                gameslist = response.body();
                adapter = new GameRecyclerViewAdapter(MainActivity.this, gameslist);
                //change your Activity name here insted of MainActivity
                recyclerView.setAdapter(adapter);
            }
        }


来源: stackexchange

问:
java.lang.ClassNotFoundException: org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer
I was trying to run a JAR file for the project, but the following error shows up :

Caused by: java.lang.ClassNotFoundException: org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

I tried to look for the class manually within my libraries, but the class was not present. It seems the specific class is not present in the current version of spring-boot-starter-web. Below is the POM for the project

```<code><dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

  <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <version>2.1.3.RELEASE</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
  <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>2.1.2.RELEASE</version>
  </dependency>

  <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>

  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
  </dependency>
</code>```

答:
Try adding the following dependency :

```<code>  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter</artifactId>
   <version>2.1.3.RELEASE</version>
  </dependency>
</code>```

The dependency spring-boot-starter includes the dependencies for logging spring-boot-starter-logging, which has the class org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

ContentLicense: CC BY-SA 4.0

Body:
I was trying to run a JAR file for the project, but the following error shows up :

Caused by: java.lang.ClassNotFoundException: org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

I tried to look for the class manually within my libraries, but the class was not present. It seems the specific class is not present in the current version of spring-boot-starter-web. Below is the POM for the project

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <version>2.1.3.RELEASE</version>
</dependency>

  <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>2.1.2.RELEASE</version>
  </dependency>

  <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
  <scope>provided</scope>
</dependency>

  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
  </dependency>

Body:
Try adding the following dependency :

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter</artifactId>
   <version>2.1.3.RELEASE</version>
  </dependency>

The dependency spring-boot-starter includes the dependencies for logging spring-boot-starter-logging, which has the class org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer


问:
Can't resolve 'core-js/client/shim — Upgrade Angular from v6 to v7
After upgrade new version of Angular that error occurs:

```<code>Can't resolve 'core-js/client/shim
</code>```

In main.ts I have code:

```<code>// Shim the environment
import 'core-js/client/shim';
</code>```

Any ideas on how to resolve?

答:
Try to replace:

```<code>// Shim the environment
import 'core-js/client/shim';
</code>```

by:

```<code>// Shim the environment
import 'core-js/features/reflect';
</code>```

Angular use Reflecting to make Dependency Injection works.

Body:
After upgrade new version of Angular that error occurs:

Can't resolve 'core-js/client/shim

In main.ts I have code:

// Shim the environment
import 'core-js/client/shim';

Any ideas on how to resolve?

Body:
Try to replace:

// Shim the environment
import 'core-js/client/shim';

by:

// Shim the environment
import 'core-js/features/reflect';

Angular use Reflecting to make Dependency Injection works.


问:
Error when querying using JDBC SQL server connection
I query data using the below code:

```<code>tBPMDataSource = getJndiDataSource("java:/NaNaDS");
tBPMConnection = tBPMDataSource.getConnection();
tBPMStatement=tBPMConnection.createStatement();
if (tBPMDataSource!=null)
{
    tBPMResultSet = tBPMStatement.executeQuery("select OID from ProcessInstance where serialNumber='"+ProcessSerial+"'");
    while (tBPMResultSet.next()) {
        ProcessOID=tBPMResultSet.getString(0);
        }
}
</code>```

And error occured,below is the error log

```<code>   2019-05-27 14:44:07,616 FINE  [com.microsoft.sqlserver.jdbc.SQLServerException] (default task-96) *** SQLException:com.microsoft.sqlserver.jdbc.SQLServerStatement@2b71098e com.microsoft.sqlserver.jdbc.SQLServerException: ̷ӽ 0 ӬԶ׶Χc ̷ӽ 0 ӬԶ׶Χc
</code>```

Can anyone help on ow to find the error code of this exception? I tried to excute the query in sql server and it worked fine. Thx.

答:
The JDBC API the column indexes would be base-1 instead of base-0 like you were expecting.
I wish all index-related methods were base-0 for consistency reasons. It is kind of annoying to have to remember which methods use 0 and which use 1.</p>

Body:
I query data using the below code:

tBPMDataSource = getJndiDataSource("java:/NaNaDS");
tBPMConnection = tBPMDataSource.getConnection();
tBPMStatement=tBPMConnection.createStatement();
if (tBPMDataSource!=null)
{
    tBPMResultSet = tBPMStatement.executeQuery("select OID from ProcessInstance where serialNumber='"+ProcessSerial+"'");
    while (tBPMResultSet.next()) {
        ProcessOID=tBPMResultSet.getString(0);
        }
}

And error occured,below is the error log

   2019-05-27 14:44:07,616 FINE  [com.microsoft.sqlserver.jdbc.SQLServerException] (default task-96) *** SQLException:com.microsoft.sqlserver.jdbc.SQLServerStatement@2b71098e com.microsoft.sqlserver.jdbc.SQLServerException: ̷ӽ 0 ӬԶ׶Χc ̷ӽ 0 ӬԶ׶Χc

Can anyone help on ow to find the error code of this exception? I tried to excute the query in sql server and it worked fine. Thx.


问:
How to reset Liferay? (delete all content/users/customizations)
I totally messed up my development Liferay (trial-and-error experiments lead to many wrong identifiers being written in many wrong MySQL rows/columns).

How to reset it, so that I get a fresh clean Liferay?

I want to get back to the situation where you have just installed Liferay, and there are no users, no customizations, no pages, no content.

I should take less time than reinstalling all of Liferay (Java, database, etc).

答:
1) Shut down Liferay.

2) Drop the database and create it again (Example for MySQL. You can find the exact database name in a .properties file in Liferay's home folder):

```<code>drop database lportal;
create database lportal character set utf8;
</code>```

3) In Liferay's home folder, remove the content of each of these folders:

osgi/modules/

osgi/state/

data/document_library/

data/elasticsearch/

Note: I suggest keeping the license folder, to avoid the hassle of reinstalling the license. It has always worked for me.

4) Still in Liferay's home folder, remove the files portal-ext.properties and portal-setup-wizard.properties (or keep them if you have no added anything special to them, that will spare you from having to configure the database access again)

5) Start Liferay again.

Body:
1) Shut down Liferay.

2) Drop the database and create it again (Example for MySQL. You can find the exact database name in a .properties file in Liferay's home folder):

drop database lportal;
create database lportal character set utf8;

3) In Liferay's home folder, remove the content of each of these folders:

osgi/modules/

osgi/state/

data/document_library/

data/elasticsearch/

Note: I suggest keeping the license folder, to avoid the hassle of reinstalling the license. It has always worked for me.

4) Still in Liferay's home folder, remove the files portal-ext.properties and portal-setup-wizard.properties (or keep them if you have no added anything special to them, that will spare you from having to configure the database access again)

5) Start Liferay again.


问:
Can't seem to close this modal without destroying the parent as well?
I'm opening a modal when the page loads and that part works fine. The problem is, when I click on it to close, it wipes out the parent page as well. See my fiddle..

https://jsfiddle.net/L8vk0frg/

```<code><head>
<script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://codeorigin.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
</head>
<style>
.cookieBtn {
  font-size: 12px;
  cursor: pointer;
  background-color: #A02525;
  color: white;
  padding: 5px 5px;
  border: none;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  border-radius: 5px;
}

.cookieBtn:hover {
  background-color: #761010;
}

.cookieWrapper {
  border-radius: 10px;
  background-color: white;
  width: 400px;
  height: 175px;
  padding: 10px;
  -webkit-box-shadow: 0px 0px 39px 12px rgba(0,0,0,0.75);
  -moz-box-shadow: 0px 0px 39px 12px rgba(0,0,0,0.75);
   box-shadow: 0px 0px 39px 12px rgba(0,0,0,0.75);
   z-index: 999;
   }
   </style>
   <body>
   <p>text on page</p>

   <div id="cookieWrapper" class="cookieWrapper" title="Dialog" onClick="parentNode.remove()" align="center">
   <iframe src="rndcookie.asp" width="392" height="150" scrolling="no" frameborder="0" style="border-radius: 10px;"></iframe>
   <button class="cookieBtn" onclick="" data-dismiss="cookieWrapper" type="button">ACCEPT ALL COOKIES</button>
   </div>

   <script>
    window.onload = function () {
     document.getElementById('button').onclick = function () {
      document.getElementById('cookieWrapper').style.display = "none"
   };
};
</script>
</code>```

答:
There are 2 problems:

you have no element with the ID button

the reason your
 tag and others disappear is because of onClick="parentNode.remove()"

Demo

window.onload = function() {
  document.getElementById('button').onclick = function() {
    document.getElementById('cookieWrapper').style.display = "none"
  };
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cookieBtn {
  font-size: 12px;
  cursor: pointer;
  background-color: #A02525;
  color: white;
  padding: 5px 5px;
  border: none;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}

.cookieBtn:hover {
  background-color: #761010;
}

.cookieWrapper {
  border-radius: 10px;
  background-color: white;
  width: 400px;
  height: 175px;
  padding: 10px;
  -webkit-box-shadow: 0px 0px 39px 12px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 0px 0px 39px 12px rgba(0, 0, 0, 0.75);
  box-shadow: 0px 0px 39px 12px rgba(0, 0, 0, 0.75);
  z-index: 999;
}</code>```

text on page

    <button class="cookieBtn" id="button" onclick="" data-dismiss="cookieWrapper" type="button">ACCEPT ALL COOKIES</button>

```

Body:
I'm opening a modal when the page loads and that part works fine. The problem is, when I click on it to close, it wipes out the parent page as well. See my fiddle..

https://jsfiddle.net/L8vk0frg/

text on page

   <button class="cookieBtn" onclick="" data-dismiss="cookieWrapper" type="button">ACCEPT ALL COOKIES</button>

Body:
There are 2 problems:

you have no element with the ID button

the reason your <p> tag and others disappear is because of onClick="parentNode.remove()"

Demo

window.onload = function() {
  document.getElementById('button').onclick = function() {
    document.getElementById('cookieWrapper').style.display = "none"
  };
};

.cookieBtn {
  font-size: 12px;
  cursor: pointer;
  background-color: #A02525;
  color: white;
  padding: 5px 5px;
  border: none;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}

.cookieBtn:hover {
  background-color: #761010;
}

.cookieWrapper {
  border-radius: 10px;
  background-color: white;
  width: 400px;
  height: 175px;
  padding: 10px;
  -webkit-box-shadow: 0px 0px 39px 12px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 0px 0px 39px 12px rgba(0, 0, 0, 0.75);
  box-shadow: 0px 0px 39px 12px rgba(0, 0, 0, 0.75);
  z-index: 999;
}

<script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://codeorigin.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>

<body>
  <p>text on page</p>

  <div id="cookieWrapper" class="cookieWrapper" title="Dialog"  align="center">
    <iframe src="rndcookie.asp" width="392" height="150" scrolling="no" frameborder="0" style="border-radius: 10px;"></iframe>
    <button class="cookieBtn" id="button" onclick="" data-dismiss="cookieWrapper" type="button">ACCEPT ALL COOKIES</button>
  </div>


问:
I am using android studio and the mainactivity class is .kt type. I keep having this error: Expecting member declaration
I am using android studio and I have some issues with this piece of code. Could someone tell me what I am doing wrong?
The system keeps telling me "Expecting member declaration."

This is the code

```<code>class MainActivity: AppCompatActivity() {

   class TextView totalTextView;    //This is where I am having the error

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
</code>```

答:
I am assuming you are trying to create a totalTextView variable. In kotlin you can declare a variable like this </p>

```<code>lateinit var totalTextView : TotalTextView
</code>```

Body:
I am using android studio and I have some issues with this piece of code. Could someone tell me what I am doing wrong?
The system keeps telling me "Expecting member declaration."

This is the code

class MainActivity: AppCompatActivity() {

   class TextView totalTextView;    //This is where I am having the error

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

Body:
I am assuming you are trying to create a totalTextView variable. In kotlin you can declare a variable like this

lateinit var totalTextView : TotalTextView


问:
Container is automatically exiting
Below is my Dockerfile:

FROM python:3
COPY . /Demo
WORKDIR /Demo
RUN pip install -r requirements.txt
EXPOSE 9005
CMD python ./app.py
```

<p>I am using following command to run the resulting image:</p>

```docker run -it -d host:port imagename:v1
```

The container is automatically exiting.  When I run docker ps, no running container is shown.

答:
Instead of this line:

```<code>CMD python ./app.py
</code>```

give absolute path like below:

```<code>CMD python /<path-to-script>/app.py
</code>```

Title: Container is automatically exiting

Body:
Below is my Dockerfile:

FROM python:3
COPY . /Demo
WORKDIR /Demo
RUN pip install -r requirements.txt
EXPOSE 9005
CMD python ./app.py

I am using following command to run the resulting image:

docker run -it -d host:port imagename:v1

The container is automatically exiting.  When I run docker ps, no running container is shown.

Body:
Instead of this line:

CMD python ./app.py

give absolute path like below:

CMD python /<path-to-script>/app.py


问:
Bind TextBox on Enter-key press
The default databinding on TextBox is TwoWay and it commits the text to the property only when TextBox lost its focus.

Is there any easy XAML way to make the databinding happen when I press the Enter key on the TextBox?. I know it is pretty easy to do in the code behind, but imagine if this TextBox is inside some complex DataTemplate.

答:
I don't believe that there's any "pure XAML" way to do what you're describing. You can set up a binding so that it updates whenever the text in a TextBox changes (rather than when the TextBox loses focus) by setting the UpdateSourceTrigger property, like this:

```<code><TextBox Name="itemNameTextBox"
    Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}" />
</code>```

If you set UpdateSourceTrigger to "Explicit" and then handled the TextBox's PreviewKeyDown event (looking for the Enter key) then you could achieve what you want, but it would require code-behind. Perhaps some sort of attached property (similar to my EnterKeyTraversal property) woudld work for you.

OwnerDisplayName: Jobi Joy

ContentLicense: CC BY-SA 3.0

Title: Bind TextBox on Enter-key press

Body:
I don't believe that there's any "pure XAML" way to do what you're describing. You can set up a binding so that it updates whenever the text in a TextBox changes (rather than when the TextBox loses focus) by setting the UpdateSourceTrigger property, like this:

<TextBox Name="itemNameTextBox"
    Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}" />

If you set UpdateSourceTrigger to "Explicit" and then handled the TextBox's PreviewKeyDown event (looking for the Enter key) then you could achieve what you want, but it would require code-behind. Perhaps some sort of attached property (similar to my EnterKeyTraversal property) woudld work for you.

OwnerDisplayName: Matt Hamilton

ContentLicense: CC BY-SA 2.5


问:
Detect base64 encoding in PHP?
Is there some way to detect if a string has been base64_encoded() in PHP?

We're converting some storage from plain text to base64 and part of it lives in a cookie that needs to be updated. I'd like to reset their cookie if the text has not yet been encoded, otherwise leave it alone.

答:
Apologies for a late response to an already-answered question, but I don't think base64_decode($x,true) is a good enough solution for this problem. In fact, there may not be a very good solution that works against any given input. For example, I can put lots of bad values into $x and not get a false return value.

```<code>var_dump(base64_decode('wtf mate',true));
string(5) "���j�"

var_dump(base64_decode('This is definitely not base64 encoded',true));
string(24) "N���^~)��r��[jǺ��ܡם"
</code>```

I think that in addition to the strict return value check, you'd also need to do post-decode validation. The most reliable way is if you could decode and then check against a known set of possible values.

A more general solution with less than 100% accuracy (closer with longer strings, inaccurate for short strings) is if you check your output to see if many are outside of a normal range of utf-8 (or whatever encoding you use) characters.

See this example:

```<code><?php
$english = array();
foreach (str_split('az019AZ~~~!@#$%^*()_+|}?><": Iñtërnâtiônàlizætiøn') as $char) {
  echo ord($char) . "\n";
  $english[] = ord($char);
}
  echo "Max value english = " . max($english) . "\n";

$nonsense = array();
echo "\n\nbase64:\n";
foreach (str_split(base64_decode('Not base64 encoded',true)) as $char) {
  echo ord($char) . "\n";
  $nonsense[] = ord($char);
}

  echo "Max nonsense = " . max($nonsense) . "\n";

?>
</code>```

Results:

```<code>Max value english = 195
Max nonsense = 233
</code>```

So you may do something like this:

```<code>if ( $maxDecodedValue > 200 ) {} //decoded string is Garbage - original string not base64 encoded

else {} //decoded string is useful - it was base64 encoded
</code>```

You should probably use the mean() of the decoded values instead of the max(), I just used max() in this example because there is sadly no built-in mean() in PHP. What measure you use (mean,max, etc) against what threshold (eg 200) depends on your estimated usage profile.

In conclusion, the only winning move is not to play. I'd try to avoid having to discern base64 in the first place.

Title: Detect base64 encoding in PHP?

Body:
Apologies for a late response to an already-answered question, but I don't think base64_decode($x,true) is a good enough solution for this problem. In fact, there may not be a very good solution that works against any given input. For example, I can put lots of bad values into $x and not get a false return value.

var_dump(base64_decode('wtf mate',true));
string(5) "���j�"

var_dump(base64_decode('This is definitely not base64 encoded',true));
string(24) "N���^~)��r��[jǺ��ܡם"

I think that in addition to the strict return value check, you'd also need to do post-decode validation. The most reliable way is if you could decode and then check against a known set of possible values.

A more general solution with less than 100% accuracy (closer with longer strings, inaccurate for short strings) is if you check your output to see if many are outside of a normal range of utf-8 (or whatever encoding you use) characters.

See this example:

<?php
$english = array();
foreach (str_split('az019AZ~~~!@#$%^*()_+|}?><": Iñtërnâtiônàlizætiøn') as $char) {
  echo ord($char) . "\n";
  $english[] = ord($char);
}
  echo "Max value english = " . max($english) . "\n";

$nonsense = array();
echo "\n\nbase64:\n";
foreach (str_split(base64_decode('Not base64 encoded',true)) as $char) {
  echo ord($char) . "\n";
  $nonsense[] = ord($char);
}

  echo "Max nonsense = " . max($nonsense) . "\n";

?>

Results:

Max value english = 195
Max nonsense = 233

So you may do something like this:

if ( $maxDecodedValue > 200 ) {} //decoded string is Garbage - original string not base64 encoded

else {} //decoded string is useful - it was base64 encoded

You should probably use the mean() of the decoded values instead of the max(), I just used max() in this example because there is sadly no built-in mean() in PHP. What measure you use (mean,max, etc) against what threshold (eg 200) depends on your estimated usage profile.

In conclusion, the only winning move is not to play. I'd try to avoid having to discern base64 in the first place.


问:
Jenkins plugin repo as proxy repo when behind a corporate proxy
Is there a way - or a tool - that let me setup the jenkins plugin site as proxy repo so that within Jenkins I can get the plugin updates from the proxy repo rather than the original site?

The issue arises specially in environments where you cannot have direct access to the internet. So in my scenario I have a Nexus Repo Server which has access to the internet. The Jenkins server has not. So my approach was to

Setup a proxy repo (let's say https://nexus.intra/repository/updates.jenkins.io/ which is a proxy to https://updates.jenkins.io/

Configure Jenkins so that the plugins are gathered from the proxy repo. Thus I configure the plugin udate site to https://nexus.intra/repository/updates.jenkins.io/update-center.json

This does not work. I get the notification of new plugins, but when I try to download the plugin the connection fails, as within the update-center.json the pointer to the plugins is still https://updates.jenkins.io/. See here ...

```<code>updateCenter.post(
....
,"url":"http://updates.jenkins-ci.org/download/plugins/AnchorChain/1.0/AnchorChain.hpi",
....
</code>```

So any ideas how to achieve this?

答:
One solution I have implemented is to modify the hosts file on the Jenkins host to point to the artifact repo when querying updates.jenkins-ci.org. However this requires a reverse proxy in front of your artifact repo.

Step-by-Step

On Jenkins host update the hosts file as follows

```<code><artifact repo ip> plugins.jenkins.io updates.jenkins.io updates.jenkins-ci.org mirrors.jenkins.io
</code>```

Setup a reverse proxy in front of the artifact repo which handles traffic for updates.jenkins.io, updates.jenkins-ci.org, plugins.jenkins.io and mirrors.jenkins.io to your artifact repo

If you are running your artifact repo in k8s your Ingress may look as follows:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: artifactory-repo-jenkins
annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /artifactory/remote-generic-updates.jenkins/
    nginx.ingress.kubernetes.io/upstream-vhost: "artifactory.intra"
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
spec:
tls:
- hosts:
    - updates.jenkins.io
    - updates.jenkins-ci.org
    - mirrors.jenkins.io
    secretName: artifactory-jenkins-ingress-cert
rules:
- host: jenkins.intra
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /
- host: updates.jenkins.io
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /
- host: updates.jenkins-ci.org
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /
- host: mirrors.jenkins.io
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /
</code>```

Optionally if you want to use ssl, you have to create a certificate which includes the urls as alternate names.

```<code>[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no
[req_distinguished_name]
C = CH
O=My Company
OU = Artifactory
CN = jenkins.intra
[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = jenkins.intra
DNS.2 = updates.jenkins-ci.org
DNS.3 = plugins.jenkins.io
DNS.4 = updates.jenkins.io
DNS.5 = mirrors.jenkins.io
</code>```

Firewall

In addition, if you have restricted connection I recommend to white-list all mirrors for your artifact repository so it can get the artifacts properly

plugins.jenkins.io

updates.jenkins-ci.org

mirrors.tuna.tsinghua.edu.cn

ftp.yz.yamagata-u.ac.jp

mirror.esuni.jp

mirrors.seville-jam.es

mirror.xmission.com

archives.jenkins-ci.org

ftp-chi.osuosl.org
ftp-nyc.osuosl.org

Body:
Is there a way - or a tool - that let me setup the jenkins plugin site as proxy repo so that within Jenkins I can get the plugin updates from the proxy repo rather than the original site?

The issue arises specially in environments where you cannot have direct access to the internet. So in my scenario I have a Nexus Repo Server which has access to the internet. The Jenkins server has not. So my approach was to

Setup a proxy repo (let's say https://nexus.intra/repository/updates.jenkins.io/ which is a proxy to https://updates.jenkins.io/

Configure Jenkins so that the plugins are gathered from the proxy repo. Thus I configure the plugin udate site to https://nexus.intra/repository/updates.jenkins.io/update-center.json

This does not work. I get the notification of new plugins, but when I try to download the plugin the connection fails, as within the update-center.json the pointer to the plugins is still https://updates.jenkins.io/. See here ...

updateCenter.post(
....
,"url":"http://updates.jenkins-ci.org/download/plugins/AnchorChain/1.0/AnchorChain.hpi",
....

So any ideas how to achieve this?

Body:
One solution I have implemented is to modify the hosts file on the Jenkins host to point to the artifact repo when querying updates.jenkins-ci.org. However this requires a reverse proxy in front of your artifact repo.

Step-by-Step

On Jenkins host update the hosts file as follows

<artifact repo ip> plugins.jenkins.io updates.jenkins.io updates.jenkins-ci.org mirrors.jenkins.io

Setup a reverse proxy in front of the artifact repo which handles traffic for updates.jenkins.io, updates.jenkins-ci.org, plugins.jenkins.io and mirrors.jenkins.io to your artifact repo

If you are running your artifact repo in k8s your Ingress may look as follows:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: artifactory-repo-jenkins
annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /artifactory/remote-generic-updates.jenkins/
    nginx.ingress.kubernetes.io/upstream-vhost: "artifactory.intra"
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
spec:
tls:
- hosts:
    - updates.jenkins.io
    - updates.jenkins-ci.org
    - mirrors.jenkins.io
    secretName: artifactory-jenkins-ingress-cert
rules:
- host: jenkins.intra
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /
- host: updates.jenkins.io
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /
- host: updates.jenkins-ci.org
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /
- host: mirrors.jenkins.io
    http:
    paths:
    - backend:
        serviceName: artifactory-artifactory
        servicePort: 8081
        path: /

Optionally if you want to use ssl, you have to create a certificate which includes the urls as alternate names.

[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no
[req_distinguished_name]
C = CH
O=My Company
OU = Artifactory
CN = jenkins.intra
[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = jenkins.intra
DNS.2 = updates.jenkins-ci.org
DNS.3 = plugins.jenkins.io
DNS.4 = updates.jenkins.io
DNS.5 = mirrors.jenkins.io

Firewall

In addition, if you have restricted connection I recommend to white-list all mirrors for your artifact repository so it can get the artifacts properly

plugins.jenkins.io

updates.jenkins-ci.org

mirrors.tuna.tsinghua.edu.cn

ftp.yz.yamagata-u.ac.jp

mirror.esuni.jp

mirrors.seville-jam.es

mirror.xmission.com

archives.jenkins-ci.org

ftp-chi.osuosl.org
ftp-nyc.osuosl.org


问:
Is there a way to create TestMethods on-the-fly for VS2017?
I have a C# application built over .NET 4.6.1 (VS2017).

I am now building a test environment and would like to include user base tests.

The user provide a folder of files, each one is a seperate user test i need to run against.

I would like to create a TestMethod for each file to run against my application within VS2017.

Is there a way to automate such task? or the only way is to write a script to create the TestClass implementing a uniqueTestMethod for each file

答: You can make use of the xUnit tests using parameterised tests with InlineData. Article with examples


问:
How can I collapse multiple columns and to generate new variables from the different levels/values that were collapsed?
I have a dataset (df) similar to this one:

```<code>df <- data.frame("ID"=c(1, 1, 1, 2, 2),
                 "Method of payment"=c("cash","liabilities",
                                       "shares", "cash", NA),
                 "USD"=c(110, 130, 200, 100, NA),
                 "var3"=c(1500, NA, NA, "ab", "bc"))
df
#   ID Method.of.payment USD var3
# 1  1              cash 110 1500
# 2  1       liabilities 130 <NA>
# 3  1            shares 200 <NA>
# 4  2              cash 100   ab
# 5  2              <NA>  NA   bc
</code>```

And I would like to have:

```<code>data.frame("ID"=c(1, 2),
           "Method of payment"=c("cash, liabilities, shares", "cash"),
           "Cash"=c(110, 100),
           "Liabilities"=c(130, 0),
           "Shares"=c(200, 0),
           "var3"=c(1500, "ab,bc"))

#   ID         Method.of.payment Cash Liabilities Shares  var3
# 1  1 cash, liabilities, shares  110         130    200  1500
# 2  2                      cash  100           0      0 ab,bc
</code>```

Therefore, I would like to

collapse the variables "method of payment" and "var3" in order to have only one row per ID, having all the levels/values linked to an ID pasted in one row;

generate new variables from existing levels of the factor variable method of payment ("cash", "liabilities", "shares") whose values should be the corresponding values of the variable USD or 0 if there is no corresponding value.

I am working with a very large dataset, so I am looking for something that works also on large data. I hope it is clear.

答:
You could use by and reshape to get the USD into wide format, dropping the var3 column.

```<code>b <- by(df1, df1$id, reshape, direction="wide", timevar="method.of.payment", drop="var3")
b <- Reduce(function(x, y) merge(x, y, all=TRUE), b)  # merge the list resulting from `by`
</code>```

To collapse the levels, you could use toString in another by and cbind it to the merged

```<code>res <- cbind(b, do.call(rbind, by(df1[c(2, 4)], df1$id, function(X)
  lapply(X, function(x) toString(na.omit(x))))))[c(1, 6, 2:4, 7)]  # some column sorting
res
#   id         method.of.payment usd.cash usd.liabilities usd.shares   var3
# 1  1 cash, liabilities, shares      110             130        200   1500
# 2  2                      cash      100              NA         NA ab, bc
</code>```

Edit: Perhaps it is more elegant to do this in just one by.

```<code>b <- by(df1, df1$id, function(X) {
  r <- reshape(X, direction="wide", timevar="method.of.payment", drop="var3")
  s <- lapply(X[c(2, 4)], function(x) toString(na.omit(x)))
  return(merge(r, s))
  })

res <- Reduce(function(x, y) merge(x, y, all=TRUE), b)[c(1, 3, 2, 5:6, 4)]
res
#   id         method.of.payment usd.cash usd.liabilities usd.shares   var3
# 1  1 cash, liabilities, shares      110             130        200   1500
# 2  2                      cash      100              NA         NA ab, bc
</code>```

Data

Note: Better avoid spaces in column names in R.

```<code>df1 <- structure(list(id = c(1, 1, 1, 2, 2), method.of.payment = structure(c(1L,
2L, 3L, 1L, NA), .Label = c("cash", "liabilities", "shares"), class = "factor"),
    usd = c(110, 130, 200, 100, NA), var3 = structure(c(1L, NA,
    NA, 2L, 3L), .Label = c("1500", "ab", "bc"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))
</code>```

Body:
I have a dataset (df) similar to this one:

df <- data.frame("ID"=c(1, 1, 1, 2, 2),
                 "Method of payment"=c("cash","liabilities",
                                       "shares", "cash", NA),
                 "USD"=c(110, 130, 200, 100, NA),
                 "var3"=c(1500, NA, NA, "ab", "bc"))
df
#   ID Method.of.payment USD var3
# 1  1              cash 110 1500
# 2  1       liabilities 130 <NA>
# 3  1            shares 200 <NA>
# 4  2              cash 100   ab
# 5  2              <NA>  NA   bc

And I would like to have:

data.frame("ID"=c(1, 2),
           "Method of payment"=c("cash, liabilities, shares", "cash"),
           "Cash"=c(110, 100),
           "Liabilities"=c(130, 0),
           "Shares"=c(200, 0),
           "var3"=c(1500, "ab,bc"))

#   ID         Method.of.payment Cash Liabilities Shares  var3
# 1  1 cash, liabilities, shares  110         130    200  1500
# 2  2                      cash  100           0      0 ab,bc

Therefore, I would like to

collapse the variables "method of payment" and "var3" in order to have only one row per ID, having all the levels/values linked to an ID pasted in one row;

generate new variables from existing levels of the factor variable method of payment ("cash", "liabilities", "shares") whose values should be the corresponding values of the variable USD or 0 if there is no corresponding value.

I am working with a very large dataset, so I am looking for something that works also on large data. I hope it is clear.

Body:
You could use by and reshape to get the USD into wide format, dropping the var3 column.

b <- by(df1, df1$id, reshape, direction="wide", timevar="method.of.payment", drop="var3")
b <- Reduce(function(x, y) merge(x, y, all=TRUE), b)  # merge the list resulting from `by`

To collapse the levels, you could use toString in another by and cbind it to the merged

res <- cbind(b, do.call(rbind, by(df1[c(2, 4)], df1$id, function(X)
  lapply(X, function(x) toString(na.omit(x))))))[c(1, 6, 2:4, 7)]  # some column sorting
res
#   id         method.of.payment usd.cash usd.liabilities usd.shares   var3
# 1  1 cash, liabilities, shares      110             130        200   1500
# 2  2                      cash      100              NA         NA ab, bc

Edit: Perhaps it is more elegant to do this in just one by.

b <- by(df1, df1$id, function(X) {
  r <- reshape(X, direction="wide", timevar="method.of.payment", drop="var3")
  s <- lapply(X[c(2, 4)], function(x) toString(na.omit(x)))
  return(merge(r, s))
  })

res <- Reduce(function(x, y) merge(x, y, all=TRUE), b)[c(1, 3, 2, 5:6, 4)]
res
#   id         method.of.payment usd.cash usd.liabilities usd.shares   var3
# 1  1 cash, liabilities, shares      110             130        200   1500
# 2  2                      cash      100              NA         NA ab, bc

Data

Note: Better avoid spaces in column names in R.

df1 <- structure(list(id = c(1, 1, 1, 2, 2), method.of.payment = structure(c(1L,
2L, 3L, 1L, NA), .Label = c("cash", "liabilities", "shares"), class = "factor"),
    usd = c(110, 130, 200, 100, NA), var3 = structure(c(1L, NA,
    NA, 2L, 3L), .Label = c("1500", "ab", "bc"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))


问:
how to use setState in SearchDelegate
I want to add more filter on search result by adding a form with some radio buttons and other widgets. The doc states that Radio does not keep state and should call parent's setState onChange method to rebuild widget. The form will be displayed after calling showModalBottomSheet.
Looking at search.dart looks like setState is called internally only on query changed

what i did
assuming there was no such method, setState, I redisplay dialogue, call Navigation.pop(context) followed by showModalBottomSheet. The radio buttons can now update the value onChanged but the transition to redislay the dialogue looks ugly (sliding animation every time the value changes).

Is it possible to use setState in searchDelegate and how?

答:
What you need to use is StatefulBuilder, returned by showModalBottomSheet's builder.

StatefulBuilder provides setState method to rebuild its own subtree.

e.g.

int selected;

showModalBottomSheet(context: context, builder: (_) =>
  StatefulBuilder(builder: (modalContext, modalSetState) =>
    Column(children: <Widget>[

      Text("Select radio button"),
      RadioListTile(
        value: 1,
        groupValue: selected,
        onChanged: (val) => modalSetState(() => selected = val),
        title: Text("One")
      ),
      RadioListTile(
        value: 2,
        groupValue: selected,
        onChanged: (val) => modalSetState(() => selected = val),
        title: Text("Two")
      ),

    ])
  )
).whenComplete(() {
  print("Selected: $selected");
});
```

In my example setState for the content of the modal is declared as modalSetState builder argument.

Title: how to use setState in SearchDelegate

Body:
What you need to use is StatefulBuilder, returned by showModalBottomSheet's builder.

StatefulBuilder provides setState method to rebuild its own subtree.

e.g.

int selected;

showModalBottomSheet(context: context, builder: (_) =>
  StatefulBuilder(builder: (modalContext, modalSetState) =>
    Column(children: <Widget>[

      Text("Select radio button"),
      RadioListTile(
        value: 1,
        groupValue: selected,
        onChanged: (val) => modalSetState(() => selected = val),
        title: Text("One")
      ),
      RadioListTile(
        value: 2,
        groupValue: selected,
        onChanged: (val) => modalSetState(() => selected = val),
        title: Text("Two")
      ),

    ])
  )
).whenComplete(() {
  print("Selected: $selected");
});

In my example setState for the content of the modal is declared as modalSetState builder argument.


问:
Save child objects automatically after saving parent
I've already looked at -
Save child objects automatically using JPA Hibernate

Hibernate: OneToMany save children by cascade

I have following tables -

Instructor_Detail(id, youtubechannel, hobby) -  PRIMARY_KEY (id)

Instructor(id, first_name, last_name, email, instructor_detail_id) -
PRIMARY_KEY (id), FOREIGN_KEY (instructor_detail_id)

course(id, title, instructor_id) -  PRIMARY_KEY (id), FOREIGN_KEY
(instructor_id)

I'm trying to do - save(instructorDetail) in my MainApp and expecting associated instructors and courses to be save automatically

Here are my classes -

```<code></p>

@Entity
@Table(name="instructor_detail")
public class InstructorDetail {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="youtube_channel")
    private String youtubeChannel;

    @Column(name="hobby")
    private String hobby;

    @OneToOne(mappedBy = "instructorDetail", cascade= {
            CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH
    })
    private Instructor instructor;
    //getters and setters
}

@Entity
@Table(name="instructor")
public class Instructor {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="email")
    private String email;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="instructor_detail_id")
    private InstructorDetail instructorDetail;

    @OneToMany(mappedBy="instructor",
            cascade =
        {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
    private List<Course> courses;

//...getters and setters

//one more method to add courses
public void addCourse(Course c) {
        if(courses == null) {
            courses = new ArrayList<>();
        }
        courses.add(c);
        c.setInstructor(this);
    }
}

@Entity
@Table(name="course")
public class Course {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="title")
    private String title;

    @ManyToOne(cascade=
        {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
    @JoinColumn(name="instructor_id")
    private Instructor instructor;

//getters and setters
}

//MainClass -
public class OneToManyBiDirectionalDemo {

    public static void main(String[] args) {
        Course c1 = new Course("Multithreading");
        Course c2 = new Course("WebDevelopment");
        Instructor ins1 = new Instructor("John","Purcell","john.purcell@email.com");
        InstructorDetail insDet1 = new InstructorDetail("com.john.purcell","teaching");

        insDet1.setInstructor(ins1);
        ins1.setInstructorDetail(insDet1);

        ins1.addCourse(c1);
        ins1.addCourse(c2);

        SessionFactory factory = new Configuration().
                         configure("hibernate.cfg.xml").             addAnnotatedClass(Course.class).                        addAnnotatedClass(Instructor.class).                        addAnnotatedClass(InstructorDetail.class).                      buildSessionFactory();

        Session session = factory.getCurrentSession();
        session.beginTransaction();
        session.save(insDet1);
        session.getTransaction().commit();
        session.close();
        factory.close();
    }
}
</code>```

My expectation is - when save(instructorDetail) is called in MainClass, the instructor and courses should also be save automatically. However, executing the current only saves instructor detail and not instructor and courses. Only one insert is fired in log and there are not exceptions generated. I'm new to Hibernate, so my expectations or understanding may be off. Is this possible though?

答:
The JPA CascadeType that you configured (DETACH,MERGE,PERSIST,REFRESH) only has cascading effect when using with Session 's evict() , merge() , persist() , refresh(). (See this)

But you are using session.save() for saving the objects .That 's why it does not any the cascading effect. Change to either one of the following should solve the problem:

(1) Change all CascadeType to ALL.

(2) Use session.persist() to insert the record:

```<code>  session.persist(insDet1);
</code>```

Body:
I've already looked at -
Save child objects automatically using JPA Hibernate

Hibernate: OneToMany save children by cascade

I have following tables -

Instructor_Detail(id, youtubechannel, hobby) -  PRIMARY_KEY (id)

Instructor(id, first_name, last_name, email, instructor_detail_id) -
PRIMARY_KEY (id), FOREIGN_KEY (instructor_detail_id)

course(id, title, instructor_id) -  PRIMARY_KEY (id), FOREIGN_KEY
(instructor_id)

I'm trying to do - save(instructorDetail) in my MainApp and expecting associated instructors and courses to be save automatically

Here are my classes -

@Entity
@Table(name="instructor_detail")
public class InstructorDetail {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="youtube_channel")
    private String youtubeChannel;

    @Column(name="hobby")
    private String hobby;

    @OneToOne(mappedBy = "instructorDetail", cascade= {
            CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH
    })
    private Instructor instructor;
    //getters and setters
}

@Entity
@Table(name="instructor")
public class Instructor {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="email")
    private String email;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="instructor_detail_id")
    private InstructorDetail instructorDetail;

    @OneToMany(mappedBy="instructor",
            cascade =
        {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
    private List<Course> courses;

//...getters and setters

//one more method to add courses
public void addCourse(Course c) {
        if(courses == null) {
            courses = new ArrayList<>();
        }
        courses.add(c);
        c.setInstructor(this);
    }
}

@Entity
@Table(name="course")
public class Course {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="title")
    private String title;

    @ManyToOne(cascade=
        {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
    @JoinColumn(name="instructor_id")
    private Instructor instructor;

//getters and setters
}

//MainClass -
public class OneToManyBiDirectionalDemo {

    public static void main(String[] args) {
        Course c1 = new Course("Multithreading");
        Course c2 = new Course("WebDevelopment");
        Instructor ins1 = new Instructor("John","Purcell","john.purcell@email.com");
        InstructorDetail insDet1 = new InstructorDetail("com.john.purcell","teaching");

        insDet1.setInstructor(ins1);
        ins1.setInstructorDetail(insDet1);

        ins1.addCourse(c1);
        ins1.addCourse(c2);

        SessionFactory factory = new Configuration().
                         configure("hibernate.cfg.xml").             addAnnotatedClass(Course.class).                        addAnnotatedClass(Instructor.class).                        addAnnotatedClass(InstructorDetail.class).                      buildSessionFactory();

        Session session = factory.getCurrentSession();
        session.beginTransaction();
        session.save(insDet1);
        session.getTransaction().commit();
        session.close();
        factory.close();
    }
}

My expectation is - when save(instructorDetail) is called in MainClass, the instructor and courses should also be save automatically. However, executing the current only saves instructor detail and not instructor and courses. Only one insert is fired in log and there are not exceptions generated. I'm new to Hibernate, so my expectations or understanding may be off. Is this possible though?

Body:
The JPA CascadeType that you configured (DETACH,MERGE,PERSIST,REFRESH) only has cascading effect when using with Session 's evict() , merge() , persist() , refresh(). (See this)

But you are using session.save() for saving the objects .That 's why it does not any the cascading effect. Change to either one of the following should solve the problem:

(1) Change all CascadeType to ALL.

(2) Use session.persist() to insert the record:

  session.persist(insDet1);


问:
Way to pass value during Button on click to another component with async in react
I am having a difficulty in creating a dynamic application that will change the displayed values of a table when an api call is triggered.

The table contents will be refreshed when a button is pressed.

The button will determine the url link for the get api call

```<code>Component 1

<Button onClick={() => viewDetails()}>View Details</Button>

function viewDetails() {
const url= "url" +    detail +    "/details");
}

</code>```

Then the url will send on another component, that will get the response

```<code>Component 2

const getServerData = async ({ filters, sortBy, pageSize, pageIndex }) => {
  await new Promise(resolve => setTimeout(resolve, 500));

   const res = await axios.get(url)
}

export default function() {
const { rows, pageCount } = await getServerData({
      filters,
      sortBy,
      pageSize,
      pageIndex
    });

}
</code>```

Is it possible to send the url to the other component?

If it is possible, how do I import/ export the const to retrieve in other component? And does it affect the performance of application if I will do it this way? Is there a better approach?

答:
ParentComponent.js

```<code>class Parent extends React.Component{
  state = {
    url: '',
  }
  setURL = (url) => { this.setState({ url: url }) };

  render(){
    return (
      <>
        <Button onClick={this.setURL} />
        <Another url={this.state.url} />
      </>
    )
  }
}
</code>```

Button.js

```<code>const Button = (props) => {
  return ( <button onClick={props.onClick}>button</button>);
}
</code>```

Another.js

```<code>const Another = (props) => {

  console.log(props.url); // You can use updated URL
  return (
    <div>
      ...
    </div>
  )
}
</code>```

Body:
I am having a difficulty in creating a dynamic application that will change the displayed values of a table when an api call is triggered.

The table contents will be refreshed when a button is pressed.

The button will determine the url link for the get api call

Component 1

<Button onClick={() => viewDetails()}>View Details</Button>

function viewDetails() {
const url= "url" +    detail +    "/details");
}

Then the url will send on another component, that will get the response

Component 2

const getServerData = async ({ filters, sortBy, pageSize, pageIndex }) => {
  await new Promise(resolve => setTimeout(resolve, 500));

   const res = await axios.get(url)
}

export default function() {
const { rows, pageCount } = await getServerData({
      filters,
      sortBy,
      pageSize,
      pageIndex
    });

}

Is it possible to send the url to the other component?

If it is possible, how do I import/ export the const to retrieve in other component? And does it affect the performance of application if I will do it this way? Is there a better approach?

Body:
ParentComponent.js

class Parent extends React.Component{
  state = {
    url: '',
  }
  setURL = (url) => { this.setState({ url: url }) };

  render(){
    return (
      <>
        <Button onClick={this.setURL} />
        <Another url={this.state.url} />
      </>
    )
  }
}

Button.js

const Button = (props) => {
  return ( <button onClick={props.onClick}>button</button>);
}

Another.js

const Another = (props) => {

  console.log(props.url); // You can use updated URL
  return (
    <div>
      ...
    </div>
  )
}


问:
jQuery load() is not loading content properly
I am trying to load new links without page refresh using html5 window.history.pushState() function.

Everything works good but when I open my inspect element in Chrome or in Firefox the head tag and body tag are missing. I don't know why.

Here is my code:

```<code>function goto(event,el)
{
    url=el.href;
    event.preventDefault();
    window.history.pushState('','',url);
    $('html').load(url);
}
</code>```

and the new loading page is this:-

```<code><html>
<head>
<script type="text/javascript" src="http://localhost/js/jquery.js"></script>
</head>
<body>
<div id="menu">
<a href="menu1.php">Menu1</a>
<a href="menu2.php">Menu2</a>
</div>
</body>
</html>
</code>```

I really want to navigate through pages without page refresh properly.

How to solve this issue using history.pushstate() function or is there any other way.

My main motive is to achieve speed like Facebook or Twitter.

答:
I have tried many options but I found my solution on this code

```<code>function goto(event,el)
{
    url=el.href;
    event.preventDefault();
    window.history.pushState('','',url);
    $.get(url, function(data) {
        var head=data.match(/<head[^>]*>[\s\S]*<\/head>/gi);
        $('head').html(head[0]);
        $('#content').html($(data).find('#content').html());
    });
}
</code>```

Do you have any better solution than this and is this solution works same in all the browsers and what about speed/load time/performance issue is there any.

My main purpose to load new page content without page refresh instantly like twitter or facebook doing

Any suggestion or help will be highly appreciated

Body:
I am trying to load new links without page refresh using html5 window.history.pushState() function.

Everything works good but when I open my inspect element in Chrome or in Firefox the head tag and body tag are missing. I don't know why.

Here is my code:

function goto(event,el)
{
    url=el.href;
    event.preventDefault();
    window.history.pushState('','',url);
    $('html').load(url);
}

and the new loading page is this:-

Menu1
Menu2

I really want to navigate through pages without page refresh properly.

How to solve this issue using history.pushstate() function or is there any other way.

My main motive is to achieve speed like Facebook or Twitter.

Body:
I have tried many options but I found my solution on this code

function goto(event,el)
{
    url=el.href;
    event.preventDefault();
    window.history.pushState('','',url);
    $.get(url, function(data) {
        var head=data.match(/<head[^>]*>[\s\S]*<\/head>/gi);
        $('head').html(head[0]);
        $('#content').html($(data).find('#content').html());
    });
}

Do you have any better solution than this and is this solution works same in all the browsers and what about speed/load time/performance issue is there any.

My main purpose to load new page content without page refresh instantly like twitter or facebook doing

Any suggestion or help will be highly appreciated


问:
how to do a SQL Join that returns the rows that are not present in my table 2
I want to run a query between my two tables and returns the results to me the lines that are not present in my table 2</p>

答:
Should be something like this:</p>

```<code>SELECT * FROM table2 WHERE table1_id NOT IN (SELECT id FROM table1)
</code>```

Body:
Should be something like this:

SELECT * FROM table2 WHERE table1_id NOT IN (SELECT id FROM table1)


问:
Plot intersection of 2 planes in mayavi
I am trying to render 2 planes and then their intersection line in mayavi.

Equation of planes

x - 5*y + 2*z -11 = 0

3*x - 2*y + 3*z -7 = 0

The line where these 2 planes intersect is (I calculated this manually) -

11*x - 3*y - 13*z - 17 = 0

Code

%gui qt
from mayavi import mlab
import numpy as np
mlab.clf()

# first plane
x, y = np.mgrid[-100:100:1000j, -100:10:1000j]
z = (-x+5*y+11)/2
mlab.surf(x,y,z, warp_scale='auto',color=(0.1,0.2,0.3))

# second plane
x, y = np.mgrid[-100:100:1000j, -100:100:1000j]
z = (-3*x+2*y+7)/3
mlab.surf(x,y,z, warp_scale='auto')

# intersection line
x = np.linspace(-1000, 1000, num=4000)
y = np.linspace(-1000, 1000, num=4000)
z = (11*x-3*y-17)/13
mlab.points3d(x, y, z,scale_factor=0.95)
```

Plot

This is the final plot I am getting, which is clearly wrong. I am not able to find the error here.

答:
There are multiple misunderstandings here. You have two planes, with equations x - 5y + 2z -11 = 0 and 3x - 2y + 3z - 7 = 0. Saying that the line where those two planes intersect obeys the equation 11x - 3y - 13z - 17 = 0 is a non-sense. This is the equation of a plane, not a line. And even if the line you are looking for is included in this plane, how do you choose (x, y, z)?

The approach here is to note that all (x, y, z) describing the line describe also the planes, then to express one coordinate according to the others for one plane and finally inject this in the second plane equation. This gives

y = (-3x - 19) / 11

z = (-x + 5y + 11) / 2

Using the following piece of code

```<code>from mayavi import mlab
import numpy
x, y = numpy.mgrid[-10:10:21*1j, -10:10:21*1j]
z = (-x + 5 * y + 11) / 2
zz = (-3 * x + 2 * y + 7) / 3
xx = numpy.linspace(-10, 10, 21)
yy = -3 / 11 * xx - 19 / 11
zzz = (-xx + 5 * yy + 11) / 2
mlab.surf(x, y, z)
mlab.surf(x, y, zz)
mlab.points3d(xx, yy, zzz)
mlab.show()
</code>```

This figure is produced

Title: Plot intersection of 2 planes in mayavi

Body:
I am trying to render 2 planes and then their intersection line in mayavi.

Equation of planes

x - 5*y + 2*z -11 = 0

3*x - 2*y + 3*z -7 = 0

The line where these 2 planes intersect is (I calculated this manually) -

11*x - 3*y - 13*z - 17 = 0

Code

%gui qt
from mayavi import mlab
import numpy as np
mlab.clf()

# first plane
x, y = np.mgrid[-100:100:1000j, -100:10:1000j]
z = (-x+5*y+11)/2
mlab.surf(x,y,z, warp_scale='auto',color=(0.1,0.2,0.3))

# second plane
x, y = np.mgrid[-100:100:1000j, -100:100:1000j]
z = (-3*x+2*y+7)/3
mlab.surf(x,y,z, warp_scale='auto')

# intersection line
x = np.linspace(-1000, 1000, num=4000)
y = np.linspace(-1000, 1000, num=4000)
z = (11*x-3*y-17)/13
mlab.points3d(x, y, z,scale_factor=0.95)

Plot

This is the final plot I am getting, which is clearly wrong. I am not able to find the error here.

Body:
There are multiple misunderstandings here. You have two planes, with equations x - 5y + 2z -11 = 0 and 3x - 2y + 3z - 7 = 0. Saying that the line where those two planes intersect obeys the equation 11x - 3y - 13z - 17 = 0 is a non-sense. This is the equation of a plane, not a line. And even if the line you are looking for is included in this plane, how do you choose (x, y, z)?

The approach here is to note that all (x, y, z) describing the line describe also the planes, then to express one coordinate according to the others for one plane and finally inject this in the second plane equation. This gives

y = (-3x - 19) / 11

z = (-x + 5y + 11) / 2

Using the following piece of code

from mayavi import mlab
import numpy
x, y = numpy.mgrid[-10:10:21*1j, -10:10:21*1j]
z = (-x + 5 * y + 11) / 2
zz = (-3 * x + 2 * y + 7) / 3
xx = numpy.linspace(-10, 10, 21)
yy = -3 / 11 * xx - 19 / 11
zzz = (-xx + 5 * yy + 11) / 2
mlab.surf(x, y, z)
mlab.surf(x, y, zz)
mlab.points3d(xx, yy, zzz)
mlab.show()

This figure is produced


问:
Implement datatable in angular 7
I am new to angular 7 and want to implement datatable in angular 7.First i have create a module admin within admin module i have create a component as manage-categories and i want to implement datatable in this component,below is my code

angular.json

```<code>    "styles": [
          "src/styles.css",
          "node_modules/datatables.net-dt/css/jquery.dataTables.css"
        ],
        "scripts": [
    "node_modules/datatables.net/js/jquery.dataTables.js"
        ]
      },
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { AdminModule } from './admin/admin.module';
import { AuthModule } from './auth/auth.module';
import { httpInterceptorProviders } from './http-interceptors/index';

@NgModule({
declarations: [
AppComponent,
HeaderComponent
],
imports: [
BrowserModule,
HttpClientModule,
AdminModule,
AuthModule,
AppRoutingModule
],
providers: [httpInterceptorProviders],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

admin.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataTablesModule } from 'angular-datatables';
import { AdminRoutingModule } from './admin-routing.module';
import { AdminDashboardComponent } from './admin-dashboard/admin-
dashboard.component';
import { ManageCategoriesComponent } from './manage-categories/manage-
categories.component';

@NgModule({
declarations: [AdminDashboardComponent,ManageCategoriesComponent,
ManagePagesComponent],
imports: [
CommonModule,
DataTablesModule ,
AdminRoutingModule
]
})
export class AdminModule { }
</code>```

manage-categories.ts

```<code>import { Component, OnInit } from '@angular/core';
import { BlogService } from '../../services/blog.service';
import { Blog } from '../../models/blog';

@Component({
selector: 'app-manage-categories',
templateUrl: './manage-categories.component.html',
styleUrls: ['./manage-categories.component.css']
})
export class ManageCategoriesComponent implements OnInit {

title = 'Manage Blogs';
blogs: Blog;
error: string;
constructor(private blogService: BlogService) { }

ngOnInit() {
this.blogService.getBlogs().subscribe(
  (data: Blog) => this.blogs = data,
  error => this.error = error
);
}
}
</code>```

manage-categories.html

```<code>   <div class="box-body">
          <table datatable class="table table-bordered table-hover">
            <thead>
            <tr>
              <th>#ID</th>
              <th>Image</th>
              <th>Title
              </th>
              <th >Created At
              </th>
              <th>Action</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let blog of blogs">
              <td>{{blog.id}}</td>
              <td><img src="{{blog.image}}" class="col-md-3"></td>
              <td>{{blog.title}}</td>
              <td>{{blog.created_at | date: 'mediumDate'}}</td>
              <td class="action">
                  <a href="#" class="btn btn-info btn-sm">Edit</a>
                  <a href="#" class="btn btn-danger btn-sm">Delete</a>
              </td>
          </tr>
  </tbody>
  </table>
  </div>
</code>```

Above is my code ,i have already tries in below link

https://l-lin.github.io/angular-datatables/#/getting-started

it working on static data but it dont work when bind dynamic data in my table,its sorting,pagination and searching filter will not work.

答:
You have to re-render your table once data gets updated. You can use DataTableDirective for child element and then destroy the table and re-create. I will change your component as -

```<code>import { Component, OnInit } from '@angular/core';
import { BlogService } from '../../services/blog.service';
import { Blog } from '../../models/blog';
import { DataTableDirective } from 'angular-datatables';

@Component({
selector: 'app-manage-categories',
templateUrl: './manage-categories.component.html',
styleUrls: ['./manage-categories.component.css']
})
export class ManageCategoriesComponent implements OnInit {
@ViewChild(DataTableDirective)
dtElement: DataTableDirective;
title = 'Manage Blogs';
blogs: Blog;
error: string;
dtTrigger: Subject<any> = new Subject();
dtOptions: any = {};
constructor(private blogService: BlogService) { }

ngOnInit() {
this.blogService.getBlogs().subscribe(
  (data: Blog) => { this.blogs = data; this.rerender(); },
  error => this.error = error
);
}

rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
  // Destroy the table first
  dtInstance.destroy();
  // Call the dtTrigger to rerender again
  this.dtTrigger.next();
});
 }
}
</code>```

and your template will have datatable tags as -

```<code><div class="box-body">
          <table datatable  [dtOptions]="dtOptions" [dtTrigger]="dtTrigger"
          class="table table-bordered table-hover">
            <thead>
            <tr>
              <th>#ID</th>
              <th>Image</th>
              <th>Title
              </th>
              <th >Created At
              </th>
              <th>Action</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let blog of blogs">
              <td>{{blog.id}}</td>
              <td><img src="{{blog.image}}" class="col-md-3"></td>
              <td>{{blog.title}}</td>
              <td>{{blog.created_at | date: 'mediumDate'}}</td>
              <td class="action">
                  <a href="#" class="btn btn-info btn-sm">Edit</a>
                  <a href="#" class="btn btn-danger btn-sm">Delete</a>
              </td>
          </tr>
  </tbody>
  </table>
  </div>
</code>```

Title: Implement datatable in angular 7

Body:
I am new to angular 7 and want to implement datatable in angular 7.First i have create a module admin within admin module i have create a component as manage-categories and i want to implement datatable in this component,below is my code

angular.json

    "styles": [
          "src/styles.css",
          "node_modules/datatables.net-dt/css/jquery.dataTables.css"
        ],
        "scripts": [
    "node_modules/datatables.net/js/jquery.dataTables.js"
        ]
      },

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { AdminModule } from './admin/admin.module';
import { AuthModule } from './auth/auth.module';
import { httpInterceptorProviders } from './http-interceptors/index';

@NgModule({
declarations: [
AppComponent,
HeaderComponent
],
imports: [
BrowserModule,
HttpClientModule,
AdminModule,
AuthModule,
AppRoutingModule
],
providers: [httpInterceptorProviders],
bootstrap: [AppComponent]
})
export class AppModule { }

admin.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataTablesModule } from 'angular-datatables';
import { AdminRoutingModule } from './admin-routing.module';
import { AdminDashboardComponent } from './admin-dashboard/admin-
dashboard.component';
import { ManageCategoriesComponent } from './manage-categories/manage-
categories.component';

@NgModule({
declarations: [AdminDashboardComponent,ManageCategoriesComponent,
ManagePagesComponent],
imports: [
CommonModule,
DataTablesModule ,
AdminRoutingModule
]
})
export class AdminModule { }

manage-categories.ts

import { Component, OnInit } from '@angular/core';
import { BlogService } from '../../services/blog.service';
import { Blog } from '../../models/blog';

@Component({
selector: 'app-manage-categories',
templateUrl: './manage-categories.component.html',
styleUrls: ['./manage-categories.component.css']
})
export class ManageCategoriesComponent implements OnInit {

title = 'Manage Blogs';
blogs: Blog;
error: string;
constructor(private blogService: BlogService) { }

ngOnInit() {
this.blogService.getBlogs().subscribe(
  (data: Blog) => this.blogs = data,
  error => this.error = error
);
}
}

manage-categories.html

              #ID
              Image
              Title

              Created At

              Action

              {{blog.id}}

              {{blog.title}}
              {{blog.created_at | date: 'mediumDate'}}

                  Edit
                  Delete

Above is my code ,i have already tries in below link

https://l-lin.github.io/angular-datatables/#/getting-started

it working on static data but it dont work when bind dynamic data in my table,its sorting,pagination and searching filter will not work.

Body:
You have to re-render your table once data gets updated. You can use DataTableDirective for child element and then destroy the table and re-create. I will change your component as -

import { Component, OnInit } from '@angular/core';
import { BlogService } from '../../services/blog.service';
import { Blog } from '../../models/blog';
import { DataTableDirective } from 'angular-datatables';

@Component({
selector: 'app-manage-categories',
templateUrl: './manage-categories.component.html',
styleUrls: ['./manage-categories.component.css']
})
export class ManageCategoriesComponent implements OnInit {
@ViewChild(DataTableDirective)
dtElement: DataTableDirective;
title = 'Manage Blogs';
blogs: Blog;
error: string;
dtTrigger: Subject<any> = new Subject();
dtOptions: any = {};
constructor(private blogService: BlogService) { }

ngOnInit() {
this.blogService.getBlogs().subscribe(
  (data: Blog) => { this.blogs = data; this.rerender(); },
  error => this.error = error
);
}

rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
  // Destroy the table first
  dtInstance.destroy();
  // Call the dtTrigger to rerender again
  this.dtTrigger.next();
});
 }
}

and your template will have datatable tags as -

<div class="box-body">
          <table datatable  [dtOptions]="dtOptions" [dtTrigger]="dtTrigger"
          class="table table-bordered table-hover">
            <thead>
            <tr>
              <th>#ID</th>
              <th>Image</th>
              <th>Title
              </th>
              <th >Created At
              </th>
              <th>Action</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let blog of blogs">
              <td>{{blog.id}}</td>
              <td><img src="{{blog.image}}" class="col-md-3"></td>
              <td>{{blog.title}}</td>
              <td>{{blog.created_at | date: 'mediumDate'}}</td>
              <td class="action">
                  <a href="#" class="btn btn-info btn-sm">Edit</a>
                  <a href="#" class="btn btn-danger btn-sm">Delete</a>
              </td>
          </tr>
  </tbody>
  </table>
  </div>


问:
How to stop DoCmd.OutputTo from printing file?
I have created report in MS Access and an on_click command to save the mentioned report as a PDF on the user's desktop.

The problem is that after running this command not only save PDF version, but also prints it.

I am confused, which part of my code gives command to print whole thing?

```<code>Private Sub Oldsys_atask_isorei_Click()
    'file name
    ReportName = "Report_" & Format(Now, "_yyyy-mm-dd") & ".pdf"
    'path to Users desktop
    DTAddress = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "/"

    'opens report in background (without it OutputTo did not seemed to work)
    DoCmd.OpenReport "rprtOldsys_isorei", acViewNormal, , , acHidden
    'saves report in PDF on Users desktop
    DoCmd.OutputTo acOutputReport, "rprtOldsys_isorei", acFormatPDF, DTAddress & ReportName, True
    'closes opened report
    DoCmd.Close acReport, "rprtOldsys_isorei", acSaveNo
End Sub
</code>```

答:
acViewNormal means print this for a report, that's the default view.

Either use acViewReport (report view) or acViewPreview (print preview) to not print the report.

Body:
I have created report in MS Access and an on_click command to save the mentioned report as a PDF on the user's desktop.

The problem is that after running this command not only save PDF version, but also prints it.

I am confused, which part of my code gives command to print whole thing?

Private Sub Oldsys_atask_isorei_Click()
    'file name
    ReportName = "Report_" & Format(Now, "_yyyy-mm-dd") & ".pdf"
    'path to Users desktop
    DTAddress = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "/"

    'opens report in background (without it OutputTo did not seemed to work)
    DoCmd.OpenReport "rprtOldsys_isorei", acViewNormal, , , acHidden
    'saves report in PDF on Users desktop
    DoCmd.OutputTo acOutputReport, "rprtOldsys_isorei", acFormatPDF, DTAddress & ReportName, True
    'closes opened report
    DoCmd.Close acReport, "rprtOldsys_isorei", acSaveNo
End Sub


问:
Upload image to two different folder locations using Laravel 5.8
This Code save image in only one folder. I want to upload the image at the same time in two different folders,
example
folder-one
and
folder-two

my controler

```<code>protected function validator(array $data)
{
    return Validator::make($data, [

       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',

    ]);
}
protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
            $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

return user::create([

        'photo_jpeg' => $photo_jpeg,

       ]);

}
</code>```

答:
Please make sure these things. if you are going to update file on different location.

The folder must have the writtable permission.

Directory path should be defined absolute and point to correct location.

Now change verify the changes in code as follow.

```<code>$fileName = time() . '.' .$request->file('User_jpeg')->getClientOriginalExtension();

$storageLocation = '../../WEBSITE-FILE/TEAM/USER';  //it should be absolute path of storage location.

$request->file('User_jpeg')
        ->storeAs($storageLocation, $fileName);

$request->file('User_jpeg')
        ->storeAs($storageLocation . '/User_Profile_Image', $fileName);
</code>```

Edits:

As per the requested current status, try this.

```<code>public function store(Request $request) {
    $this->validate($request, [ 'image' => 'required|image|mimes:jpeg,png,jpg|max:2048', ]); $input['image'] = time().'.'.$request->image->getClientOriginalExtension();

    $request->image->move(public_path('folder-a'), $input['image']);

    $fileSrc = public_path('folder-a') . $input['image'];
    $fileDest = public_path('folder-b') . $input['image'];

    \File::copy($fileSrc, $fileDest);

    Service::create($input);

    return back()->with('success',' CREATED SUCCESSFULLY .');
}
</code>```

Body:
This Code save image in only one folder. I want to upload the image at the same time in two different folders,
example
folder-one
and
folder-two

my controler

protected function validator(array $data)
{
    return Validator::make($data, [

       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',

    ]);
}
protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
            $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

return user::create([

        'photo_jpeg' => $photo_jpeg,

       ]);

}

Body:
Please make sure these things. if you are going to update file on different location.

The folder must have the writtable permission.

Directory path should be defined absolute and point to correct location.

Now change verify the changes in code as follow.

$fileName = time() . '.' .$request->file('User_jpeg')->getClientOriginalExtension();

$storageLocation = '../../WEBSITE-FILE/TEAM/USER';  //it should be absolute path of storage location.

$request->file('User_jpeg')
        ->storeAs($storageLocation, $fileName);

$request->file('User_jpeg')
        ->storeAs($storageLocation . '/User_Profile_Image', $fileName);

Edits:

As per the requested current status, try this.

public function store(Request $request) {
    $this->validate($request, [ 'image' => 'required|image|mimes:jpeg,png,jpg|max:2048', ]); $input['image'] = time().'.'.$request->image->getClientOriginalExtension();

    $request->image->move(public_path('folder-a'), $input['image']);

    $fileSrc = public_path('folder-a') . $input['image'];
    $fileDest = public_path('folder-b') . $input['image'];

    \File::copy($fileSrc, $fileDest);

    Service::create($input);

    return back()->with('success',' CREATED SUCCESSFULLY .');
}


问:
Why does tcp::socket::is_open() method return true when connecting a non-existent address?
I connected a non-existent address using tcp::socket::connect method and it returned WSAETIMEDOUT(10060) as expected. But why invoking tcp::socket::is_open() returned 1(true) ? I think it should return 0(false), because of establishing connection failed.

```<code>int main(int argc, char* argv[]) {
    boost::asio::io_context context;
    tcp::socket socket(context);
    /*non-existent address 111.111.111.111:8080*/
    tcp::endpoint endpoint(address::from_string("111.111.111.111"), 8080);
    error_code result_error;
    socket.connect(endpoint, result_error);

    /* error code: WSAETIMEDOUT [10060]
    *  description: established connection failed because connected host has failed to respond
    */
    std::cout << "error code: " << result_error.value()<< result_error.message() << std::endl;

    /*returned 1*/
    std::cout << "is_open returned: "<< socket.is_open() << std::endl;
}
</code>```

I expect the output of is_open to be 0, but the actual output is 1.

答:
The is_open function just check if the socket is "open" (the open function have been successfully called), not if the socket is connected.

In short, is_open checks socket creation status, not socket connection status.

If you see this old SO answer it will tell you that it's impossible to know the connection status, and also gives a workaround (keep the connection status yourself).

Body:
I connected a non-existent address using tcp::socket::connect method and it returned WSAETIMEDOUT(10060) as expected. But why invoking tcp::socket::is_open() returned 1(true) ? I think it should return 0(false), because of establishing connection failed.

int main(int argc, char* argv[]) {
    boost::asio::io_context context;
    tcp::socket socket(context);
    /*non-existent address 111.111.111.111:8080*/
    tcp::endpoint endpoint(address::from_string("111.111.111.111"), 8080);
    error_code result_error;
    socket.connect(endpoint, result_error);

    /* error code: WSAETIMEDOUT [10060]
    *  description: established connection failed because connected host has failed to respond
    */
    std::cout << "error code: " << result_error.value()<< result_error.message() << std::endl;

    /*returned 1*/
    std::cout << "is_open returned: "<< socket.is_open() << std::endl;
}

I expect the output of is_open to be 0, but the actual output is 1.


问:
How to restrict the validation only for some elements
I have an xsd with some elements defined in it, an example given below,

```<code><xs:complexType name="carType">
        <xs:complexContent>
            <xs:extension base="vehicleType">
                <xs:all>
                    <xs:element name="mode">
                        <xs:complexType>
                            <xs:choice>
                                <xs:element name="off"/>
                                <xs:element name="driving"/>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                    <xs:element ref="speed" minOccurs="0"/>
                    <xs:element ref="properties"/>
                </xs:all>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
    <xs:element name="CarA" type="carType" substitutionGroup="vehicleType"/>
<xs:element name="CarB" substitutionGroup="vehicleType"/>
</code>```

I would like to skipe the validation if any xml with elements other than CarA and CarB.

```<code><CarC>
    <myCarType/>
</CarC>
</code>```

Currently i am getting 'cvc-elt.1: Cannot find the declaration of element 'CarC'.'

答:
This depends on the API that you are using to invoke the schema validator. Look for the option "lax validation". If you use the Saxon s9api interface, you can invoke lax validation by setting SchemaValidator.setLax(true). It's quite possible, of course, that your chosen schema processor does not offer this option.

Lax validation means "if the schema contains a declaration of the relevant element, then validate against that declaration; otherwise treat the content as valid.".

Body:
I have an xsd with some elements defined in it, an example given below,

<xs:complexType name="carType">
        <xs:complexContent>
            <xs:extension base="vehicleType">
                <xs:all>
                    <xs:element name="mode">
                        <xs:complexType>
                            <xs:choice>
                                <xs:element name="off"/>
                                <xs:element name="driving"/>
                            </xs:choice>
                        </xs:complexType>
                    </xs:element>
                    <xs:element ref="speed" minOccurs="0"/>
                    <xs:element ref="properties"/>
                </xs:all>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
    <xs:element name="CarA" type="carType" substitutionGroup="vehicleType"/>
<xs:element name="CarB" substitutionGroup="vehicleType"/>

I would like to skipe the validation if any xml with elements other than CarA and CarB.

<CarC>
    <myCarType/>
</CarC>

Currently i am getting 'cvc-elt.1: Cannot find the declaration of element 'CarC'.'