问:
how to send multiple dropdown list value into database
i tried to insert multiple dropdownlist value into one table in the database. But it only send the last entry. Newbies here. Need help

This is my code

```<code> <tr>
    <td><select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>
  </tr>
  <tr>
    <td><select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>
</code>```

As i mention when i run this it only send the second entry into the database. Some suggest me to use an array. but i dont know exactly how.

答:
Get the values of the fields when submit button clicks

```<code>$_POST['subjekSPM'];
$_POST['gred'];
$_POST['subjekSPM'];
</code>```

then you can insert in into database

Body:
i tried to insert multiple dropdownlist value into one table in the database. But it only send the last entry. Newbies here. Need help

This is my code

    <select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select>
    <select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select>

    <select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select>
    <select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select>

As i mention when i run this it only send the second entry into the database. Some suggest me to use an array. but i dont know exactly how.

Body:
Get the values of the fields when submit button clicks

$_POST['subjekSPM'];
$_POST['gred'];
$_POST['subjekSPM'];

then you can insert in into database


来源: stackexchange

问:
Autoplay of YouTube using iframe not working in android and iphones
I am using jquery to load YouTube Video through iframe to reduce the initial page load time. Using this approach – only the video thumbnail is loaded along with the page and the actual player loads when the user hits the play button. But AutoPlay is not working on Android and Iphones though it is perfectly working on desktops using windows. When I googled this problem, it turns out "Chrome and Safari browsers on iPhone and Android only allow playback of HTML5 video when initiated by a user interaction. They block embedded media from automatic playback to prevent unsolicited downloads over cellular networks." I want to autoplay the video. Please help.

Here is my jquery

```<code>document.addEventListener("DOMContentLoaded",
    function() {
        var div, n,
            v = document.getElementsByClassName("youtube-player");
        for (n = 0; n < v.length; n++) {
            div = document.createElement("div");
            div.setAttribute("data-id", v[n].dataset.id);
            div.innerHTML = YouTubeThumb(v[n].dataset.id);
            div.onclick = YouTubeIframe;
            v[n].appendChild(div);
        }
    });

function YouTubeThumb(id) {
    var thumb = '<img src="https://i.ytimg.com/vi/ID/mqdefault.jpg">',
        play = '<div class="play"></div>';
    return thumb.replace("ID", id) + play;
}

function YouTubeIframe() {
    var iframe = document.createElement("iframe");
    var embed = "https://www.youtube.com/embed/ID?autoplay=1";
    iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
    iframe.setAttribute("frameborder", "0");
    iframe.setAttribute("allowfullscreen", "1");
    this.parentNode.replaceChild(iframe, this);
}
</code>```

and the HTML

```<code><div class="youtube-player" data-id="YouTube_Video_ID"></div>
</code>```

答:
try this example:-</p>

```<code>  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an  (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using jquery to load YouTube Video through iframe to reduce the initial page load time. Using this approach – only the video thumbnail is loaded along with the page and the actual player loads when the user hits the play button. But AutoPlay is not working on Android and Iphones though it is perfectly working on desktops using windows. When I googled this problem, it turns out "Chrome and Safari browsers on iPhone and Android only allow playback of HTML5 video when initiated by a user interaction. They block embedded media from automatic playback to prevent unsolicited downloads over cellular networks." I want to autoplay the video. Please help.

Here is my jquery

document.addEventListener("DOMContentLoaded",
    function() {
        var div, n,
            v = document.getElementsByClassName("youtube-player");
        for (n = 0; n < v.length; n++) {
            div = document.createElement("div");
            div.setAttribute("data-id", v[n].dataset.id);
            div.innerHTML = YouTubeThumb(v[n].dataset.id);
            div.onclick = YouTubeIframe;
            v[n].appendChild(div);
        }
    });

function YouTubeThumb(id) {
    var thumb = '',
        play = '

';
    return thumb.replace("ID", id) + play;
}

function YouTubeIframe() {
    var iframe = document.createElement("iframe");
    var embed = "https://www.youtube.com/embed/ID?autoplay=1";
    iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
    iframe.setAttribute("frameborder", "0");
    iframe.setAttribute("allowfullscreen", "1");
    this.parentNode.replaceChild(iframe, this);
}

and the HTML

Body:
try this example:-

  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an  (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }


问:
wordpress update meta not working
hey i am trying to update user meta but its not updating

```<code>  $dobs=$_REQUEST['day'].'_'.$_REQUEST['month'].'_'.$_REQUEST['year'];
  $gender=$_REQUEST['gender'];
  $country=$_REQUEST['country'];
  $state=$_REQUEST['state'];
  $city=$_REQUEST['city'];

  update_user_meta( $user_id, 'date_of_birth', $dobs, true );
  update_user_meta((int) $user_id, 'gender', (int) $gender, true );
  update_user_meta( $user_id, 'country', $country, true );
  update_user_meta( $user_id, 'state', $state, true );
  update_user_meta( $user_id, 'city', $city, true );
</code>```

here i tried typecasting like (int) (string) interesting part is insert working properly don't know if there is an error in DB structure.

答:
You need to remove the 4th param of the update_user_meta

update_user_meta( $user_id, 'date_of_birth', $dobs );

The 4th param is used by wordpress to update only the fields that have a previous value equal with the value of the 4th param

So wordpress is looking for  date_of_birth that has a previous value of true for that user

more info

Title: wordpress update meta not working

Body:
hey i am trying to update user meta but its not updating

  $dobs=$_REQUEST['day'].'_'.$_REQUEST['month'].'_'.$_REQUEST['year'];
  $gender=$_REQUEST['gender'];
  $country=$_REQUEST['country'];
  $state=$_REQUEST['state'];
  $city=$_REQUEST['city'];

  update_user_meta( $user_id, 'date_of_birth', $dobs, true );
  update_user_meta((int) $user_id, 'gender', (int) $gender, true );
  update_user_meta( $user_id, 'country', $country, true );
  update_user_meta( $user_id, 'state', $state, true );
  update_user_meta( $user_id, 'city', $city, true );

here i tried typecasting like (int) (string) interesting part is insert working properly don't know if there is an error in DB structure.


问:
Getting rows inserted with SqlBulkCopy
I am switching some of my Linq to Sql code to use SqlBulkCopy, and problem is I need to do two inserts of multiple thousands of rows into two tables.

The service takes your batch of 10,000 links (imported from sitemap, backlink builders, etc), and chops them into RSS feeds of X per feed for aggregation. Problem is, I already have a table of 32 million rows. If i am doing linq to sql inserts, it takes depending on site traffic anywhere between 5 and 10 mintues to load 10,000 links.

The structure is very basic.

Feeds: Id bigint (PK), Title varchar(1000), Description varchar(1000), Published datetime, Aggregated datetime null, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data]

Items: Id bigint (PK), FeedId bigint (FK), Title varchar(1000), Description varchar(1000), Published datetime, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data], ShortId bigint null [updated after insert to equal Id (used in partitioning)]

FutureItems: Id bigint (PK), FeedId bigint (FK), Title varchar(1000), Description varchar(1000), Published datetime, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data], ShortId bigint null [updated after insert to equal Id (used in partitioning)]

OldItems: Id bigint (PK), FeedId bigint (FK), Title varchar(1000), Description varchar(1000), Published datetime, ShortCode varchar(8) [antiquated, not inserted anymore, but used for legacy data], ShortId bigint null [updated after insert to equal Id (used in partitioning)]

So if you have a feed size of 20, you get 500 inserts into the Feeds table, then 10000 inserted into the Items table, then and update runs to set the ShortId equal to the Id. Once a night, a job runs that separates the data into the other two tables, and shift future items into the Items table.

I read that SqlBulkCopy can do 20 million rows in the matter of mintues, but I can't find any good examples of doing it into multiple tables with a FK Constraint.

Our SQL server is a "monster" especially for this application. It is SQL 2008 R2 Web, Windows 2008 R2 Enterprise, 12GB Ram, Dual 4 core Xeons @ 2.8ghz.

Our web server is a clone without the database service.

The CPU runs about 85% when inserting links, and the database fills the RAM.

If SqlBulkCopy isn't good, any suggestion is welcome, we have paying customers who are getting mad, and I am not a DBA, just a plain-old-programmer.

答:
SqlBulkCopy is indeed faster than ordinary inserts. But is faster as in it can transform a job that runs 1000 inserts per second into one that does 10000/sec. If you can only do  10000 links in 10 minutes, you must be having different problems, something that bulk copy is unlikely to solve.

You need to first investigate why it takes so incredibly long to insert 10000 links. Only after you understand that can you make a call that determines if moving to SqlBulkCopy is a solution. I understand that you are not a DBA, but I'm going to direct you a 'dbaish' white paper for troubleshooting SQL Server performance: Waits and Queues. This is a not a cookie cutter recipe solution, is actually a methodology that will teach you how to identify performance bottlenecks in SQL Server.

And to address your question: how does one use SqlBulkCopy when there are constraints? The more generic question is how does one do bulk insert operations when constraints are in place? For serious volumes one actually disables the constraints, performs the bulk uploads, then enables back the constraints. For more streamlined online operations with minimal downtime (the database is basically 'down' for the period when constraints are disabled) one use a different strategy, namely it pre-loads the data in staging tables, validates it and then switches it in with a partition switch operation, see Transferring Data Efficiently by Using Partition Switching.

ContentLicense: CC BY-SA 2.5

Title: Getting rows inserted with SqlBulkCopy


问:
Deserializing from Json throw exception
I am reading a JSOn text in my application as follow, I replaced the special characters as well..

```<code>    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new StringReader("[{ \"alg\":\"rf\", \"response_variable\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"regressionparam\":{ \"maxIterations\":10, \"objReg\":0.3, \"ntrees\":35, \"nbins\":10, \"maxDepth\":5, \"scoreTreeInterval\":10, \"epochs\":0.0, \"hidden\":[ 200, 200 ], \"sparse\":true, \"activation\":\"Tanh\", \"stopping_metric\":\"AUTO\", \"stopping_tolerance\":0.001, \"max_runtime_secs\":0.0, \"overwrite_with_best_model\":true, \"missing_values_handling\":\"MeanImputation\", \"weight_column\":\"\", \"standardize\":true, \"score_interval\":10, \"ignore_const_cols\":true, \"distribution\":\"AUTO\", \"number_of_similiar_clusters\":1, \"estimate_k\":false, \"family\":\"gaussian\" }, \"aggParam\":{ \"nodeId\":\"d7c3d762-6078-4f98-a5a4-cc164c76fb34\", \"features\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ], \"dataTypeToFeatureMap\":{ \"ANALOG\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ] }, \"predictor\":{ \"fnodeid\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"nodename\":\"PV\", \"sensordata_type\":\"ANALOG\" }, \"starttime\":1491235200000, \"endtime\":1506700800000, \"samplingRate\":10, \"samplingTimePeriod\":\"MINUTE\", \"aggregator\":\"AVG\" }, \"keyspace\":\"vroc\", \"phoenixHost\":\"auper01-01-20-01-0.prod.vroc.com.au:2181:/hbase-unsecure\", \"number_of_features\":1, \"feature_selection\":false, \"model_parameters_optimization\":false, \"training_ratio\":0.5, \"validation_ratio\":0.7, \"ttf_calculation\":false, \"ttf_threshold\":0.0, \"ttf_thershold_greater\":false, \"number_of_lags\":5, \"modelMetadata\":{ \"startedByUser\":\"Livy Demo\", \"userOrganization\":\"Livy Demo\", \"nodeName\":\"VROC.Rishi_trial.Update_test.try1_1\" } }]"));
    ModelParameter modelParam = gson.fromJson(reader, ModelParameter.class);
</code>```

The model parameter class is as follow:

```<code>package au.com.vroc.mdm.model;

import java.io.Serializable;

import com.google.gson.Gson;

/**
 * The Class ModelParameter.
 */
public class ModelParameter implements Serializable {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -8395899340046386755L;

    /** The alg. */
    public String alg = "rf";

    /** The response_variable. */
    public String response_variable = "";

    /** The regressionparam. */
    public RegressionParameter regressionparam = new RegressionParameter();

    /** The agg param. */
    public AggregationParameter aggParam = new AggregationParameter();;

    /** The keyspace. */
    public String keyspace = "vroctest";

    /** The keyspace. */
    public String phoenixHost = null;

    /** The automatic feature selection. */
    public Integer number_of_features =10 ;

    /** Feature selection. */
    public Boolean feature_selection =false ;

    /** The model parameter optimization. */
    public Boolean model_parameters_optimization=false;

    /** Training ratio. */
    public Double training_ratio=0.5;

    /** Validation ratio. */
    public Double validation_ratio=0.7;

    /** TTF calculation. */
    public Boolean ttf_calculation=false;

    /** TTF threshold. */
    public Double ttf_threshold=0.5;

    /** Values greater than TTF threshold become alarms otherwise values below threshold become alarm. */
    public Boolean ttf_thershold_greater=true;

    /** Number of lags. */
    public Integer number_of_lags=1;

    public ModelMetadata modelMetadata;

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return new Gson().toJson(this);
    }
}
</code>```

However, it throws exception like below:

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
        at com.google.gson.Gson.fromJson(Gson.java:803)
        at au.com.vroc.mdm.SparkSubmitModel.main(SparkSubmitModel.java:404)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code>```

I don't know what is wrong with the codes. Is there anything wrong with my model parameter class? I have very nested collections in my model parameter class as well..

答:
As stated by @Udith input text is an array of ModelParameter class so to fix the issue you would need to either remove the [] from beginning and end of the json string or change the reader code as below

```<code>ModelParameter[] modelParams = gson.fromJson(reader, ModelParameter[].class);
</code>```

This will give you array of modelParameters from the input text.

Title: Deserializing from Json throw exception

Body:
I am reading a JSOn text in my application as follow, I replaced the special characters as well..

    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new StringReader("[{ \"alg\":\"rf\", \"response_variable\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"regressionparam\":{ \"maxIterations\":10, \"objReg\":0.3, \"ntrees\":35, \"nbins\":10, \"maxDepth\":5, \"scoreTreeInterval\":10, \"epochs\":0.0, \"hidden\":[ 200, 200 ], \"sparse\":true, \"activation\":\"Tanh\", \"stopping_metric\":\"AUTO\", \"stopping_tolerance\":0.001, \"max_runtime_secs\":0.0, \"overwrite_with_best_model\":true, \"missing_values_handling\":\"MeanImputation\", \"weight_column\":\"\", \"standardize\":true, \"score_interval\":10, \"ignore_const_cols\":true, \"distribution\":\"AUTO\", \"number_of_similiar_clusters\":1, \"estimate_k\":false, \"family\":\"gaussian\" }, \"aggParam\":{ \"nodeId\":\"d7c3d762-6078-4f98-a5a4-cc164c76fb34\", \"features\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ], \"dataTypeToFeatureMap\":{ \"ANALOG\":[ { \"fnodeid\":\"99d63623-1c99-4272-8d59-f836226500a5\", \"nodename\":\"ALM_EN\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"be090fd2-2274-453e-a853-6bad53468b90\", \"nodename\":\"HI_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7b3b9f67-ea86-43ba-9fe5-0ed2d446d700\", \"nodename\":\"LOLO_SP\", \"sensordata_type\":\"ANALOG\" }, { \"fnodeid\":\"7e311fca-28b1-4555-be86-c756c96d8794\", \"nodename\":\"LO_SP\", \"sensordata_type\":\"ANALOG\" } ] }, \"predictor\":{ \"fnodeid\":\"04faa082-b19b-45c1-a0ac-f20794a8ad42\", \"nodename\":\"PV\", \"sensordata_type\":\"ANALOG\" }, \"starttime\":1491235200000, \"endtime\":1506700800000, \"samplingRate\":10, \"samplingTimePeriod\":\"MINUTE\", \"aggregator\":\"AVG\" }, \"keyspace\":\"vroc\", \"phoenixHost\":\"auper01-01-20-01-0.prod.vroc.com.au:2181:/hbase-unsecure\", \"number_of_features\":1, \"feature_selection\":false, \"model_parameters_optimization\":false, \"training_ratio\":0.5, \"validation_ratio\":0.7, \"ttf_calculation\":false, \"ttf_threshold\":0.0, \"ttf_thershold_greater\":false, \"number_of_lags\":5, \"modelMetadata\":{ \"startedByUser\":\"Livy Demo\", \"userOrganization\":\"Livy Demo\", \"nodeName\":\"VROC.Rishi_trial.Update_test.try1_1\" } }]"));
    ModelParameter modelParam = gson.fromJson(reader, ModelParameter.class);

The model parameter class is as follow:

package au.com.vroc.mdm.model;

import java.io.Serializable;

import com.google.gson.Gson;

/**
 * The Class ModelParameter.
 */
public class ModelParameter implements Serializable {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = -8395899340046386755L;

    /** The alg. */
    public String alg = "rf";

    /** The response_variable. */
    public String response_variable = "";

    /** The regressionparam. */
    public RegressionParameter regressionparam = new RegressionParameter();

    /** The agg param. */
    public AggregationParameter aggParam = new AggregationParameter();;

    /** The keyspace. */
    public String keyspace = "vroctest";

    /** The keyspace. */
    public String phoenixHost = null;

    /** The automatic feature selection. */
    public Integer number_of_features =10 ;

    /** Feature selection. */
    public Boolean feature_selection =false ;

    /** The model parameter optimization. */
    public Boolean model_parameters_optimization=false;

    /** Training ratio. */
    public Double training_ratio=0.5;

    /** Validation ratio. */
    public Double validation_ratio=0.7;

    /** TTF calculation. */
    public Boolean ttf_calculation=false;

    /** TTF threshold. */
    public Double ttf_threshold=0.5;

    /** Values greater than TTF threshold become alarms otherwise values below threshold become alarm. */
    public Boolean ttf_thershold_greater=true;

    /** Number of lags. */
    public Integer number_of_lags=1;

    public ModelMetadata modelMetadata;

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return new Gson().toJson(this);
    }
}

However, it throws exception like below:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
        at com.google.gson.Gson.fromJson(Gson.java:803)
        at au.com.vroc.mdm.SparkSubmitModel.main(SparkSubmitModel.java:404)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

I don't know what is wrong with the codes. Is there anything wrong with my model parameter class? I have very nested collections in my model parameter class as well..

Body:
As stated by @Udith input text is an array of ModelParameter class so to fix the issue you would need to either remove the [] from beginning and end of the json string or change the reader code as below

ModelParameter[] modelParams = gson.fromJson(reader, ModelParameter[].class);

This will give you array of modelParameters from the input text.


问:
Unknown column '$data' in 'field list' in codeigniter
Im trying to insert data in my database and this error appears:

Error Number: 1054

Unknown column '$data' in 'field list'

INSERT INTO crud ($data) VALUES ('')

Filename: C:/AppServ/www/parcial/system/database/DB_driver.php

Line Number: 691

This is my form:

```<code> <?php echo form_open('home/save',['class'=>'form-horizontal']); ?>
  <fieldset>

      <label for="exampleInputEmail1">Titulo</label>
    <?php echo form_input(['name'=>'id','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('')]); ?>

      <?php echo form_input(['name'=>'titulo','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('titulo')]); ?>

      <label for="exampleInputEmail1">Resumen</label>
  <?php echo form_input(['name'=>'resumen','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('resumen')]); ?>

      <label for="exampleInputEmail1">Ano</label>
    <?php echo form_input(['name'=>'ano','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('ano')]); ?>

          <label for="exampleInputEmail1">Pais</label>
      <?php echo form_input(['name'=>'pais','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('pais')]); ?>
      <label for="exampleInputEmail1">Protagonista</label>
        <?php echo form_input(['name'=>'progatonista','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('protagonista')]); ?>
  <br>

  <?php echo form_close(); ?>
<?php echo form_submit(['value'=>'Submit', 'class'=>'btn btn-primary']); ?>
</code>```

This is my function to save records:

```<code>  public function save() {

    $data = $this->input->post();
$this->load->model('Crudmodel');
if($this->Crudmodel->saveRecords($data)) {

}
}
</code>```

this is my code to insert:

```<code>public function saveRecords($data) {

  return  $this->db->insert('crud','$data');

}
</code>```

What can i do? please help me

答:
You may try to execute this command:</p>

```<code>return  $this->db->insert('crud',$data);
</code>```

Body:
Im trying to insert data in my database and this error appears:

Error Number: 1054

Unknown column '$data' in 'field list'

INSERT INTO crud ($data) VALUES ('')

Filename: C:/AppServ/www/parcial/system/database/DB_driver.php

Line Number: 691

This is my form:

 <?php echo form_open('home/save',['class'=>'form-horizontal']); ?>
  <fieldset>

      Titulo
    <?php echo form_input(['name'=>'id','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('')]); ?>

      <?php echo form_input(['name'=>'titulo','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('titulo')]); ?>

      Resumen
  <?php echo form_input(['name'=>'resumen','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('resumen')]); ?>

      Ano
    <?php echo form_input(['name'=>'ano','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('ano')]); ?>

          Pais
      <?php echo form_input(['name'=>'pais','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('pais')]); ?>
      Protagonista
        <?php echo form_input(['name'=>'progatonista','class'=>'form-control','placeholder'=>'Titulo', 'value'=>set_value('protagonista')]); ?>

  <?php echo form_close(); ?>
<?php echo form_submit(['value'=>'Submit', 'class'=>'btn btn-primary']); ?>

This is my function to save records:

  public function save() {

    $data = $this->input->post();
$this->load->model('Crudmodel');
if($this->Crudmodel->saveRecords($data)) {

}
}

this is my code to insert:

public function saveRecords($data) {

  return  $this->db->insert('crud','$data');

}

What can i do? please help me

Body:
You may try to execute this command:

return  $this->db->insert('crud',$data);


问:
Getting R printed texts to have color esp. in R markdown knits?
Very simple question: I love writing R notebooks/markdowns, and with something like highlight: tango I can give background color to codes when I knit my notebook to pdfs.

However, I don't know how to give colored backgrounds or colored fonts to printed outputs in R. For example, suppose I have the following chunk.

```<code>```{r, echo = FALSE}
writeLines("Help")
```
</code>```

I'd like to see the word Help to be highlighted, say in red font with gray background. How can I achieve this?

Many thanks in advance.

答:
For PDF output, below are some latex commands to get colored text and shading. (For additional shading options, see this answer at the Tex Stack Exchange site.) However, I'm not sure how to get the output from writeLines shaded. Enclosing the code chunk in a \shaded environment causes an error. Hopefully someone will come along with a solution that works with code chunk output.

```<code>---
output: pdf_document
header-includes:
  - \usepackage{xcolor}
  - \usepackage{framed}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

\colorlet{shadecolor}{gray!10}

\color{red}

```{r}
writeLines("help")
```

\begin{shaded}

Red text with a gray background.

\end{shaded}

Red text.

\color{black}

Black text.

\colorlet{shadecolor}{red!10}

\begin{shaded}

Black text with a red background.

\end{shaded}

\colorlet{shadecolor}{red!90}

\begin{shaded}

Black text with a darker red background.

\end{shaded}
</code>```

And here's the resulting PDF document:

Body:
Very simple question: I love writing R notebooks/markdowns, and with something like highlight: tango I can give background color to codes when I knit my notebook to pdfs.

However, I don't know how to give colored backgrounds or colored fonts to printed outputs in R. For example, suppose I have the following chunk.

```{r, echo = FALSE}
writeLines("Help")
```

I'd like to see the word Help to be highlighted, say in red font with gray background. How can I achieve this?

Many thanks in advance.

Body:
For PDF output, below are some latex commands to get colored text and shading. (For additional shading options, see this answer at the Tex Stack Exchange site.) However, I'm not sure how to get the output from writeLines shaded. Enclosing the code chunk in a \shaded environment causes an error. Hopefully someone will come along with a solution that works with code chunk output.

---
output: pdf_document
header-includes:
  - \usepackage{xcolor}
  - \usepackage{framed}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

\colorlet{shadecolor}{gray!10}

\color{red}

```{r}
writeLines("help")
```

\begin{shaded}

Red text with a gray background.

\end{shaded}

Red text.

\color{black}

Black text.

\colorlet{shadecolor}{red!10}

\begin{shaded}

Black text with a red background.

\end{shaded}

\colorlet{shadecolor}{red!90}

\begin{shaded}

Black text with a darker red background.

\end{shaded}

And here's the resulting PDF document:


问:
What is the difference between .catch and .fail in jQuery?
The short doc for .fail says:

Add handlers to be called when the Deferred object is rejected.

and the short doc for .catch is exactly the same:

Add handlers to be called when the Deferred object is rejected.

Source: http://api.jquery.com/category/deferred-object/

The arguments accepted by the two methods seem to be different, and the doc of
.catch states that .catch is an alias of .then(null, fn)

Are there cases where I should use .fail and others where I should use .catch?

Or ... if I only have one function ... are following commands interchangeable  and they only exist for compatibility/historical reasons?

```<code>a) .fail(fn)

b) .catch(fn)

c) .then(null, fn)
</code>```

I created a jsFiddle:

https://jsfiddle.net/sq3mh9j5/

If there is a difference, could you please provide some examples since I am new to jquery and not yet familiar with all promise terms.

Why does the doc of .catch does not reference the doc of .fail and clarify the difference/similarity?

Edit
I found some notes in the 3.0 release notes that the behavior of .then changed.
https://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/
Nevertheless I am still unsure when to use .fail and when to use .catch.

答:
So I think the major difference is what you get out of each.

A catch allows you to run a single function.

A fail allows you to run a number of functions.

Other than that I concur with your findings. They are very similar.

I added an example code to showcase how fail will run both functions, and the catch will only run the one.

```<code> $.ajax({
            url: "abc"
        }).done(function (data) {

        }).fail(function () {
            alert("a");
        }, function () {
            alert("b");
        })
                .catch(function () {
                    alert("c");
                }, function () {
                    alert("d");
                });
</code>```

If you run this you get 'a','b','c' and then 'd' doesn't run.

I hope this simple example showcases the difference.

ContentLicense: CC BY-SA 4.0

Body:
The short doc for .fail says:

Add handlers to be called when the Deferred object is rejected.

and the short doc for .catch is exactly the same:

Add handlers to be called when the Deferred object is rejected.

Source: http://api.jquery.com/category/deferred-object/

The arguments accepted by the two methods seem to be different, and the doc of
.catch states that .catch is an alias of .then(null, fn)

Are there cases where I should use .fail and others where I should use .catch?

Or ... if I only have one function ... are following commands interchangeable  and they only exist for compatibility/historical reasons?

a) .fail(fn)

b) .catch(fn)

c) .then(null, fn)

I created a jsFiddle:

https://jsfiddle.net/sq3mh9j5/

If there is a difference, could you please provide some examples since I am new to jquery and not yet familiar with all promise terms.

Why does the doc of .catch does not reference the doc of .fail and clarify the difference/similarity?

Edit
I found some notes in the 3.0 release notes that the behavior of .then changed.
https://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/
Nevertheless I am still unsure when to use .fail and when to use .catch.

Body:
So I think the major difference is what you get out of each.

A catch allows you to run a single function.

A fail allows you to run a number of functions.

Other than that I concur with your findings. They are very similar.

I added an example code to showcase how fail will run both functions, and the catch will only run the one.

 $.ajax({
            url: "abc"
        }).done(function (data) {

        }).fail(function () {
            alert("a");
        }, function () {
            alert("b");
        })
                .catch(function () {
                    alert("c");
                }, function () {
                    alert("d");
                });

If you run this you get 'a','b','c' and then 'd' doesn't run.

I hope this simple example showcases the difference.


问:
xhttp.send returning 404 not found but file exist
please look at the picture, I'm calling same function in two page.

when I call function within the page opened without any parameter, status code is 200 and I get result correctly.

but when I call function within the page opened with GET parameter, status code is 404 and I get error "Failed to load resource: the server responded with a status of 404 (Not Found)"

my function is:

```<code>function myajax(method, api, data, callback){

var xhttp = new XMLHttpRequest();

xhttp.open(method, api, true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        callback(this.responseText);
    }
};

xhttp.send(data);
}
</code>```

and call that with:

```<code>myajax("POST", "../wp-content/themes/ad/config.php", "data="+data+"&api="+myapi, myCallBack);
</code>```

答: The reason for this was a lengthy data payload. Whenever the data to be sent is goes beyond the size of packets received in the config.php file, this file will not respond to request and the client receives a response with a 404 header.

Body:
please look at the picture, I'm calling same function in two page.

when I call function within the page opened without any parameter, status code is 200 and I get result correctly.

but when I call function within the page opened with GET parameter, status code is 404 and I get error "Failed to load resource: the server responded with a status of 404 (Not Found)"

my function is:

function myajax(method, api, data, callback){

var xhttp = new XMLHttpRequest();

xhttp.open(method, api, true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        callback(this.responseText);
    }
};

xhttp.send(data);
}

and call that with:

myajax("POST", "../wp-content/themes/ad/config.php", "data="+data+"&api="+myapi, myCallBack);


问:
Convert SQL query to mongo query
I want to convert the following SQL to mongo query:

```<code>SELECT brand_name,
    count(`inventory`) AS totalstock,
    count(if(`inventory`=0, `inventory`, NULL)) as outofstock,
    count(if(`inventory`!=0, `inventory`, NULL)) as availablestock,
    DATE_ADD(stock_updated_at, INTERVAL 318 minute) as stock_updated_at
FROM x group by Brand order by stock_updated_at desc;
</code>```

I want to find stock_updated_at in project without using it on group.

This is my mongoquery

```<code>db.x.aggregate([
    {
        "$group": {
            "_id": { "Brand": "$Brand"},
            "TotalStock": { "$sum": 1 },
            "OutOfStock": { "$sum": ....
       ....
   ....
</code>```

答:
Maybe you can try https://github.com/alonho/pql

PQL stands for Python-Query-Language. PQL translates python expressions to MongoDB queries.

```<code>>>> import pql
>>> pql.find("a > 1 and b == 'foo' or not c.d == False")
{'$or': [{'$and': [{'a': {'$gt': 1}}, {'b': 'foo'}]}, {'$not': {'c.d': False}}]}
</code>```

Title: Convert SQL query to mongo query

Body:
I want to convert the following SQL to mongo query:

SELECT brand_name,
    count(`inventory`) AS totalstock,
    count(if(`inventory`=0, `inventory`, NULL)) as outofstock,
    count(if(`inventory`!=0, `inventory`, NULL)) as availablestock,
    DATE_ADD(stock_updated_at, INTERVAL 318 minute) as stock_updated_at
FROM x group by Brand order by stock_updated_at desc;

I want to find stock_updated_at in project without using it on group.

This is my mongoquery

db.x.aggregate([
    {
        "$group": {
            "_id": { "Brand": "$Brand"},
            "TotalStock": { "$sum": 1 },
            "OutOfStock": { "$sum": ....
       ....
   ....

Body:
Maybe you can try https://github.com/alonho/pql

PQL stands for Python-Query-Language. PQL translates python expressions to MongoDB queries.

>>> import pql
>>> pql.find("a > 1 and b == 'foo' or not c.d == False")
{'$or': [{'$and': [{'a': {'$gt': 1}}, {'b': 'foo'}]}, {'$not': {'c.d': False}}]}


问:
IntelliJ Github Issue
Trying to push a project to github and I'm getting the following Error

```<code>remote: Permission to RedNetty/RedPractice.git denied to JackCDev.
fatal: unable to access 'https://github.com/RedNetty/RedPractice.git/': The requested URL returned error: 403
</code>```

The issue isn't as simple as me going into Settings > Version Control > Github

I've already changed that but its still trying to push via the wrong account.

答:
Check if you have a git **credential helper**active:

```<code>git config credential.helper
</code>```

For instance, on Windows, that would be the Windows Credential Managers.

Open the Windows Credential Store, and see if the first user is registered there: delete that entry, and you will be able to authenticate with the second user.

(Here is an example for BitBucket)

Title: IntelliJ Github Issue

Body:
Trying to push a project to github and I'm getting the following Error

remote: Permission to RedNetty/RedPractice.git denied to JackCDev.
fatal: unable to access 'https://github.com/RedNetty/RedPractice.git/': The requested URL returned error: 403

The issue isn't as simple as me going into Settings > Version Control > Github

I've already changed that but its still trying to push via the wrong account.

Body:
Check if you have a git **credential helper**active:

git config credential.helper

For instance, on Windows, that would be the Windows Credential Managers.

Open the Windows Credential Store, and see if the first user is registered there: delete that entry, and you will be able to authenticate with the second user.

(Here is an example for BitBucket)


问:
how to remove compactbuffer in spark output
below is program i ran in spark shell,but when i save output in HDFS i am getting output with compactbuffer.how to remove compactbuffer in spark output.

Program:

```<code>val a=sc.textFile("/datagen_10.txt")

val b=a.map(p=>(p.split(",")(1),p.split(2))

val c=sc.textFile("/drug.txt")

val d =c.map(p=>(p.split(",")(1),p.split(",")(0)))

val e=b.cogroup(d)

e.saveAsTextfile("/cogroup")
</code>```

Output:

```<code>(avil,(CompactBuffer(Brandon Buckner, Veda Hopkins, Mara Higgins, Sybill

Crosby, Ivan Hale),CompactBuffer(1)))

(metacin,(CompactBuffer(Len Burgess),CompactBuffer(2)))

(paracetamol,(CompactBuffer(Zia Underwood, Austin Mayer, Tyler Rosales, Alika

Gilmore),CompactBuffer(3)))
</code>```

答:
Try like</p>

```<code>rdd1.map(rec => (rec._2._1.mkString(""))) //output will be like Brandon Buckner, Veda Hopkins, Mara Higgins, Sybill Crosby, Ivan Hale
</code>```

Body:
below is program i ran in spark shell,but when i save output in HDFS i am getting output with compactbuffer.how to remove compactbuffer in spark output.

Program:

val a=sc.textFile("/datagen_10.txt")

val b=a.map(p=>(p.split(",")(1),p.split(2))

val c=sc.textFile("/drug.txt")

val d =c.map(p=>(p.split(",")(1),p.split(",")(0)))

val e=b.cogroup(d)

e.saveAsTextfile("/cogroup")

Output:

(avil,(CompactBuffer(Brandon Buckner, Veda Hopkins, Mara Higgins, Sybill

Crosby, Ivan Hale),CompactBuffer(1)))

(metacin,(CompactBuffer(Len Burgess),CompactBuffer(2)))

(paracetamol,(CompactBuffer(Zia Underwood, Austin Mayer, Tyler Rosales, Alika

Gilmore),CompactBuffer(3)))

Body:
Try like

rdd1.map(rec => (rec._2._1.mkString(""))) //output will be like Brandon Buckner, Veda Hopkins, Mara Higgins, Sybill Crosby, Ivan Hale


问:
Autosys Job depends regular expression
I am using the Jobdepends command to get a list of jobs stating with tax_check_d_%
I need files like tax_check_d_job
but it returns
tax_check_djob
tax_check_d_job
tax_check_djob_job

how can i select only tax_check_d_job?

答:
When used in a job filter, the _ (underscore) character is a wildcard that matches exactly one character. This explains why you are seeing the unwanted results coming back -tax_check_d_job_% is essentially the same as tax_check_d_job%.

Unfortunately I don't think there's a way around this - according to the Autosys 4.0 reference guide, the SQL ESCAPE option is not supported for wildcards.

I would suggest adding one more character onto your search criteria to filter out the unwanted results, running the command multiple times if necessary. E.g. run it with tax_check_d_job_a%, tax_check_d_job_b%, ... as necessary.

You could also use some custom code to strip out the results you don't want to see. Depending on your needs, this could be a simple as

```<code>job_depends -d -J tax_check_d_job_% | grep "tax_check_d_job_.*"
</code>```

Title: Autosys Job depends regular expression

Body:
When used in a job filter, the _ (underscore) character is a wildcard that matches exactly one character. This explains why you are seeing the unwanted results coming back -tax_check_d_job_% is essentially the same as tax_check_d_job%.

Unfortunately I don't think there's a way around this - according to the Autosys 4.0 reference guide, the SQL ESCAPE option is not supported for wildcards.

I would suggest adding one more character onto your search criteria to filter out the unwanted results, running the command multiple times if necessary. E.g. run it with tax_check_d_job_a%, tax_check_d_job_b%, ... as necessary.

You could also use some custom code to strip out the results you don't want to see. Depending on your needs, this could be a simple as

job_depends -d -J tax_check_d_job_% | grep "tax_check_d_job_.*"


问:
Best practice for improving type-stability of `hvcat`?
Please take a look at the following MWE:

```<code>julia> function foo()
        # do something
        R = rand(3,3)
        t = rand(3)
        y = [  R   t;
             0 0 0 1]
        # do something
       end
foo (generic function with 1 method)

julia> @code_warntype foo()
Variables:
  #self#::#foo
  R::Array{Float64,2}
  t::Array{Float64,1}

Body:
  begin
      # ..........................
      R::Array{Float64,2} = $(Expr(:invoke, MethodInstance for rand!(::MersenneT
wister, ::Array{Float64,2}, ::Int64, ::Type{Base.Random.CloseOpen}), :(Base.Rand
om.rand!), :(Base.Random.GLOBAL_RNG), SSAValue(4), :((Base.arraylen)(SSAValue(4)
)::Int64), :(Base.Random.CloseOpen))) # line 3:
      # .............................
      t::Array{Float64,1} = $(Expr(:invoke, MethodInstance for rand!(::MersenneT
wister, ::Array{Float64,1}, ::Int64, ::Type{Base.Random.CloseOpen}), :(Base.Rand
om.rand!), :(Base.Random.GLOBAL_RNG), SSAValue(8), :((Base.arraylen)(SSAValue(8)
)::Int64), :(Base.Random.CloseOpen))) # line 4:
      return $(Expr(:invoke, MethodInstance for hvcat(::Tuple{Int64,Int64}, ::Ar
ray{Float64,2}, ::Vararg{Any,N} where N), :(Main.hvcat), (2, 4), :(R), :(t), 0,
0, 0, 1))
  end::Any
</code>```

It shows that hvcat can't infer the type because it needs to know the size of R and t which is not compile time info. My current workaround is to write something like this:

```<code>y = zeros(4,4)
y[1:3,1:3] = R
y[:,4] = [t; 1]
</code>```

But it looks a little bit cumbersome, is there any concise way to do this?

答:
Replacing the scalar parameters with Array typed ones seems to do the trick:

```<code>function foo()
    # do something
    R = rand(3,3)
    t = rand(3)
    y = [  R   t;
      [0 0 0 1]]        # <-- the change is here
    # do something
end
</code>```

The @code_warntype is:

```<code>julia> @code_warntype foo()
Variables:
  #self# <optimized out>
  R::Array{Float64,2}
  t::Array{Float64,1}
  y <optimized out>

Body:
  begin
⋮
⋮
  return SSAValue(0)
end::Array{Float64,2}
</code>```

Body:
Please take a look at the following MWE:

julia> function foo()
        # do something
        R = rand(3,3)
        t = rand(3)
        y = [  R   t;
             0 0 0 1]
        # do something
       end
foo (generic function with 1 method)

julia> @code_warntype foo()
Variables:
  #self#::#foo
  R::Array{Float64,2}
  t::Array{Float64,1}

Body:
  begin
      # ..........................
      R::Array{Float64,2} = $(Expr(:invoke, MethodInstance for rand!(::MersenneT
wister, ::Array{Float64,2}, ::Int64, ::Type{Base.Random.CloseOpen}), :(Base.Rand
om.rand!), :(Base.Random.GLOBAL_RNG), SSAValue(4), :((Base.arraylen)(SSAValue(4)
)::Int64), :(Base.Random.CloseOpen))) # line 3:
      # .............................
      t::Array{Float64,1} = $(Expr(:invoke, MethodInstance for rand!(::MersenneT
wister, ::Array{Float64,1}, ::Int64, ::Type{Base.Random.CloseOpen}), :(Base.Rand
om.rand!), :(Base.Random.GLOBAL_RNG), SSAValue(8), :((Base.arraylen)(SSAValue(8)
)::Int64), :(Base.Random.CloseOpen))) # line 4:
      return $(Expr(:invoke, MethodInstance for hvcat(::Tuple{Int64,Int64}, ::Ar
ray{Float64,2}, ::Vararg{Any,N} where N), :(Main.hvcat), (2, 4), :(R), :(t), 0,
0, 0, 1))
  end::Any

It shows that hvcat can't infer the type because it needs to know the size of R and t which is not compile time info. My current workaround is to write something like this:

y = zeros(4,4)
y[1:3,1:3] = R
y[:,4] = [t; 1]

But it looks a little bit cumbersome, is there any concise way to do this?

Body:
Replacing the scalar parameters with Array typed ones seems to do the trick:

function foo()
    # do something
    R = rand(3,3)
    t = rand(3)
    y = [  R   t;
      [0 0 0 1]]        # <-- the change is here
    # do something
end

The @code_warntype is:

julia> @code_warntype foo()
Variables:
  #self# <optimized out>
  R::Array{Float64,2}
  t::Array{Float64,1}
  y <optimized out>

Body:
  begin
⋮
⋮
  return SSAValue(0)
end::Array{Float64,2}


问:
c++ deep copy constructor
this is my code:

```<code>#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = NULL); // constructor
    String& operator=(String &c){
        size = strlen(c.s);
        s = new char[size+1];
        strcpy(s, c.s);
    }
    ~String() { delete [] s; }// destructor
    void print() { cout << s << endl; }
    void change(const char *); // Function to change
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

void String::change(const char *str)
{
    delete [] s;
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

int main()
{
    String str1("learnc++");
    String str2 = str1;

    str1.print(); // what is printed ?
    str2.print();

    str2.change("learnjava");

    str1.print(); // what is printed now ?
    str2.print();
    return 0;
}
</code>```

it can be compiled, and the result is:

```<code>learnc++
learnc++
learnjava
learnjava
</code>```

in addition to that,there is:

```<code>*** Error in `./code': double free or corruption (fasttop): 0x0000000000f7f010 ***
</code>```

BTY, if I delete "delete [] s;" in String::change,the result just becomes:

```<code>learnc++
learnc++
learnc++
learnjava
</code>```

and no error appers, and why ?
the code is from geek foe feeks, I have changes some strings, and the code can be run in its IDE, but in my ubuntu 14.04, it cannot.

答:
Add a copy constructor.</p>

```<code>String(const String& c){
    size = strlen(c.s);
    s = new char[size+1];
    strcpy(s, c.s);
}
</code>```

Title: c++ deep copy constructor

Body:
this is my code:

#include<iostream>
#include<cstring>
using namespace std;

class String
{
private:
    char *s;
    int size;
public:
    String(const char *str = NULL); // constructor
    String& operator=(String &c){
        size = strlen(c.s);
        s = new char[size+1];
        strcpy(s, c.s);
    }
    ~String() { delete [] s; }// destructor
    void print() { cout << s << endl; }
    void change(const char *); // Function to change
};

String::String(const char *str)
{
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

void String::change(const char *str)
{
    delete [] s;
    size = strlen(str);
    s = new char[size+1];
    strcpy(s, str);
}

int main()
{
    String str1("learnc++");
    String str2 = str1;

    str1.print(); // what is printed ?
    str2.print();

    str2.change("learnjava");

    str1.print(); // what is printed now ?
    str2.print();
    return 0;
}

it can be compiled, and the result is:

learnc++
learnc++
learnjava
learnjava

in addition to that,there is:

*** Error in `./code': double free or corruption (fasttop): 0x0000000000f7f010 ***

BTY, if I delete "delete [] s;" in String::change,the result just becomes:

learnc++
learnc++
learnc++
learnjava

and no error appers, and why ?
the code is from geek foe feeks, I have changes some strings, and the code can be run in its IDE, but in my ubuntu 14.04, it cannot.

Body:
Add a copy constructor.

String(const String& c){
    size = strlen(c.s);
    s = new char[size+1];
    strcpy(s, c.s);
}


问:
How to scroll to bottom in react?
I want to build a chat system and automatically scroll to the bottom when entering the window and when new messages come in. How do you automatically scroll to the bottom of a container in React?</p>

答:
Working Example:

You can use the DOM scrollIntoView method to make a component visible in the view.

For this, while rendering the component just give a reference ID for the DOM element using ref attribute. Then use the method scrollIntoView on componentDidMount life cycle. I am just putting a working sample code for this solution. The following is a component rendering each time a message received. You should write code/methods for rendering this component.

```<code>class ChatMessage extends Component {
    scrollToBottom = (ref) => {
        this.refs[ref].scrollIntoView({ behavior: "smooth" });
    }

    componentDidMount() {
        this.scrollToBottom(this.props.message.MessageId);
    }

    render() {
        return(
            <div ref={this.props.message.MessageId}>
                <div>Message content here...</div>
            </div>
        );
    }
}
</code>```

Here this.props.message.MessageId is the unique ID of the particular chat message passed as props

Title: How to scroll to bottom in react?

Body:
Working Example:

You can use the DOM scrollIntoView method to make a component visible in the view.

For this, while rendering the component just give a reference ID for the DOM element using ref attribute. Then use the method scrollIntoView on componentDidMount life cycle. I am just putting a working sample code for this solution. The following is a component rendering each time a message received. You should write code/methods for rendering this component.

class ChatMessage extends Component {
    scrollToBottom = (ref) => {
        this.refs[ref].scrollIntoView({ behavior: "smooth" });
    }

    componentDidMount() {
        this.scrollToBottom(this.props.message.MessageId);
    }

    render() {
        return(
            <div ref={this.props.message.MessageId}>
                <div>Message content here...</div>
            </div>
        );
    }
}

Here this.props.message.MessageId is the unique ID of the particular chat message passed as props


问:
Export CloudFormation JSON template from GIT repository to AWS
I have a JSON file for CloudFormation in GIT repository, and I would like to push it to AWS and create a stack. Is there a best practice to achieve this task ? </p>

答:
There is no single way of doing it. You can either deploy the template through

AWS Console or AWS cli

If you are looking for continuous deployment then  a cloud-native way would be to use CodePipeline. You can find a walkthrough here

Another approach is to use a build server like jenkins


问:
Using SQLite Triggers to Preserve Tree Order
I have a hierarchical tree stored in a table, with each element having a parentID and an 'order' value, which is the order of elements if the tree were flattened into a list. See the following (simplified):

```<code>CREATE TABLE Section (
    sectionID INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    sOrder INTEGER NOT NULL,
    parentID INTEGER NOT NULL,
    FOREIGN KEY (parentID) REFERENCES Section (sectionID)
);
</code>```

I wrote some triggers to keep this sOrder value accurate.

```<code>CREATE TRIGGER SectionUpdateOrderOnInsert BEFORE INSERT ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateUp BEFORE UPDATE ON Section
WHEN OLD.sOrder < NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder AND sOrder <= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateDown BEFORE UPDATE ON Section
WHEN OLD.sOrder > NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder < OLD.sOrder AND sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnDelete BEFORE DELETE ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder;
END;
</code>```

The triggers work... sometimes. For example:

```<code>INSERT INTO Section VALUES (1, "Part I", 1, 1);
INSERT INTO Section VALUES (2, "Part II", 2, 2);
INSERT INTO Section VALUES (3, "Chapter 1", 3, 1);
INSERT INTO Section VALUES (4, "Chapter 2", 4, 1);
INSERT INTO Section VALUES (5, "Chapter 1.5", 4, 1);
</code>```

works as intended, with the last insert shifting Chapter 2 up to sOrder = 5. But the following doesn't work:

```<code>INSERT INTO Section VALUES (1, "Part I", 1, 1);
INSERT INTO Section VALUES (2, "Part II", 2, 2);
INSERT INTO Section VALUES (3, "Chapter 1", 3, 1);
INSERT INTO Section VALUES (4, "Chapter 2", 4, 1);
INSERT INTO Section VALUES (5, "Chapter 1.5", 3, 1);
</code>```

In this example, Chapter 1 and Chapter 2 retain their original sOrder value. I expect them both to be shifted up to 4 and 5 respectively.

What am I missing? Is it my logic, or something I'm doing wrong with the triggers?

Minimal example:

```<code>DROP TABLE IF EXISTS Section;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnDelete;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnInsert;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnUpdateDown;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnUpdateUp;

CREATE TABLE Section (
    sectionID INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    sOrder INTEGER NOT NULL,
    parentID INTEGER NOT NULL,
    FOREIGN KEY (parentID) REFERENCES Section (sectionID)
);

CREATE TRIGGER SectionUpdateOrderOnInsert BEFORE INSERT ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateUp BEFORE UPDATE ON Section
WHEN OLD.sOrder < NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder AND sOrder <= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateDown BEFORE UPDATE ON Section
WHEN OLD.sOrder > NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder < OLD.sOrder AND sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnDelete BEFORE DELETE ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder;
END;

INSERT INTO Section VALUES (1, "Part I", 1, 1);
INSERT INTO Section VALUES (2, "Part II", 2, 2);
INSERT INTO Section VALUES (3, "Chapter 1", 3, 1);
INSERT INTO Section VALUES (4, "Chapter 2", 4, 1);
INSERT INTO Section VALUES (5, "Chapter 0.5", 3, 1);
</code>```

答:
While I have actually abandoned my tree structure for now (the db was only part of the problem - writing a model and view to actually display and edit it is another ball game entirely), I still need to maintain the order of the elements in the table. I did what CL. suggested, creating a view and using 'instead of' triggers:

```<code>CREATE TABLE Section (
    sectionID INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT NOT NULL,
    sectionOrder INTEGER NOT NULL,
    parentID INTEGER NOT NULL,
    FOREIGN KEY (parentID) REFERENCES Section (sectionID)
);

CREATE VIEW SectionView AS SELECT * FROM Section;

CREATE TRIGGER InsertSection INSTEAD OF INSERT ON SectionView
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder + 1 WHERE sectionOrder >= NEW.sectionOrder;
    INSERT INTO Section VALUES (NEW.sectionID, NEW.name, NEW.description, NEW.sectionOrder, NEW.parentID);
END;

CREATE TRIGGER DeleteSection INSTEAD OF DELETE ON SectionView
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder - 1 WHERE sectionOrder > OLD.sectionOrder;
    DELETE FROM Section WHERE sectionID = OLD.sectionID;
END;

CREATE TRIGGER UpdateSectionUp INSTEAD OF UPDATE ON SectionView
WHEN OLD.sectionOrder < NEW.sectionOrder
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder - 1 WHERE sectionOrder > OLD.sectionOrder AND sectionOrder <= NEW.sectionOrder;
    UPDATE Section SET name = NEW.name, description = NEW.description, sectionOrder = NEW.sectionOrder, parentID = NEW.parentID WHERE sectionID = NEW.sectionID;
END;

CREATE TRIGGER UpdateSectionDown INSTEAD OF UPDATE ON SectionView
WHEN OLD.sectionOrder > NEW.sectionOrder
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder + 1 WHERE sectionOrder < OLD.sectionOrder AND sectionOrder >= NEW.sectionOrder;
    UPDATE Section SET name = NEW.name, description = NEW.description, sectionOrder = NEW.sectionOrder, parentID = NEW.parentID WHERE sectionID = NEW.sectionID;
END;
</code>```

Now, when I want to update the order, I call INSERT, UPDATE, and DELETE on the view, rather than the actual table.

Body:
I have a hierarchical tree stored in a table, with each element having a parentID and an 'order' value, which is the order of elements if the tree were flattened into a list. See the following (simplified):

CREATE TABLE Section (
    sectionID INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    sOrder INTEGER NOT NULL,
    parentID INTEGER NOT NULL,
    FOREIGN KEY (parentID) REFERENCES Section (sectionID)
);

I wrote some triggers to keep this sOrder value accurate.

CREATE TRIGGER SectionUpdateOrderOnInsert BEFORE INSERT ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateUp BEFORE UPDATE ON Section
WHEN OLD.sOrder < NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder AND sOrder <= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateDown BEFORE UPDATE ON Section
WHEN OLD.sOrder > NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder < OLD.sOrder AND sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnDelete BEFORE DELETE ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder;
END;

The triggers work... sometimes. For example:

INSERT INTO Section VALUES (1, "Part I", 1, 1);
INSERT INTO Section VALUES (2, "Part II", 2, 2);
INSERT INTO Section VALUES (3, "Chapter 1", 3, 1);
INSERT INTO Section VALUES (4, "Chapter 2", 4, 1);
INSERT INTO Section VALUES (5, "Chapter 1.5", 4, 1);

works as intended, with the last insert shifting Chapter 2 up to sOrder = 5. But the following doesn't work:

INSERT INTO Section VALUES (1, "Part I", 1, 1);
INSERT INTO Section VALUES (2, "Part II", 2, 2);
INSERT INTO Section VALUES (3, "Chapter 1", 3, 1);
INSERT INTO Section VALUES (4, "Chapter 2", 4, 1);
INSERT INTO Section VALUES (5, "Chapter 1.5", 3, 1);

In this example, Chapter 1 and Chapter 2 retain their original sOrder value. I expect them both to be shifted up to 4 and 5 respectively.

What am I missing? Is it my logic, or something I'm doing wrong with the triggers?

Minimal example:

DROP TABLE IF EXISTS Section;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnDelete;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnInsert;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnUpdateDown;
DROP TRIGGER IF EXISTS SectionUpdateOrderOnUpdateUp;

CREATE TABLE Section (
    sectionID INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    sOrder INTEGER NOT NULL,
    parentID INTEGER NOT NULL,
    FOREIGN KEY (parentID) REFERENCES Section (sectionID)
);

CREATE TRIGGER SectionUpdateOrderOnInsert BEFORE INSERT ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateUp BEFORE UPDATE ON Section
WHEN OLD.sOrder < NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder AND sOrder <= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnUpdateDown BEFORE UPDATE ON Section
WHEN OLD.sOrder > NEW.sOrder
BEGIN
    UPDATE Section SET sOrder = sOrder + 1 WHERE sOrder < OLD.sOrder AND sOrder >= NEW.sOrder;
END;

CREATE TRIGGER SectionUpdateOrderOnDelete BEFORE DELETE ON Section
BEGIN
    UPDATE Section SET sOrder = sOrder - 1 WHERE sOrder > OLD.sOrder;
END;

INSERT INTO Section VALUES (1, "Part I", 1, 1);
INSERT INTO Section VALUES (2, "Part II", 2, 2);
INSERT INTO Section VALUES (3, "Chapter 1", 3, 1);
INSERT INTO Section VALUES (4, "Chapter 2", 4, 1);
INSERT INTO Section VALUES (5, "Chapter 0.5", 3, 1);

Body:
While I have actually abandoned my tree structure for now (the db was only part of the problem - writing a model and view to actually display and edit it is another ball game entirely), I still need to maintain the order of the elements in the table. I did what CL. suggested, creating a view and using 'instead of' triggers:

CREATE TABLE Section (
    sectionID INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    description TEXT NOT NULL,
    sectionOrder INTEGER NOT NULL,
    parentID INTEGER NOT NULL,
    FOREIGN KEY (parentID) REFERENCES Section (sectionID)
);

CREATE VIEW SectionView AS SELECT * FROM Section;

CREATE TRIGGER InsertSection INSTEAD OF INSERT ON SectionView
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder + 1 WHERE sectionOrder >= NEW.sectionOrder;
    INSERT INTO Section VALUES (NEW.sectionID, NEW.name, NEW.description, NEW.sectionOrder, NEW.parentID);
END;

CREATE TRIGGER DeleteSection INSTEAD OF DELETE ON SectionView
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder - 1 WHERE sectionOrder > OLD.sectionOrder;
    DELETE FROM Section WHERE sectionID = OLD.sectionID;
END;

CREATE TRIGGER UpdateSectionUp INSTEAD OF UPDATE ON SectionView
WHEN OLD.sectionOrder < NEW.sectionOrder
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder - 1 WHERE sectionOrder > OLD.sectionOrder AND sectionOrder <= NEW.sectionOrder;
    UPDATE Section SET name = NEW.name, description = NEW.description, sectionOrder = NEW.sectionOrder, parentID = NEW.parentID WHERE sectionID = NEW.sectionID;
END;

CREATE TRIGGER UpdateSectionDown INSTEAD OF UPDATE ON SectionView
WHEN OLD.sectionOrder > NEW.sectionOrder
BEGIN
    UPDATE Section SET sectionOrder = sectionOrder + 1 WHERE sectionOrder < OLD.sectionOrder AND sectionOrder >= NEW.sectionOrder;
    UPDATE Section SET name = NEW.name, description = NEW.description, sectionOrder = NEW.sectionOrder, parentID = NEW.parentID WHERE sectionID = NEW.sectionID;
END;

Now, when I want to update the order, I call INSERT, UPDATE, and DELETE on the view, rather than the actual table.


问:
Angular template validation form
I am working on the form validation. I am using template-driven validation form whose coding is below. Its working fine now but when I try to add #username = "ngModel" and #password = "ngModel" in input to create validation classes it's showing me an error. Please find the error also.

```<code><div class="container">
  <div class="row">
    <div class="centering text-center">
      <div class="login-cont col-md-4 col-md-offset-4 vcenter">
        <form id="login_form" name="login-form" #f="ngForm"  role="form" (ngSubmit)="f.form.valid && login()" novalidate>

          <input id="username" [(ngModel)]="username"  name="username"  required  class="form-control"  type="text"   placeholder="Username" >
<input id="userPassword" class="form-control"  required type="password" name="userPassword" required placeholder="Password" [(ngModel)]="password" >
<button type="submit" class="btn login-btn">Login</button>
</form>
</div>
</div>
</div>
</div>
</code>```

```<code> Cannot assign to a reference or variable!
    at _AstToIrVisitor.visitPropertyWrite (webpack-internal:///../../../compiler/esm5/compiler.js:26226:23)
    at PropertyWrite.visit (webpack-internal:///../../../compiler/esm5/compiler.js:4803:24)
    at convertActionBinding (webpack-internal:///../../../compiler/esm5/compiler.js:25676:45)
    at eval (webpack-internal:///../../../compiler/esm5/compiler.js:28166:22)
    at Array.forEach (<anonymous>)
    at ViewBuilder._createElementHandleEventFn (webpack-internal:///../../../compiler/esm5/compiler.js:28162:18)
    at nodes.(anonymous function) (webpack-internal:///../../../compiler/esm5/compiler.js:27581:27)
    at eval (webpack-internal:///../../../compiler/esm5/compiler.js:28107:22)
    at Array.map (<anonymous>)
    at ViewBuilder._createNodeExpressions (webpack-internal:///../../../compiler/esm5/compiler.js:28106:56)
</code>```

This is what I tried but it gives me an error

```<code>   <input id="username" class="form-control"  type="text" required  name="username" placeholder="Username" [(ngModel)]="username" minlength="4"  #names="ngModel">

          <div *ngIf="names.invalid && (names.dirty || names.touched)"
               class="alert alert-danger">
          </div>
            <div *ngIf="names.errors.required">
              Name is required.
            </div>

            <div *ngIf="names.errors.minlength">
              Name must be at least 4 characters long.
            </div>
</code>```

答:
FormBuilder can help you.

export class MyComp {
  myForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.myForm = fb.group({
      username: ['', [Validator.required]],
      userPassword: ['', [Validator.required]]
    });
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="centering text-center">
      <div class="login-cont col-md-4 col-md-offset-4 vcenter">
        <form [formGroup]="myForm" id="login_form"(submit)="login()">
          <input id="username" class="form-control" type="text" placeholder="Username" >
          <input id="userPassword" class="form-control" type="password" placeholder="Password">
          <button type="submit" class="btn login-btn" [disabled]="myForm.invalid">Login</button>
        </form>
      </div>
    </div>
  </div>
</div></code>```

Title: Angular template validation form

Body:
I am working on the form validation. I am using template-driven validation form whose coding is below. Its working fine now but when I try to add #username = "ngModel" and #password = "ngModel" in input to create validation classes it's showing me an error. Please find the error also.

        <form id="login_form" name="login-form" #f="ngForm"  role="form" (ngSubmit)="f.form.valid && login()" novalidate>

          <input id="username" [(ngModel)]="username"  name="username"  required  class="form-control"  type="text"   placeholder="Username" >
<input id="userPassword" class="form-control"  required type="password" name="userPassword" required placeholder="Password" [(ngModel)]="password" >
<button type="submit" class="btn login-btn">Login</button>
</form>

 Cannot assign to a reference or variable!
    at _AstToIrVisitor.visitPropertyWrite (webpack-internal:///../../../compiler/esm5/compiler.js:26226:23)
    at PropertyWrite.visit (webpack-internal:///../../../compiler/esm5/compiler.js:4803:24)
    at convertActionBinding (webpack-internal:///../../../compiler/esm5/compiler.js:25676:45)
    at eval (webpack-internal:///../../../compiler/esm5/compiler.js:28166:22)
    at Array.forEach (<anonymous>)
    at ViewBuilder._createElementHandleEventFn (webpack-internal:///../../../compiler/esm5/compiler.js:28162:18)
    at nodes.(anonymous function) (webpack-internal:///../../../compiler/esm5/compiler.js:27581:27)
    at eval (webpack-internal:///../../../compiler/esm5/compiler.js:28107:22)
    at Array.map (<anonymous>)
    at ViewBuilder._createNodeExpressions (webpack-internal:///../../../compiler/esm5/compiler.js:28106:56)

This is what I tried but it gives me an error

   <input id="username" class="form-control"  type="text" required  name="username" placeholder="Username" [(ngModel)]="username" minlength="4"  #names="ngModel">

              Name is required.

              Name must be at least 4 characters long.

Body:
FormBuilder can help you.

export class MyComp {
  myForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.myForm = fb.group({
      username: ['', [Validator.required]],
      userPassword: ['', [Validator.required]]
    });
  }

<div class="container">
  <div class="row">
    <div class="centering text-center">
      <div class="login-cont col-md-4 col-md-offset-4 vcenter">
        <form [formGroup]="myForm" id="login_form"(submit)="login()">
          <input id="username" class="form-control" type="text" placeholder="Username" >
          <input id="userPassword" class="form-control" type="password" placeholder="Password">
          <button type="submit" class="btn login-btn" [disabled]="myForm.invalid">Login</button>
        </form>
      </div>
    </div>
  </div>
</div>


问:
Yii-2 how to update a record on basis of id
I want to update my table/model. The scenario is, I have a 'status' column, I want to SET this column to a value then update the model based on the id. I want to do something like update statement.

Update 'table' SET status = 'status value' where id = 'myid'

My action controller look like

```<code>$model = $this->findModel($id);
$ogp_id = $model->id;
$status = $model->status;
</code>```

I have searched for it but couldn't find a solution

Any help would be highly appreciated

答:
Try like this,

```<code>  $model =Table::find($id);
    $model->status = 'Active';
    $model->save();
</code>```

also use Create command can be used directly as follows :

```<code>Yii::$app->db->createCommand("UPDATE table SET status=:status WHERE id=:id")
->bindValue(':id', your_id)
->execute();
</code>```

Body:
I want to update my table/model. The scenario is, I have a 'status' column, I want to SET this column to a value then update the model based on the id. I want to do something like update statement.

Update 'table' SET status = 'status value' where id = 'myid'

My action controller look like

$model = $this->findModel($id);
$ogp_id = $model->id;
$status = $model->status;

I have searched for it but couldn't find a solution

Any help would be highly appreciated

Body:
Try like this,

  $model =Table::find($id);
    $model->status = 'Active';
    $model->save();

also use Create command can be used directly as follows :

Yii::$app->db->createCommand("UPDATE table SET status=:status WHERE id=:id")
->bindValue(':id', your_id)
->execute();


问:
Could not load file or assembly of Microsoft.mshtml error in application
I've created an window application. When i installed it on another PC for testing it gives me following error:

could not load file or assembly 'Miscrosoft.mshtml Version=7.0.3300.0, Culture=neutral..'

Why my set program files are not picking up Microsoft.mshtml.dll from my bin folder.

I gave proper reference and already set copy local property of reference

答: I have set property of my  reference as Embed Interop Types=True and it works on another PC anyway.


问:
How to click at an element by the CSS code using Protractor?
I've been trying to click at the element using CSS Selector but it doesn't work:

```<code><button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view">
         <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i>
</button>
</code>```

I'm trying:

```<code>element.all(by.css('.btn .btn-flat .btn-no-text .btn-kebab-view')).first().click();
</code>```

Protractor gives me error:

Failed: Index out of bound. Trying to access element at index: 0, but
  there are only 0 elements that match locator By(css selector, .btn
  .btn-flat .btn-no-text .btn-kebab-view)

答:
Simply using class name locator:

```<code>by.className('btn btn-flat btn-no-text btn-kebab-view')
</code>```

or you can use XPath:

```<code>//*[@class='btn btn-flat btn-no-text btn-kebab-view']
</code>```

Body:
I've been trying to click at the element using CSS Selector but it doesn't work:

<button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view">

</button>

I'm trying:

element.all(by.css('.btn .btn-flat .btn-no-text .btn-kebab-view')).first().click();

Protractor gives me error:

Failed: Index out of bound. Trying to access element at index: 0, but
  there are only 0 elements that match locator By(css selector, .btn
  .btn-flat .btn-no-text .btn-kebab-view)

Body:
Simply using class name locator:

by.className('btn btn-flat btn-no-text btn-kebab-view')

or you can use XPath:

//*[@class='btn btn-flat btn-no-text btn-kebab-view']


问:
Should a

 list always look like a list for it to be semantically correct?
I like to do my post layouts in the context of a blog like this:

```<code><ul class="layout1">
    <li class="post">..</li>
    <li class="post">..</li>
    ..
</ul>
</code>```

Which pans out to something like:

This allows me to, in my brain say "Okay, this is a LIST OF posts", it just doesn't look like a vertical list:

Concretely, is this an issue in terms of (1) performance and (2) SEO?

答: No, you're fine. This wouldn't be an issue for SEO or performance.</p>

Title: Should a <ul><li> list always look like a list for it to be semantically correct?

Body:
I like to do my post layouts in the context of a blog like this:

..

..

    ..

Which pans out to something like:

This allows me to, in my brain say "Okay, this is a LIST OF posts", it just doesn't look like a vertical list:

Concretely, is this an issue in terms of (1) performance and (2) SEO?


问:
C# how calculate my price in my listbox
I am a beginner and trying to create a simple inventory for our future business :)

How can I do to this problem ?

I want to calculate the price when I click every button to my listbox.

Example:

When I add items and the price is 6 he display to the bottom (Total) 6 and when I add another and the price is 7 is added to 6 so the total will 13 what can I do to this scenario can I use foreach or something or I revise my code ? help guys thank you :)

enter image description here

```<code>private void button4_Click(object sender, EventArgs e)
{
    int sum = 0;
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
        sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

    }
    label7.Text = sum.ToString();
}
</code>```

and I cannot deduct when I void the list of transaction

```<code>private void button6_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1)
    {
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        sum -= Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());
    }
}
</code>```

答:
You are using int sum = 0; inside button click event. Therefore, everytime you click on button, Sum will be set to default 0.

set int sum = 0; as global declaration and then try.

Something like below:

```<code>int sum = 0;
private void button4_Click(object sender, EventArgs e)
    {

        if (listBox1.Items.Count >= 0)
        {
            listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
            sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

        }
        label7.Text = sum.ToString();
    }
</code>```

Title: C# how calculate my price in my listbox

Body:
I am a beginner and trying to create a simple inventory for our future business :)

How can I do to this problem ?

I want to calculate the price when I click every button to my listbox.

Example:

When I add items and the price is 6 he display to the bottom (Total) 6 and when I add another and the price is 7 is added to 6 so the total will 13 what can I do to this scenario can I use foreach or something or I revise my code ? help guys thank you :)

enter image description here

private void button4_Click(object sender, EventArgs e)
{
    int sum = 0;
    if (listBox1.Items.Count >= 0)
    {
        listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
        sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

    }
    label7.Text = sum.ToString();
}

and I cannot deduct when I void the list of transaction

private void button6_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1)
    {
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        sum -= Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());
    }
}

Body:
You are using int sum = 0; inside button click event. Therefore, everytime you click on button, Sum will be set to default 0.

set int sum = 0; as global declaration and then try.

Something like below:

int sum = 0;
private void button4_Click(object sender, EventArgs e)
    {

        if (listBox1.Items.Count >= 0)
        {
            listBox1.Items.Add(dataGridView1.CurrentRow.Cells[0].Value.ToString() + "                 " + dataGridView1.CurrentRow.Cells[1].Value.ToString() + "                                                      " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[2].Value.ToString()) + "                        " + Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString()));
            sum += Convert.ToInt32(dataGridView1.CurrentRow.Cells[3].Value.ToString());

        }
        label7.Text = sum.ToString();
    }


问:
Jenkins Slave Installation as windows service
I'm unable to install Jenkins slave as Windows service and getting the following exception:</p>

```<code>WMI.WmiException:AccessDenied
</code>```

答:
If you facing the access denied issue for install as windows service after installing the jenkins.war.

Just close everything.
- Run command prompt with Admin rights.
- Proceed to your jenkins directory using cd (or just copy paste the path into the command prompt).
- Run the command: java -jar jenkins.war
- wait for jenkins to be up.
- Login into the Jenkins
- Manage Jenkins > Select install as Windows service.
-  This will install it as windows service.

Body:
I'm unable to install Jenkins slave as Windows service and getting the following exception:

WMI.WmiException:AccessDenied


问:
Why can't I see the mongo PID in process state list on mac
I'm using docker. so docker is a process, not a VM. to check this. So  I tried to run 'docker run --name mongo -d mongo', it works fine . then I checked the 'PID' using 'docker top mongo' it return the 'PID' details. then i tried 'ps aux' to see all process states. but I cannot see that mongo 'PID' in the list. why is that. I'm using mac with newest mac os.</p>

答:
You need to docker exec to your mongodb container, running in your XHyve/HyperKit VM.

```<code> docker exec -it <containerID> bash
</code>```

Then you can execute a ps, and see the mongodb pid there.

See as an example (on Mac) this article "How to use MongoDB & NodeJS with Docker".

As Matt adds in the comments:

You can also connect to the vm to see the real pid with

```<code>screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty
</code>```

(as mentioned in "Where is /var/lib/docker on Mac/OS X")

Body:
You need to docker exec to your mongodb container, running in your XHyve/HyperKit VM.

 docker exec -it <containerID> bash

Then you can execute a ps, and see the mongodb pid there.

See as an example (on Mac) this article "How to use MongoDB & NodeJS with Docker".

As Matt adds in the comments:

You can also connect to the vm to see the real pid with

screen ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/tty

(as mentioned in "Where is /var/lib/docker on Mac/OS X")


问:
How to make my if (condition) work only when it's > 768 px?
My script works, however it works only half way, since I'm giving if (condition) and it's working only after refresh the cache on the browser.

My main goal is to make my subheader fixed on desktop version and it should be not fixed on mobile devices

This is my code

```<code>var windowWidth = $(window).width();
if(windowWidth > 768){
    var fixedMenu = $('.subheader-wrapper.row');
    var navOffset = fixedMenu.offset().top;
    $(window).scroll(function () {
        var scrollPos = $(window).scrollTop();
        if(scrollPos > navOffset) {
            fixedMenu.addClass('fixed');
            fixedMenu.addClass('animated fadeIn');
        }
        else {
            fixedMenu.removeClass('fixed');
            fixedMenu.removeClass('animated fadeIn')
        }
        if ( window.location.pathname == '/' ||  window.location.pathname == '/o-kompanii' || window.location.pathname == '/otzyivyi' || window.location.pathname == '/vopros-otvet' ) {
            var infoUs = $('#info-us');
            var infoUsOff = infoUs.offset().top;
            if (scrollPos > infoUsOff - 480) {
                infoUs.find('div:first-child').addClass('animated fadeInLeft');
                infoUs.find('div:nth-child(2)').addClass('animated fadeInUp');
                infoUs.find('div:last-child').addClass('animated fadeInRight');
            }
        }

    });
}
</code>```

答:
it's working only after refresh the cache on the browser.

You are assigning the event handler only when windowWidth > 768 and your code doesn't seem to be responsive to changing windowWidth as well.

Use resize event and put conditions inside the event handlers

```<code>$(window).on( "resize" , function () {
  if ( $(window).width() > 768 )
  {
     //add scroll event now
  }
});
</code>```

Body:
My script works, however it works only half way, since I'm giving if (condition) and it's working only after refresh the cache on the browser.

My main goal is to make my subheader fixed on desktop version and it should be not fixed on mobile devices

This is my code

var windowWidth = $(window).width();
if(windowWidth > 768){
    var fixedMenu = $('.subheader-wrapper.row');
    var navOffset = fixedMenu.offset().top;
    $(window).scroll(function () {
        var scrollPos = $(window).scrollTop();
        if(scrollPos > navOffset) {
            fixedMenu.addClass('fixed');
            fixedMenu.addClass('animated fadeIn');
        }
        else {
            fixedMenu.removeClass('fixed');
            fixedMenu.removeClass('animated fadeIn')
        }
        if ( window.location.pathname == '/' ||  window.location.pathname == '/o-kompanii' || window.location.pathname == '/otzyivyi' || window.location.pathname == '/vopros-otvet' ) {
            var infoUs = $('#info-us');
            var infoUsOff = infoUs.offset().top;
            if (scrollPos > infoUsOff - 480) {
                infoUs.find('div:first-child').addClass('animated fadeInLeft');
                infoUs.find('div:nth-child(2)').addClass('animated fadeInUp');
                infoUs.find('div:last-child').addClass('animated fadeInRight');
            }
        }

    });
}

Body:
it's working only after refresh the cache on the browser.

You are assigning the event handler only when windowWidth > 768 and your code doesn't seem to be responsive to changing windowWidth as well.

Use resize event and put conditions inside the event handlers

$(window).on( "resize" , function () {
  if ( $(window).width() > 768 )
  {
     //add scroll event now
  }
});


问:
How to prevent root of the host OS from accessing content inside a container?
We are new to container technology and are currently evaluating whether it can be used in our new project. One of our key requirements is data security of multi-tenants. i.e. each container contains data that is owned by a particular tenant only. Even we, the server admin of the host servers, should NOT be able to access the content inside a container.

By some googling, we know that root of the host OS can execute command inside a container, for example, by the "docker execute" command. I suppose the command is executed with root privileges?
How to get into a docker container?

We wonder if such kinds of access (not just "docker execute", but also any method to access a container's content by server admin of the host servers) can be blocked/disabled by some security configurations?

答:
For the bash command specifically,
Add the exit command in the end of the .bashrc file. So the user logs in and finally gets kicked out.

You can go through this link for the better understanding of why it is not implemented by default
https://github.com/moby/moby/issues/8664


问:
Pythonic way to loop over dictionary
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

```<code>directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}
</code>```

```<code># My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]
</code>```

Which way is more "Pythonic"? Or is there a better way to approach this?

答:
Your method will get it done... but I don't like reading in the entire file and creating a dataframe just to count the columns.  You could do the same thing by just reading the first line of each file and counting the number of commas.  Notice that I add 1 because there will always be one less comma than there are columns.

```<code>columns = [open(f).readline().count(',') + 1 for _, f in directory.items()]
</code>```

Title: Pythonic way to loop over dictionary

Body:
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}

# My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]

Which way is more "Pythonic"? Or is there a better way to approach this?

Body:
Your method will get it done... but I don't like reading in the entire file and creating a dataframe just to count the columns.  You could do the same thing by just reading the first line of each file and counting the number of commas.  Notice that I add 1 because there will always be one less comma than there are columns.

columns = [open(f).readline().count(',') + 1 for _, f in directory.items()]