问:
PDO were rows affected during execute statement
I have found many ways to use the exec statement for PDO, but I'm not sure it helps me.  My understanding is that I have to use the execute() function for prepared statements.  I am updating a row with data from user input, so I would like to use a prepared statement instead of the query() call.

My code is as follows:

```<code>$dbh = buildDBConnector();
$sql = "UPDATE tb_users
    SET authState=1
    WHERE id = ? AND authPass = ?";
$q = $dbh->prepare($sql);
$f = $q->execute(array($id,$authPass));
if($f){
    echo '<br />Success<br />';
}else{
    echo '<br />Failure<br />';
}
</code>```

The issue is that the query itself is error free and executes fine, so there is no failure to store in $f.  However, I need to know if it actually found the row to update, then successfully updated it.  In other words, I need the affected rows.  When googling and such, it keeps coming to the exec statement, but from my understanding, exec isn't for prepared statements?  Any suggestions?

答:
A side note: when updating a table with identical values rowCount() will return always 0. This is normal behavior. You can change it yourself since PHP 5.3 by creating a PDO object with following attribute:

```<code><? php
$p = new PDO($dsn, $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
?>
</code>```

The rowCount() then will return how many rows your update-query actually found/matched.

Body:
I have found many ways to use the exec statement for PDO, but I'm not sure it helps me.  My understanding is that I have to use the execute() function for prepared statements.  I am updating a row with data from user input, so I would like to use a prepared statement instead of the query() call.

My code is as follows:

$dbh = buildDBConnector();
$sql = "UPDATE tb_users
    SET authState=1
    WHERE id = ? AND authPass = ?";
$q = $dbh->prepare($sql);
$f = $q->execute(array($id,$authPass));
if($f){
    echo '
Success
';
}else{
    echo '
Failure
';
}

The issue is that the query itself is error free and executes fine, so there is no failure to store in $f.  However, I need to know if it actually found the row to update, then successfully updated it.  In other words, I need the affected rows.  When googling and such, it keeps coming to the exec statement, but from my understanding, exec isn't for prepared statements?  Any suggestions?

Body:
A side note: when updating a table with identical values rowCount() will return always 0. This is normal behavior. You can change it yourself since PHP 5.3 by creating a PDO object with following attribute:

<? php
$p = new PDO($dsn, $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
?>

The rowCount() then will return how many rows your update-query actually found/matched.


来源: stackexchange

问:
ALTER TABLE in Magento setup script without using SQL
Jonathon Day says

"updates SHOULD NOT be in the form of
  SQL commands". I haven't come across
  any DDL or DML statments that cannot
  be executed via Magento's config
  structures.

(In the question How can I migrate configuration changes from development to production environment?)

I would like to know how best to add/modify/remove a column or index to/from a table in this manner, but without relying on SQL? Is it even possible?

Furthermore, what other actions can only be done in SQL?

答:
The idea that any Magento updates SHOULD NOT include SQL is based on the idea that

Magento Objects provide abstractions on top of you database/datastore layer

You should use the abstractions to update Magento, which ensures if the Magento team changes how the objects interact with the datastore, your updates will still work (assuming the core team maintains the original "contracts" implied by the Object methods)

So, the problem is an ALTER TABLE statement directly changes the datastore.  If you subscribe exclusively to the above two ideas, you should never be changing the data store. (which, in the case of adding a column or an index means using EAV models exclusively, using the Setup Resources to manage changes, and accepting Magento's indexing).

A good general rule of thumb is, if you're changing or adding onto some core Magento functionality (Products, Reviews, etc.), stay away from directly changing the database structure unless you're willing to carefully manage it during upgrades.

If you're building new objects and functionality use whatever SQL you want to create and change your tables via Setup Resources.  If you look at the installer/upgrade files you can see that the core Magento team does this themselves.

ContentLicense: CC BY-SA 2.5


问:
Global Exception Handler via Class Library - Exposing MyApplication?
I've been trying to write an external class library for my program. This would be to act as an easier-to-implement Global Exception handler. I've taken a look at this question here. I've implemented that myself within my own project's code. My aim, now, is to stick that code in a library which can be instantiated so it can handle the exceptions easily with no hassle whatsoever.

```<code>Private Sub MyApplication_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs) Handles Me.UnhandledException

End Sub
</code>```

The above is the handler in my main form. Now, in a class library, how can I create a handler when New() is called? I've tried adding a parameter such as m As My.MyApplication, however I get this error:

'm' cannot expose type 'MyApplication' outside the project through class 'xxx'.

While I understand this was a long shot, I had no clue whatsoever.

Would anyone be able to guide me along as to how I should approach this?

Kind regards,
Alex.

答:
If you use the AppDomain.UnhandledException event instead you will be able to do so. It's part of the entire .NET Framework and not just Visual Basic.

```<code>Public Sub AppDomain_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs)
    Dim ex As Exception = DirectCast(e.ExceptionObject, Exception)
    'Do your logging of 'ex' here.
End Sub
</code>```

In some other part of your code:

```<code>AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf <some class here>.AppDomain_UnhandledException
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to write an external class library for my program. This would be to act as an easier-to-implement Global Exception handler. I've taken a look at this question here. I've implemented that myself within my own project's code. My aim, now, is to stick that code in a library which can be instantiated so it can handle the exceptions easily with no hassle whatsoever.

Private Sub MyApplication_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs) Handles Me.UnhandledException

End Sub

The above is the handler in my main form. Now, in a class library, how can I create a handler when New() is called? I've tried adding a parameter such as m As My.MyApplication, however I get this error:

'm' cannot expose type 'MyApplication' outside the project through class 'xxx'.

While I understand this was a long shot, I had no clue whatsoever.

Would anyone be able to guide me along as to how I should approach this?

Kind regards,
Alex.

Body:
If you use the AppDomain.UnhandledException event instead you will be able to do so. It's part of the entire .NET Framework and not just Visual Basic.

Public Sub AppDomain_UnhandledException(sender As Object, e As UnhandledExceptionEventArgs)
    Dim ex As Exception = DirectCast(e.ExceptionObject, Exception)
    'Do your logging of 'ex' here.
End Sub

In some other part of your code:

AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf <some class here>.AppDomain_UnhandledException


问:
return observable to the caller function like returning promises
I am currently migrating to angular 2 from angular 1.x. The application currently follows John Papa's style guide Return a Promise from Data Calls.

activate();

function activate() {
    /**
     * Step 1
     * Ask the getAvengers function for the
     * avenger data and wait for the promise
     */
    return getAvengers().then(function() {
        /**
         * Step 4
         * Perform an action on resolve of final promise
         */
        logger.info('Activated Avengers View');
    });
}

function getAvengers() {
      /**
       * Step 2
       * Ask the data service for the data and wait
       * for the promise
       */
      return dataservice.getAvengers()
          .then(function(data) {
              /**
               * Step 3
               * set the data and resolve the promise
               */
              vm.avengers = data;
              return vm.avengers;
      });
}
```

How can I do the same thing with Observables? with promise, i can write .then() in multiple functions and return it so that the caller functions also will wait for the promise. But with observable, What is the correct thing to do?
Where exactly i should subscribe and where i should just map the values and return the observable?

答:
Assume that your function will invoke multiple functions inside it before doing the http request.

```<code>function A() {
  B().subscribe();
}

function B() {
  return C().map();
}

function C() {
  return D().map();
}

function D() {
 // call http reuest and return data
}
</code>```

The caller function will do the actual subscription, and all the other functions that take part will simply map the data.

Coming to your code, you will have to modify this way :

```<code>activate();

    function activate() {
        /**
         * Step 1
         * Ask the getAvengers function for the
         * avenger data and wait for the promise
         */
        return getAvengers().subscribe(
            (data) => {
            // handle your result data
            logger.info('Activated Avengers View');
        });
    }

    function getAvengers() {
          /**
           * Step 2
           * Ask the data service for the data and wait
           * for the promise
           */
          return dataservice.getAvengers()
              .map((data) => {
                  /**
                   * Step 3
                   * set the data and resolve the Observable
                   */
                  vm.avengers = data;
                  return vm.avengers;
          });
    }
</code>```

Body:
I am currently migrating to angular 2 from angular 1.x. The application currently follows John Papa's style guide Return a Promise from Data Calls.

activate();

function activate() {
    /**
     * Step 1
     * Ask the getAvengers function for the
     * avenger data and wait for the promise
     */
    return getAvengers().then(function() {
        /**
         * Step 4
         * Perform an action on resolve of final promise
         */
        logger.info('Activated Avengers View');
    });
}

function getAvengers() {
      /**
       * Step 2
       * Ask the data service for the data and wait
       * for the promise
       */
      return dataservice.getAvengers()
          .then(function(data) {
              /**
               * Step 3
               * set the data and resolve the promise
               */
              vm.avengers = data;
              return vm.avengers;
      });
}

How can I do the same thing with Observables? with promise, i can write .then() in multiple functions and return it so that the caller functions also will wait for the promise. But with observable, What is the correct thing to do?
Where exactly i should subscribe and where i should just map the values and return the observable?

Body:
Assume that your function will invoke multiple functions inside it before doing the http request.

function A() {
  B().subscribe();
}

function B() {
  return C().map();
}

function C() {
  return D().map();
}

function D() {
 // call http reuest and return data
}

The caller function will do the actual subscription, and all the other functions that take part will simply map the data.

Coming to your code, you will have to modify this way :

activate();

    function activate() {
        /**
         * Step 1
         * Ask the getAvengers function for the
         * avenger data and wait for the promise
         */
        return getAvengers().subscribe(
            (data) => {
            // handle your result data
            logger.info('Activated Avengers View');
        });
    }

    function getAvengers() {
          /**
           * Step 2
           * Ask the data service for the data and wait
           * for the promise
           */
          return dataservice.getAvengers()
              .map((data) => {
                  /**
                   * Step 3
                   * set the data and resolve the Observable
                   */
                  vm.avengers = data;
                  return vm.avengers;
          });
    }


问:
Initializing an empty DataFrame and appending rows
Different from creating an empty dataframe and populating rows later , I have many many dataframes that needs to be concatenated.

If there were only two data frames, I can do this:

```<code>df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))

df1.append(df2, ignore_index=True)
</code>```

Imagine I have millions of df that needs to be appended/concatenated each time I read a new file into a DataFrame object.

But when I tried to initialize an empty dataframe and then adding the new dataframes through a loop:

```<code>import pandas as pd
alldf = pd.DataFrame(, columns=list('AB'))
for filename in os.listdir(indir):
    df = pd.read_csv(indir+filename, delimiter=' ')
    alldf.append(df, ignore_index=True)
</code>```

This would return an empty alldf with only the header row, e.g.

```<code>alldf = pd.DataFrame(columns=list('AB'))
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
for df in [df1, df2]:
    alldf.append(df, ignore_index=True)
</code>```

答:
df.concat() over an array of dataframes is probably the way to go, especially for clean CSVs. But in case you suspect your CSVs are either dirty or could get recognized by read_csv() with mixed types between files, you may want to explicity create each dataframe in a loop.

You can initialize a dataframe for the first file, and then each subsequent file start with an empty dataframe based on the first.

```<code>df2 = pd.DataFrame(data=None, columns=df1.columns,index=df1.index)
</code>```

This takes the structure of dataframe df1 but no data, and create df2. If you want to force data type on columns, then you can do it to df1 when it is created, before its structure is copied.

more details

Body:
Different from creating an empty dataframe and populating rows later , I have many many dataframes that needs to be concatenated.

If there were only two data frames, I can do this:

df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))

df1.append(df2, ignore_index=True)

Imagine I have millions of df that needs to be appended/concatenated each time I read a new file into a DataFrame object.

But when I tried to initialize an empty dataframe and then adding the new dataframes through a loop:

import pandas as pd
alldf = pd.DataFrame(, columns=list('AB'))
for filename in os.listdir(indir):
    df = pd.read_csv(indir+filename, delimiter=' ')
    alldf.append(df, ignore_index=True)

This would return an empty alldf with only the header row, e.g.

alldf = pd.DataFrame(columns=list('AB'))
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
for df in [df1, df2]:
    alldf.append(df, ignore_index=True)

Body:
df.concat() over an array of dataframes is probably the way to go, especially for clean CSVs. But in case you suspect your CSVs are either dirty or could get recognized by read_csv() with mixed types between files, you may want to explicity create each dataframe in a loop.

You can initialize a dataframe for the first file, and then each subsequent file start with an empty dataframe based on the first.

df2 = pd.DataFrame(data=None, columns=df1.columns,index=df1.index)

This takes the structure of dataframe df1 but no data, and create df2. If you want to force data type on columns, then you can do it to df1 when it is created, before its structure is copied.

more details


问:
Populate() ref nested in object array
I am trying to populate() all the subscriptions in my User model with data from the Show model. I have tried .populate('subscriptions.show') but it does nothing to the results.

If I make subscriptions a plain array of Refs like so

```<code>subscriptions: [{type: Schema.Types.ObjectId, ref: 'Show'}]
</code>```

doing a populate('subscriptions') works as intended

I have looked at every similar question I could find on Stackoverflow and what I could find on the docs. I can't see what I am doing wrong.

complete test file source that i am working with https://gist.github.com/anonymous/b7b6d6752aabdd1f9b59

Schema and Models

```<code>var userSchema = new Schema({
  email: String,
  displayName: String,
  subscriptions: [{
    show: {type: Schema.Types.ObjectId, ref: 'Show'},
    favorite: {type: Boolean, default: false}
  }]
});

var showSchema = new Schema({
  title: String,
  overview: String,
  subscribers: [{type: Schema.Types.ObjectId, ref: 'User'}],
  episodes: [{
    title: String,
    firstAired: Date
  }]
});

var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);
</code>```

Initial Data

```<code>var user = new User({
  email: "test@test.com",
  displayName: "bill"
});

user.save(function(err, user) {
  var show = new Show({
    title: "Some Show",
    overview: "A show about some stuff."
  });

  show.save();
  user.subscriptions.push(show);
  user.save();
});
</code>```

The Query

```<code>User.findOne({
  displayName: 'bill'
})
  .populate('subscriptions.show')
  .exec(function(err, user) {
    if (err) {
      console.log(err);
    }

    console.log(user);
  });
</code>```

results in:

```<code>{
  _id: 53a7a39d878a965c4de0b7f2,
  email: 'test@test.com',
  displayName: 'bill',
  __v: 1,
  subscriptions: [{
    _id: 53a7a39d878a965c4de0b7f3,
    favorite: false
  }]
}
</code>```

答:
check answer: https://stackoverflow.com/a/28180427/3327857</p>

```<code>  Car   .find()   .populate({
    path: 'partIds',
    model: 'Part',
    populate: {
      path: 'otherIds',
      model: 'Other'
    }
 })
</code>```

Title: Populate() ref nested in object array

Body:
I am trying to populate() all the subscriptions in my User model with data from the Show model. I have tried .populate('subscriptions.show') but it does nothing to the results.

If I make subscriptions a plain array of Refs like so

subscriptions: [{type: Schema.Types.ObjectId, ref: 'Show'}]

doing a populate('subscriptions') works as intended

I have looked at every similar question I could find on Stackoverflow and what I could find on the docs. I can't see what I am doing wrong.

complete test file source that i am working with https://gist.github.com/anonymous/b7b6d6752aabdd1f9b59

Schema and Models

var userSchema = new Schema({
  email: String,
  displayName: String,
  subscriptions: [{
    show: {type: Schema.Types.ObjectId, ref: 'Show'},
    favorite: {type: Boolean, default: false}
  }]
});

var showSchema = new Schema({
  title: String,
  overview: String,
  subscribers: [{type: Schema.Types.ObjectId, ref: 'User'}],
  episodes: [{
    title: String,
    firstAired: Date
  }]
});

var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);

Initial Data

var user = new User({
  email: "test@test.com",
  displayName: "bill"
});

user.save(function(err, user) {
  var show = new Show({
    title: "Some Show",
    overview: "A show about some stuff."
  });

  show.save();
  user.subscriptions.push(show);
  user.save();
});

The Query

User.findOne({
  displayName: 'bill'
})
  .populate('subscriptions.show')
  .exec(function(err, user) {
    if (err) {
      console.log(err);
    }

    console.log(user);
  });

results in:

{
  _id: 53a7a39d878a965c4de0b7f2,
  email: 'test@test.com',
  displayName: 'bill',
  __v: 1,
  subscriptions: [{
    _id: 53a7a39d878a965c4de0b7f3,
    favorite: false
  }]
}

Body:
check answer: https://stackoverflow.com/a/28180427/3327857

  Car   .find()   .populate({
    path: 'partIds',
    model: 'Part',
    populate: {
      path: 'otherIds',
      model: 'Other'
    }
 })


问:
Can't get ImageView to show up on RecyclerView
I am just learning the RecyclerView and cannot figure out why the imageView with         android:id="@+id/im_item_icon" will not show up on the screen. I even have another imageView that works but when I swap the IDs the original not working view works and the working one will not work. So basically the problem must be with the ID but I cannot figure out why. BTW I got the code from a blog "http://wiseassblog.com/tutorials/2016/03/04/how-to-build-a-recyclerview/"

DerpAdapter.java

```<code>public class DerpAdapter extends RecyclerView.Adapter<DerpAdapter.DerpHolder> {

private List<ListItem> listData;
private LayoutInflater inflater;

public DerpAdapter(List<ListItem> listData, Context c){
    inflater = LayoutInflater.from(c);
    this.listData = listData;
}

@Override
public DerpAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.list_item, parent, false);
    return new DerpHolder(view);
}

@Override
public void onBindViewHolder(DerpHolder holder, int position) {
    ListItem item = listData.get(position);
    holder.title.setText(item.getTitle());
    holder.icon.setImageResource(item.getImageResId());
}

@Override
public int getItemCount() {
    return listData.size();
}

class DerpHolder extends RecyclerView.ViewHolder {

    private TextView title;
    private ImageView icon;
    private View container;

    public DerpHolder(View itemView) {
        super(itemView);

        title = (TextView)itemView.findViewById(R.id.lbl_item_text);
        icon = (ImageView)itemView.findViewById(R.id.im_item_icon);
        //We'll need the container later on, when we add an View.OnClickListener
        container = itemView.findViewById(R.id.cont_item_root);
    }
}
</code>```

DerpData.java

```<code>public class DerpData {
private static final String[] titles = {"Nothingness cannot be defined",
        "Time is like a river made up of the events which happen, and a violent stream; " +
                "for as soon as a thing has been seen, it is carried away, and another comes" +
                " in its place, and this will be carried away too,",
        "But when I know that the glass is already broken, every minute with it is precious.",
        "For me, it is far better to grasp the Universe as it really is than to persist in" +
                " delusion, however satisfying and reassuring.",
        "The seeker after the truth is not one who studies the writings of the ancients and," +
                " following his natural disposition, puts his trust in them, but rather the" +
                " one who suspects his faith in them and questions what he gathers from them," +
                " the one who submits to argument and demonstration, and not to the " +
                "sayings of a human being whose nature is fraught with all kinds " +
                "of imperfection and deficiency.",
        "You must take personal responsibility. You cannot change the circumstances, the" +
                " seasons, or the wind, but you can change yourself. That is something you" +
                " have charge of."
};
private static final String[] subTitles = {"Bruce Lee",
        "Marcus Aurelius",
        "Meng Tzu",
        "Ajahn Chah",
        "Carl Sagan",
        "Alhazen",
        "Jim Rohn"

};
private static final int icon = R.drawable.ic_tonality_black_36dp;

public static List <ListItem> getListData() {
    List <ListItem> data = new ArrayList <>();

    //Repeat process 4 times, so that we have enough data to demonstrate a scrollable
    //RecyclerView
    for (int x = 0; x  < 4; x++) {
        //create ListItem with dummy data, then add them to our List
        for (int i = 0; i  < titles.length; i++) {
            ListItem item = new ListItem();
            item.setTitle(titles[i]);
            item.setSubTitle(subTitles[i]);
            data.add(item);
        }
    }
    return data;
}
</code>```

ListItem.java

```<code>public class ListItem {
private int imageResId;
private String subTitle;
private String title;
private boolean favourite = false;

public String getSubTitle() {
    return subTitle;
}

public void setSubTitle(String subTitle) {
    this.subTitle = subTitle;
}

public boolean isFavourite() {
    return favourite;
}

public void setFavourite(boolean favourite) {
    this.favourite = favourite;
}

public int getImageResId() {
    return imageResId;
}

public void setImageResId(int imageResId) {
    this.imageResId = imageResId;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}
</code>```

DetailActivity.java

```<code>public class DetailActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
}
</code>```

ListActivity.java

```<code>public class ListActivity extends AppCompatActivity {

private RecyclerView recView;
private DerpAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    recView = (RecyclerView)findViewById(R.id.rec_list);
    //Check out GridLayoutManager and StaggeredGridLayoutManager for more options
    recView.setLayoutManager(new LinearLayoutManager(this));

    adapter = new DerpAdapter(DerpData.getListData(), this);
    recView.setAdapter(adapter);
}
</code>```

activity_detail.xml

```<code>android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="application.binarysoup.jsonpractice.ui.DetailActivity">

<TextView
    android:id="@+id/lbl_quote_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fontFamily="sans-serif-medium" />

<TextView
    android:id="@+id/lbl_quote_attribution"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/lbl_quote_text"
    android:fontFamily="sans-serif-light"
    android:textStyle="italic" />
</code>```

activity_list.xml

```<code>xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="application.binarysoup.jsonpractice.ui.ListActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">

<android.support.v7.widget.RecyclerView
    android:id="@+id/rec_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

list_item.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cont_item_root"
android:layout_width="match_parent"
android:layout_height="72dp"
android:background="@drawable/background_state_drawable"
android:clickable="true"
>

<ImageView
    android:id="@+id/im_item_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:paddingLeft="16dp"
    android:src="@drawable/ic_tonality_black_36dp" />

<TextView
    android:id="@+id/lbl_item_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/im_item_icon"
    android:layout_marginLeft="72dp"
    android:layout_marginRight="48dp"
    android:ellipsize="end"
    android:fontFamily="sans-serif"
    android:singleLine="true"
    android:text="Sois comme l'eau mon ami"
    android:textColor="@android:color/black"
    android:textSize="16sp" />

<TextView
    android:id="@+id/lbl_item_sub_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/lbl_item_text"
    android:layout_marginLeft="72dp"
    android:layout_marginRight="48dp"
    android:ellipsize="end"
    android:fontFamily="sans-serif"
    android:singleLine="true"
    android:text="Mononc' J"
    android:textSize="14sp" />

<ImageView
    android:id="@+id/im_item_icon_secondary"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:clickable="true"
    android:padding="16dp"
    android:src="@drawable/ic_star_border_black_24dp"
    android:background="@drawable/background_state_drawable"
    />
</code>```

答:
Can't get ImageView to show up on RecyclerView

You have to initialize imageResId in order to appear it in the recyclerView

```<code> for (int i = 0; i  < titles.length; i++) {
            ListItem item = new ListItem();
            item.setTitle(titles[i]);
            item.setSubTitle(subTitles[i]);
//put the code to initialise the imageResId here
            data.add(item);
        }
</code>```

Body:
I am just learning the RecyclerView and cannot figure out why the imageView with         android:id="@+id/im_item_icon" will not show up on the screen. I even have another imageView that works but when I swap the IDs the original not working view works and the working one will not work. So basically the problem must be with the ID but I cannot figure out why. BTW I got the code from a blog "http://wiseassblog.com/tutorials/2016/03/04/how-to-build-a-recyclerview/"

DerpAdapter.java

public class DerpAdapter extends RecyclerView.Adapter<DerpAdapter.DerpHolder> {

private List<ListItem> listData;
private LayoutInflater inflater;

public DerpAdapter(List<ListItem> listData, Context c){
    inflater = LayoutInflater.from(c);
    this.listData = listData;
}

@Override
public DerpAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.list_item, parent, false);
    return new DerpHolder(view);
}

@Override
public void onBindViewHolder(DerpHolder holder, int position) {
    ListItem item = listData.get(position);
    holder.title.setText(item.getTitle());
    holder.icon.setImageResource(item.getImageResId());
}

@Override
public int getItemCount() {
    return listData.size();
}

class DerpHolder extends RecyclerView.ViewHolder {

    private TextView title;
    private ImageView icon;
    private View container;

    public DerpHolder(View itemView) {
        super(itemView);

        title = (TextView)itemView.findViewById(R.id.lbl_item_text);
        icon = (ImageView)itemView.findViewById(R.id.im_item_icon);
        //We'll need the container later on, when we add an View.OnClickListener
        container = itemView.findViewById(R.id.cont_item_root);
    }
}

DerpData.java

public class DerpData {
private static final String[] titles = {"Nothingness cannot be defined",
        "Time is like a river made up of the events which happen, and a violent stream; " +
                "for as soon as a thing has been seen, it is carried away, and another comes" +
                " in its place, and this will be carried away too,",
        "But when I know that the glass is already broken, every minute with it is precious.",
        "For me, it is far better to grasp the Universe as it really is than to persist in" +
                " delusion, however satisfying and reassuring.",
        "The seeker after the truth is not one who studies the writings of the ancients and," +
                " following his natural disposition, puts his trust in them, but rather the" +
                " one who suspects his faith in them and questions what he gathers from them," +
                " the one who submits to argument and demonstration, and not to the " +
                "sayings of a human being whose nature is fraught with all kinds " +
                "of imperfection and deficiency.",
        "You must take personal responsibility. You cannot change the circumstances, the" +
                " seasons, or the wind, but you can change yourself. That is something you" +
                " have charge of."
};
private static final String[] subTitles = {"Bruce Lee",
        "Marcus Aurelius",
        "Meng Tzu",
        "Ajahn Chah",
        "Carl Sagan",
        "Alhazen",
        "Jim Rohn"

};
private static final int icon = R.drawable.ic_tonality_black_36dp;

public static List <ListItem> getListData() {
    List <ListItem> data = new ArrayList <>();

    //Repeat process 4 times, so that we have enough data to demonstrate a scrollable
    //RecyclerView
    for (int x = 0; x  < 4; x++) {
        //create ListItem with dummy data, then add them to our List
        for (int i = 0; i  < titles.length; i++) {
            ListItem item = new ListItem();
            item.setTitle(titles[i]);
            item.setSubTitle(subTitles[i]);
            data.add(item);
        }
    }
    return data;
}

ListItem.java

public class ListItem {
private int imageResId;
private String subTitle;
private String title;
private boolean favourite = false;

public String getSubTitle() {
    return subTitle;
}

public void setSubTitle(String subTitle) {
    this.subTitle = subTitle;
}

public boolean isFavourite() {
    return favourite;
}

public void setFavourite(boolean favourite) {
    this.favourite = favourite;
}

public int getImageResId() {
    return imageResId;
}

public void setImageResId(int imageResId) {
    this.imageResId = imageResId;
}

public String getTitle() {
    return title;
}

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

DetailActivity.java

public class DetailActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
}

ListActivity.java

public class ListActivity extends AppCompatActivity {

private RecyclerView recView;
private DerpAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    recView = (RecyclerView)findViewById(R.id.rec_list);
    //Check out GridLayoutManager and StaggeredGridLayoutManager for more options
    recView.setLayoutManager(new LinearLayoutManager(this));

    adapter = new DerpAdapter(DerpData.getListData(), this);
    recView.setAdapter(adapter);
}

activity_detail.xml

android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="application.binarysoup.jsonpractice.ui.DetailActivity">

<TextView
    android:id="@+id/lbl_quote_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fontFamily="sans-serif-medium" />

<TextView
    android:id="@+id/lbl_quote_attribution"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/lbl_quote_text"
    android:fontFamily="sans-serif-light"
    android:textStyle="italic" />

activity_list.xml

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="application.binarysoup.jsonpractice.ui.ListActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="81dp">

<android.support.v7.widget.RecyclerView
    android:id="@+id/rec_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

list_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cont_item_root"
android:layout_width="match_parent"
android:layout_height="72dp"
android:background="@drawable/background_state_drawable"
android:clickable="true"
>

<ImageView
    android:id="@+id/im_item_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:paddingLeft="16dp"
    android:src="@drawable/ic_tonality_black_36dp" />

<TextView
    android:id="@+id/lbl_item_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/im_item_icon"
    android:layout_marginLeft="72dp"
    android:layout_marginRight="48dp"
    android:ellipsize="end"
    android:fontFamily="sans-serif"
    android:singleLine="true"
    android:text="Sois comme l'eau mon ami"
    android:textColor="@android:color/black"
    android:textSize="16sp" />

<TextView
    android:id="@+id/lbl_item_sub_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/lbl_item_text"
    android:layout_marginLeft="72dp"
    android:layout_marginRight="48dp"
    android:ellipsize="end"
    android:fontFamily="sans-serif"
    android:singleLine="true"
    android:text="Mononc' J"
    android:textSize="14sp" />

<ImageView
    android:id="@+id/im_item_icon_secondary"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:clickable="true"
    android:padding="16dp"
    android:src="@drawable/ic_star_border_black_24dp"
    android:background="@drawable/background_state_drawable"
    />

Body:
Can't get ImageView to show up on RecyclerView

You have to initialize imageResId in order to appear it in the recyclerView

 for (int i = 0; i  < titles.length; i++) {
            ListItem item = new ListItem();
            item.setTitle(titles[i]);
            item.setSubTitle(subTitles[i]);
//put the code to initialise the imageResId here
            data.add(item);
        }


问:
Using a view from Storyboard to use its frame for another view that is set programatically
I have a view that I must set programatically, I name it progView.
I want to have its frame defined intuitively in storyboard. I thought of a work around - I will use a plain view, that I name storyView, I make an outlet to the ViewController and do something like this:

```<code>@IBOutlet weak var storyView: UIView!
</code>```

and in viewDidLoad:

```<code>let progView = ProgView(frame: storyView.frame)
</code>```

This results in progView not fitting the storyView.
I tried this as well:

```<code>let progView = ProgView(frame: storyView.bounds)
</code>```

But that results worse.
Is there a way to easily fit a view to be exactly like another view?

Please tell in the comments if my question misses information and I will try my best to add it.

答:
you should try calling let progView = ProgView(frame: storyView.frame) inside viewDidLayoutSubviews, because inside viewDidLoad the view is not layouted yet

```<code>private var didLayoutSubview = false //to call this once, because theoretically viewDidLayoutSubviews can be called multiple times
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if !self.didLayoutSubiviews {
        self.didLayoutSubiviews = true
        let progView = ProgView(frame: storyView.frame)
    }
}
</code>```

Body:
I have a view that I must set programatically, I name it progView.
I want to have its frame defined intuitively in storyboard. I thought of a work around - I will use a plain view, that I name storyView, I make an outlet to the ViewController and do something like this:

@IBOutlet weak var storyView: UIView!

and in viewDidLoad:

let progView = ProgView(frame: storyView.frame)

This results in progView not fitting the storyView.
I tried this as well:

let progView = ProgView(frame: storyView.bounds)

But that results worse.
Is there a way to easily fit a view to be exactly like another view?

Please tell in the comments if my question misses information and I will try my best to add it.

Body:
you should try calling let progView = ProgView(frame: storyView.frame) inside viewDidLayoutSubviews, because inside viewDidLoad the view is not layouted yet

private var didLayoutSubview = false //to call this once, because theoretically viewDidLayoutSubviews can be called multiple times
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if !self.didLayoutSubiviews {
        self.didLayoutSubiviews = true
        let progView = ProgView(frame: storyView.frame)
    }
}


问:
What type of application that allowed to auto-start in iPhone?
i wonder what type of application that are allowed to be started in the background/foreground when the iPhone boot , and are they limited to iOS 4 ? </p>

答: Simple answer: None are allowed to.</p>

Body: Simple answer: None are allowed to.


问:
Keras to build a CNN with variable input size
I would like to build a CNN from the following diagram

I presume that each time the sentence can have various lengths and it is still possible to build it.

The below is a something I found on the web but kind of got lost

```<code>ngram_filters = [2, 3, 4]
conv_filters = []

for n_gram in ngram_filters:
    conv_filters.append(Sequential())
    conv_filters[-1].add(Conv2D(1, 1, n_gram, 5))
    conv_filters[-1].add(MaxPooling2D(poolsize=(nb_tokens - n_gram + 1, 1)))
    conv_filters[-1].add(Flatten())

model = Sequential()
model.add(Merge(conv_filters, mode='concat'))
</code>```

The picture comes from the following blog - http://www.wildml.com/2015/11/understanding-convolutional-neural-networks-for-nlp/

答:
You don't need to use a variable input size, you just need to pad your input with zeros (make sure to mask these zeros). You can define your input size as a really big one and just pad the difference between each sentence length and the input size.

There is a built function in Keras', you can find it in Sequence Preprocessing and the function is "pad_sequences". Make sure your model is aware of the padding value by masking these values using the Masking class.

You can see an example of the implementation here.

Body:
I would like to build a CNN from the following diagram

I presume that each time the sentence can have various lengths and it is still possible to build it.

The below is a something I found on the web but kind of got lost

ngram_filters = [2, 3, 4]
conv_filters = []

for n_gram in ngram_filters:
    conv_filters.append(Sequential())
    conv_filters[-1].add(Conv2D(1, 1, n_gram, 5))
    conv_filters[-1].add(MaxPooling2D(poolsize=(nb_tokens - n_gram + 1, 1)))
    conv_filters[-1].add(Flatten())

model = Sequential()
model.add(Merge(conv_filters, mode='concat'))

The picture comes from the following blog - http://www.wildml.com/2015/11/understanding-convolutional-neural-networks-for-nlp/


问:
Javascript swap array elements
Is there any simpler way to swap two elements in an array?</p>

```<code>var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
</code>```

答:
Just for the fun of it, another way without using any extra variable would be:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// swap index 0 and 2
arr[arr.length] = arr[0];   // copy idx1 to the end of the array
arr[0] = arr[2];            // copy idx2 to idx1
arr[2] = arr[arr.length-1]; // copy idx1 to idx2
arr.length--;               // remove idx1 (was added to the end of the array)

console.log( arr ); // -> [3, 2, 1, 4, 5, 6, 7, 8, 9]```

Title: Javascript swap array elements

Body:
Is there any simpler way to swap two elements in an array?

var a = list[x], b = list[y];
list[y] = a;
list[x] = b;


问:
Convert string to int and test success in C#
How can you check whether a string is convertible to an int?

Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the string or use the parsed int value instead.

In JavaScript we had this parseInt() function. If the string couldn't be parsed, it would get back NaN.

答:
found this in one of the search results: How do I identify if a string is a number?

Adding this because the answers i saw before did not have usage:

```<code>int n;
bool isNumeric = int.TryParse("123", out n);
</code>```

here "123" can be something like string s = "123" that the OP is testing and the value n will have a value (123) after the call if it is found to be numeric.

OwnerDisplayName: Jeremy Rudd

LastEditorDisplayName: recursive

Body:
found this in one of the search results: How do I identify if a string is a number?

Adding this because the answers i saw before did not have usage:

int n;
bool isNumeric = int.TryParse("123", out n);

here "123" can be something like string s = "123" that the OP is testing and the value n will have a value (123) after the call if it is found to be numeric.


问:
Form backing bean is not retaining already set property values
i am using a form backing bean like this.

```<code>public class BeanData implements Serializable{

    private String param1;
    private String param2;
    private String param3;
    private String param4="india";

    getters setters
}
</code>```

then sending bean object in model as below-

```<code>@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView getPage(HttpSession session, ModelAndView modelAndView) {

        BeanData formBean = new BeanData();
        formBean.setParam2("123456"); // this param2 doens't have any field in JSP
        modelAndView.addObject("formBean", formBean);
        modelAndView.setViewName(PAGE);

        return modelAndView;
    }
@RequestMapping(value=submitData, headers="Accept=*/*", method={RequestMethod.POST})
    public void submitData(@Valid @ModelAttribute("formBean") BeanData formBean, BindingResult result, HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView, HttpSession session) {

        LOGGER.info("param1:"+formBean.getParam1()); // Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info(" param2:"+formBean.getParam2()); // It has not been used in JSP. Though from controller it was populated before sending the bean to the jsp. but here the value is null . This is the concern
        LOGGER.info("param3:"+formBean.getParam3());// Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info("param4:"+formBean.getParam4());//thsi field also has not been used in JSP. But this property was set in bean instantiation. It is also getting retrieved successfully.

        modelAndView.setViewName(SUCCESS PAGE);

    }
</code>```

My concern is, i want to set one bean property using setter method and want to pass the bean backing object to JSP. Then all the property values should be bind(what i explicitly bind using form filed path attribute and what i have already set while created the bean object) to the backing object and it should get received in controller. Please guide me where i am doing wrong.

答:
If you want to just hold the value of param2 field in JSP and get it back on form submit, you can bind it using the hidden field just like below:

```<code><form:hidden path="formBean.param2"/>
</code>```

It will not be displayed in your JSP yet it will hold your value as is.

Another way would be to store your BeanData into session.

Body:
i am using a form backing bean like this.

public class BeanData implements Serializable{

    private String param1;
    private String param2;
    private String param3;
    private String param4="india";

    getters setters
}

then sending bean object in model as below-

@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView getPage(HttpSession session, ModelAndView modelAndView) {

        BeanData formBean = new BeanData();
        formBean.setParam2("123456"); // this param2 doens't have any field in JSP
        modelAndView.addObject("formBean", formBean);
        modelAndView.setViewName(PAGE);

        return modelAndView;
    }
@RequestMapping(value=submitData, headers="Accept=*/*", method={RequestMethod.POST})
    public void submitData(@Valid @ModelAttribute("formBean") BeanData formBean, BindingResult result, HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView, HttpSession session) {

        LOGGER.info("param1:"+formBean.getParam1()); // Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info(" param2:"+formBean.getParam2()); // It has not been used in JSP. Though from controller it was populated before sending the bean to the jsp. but here the value is null . This is the concern
        LOGGER.info("param3:"+formBean.getParam3());// Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info("param4:"+formBean.getParam4());//thsi field also has not been used in JSP. But this property was set in bean instantiation. It is also getting retrieved successfully.

        modelAndView.setViewName(SUCCESS PAGE);

    }

My concern is, i want to set one bean property using setter method and want to pass the bean backing object to JSP. Then all the property values should be bind(what i explicitly bind using form filed path attribute and what i have already set while created the bean object) to the backing object and it should get received in controller. Please guide me where i am doing wrong.

Body:
If you want to just hold the value of param2 field in JSP and get it back on form submit, you can bind it using the hidden field just like below:

<form:hidden path="formBean.param2"/>

It will not be displayed in your JSP yet it will hold your value as is.

Another way would be to store your BeanData into session.


问:
"Default Activity Not Found" in WallpaperService
I want to use a gif image as wallpaper in Android and I'm facing some problem.
I have the following error: "Default Activity Not Found". There is no error in the project, but when I run it, I got this error on Android Studio.

```<code>public class GIFWallpaperService extends WallpaperService {

    @Override
    public WallpaperService.Engine onCreateEngine() {
        try {
            Movie movie = Movie.decodeStream(
                    getResources().getAssets().open("girl.gif"));

            return new GIFWallpaperEngine(movie);
        }catch(IOException e){
            Log.d("GIF", "Could not load asset");
            return null;
        }
    }

    private class GIFWallpaperEngine extends WallpaperService.Engine {

        private final int frameDuration = 20;

        private SurfaceHolder holder;
        private Movie movie;
        private boolean visible;
        private Handler handler;

        public GIFWallpaperEngine(Movie movie) {
            this.movie = movie;
            handler = new Handler();
        }

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            this.holder = surfaceHolder;
        }

        private Runnable drawGIF = new Runnable() {
            public void run() {
                draw();
            }
        };

        private void draw() {
            if (visible) {
                Canvas canvas = holder.lockCanvas();
                canvas.save();
                    // Adjust size and position so that
                    // the image looks good on your screen
                    canvas.scale(3f, 3f);
                    movie.draw(canvas, -100, 0);
                canvas.restore();
                holder.unlockCanvasAndPost(canvas);
                movie.setTime((int) (System.currentTimeMillis() % movie.duration()));

                handler.removeCallbacks(drawGIF);
                handler.postDelayed(drawGIF, frameDuration);
            }
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            this.visible = visible;
            if (visible) {
                handler.post(drawGIF);
            } else {
                handler.removeCallbacks(drawGIF);
            }
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            handler.removeCallbacks(drawGIF);
        }
    }
}
</code>```

This is my manifest:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hathy.gifwallpaper">

    <application android:allowBackup="true" android:label="@string/app_name"
        android:icon="@drawable/ic_launcher" android:theme="@style/AppTheme">

        <service
            android:name=".GIFWallpaperService"
            android:enabled="true"
            android:label="GIF Wallpaper"
            android:permission="android.permission.BIND_WALLPAPER" >
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService"/>

            </intent-filter>
            <meta-data
                android:name="android.service.wallpaper"
                android:resource="@xml/wallpaper" >
            </meta-data>
        </service>

    </application>

    <uses-feature
        android:name="android.software.live_wallpaper"
        android:required="true" >
    </uses-feature>
</manifest>
</code>```

答:
Run->Edit Configurations->Launch
set to "Nothing"</p>

Body:
I want to use a gif image as wallpaper in Android and I'm facing some problem.
I have the following error: "Default Activity Not Found". There is no error in the project, but when I run it, I got this error on Android Studio.

public class GIFWallpaperService extends WallpaperService {

    @Override
    public WallpaperService.Engine onCreateEngine() {
        try {
            Movie movie = Movie.decodeStream(
                    getResources().getAssets().open("girl.gif"));

            return new GIFWallpaperEngine(movie);
        }catch(IOException e){
            Log.d("GIF", "Could not load asset");
            return null;
        }
    }

    private class GIFWallpaperEngine extends WallpaperService.Engine {

        private final int frameDuration = 20;

        private SurfaceHolder holder;
        private Movie movie;
        private boolean visible;
        private Handler handler;

        public GIFWallpaperEngine(Movie movie) {
            this.movie = movie;
            handler = new Handler();
        }

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            this.holder = surfaceHolder;
        }

        private Runnable drawGIF = new Runnable() {
            public void run() {
                draw();
            }
        };

        private void draw() {
            if (visible) {
                Canvas canvas = holder.lockCanvas();
                canvas.save();
                    // Adjust size and position so that
                    // the image looks good on your screen
                    canvas.scale(3f, 3f);
                    movie.draw(canvas, -100, 0);
                canvas.restore();
                holder.unlockCanvasAndPost(canvas);
                movie.setTime((int) (System.currentTimeMillis() % movie.duration()));

                handler.removeCallbacks(drawGIF);
                handler.postDelayed(drawGIF, frameDuration);
            }
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            this.visible = visible;
            if (visible) {
                handler.post(drawGIF);
            } else {
                handler.removeCallbacks(drawGIF);
            }
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            handler.removeCallbacks(drawGIF);
        }
    }
}

This is my manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hathy.gifwallpaper">

    <application android:allowBackup="true" android:label="@string/app_name"
        android:icon="@drawable/ic_launcher" android:theme="@style/AppTheme">

        <service
            android:name=".GIFWallpaperService"
            android:enabled="true"
            android:label="GIF Wallpaper"
            android:permission="android.permission.BIND_WALLPAPER" >
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService"/>

            </intent-filter>
            <meta-data
                android:name="android.service.wallpaper"
                android:resource="@xml/wallpaper" >
            </meta-data>
        </service>

    </application>

    <uses-feature
        android:name="android.software.live_wallpaper"
        android:required="true" >
    </uses-feature>
</manifest>


问:
Parallel test failure using Selenium and Nunit
I have configured some tests to run in parallel using Selenium and Nunit but sometimes one of the tests kills off early and miss behaves. It's not always the same test and they are basic examples so am not sure what's happening.

I also followed the example in the following link (https://www.youtube.com/watch?v=18zrtO1l7EU) to the letter but it also does not work. Sometimes one of the tests halts and doesn't continue and then fails. I've tried with both chrome and IE drivers but the same thing happens. Could this be an Nunit version issue?

答: I think this was because I was initially setting the Base weddriver as Static. Since taking the static off it works fine.</p>


问:
Stop window.location execution in global context
I want to stop execution of window.location as in below when a page loads:

```<code><script type="text/javascript">
alert('Bid closed ');
window.location = '/index.html';
</script>
</code>```

I'm able to bypass alert message by replacing alert function during document_start in the manifest.json. But unable to stop window.location from executing.

答:
window object is not writable, so you cannot change document and window objects
check this link for more info

Body:
I want to stop execution of window.location as in below when a page loads:

I'm able to bypass alert message by replacing alert function during document_start in the manifest.json. But unable to stop window.location from executing.


问:
YouTube url is incomplete
I'm working on an android app which has a webview and it is used to play YouTube videos. I also have a Textview which shows the url of the currently playing video.But sometimes when a video is playing, it does not show the video id of the playing video in the url. It only shows https://m.youtube.com/
But when I refresh the same video, then the complete url is shown as https://m.youtube.com/watch?v=Wm9qCz63dQE
I'm setting values to the Textview using webview.getOriginalUrl() method and I use iframe API to play the YouTube video in webview.
Am i doing anything wrong while getting the url or is there any other way of getting the complete url of a youtube video?

答:
Use webchromeclient() of the WebView to get progress , you will  get the original url once you complete the 100% of loading then it shows you original url

```<code>webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
               if(progress == 100) {
               Log.d("original url",""+webview.getOriginalUrl();
               }
            }
        });
</code>```

Title: YouTube url is incomplete

Body:
Use webchromeclient() of the WebView to get progress , you will  get the original url once you complete the 100% of loading then it shows you original url

webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
               if(progress == 100) {
               Log.d("original url",""+webview.getOriginalUrl();
               }
            }
        });


问:
Why not a consolidated Copy constructor and Assignment operator available in C++?
I do understand the scenarios where the respective functions (Copy Constructor and Assignment operator) would be called. And both these functions are literally doing the same functionality - properly allocating memory for dynamic data members and copy the data from the passed argument object, so that both the object looks identical in data. Why not in that case, C++ provides a consolidated (one function) which would be called in both these scenarios instead of complicating things by providing two variants?</p>

答:
They are not the same, and it would be a pain in the neck if someone forced them to be.

Copy construction is a way of creating an object. Amongst other things, base member initialisers can be used. In multi-threaded code, you don't need to worry so much about mutual exclusion units in a constructor since you cannot create the same object simultaneously!

An assignment operator does a rather different thing. It operates on an object that already exists and should return a reference to self. An implementation can do subtly different things here cf. copy construction. For example, a string class might not release resources if the new assigned string is smaller.

In simple cases they may well do the same thing and the return value of an assignment discarded. But in such cases you can rely on the ones that the compiler generates automatically.


问:
Exception while calling authenticate method of Zend Authentication Service
I'm migrating my ZF2 app to ZF3.

While calling the authenticate method, getting this exception

An error occurred
  An error occurred during execution; please try again later.
  No Exception available

This is how I' calling the method,

```<code>public function __construct($authService, $sessionManager, $config)
{
    $this->authService = $authService;//Getting the Zend\Authentication\AuthenticationService object (no error here)
    $this->sessionManager = $sessionManager;
    $this->config = $config;
}
public function login($email, $password, $rememberMe)
{
    if ($this->authService->getIdentity() != null) {
        throw new \Exception('Already logged in');
    }

    // Authenticate with login/password.
    $authAdapter = $this->authService->getAdapter();
    $authAdapter->setEmail($email);//abc.gmail.com
    $authAdapter->setPassword($password);//sha1 password
    $this->authService->authenticate();//Exception is generating here
}
</code>```

What is I'm doing wrong?

答:
Your exception message is not enough,
you should check php_error.log for details.

I assume that you are not registered Auth Service in the config.

So in config/autoload/global.php add

```<code>'service_manager' => [
    'invokables' => [
        Zend\Authentication\AuthenticationService::class => Zend\Authentication\AuthenticationService::class,
    ]
],
</code>```

Body:
I'm migrating my ZF2 app to ZF3.

While calling the authenticate method, getting this exception

An error occurred
  An error occurred during execution; please try again later.
  No Exception available

This is how I' calling the method,

public function __construct($authService, $sessionManager, $config)
{
    $this->authService = $authService;//Getting the Zend\Authentication\AuthenticationService object (no error here)
    $this->sessionManager = $sessionManager;
    $this->config = $config;
}
public function login($email, $password, $rememberMe)
{
    if ($this->authService->getIdentity() != null) {
        throw new \Exception('Already logged in');
    }

    // Authenticate with login/password.
    $authAdapter = $this->authService->getAdapter();
    $authAdapter->setEmail($email);//abc.gmail.com
    $authAdapter->setPassword($password);//sha1 password
    $this->authService->authenticate();//Exception is generating here
}

What is I'm doing wrong?

Body:
Your exception message is not enough,
you should check php_error.log for details.

I assume that you are not registered Auth Service in the config.

So in config/autoload/global.php add

'service_manager' => [
    'invokables' => [
        Zend\Authentication\AuthenticationService::class => Zend\Authentication\AuthenticationService::class,
    ]
],


问:
Application legging when fragment changed by Navigation Drawer
Having Navigation Drawer by new Support Library

Here is the code

```<code> FragmentManager fragmentManager;
Fragment fragment;
 fragmentManager=getSupportFragmentManager();
    fragment= fragmentManager.findFragmentById(R.id.list_view_container);

 NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
 if (navigationView != null) {
        setupNavigationDrawerContent(navigationView);
    }
    setupNavigationDrawerContent(navigationView);

private void setupNavigationDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                        case R.id.home:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            fragment = new HomeFragment();
       fragmentManager.beginTransaction().replace(R.id.list_view_container,fragment).commit();
                            return true;
                        case R.id.current_event:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.college_events:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.national_events:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.workshops:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.trainings:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, "Launching " + menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.companies:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.talents:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.games:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                    case R.id.submission:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                    case R.id.about:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                }
                    return true;
                }
            });
}
</code>```

So When I am clicking on HOME the fragment is changing but the navigation drawer is legging while closing and also when navigation drawer is pulled back the oping process is hanging as hell in devices which are greater than jellyBean but working really fine in jelly bean and pre jelly bean devices. My application is compiled with latest api that is 23 please help me out.

so when I am removing the fragment changing code than no legging at all.
SO I think something wrong with fragment changing codes.

答: I used add() method to change the fragment instead of replace() each time when I used to click on NavigationView item, it used to add one new fragment to the activity on each and every click. Well, I asked this question when I was new to android application development.

Body:
Having Navigation Drawer by new Support Library

Here is the code

 FragmentManager fragmentManager;
Fragment fragment;
 fragmentManager=getSupportFragmentManager();
    fragment= fragmentManager.findFragmentById(R.id.list_view_container);

 NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
 if (navigationView != null) {
        setupNavigationDrawerContent(navigationView);
    }
    setupNavigationDrawerContent(navigationView);

private void setupNavigationDrawerContent(NavigationView navigationView) {
    navigationView.setNavigationItemSelectedListener(
            new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                        case R.id.home:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            fragment = new HomeFragment();
       fragmentManager.beginTransaction().replace(R.id.list_view_container,fragment).commit();
                            return true;
                        case R.id.current_event:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.college_events:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.national_events:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.workshops:
                            menuItem.setChecked(true);
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.trainings:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, "Launching " + menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.companies:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.talents:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                        case R.id.games:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                    case R.id.submission:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                    case R.id.about:
                            menuItem.setChecked(true);
                            Toast.makeText(MainActivity.this, menuItem.getTitle().toString(), Toast.LENGTH_SHORT).show();
                            drawerLayout.closeDrawer(GravityCompat.START);
                            return true;
                }
                    return true;
                }
            });
}

So When I am clicking on HOME the fragment is changing but the navigation drawer is legging while closing and also when navigation drawer is pulled back the oping process is hanging as hell in devices which are greater than jellyBean but working really fine in jelly bean and pre jelly bean devices. My application is compiled with latest api that is 23 please help me out.

so when I am removing the fragment changing code than no legging at all.
SO I think something wrong with fragment changing codes.


问:
Java multithreading - joining a CPU heavy thread and volatile keyword
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

```<code>public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}
</code>```

答:
It seems that the main thread is stuck on on t1.join() line, even though both worker threads should finish because of the stop = true from previous line.

In the absence of volatile, locking, or other safe publication mechanism, the JVM has no obligation to ever make stop = true visible to other threads. Specifically applied to your case, while your main thread sleeps for one second, the JIT compiler optimizes your while (!stop) hot loop into the equivalent of

```<code>if (!stop) {
    while (true) {
        ...
    }
}
</code>```

This particular optimization is known as "hoisting" of the read action out of the loop.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU

No, it's because PrintStream::println is a synchronized method. All known JVMs will emit a memory fence at the CPU level to ensure the semantics of an "acquire" action (in this case, lock acquisition), and this will force a reload of the stop variable. This is not required by specification, just an implementation choice.

If I mark the flag boolean stop as volatile, causing the write to immediately be seen by worker threads

The specification actually has no wall clock-time requirements on when a volatile write must become visible to other threads, but in practice it is understood that it must become visible "very soon". So this change is the correct way to ensure that the write to stop is safely published to, and subsequently observed by, other threads reading it.

If I mark the counter t as volatile... for this I have no idea what causes the un-hanging.

These are again the indirect effects of what the JVM does to ensure the semantics of a volatile read, which is another kind of a "acquire" inter-thread action.

In summary, except for the change making stop a volatile variable, your program switches from hanging forever to completing due to the accidental side-effects of the underlying JVM implementation, which for simplicity does some more flushing/invalidation of thread-local state than required by the specification.

Body:
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}

Body:
It seems that the main thread is stuck on on t1.join() line, even though both worker threads should finish because of the stop = true from previous line.

In the absence of volatile, locking, or other safe publication mechanism, the JVM has no obligation to ever make stop = true visible to other threads. Specifically applied to your case, while your main thread sleeps for one second, the JIT compiler optimizes your while (!stop) hot loop into the equivalent of

if (!stop) {
    while (true) {
        ...
    }
}

This particular optimization is known as "hoisting" of the read action out of the loop.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU

No, it's because PrintStream::println is a synchronized method. All known JVMs will emit a memory fence at the CPU level to ensure the semantics of an "acquire" action (in this case, lock acquisition), and this will force a reload of the stop variable. This is not required by specification, just an implementation choice.

If I mark the flag boolean stop as volatile, causing the write to immediately be seen by worker threads

The specification actually has no wall clock-time requirements on when a volatile write must become visible to other threads, but in practice it is understood that it must become visible "very soon". So this change is the correct way to ensure that the write to stop is safely published to, and subsequently observed by, other threads reading it.

If I mark the counter t as volatile... for this I have no idea what causes the un-hanging.

These are again the indirect effects of what the JVM does to ensure the semantics of a volatile read, which is another kind of a "acquire" inter-thread action.

In summary, except for the change making stop a volatile variable, your program switches from hanging forever to completing due to the accidental side-effects of the underlying JVM implementation, which for simplicity does some more flushing/invalidation of thread-local state than required by the specification.


问:
Unity: how to resolve class through base interface
Here is my repository class:

```<code>public interface IMyRepository : IRepository<IMyEntity>{}

public class MyRepository : IMyRepository
{
...
}
</code>```

Here is way to register it:

```<code>container.Register<IMyRepository, MyRepository >();
</code>```

Here is the way how I want to get repository resolved:

```<code>IRepository<IMyEntity> repository = container.Resolve<IRepository<IMyEntity>>();
</code>```

Attempt to resolve repository in this ways give an error:

Resolution of the dependency failed, type = "CMCore.Repository.IRepository`1[CMCore.Data.ICmCoreLog]", name = "(none)".
  Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, IRepository`1[IMyEntity], is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving IRepository`1[IMyEntity],(none)

What is wrong in my approach? What is a proper way to achieve mentioned functionality?

Thanks a lot!

P.S. Sometime I want to resolve my class through the IMyRepository, sometime through IRepository. Should I register class twice?

答:
```<code>IMyRepository repository = container.Resolve<IMyRepository>();
</code>```

Body:
Here is my repository class:

public interface IMyRepository : IRepository<IMyEntity>{}

public class MyRepository : IMyRepository
{
...
}

Here is way to register it:

container.Register<IMyRepository, MyRepository >();

Here is the way how I want to get repository resolved:

IRepository<IMyEntity> repository = container.Resolve<IRepository<IMyEntity>>();

Attempt to resolve repository in this ways give an error:

Resolution of the dependency failed, type = "CMCore.Repository.IRepository`1[CMCore.Data.ICmCoreLog]", name = "(none)".
  Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, IRepository`1[IMyEntity], is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was:

Resolving IRepository`1[IMyEntity],(none)

What is wrong in my approach? What is a proper way to achieve mentioned functionality?

Thanks a lot!

P.S. Sometime I want to resolve my class through the IMyRepository, sometime through IRepository. Should I register class twice?


问:
Anymap: Setting zIndex for single map points
is it possible to set the zIndex of a single marker on the map? I have multiple series implemented on a map and the label of a point is sometimes overlapped by another point. So I was thinking about raising the zIndex of the selected point via the pointsselected event, but I am just able to set the zIndex to the whole series.

Then I tried to raise the zIndex of the current series but that doesn't work well in firefox..

Do you have an idea?

答:
1) as of version 7.13.0 - it is not possible to set zIndex to the individual point, AnyChart will try to fix it in the next update.

update: This feature is available now, you can set zIndex for each particular point, like http://jsfiddle.net/4sskmb8k/3/

2) we tested Firefox 52 Win and 52 Mac and it seems to be working fine

```<code>firstSeries = chart.marker(dataSet1);
secondSeries = chart.marker(dataSet2).type('star').size(10);
chart.container('container').draw();
firstSeries.zIndex(secondSeries.zIndex()+1);
</code>```

http://jsfiddle.net/4sskmb8k/2/
Do you use another version or other settings?

Body:
1) as of version 7.13.0 - it is not possible to set zIndex to the individual point, AnyChart will try to fix it in the next update.

update: This feature is available now, you can set zIndex for each particular point, like http://jsfiddle.net/4sskmb8k/3/

2) we tested Firefox 52 Win and 52 Mac and it seems to be working fine

firstSeries = chart.marker(dataSet1);
secondSeries = chart.marker(dataSet2).type('star').size(10);
chart.container('container').draw();
firstSeries.zIndex(secondSeries.zIndex()+1);

http://jsfiddle.net/4sskmb8k/2/
Do you use another version or other settings?


问:
Angular2 Triggering a custom validator
I have done a custom validator which I apply on one of my two input:

```<code><input type="text"
     class="validate"
     [(ngModel)]="foo"
     name="foo"
     ngControl="foo"
     customValidator
     [validatorArg]="blah"
/>

<input type="text"
     class="validate"
     [(ngModel)]="blah"
     name="blah"
/>
</code>```

The customValidatordepends on the second input. So what I'd like here, would be to trigger the validator on the foo input when I do modified the blah input.
Any idea how to do that ? I could do it on ngModelChange

EDIT: My inputs are part of a form which is a FormGroup

答:
It's a bit problematic with template driven forms. I have done it like this

```<code><input name="blah" ... (ngModelChange)="triggerValidation(formObject.controls.foo)">

triggerValidation(control: AbstractControl) {
    control.markAsTouched();
    setTimeout(() => control.updateValueAndValidity(), 0);
}
</code>```

If you run updateValueAndValidity() synchronously (without timeout), it may use an old value of the "blah" input.

Title: Angular2 Triggering a custom validator

Body:
I have done a custom validator which I apply on one of my two input:

<input type="text"
     class="validate"
     [(ngModel)]="foo"
     name="foo"
     ngControl="foo"
     customValidator
     [validatorArg]="blah"
/>

<input type="text"
     class="validate"
     [(ngModel)]="blah"
     name="blah"
/>

The customValidatordepends on the second input. So what I'd like here, would be to trigger the validator on the foo input when I do modified the blah input.
Any idea how to do that ? I could do it on ngModelChange

EDIT: My inputs are part of a form which is a FormGroup

Body:
It's a bit problematic with template driven forms. I have done it like this

<input name="blah" ... (ngModelChange)="triggerValidation(formObject.controls.foo)">

triggerValidation(control: AbstractControl) {
    control.markAsTouched();
    setTimeout(() => control.updateValueAndValidity(), 0);
}

If you run updateValueAndValidity() synchronously (without timeout), it may use an old value of the "blah" input.


问:
iOS: Image get rotated 90 degree after saved as PNG representation data
I have researched enough to get this working but not able to fix it. After taking picture from camera as long as I have image stored as UIImage, it's fine but as soon as I stored this image as PNG representation, its get rotated 90 degree.

Following is my code and all things I tried:

```<code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];

    if([mediaType isEqualToString:(NSString*)kUTTypeImage])
    {
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        delegate.originalPhoto  = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSLog(@"Saving photo");
        [self saveImage];
        NSLog(@"Fixing orientation");
        delegate.fixOrientationPhoto  = [self fixOrientation:[UIImage imageWithContentsOfFile:[delegate filePath:imageName]]];
        NSLog(@"Scaling photo");
        delegate.scaledAndRotatedPhoto  =  [self scaleAndRotateImage:[UIImage imageWithContentsOfFile:[delegate filePath:imageName]]];
    }
    [picker dismissModalViewControllerAnimated:YES];
    [picker release];
}

- (void)saveImage
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSData *imageData = UIImagePNGRepresentation(delegate.originalPhoto);
    [imageData writeToFile:[delegate filePath:imageName] atomically:YES];
}
</code>```

Here fixOrientation and scaleAndRotateImage functions taken from here and here respectively. They works fine and rotate image when I apply them on UIImage but doesn't work if I save image as PNG representation and apply them.

Please refere the following picture after executing above functions:

答:
Swift 3.1 version of the UIImage extension posted by Rao:

```<code>extension UIImage {
    func fixOrientation() -> UIImage {
        if self.imageOrientation == UIImageOrientation.up {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        if let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() {
            UIGraphicsEndImageContext()
            return normalizedImage
        } else {
            return self
        }
    }
}
</code>```

Usage:

```<code>let cameraImage = //image captured from camera
let orientationFixedImage = cameraImage.fixOrientation()
</code>```

Swift 4/5:

UIImageOrientation.up has been renamed to UIImage.Orientation.up

Body:
I have researched enough to get this working but not able to fix it. After taking picture from camera as long as I have image stored as UIImage, it's fine but as soon as I stored this image as PNG representation, its get rotated 90 degree.

Following is my code and all things I tried:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];

    if([mediaType isEqualToString:(NSString*)kUTTypeImage])
    {
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        delegate.originalPhoto  = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSLog(@"Saving photo");
        [self saveImage];
        NSLog(@"Fixing orientation");
        delegate.fixOrientationPhoto  = [self fixOrientation:[UIImage imageWithContentsOfFile:[delegate filePath:imageName]]];
        NSLog(@"Scaling photo");
        delegate.scaledAndRotatedPhoto  =  [self scaleAndRotateImage:[UIImage imageWithContentsOfFile:[delegate filePath:imageName]]];
    }
    [picker dismissModalViewControllerAnimated:YES];
    [picker release];
}

- (void)saveImage
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSData *imageData = UIImagePNGRepresentation(delegate.originalPhoto);
    [imageData writeToFile:[delegate filePath:imageName] atomically:YES];
}

Here fixOrientation and scaleAndRotateImage functions taken from here and here respectively. They works fine and rotate image when I apply them on UIImage but doesn't work if I save image as PNG representation and apply them.

Please refere the following picture after executing above functions:

Body:
Swift 3.1 version of the UIImage extension posted by Rao:

extension UIImage {
    func fixOrientation() -> UIImage {
        if self.imageOrientation == UIImageOrientation.up {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        if let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() {
            UIGraphicsEndImageContext()
            return normalizedImage
        } else {
            return self
        }
    }
}

Usage:

let cameraImage = //image captured from camera
let orientationFixedImage = cameraImage.fixOrientation()

Swift 4/5:

UIImageOrientation.up has been renamed to UIImage.Orientation.up

ContentLicense: CC BY-SA 4.0