问:
Custom cell for UICollection view cell unable clear old data
I created a custom UICollection cell but the data sometimes appear in the wrong cell and no matter how much I refresh the UICollection view it refuses to change. I have done a print out to see if the data gotten from the array is wrong but it's not. Is there a way to clear the old data from the cell before inputting the next one. Any suggestion will be appreciated.

custom cell

```<code>class customAppointmentViewCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let thumbnailImageView: UIImageView = {
    let tniv = UIImageView()
    tniv.translatesAutoresizingMaskIntoConstraints = false
    tniv.backgroundColor = UIColor.clear
    tniv.contentMode = .scaleAspectFit
    return tniv
}()

let seperatorView: UIView = {
    let sv = UIView()
    sv.translatesAutoresizingMaskIntoConstraints = false
    sv.backgroundColor = UIColor(r: 11, g: 49, b: 68)
    return sv
}()

let clientNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let openingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let closingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let bookedBarberNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let servicePricePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 10)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .right
    return fnhp
}()

func setupViews(){
    addSubview(thumbnailImageView)
    addSubview(clientNamePlaceHolder)
    addSubview(openingTimePlaceHolder)
    addSubview(closingTimePlaceHolder)
    addSubview(bookedBarberNamePlaceHolder)
    addSubview(servicePricePlaceHolder)
    addSubview(seperatorView)
    backgroundColor = UIColor(r: 23, g: 69, b: 90)
    addContraintsWithFormat(format: "H:|-16-[v0(90)]|", views: thumbnailImageView)
    addContraintsWithFormat(format: "H:|-116-[v0][v1(50)]-10-|", views: clientNamePlaceHolder, servicePricePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: openingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: closingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)][v1(20)][v2(20)][v3(20)]-10-|", views: clientNamePlaceHolder, openingTimePlaceHolder,closingTimePlaceHolder, bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)]|", views: servicePricePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0]-10-[v1(5)]|", views: thumbnailImageView,seperatorView)
    addContraintsWithFormat(format: "H:|[v0]|", views: seperatorView)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

collection view

```<code>extension AppointmentsViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.appointments.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! customAppointmentViewCell
    //empty cell data
    //real data

    cell.openingTimePlaceHolder.text = ""
    if let opentime = self.appointments[safe: indexPath.row]?.bookingStartTimeString {
        cell.openingTimePlaceHolder.text = opentime
    } else {
        cell.openingTimePlaceHolder.text = ""
    }

    cell.closingTimePlaceHolder.text = ""
    if let closetime = self.appointments[safe: indexPath.row]?.bookingEndTimeString {
        cell.closingTimePlaceHolder.text = closetime
    } else {
        cell.closingTimePlaceHolder.text = ""
    }

    cell.bookedBarberNamePlaceHolder.text = ""
    if let barberName = self.appointments[safe: indexPath.row]?.bookedBarberName {
        cell.bookedBarberNamePlaceHolder.text = barberName
    } else {
        cell.bookedBarberNamePlaceHolder.text = ""
    }

    cell.servicePricePlaceHolder.text = ""
    if let servicepricee = self.appointments[safe: indexPath.row]?.bookedServicePrice {
        cell.servicePricePlaceHolder.text = servicepricee
    } else {
        cell.servicePricePlaceHolder.text = ""
    }

    cell.thumbnailImageView.image = UIImage()
    if let profileimagess = self.appointments[safe: indexPath.row]?.profileImage {
        cell.thumbnailImageView.image = profileimagess
    } else {
        cell.thumbnailImageView.image = UIImage()
    }

    cell.clientNamePlaceHolder.text = ""
    if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
        cell.clientNamePlaceHolder.text = clientnamess
    } else {
        cell.clientNamePlaceHolder.text = ""
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectView.frame.width, height: 100)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let uuidAvail = UserDefaults.standard.object(forKey: "theOriginalBarberShopUUID") as? String{
        if let bookIDDD = self.appointments[safe: indexPath.row]?.bookingUniqueID {
            let orderDetail = OrderDetailViewController()
            orderDetail.specificAppintment = self.appointments[indexPath.row]
            orderDetail.barberShopID = uuidAvail
            orderDetail.bookingUniqueIDDD = bookIDDD
            orderDetail.bookedBarberUUIDAX = self.appointments[indexPath.row].bookedBarberUUID
            orderDetail.appointmentsviewhold = self
            orderDetail.indexPathSelected = indexPath.row
            navigationController?.pushViewController(orderDetail, animated: true)
        }
    }
}
}
</code>```

thanks

答:
Try Passing the model object to the UICollectionViewCell class by assigning a property in cell

example:

UICollectionViewCell:

```<code>var object: Model? {
  didSet{
    // here do your assignment of text to various labels
  }
}
</code>```

CellForRow:

```<code>let cell = ...
cell.object = self.appointments[indexPath.item]
return cell
</code>```

I hope this works.

Body:
I created a custom UICollection cell but the data sometimes appear in the wrong cell and no matter how much I refresh the UICollection view it refuses to change. I have done a print out to see if the data gotten from the array is wrong but it's not. Is there a way to clear the old data from the cell before inputting the next one. Any suggestion will be appreciated.

custom cell

class customAppointmentViewCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

let thumbnailImageView: UIImageView = {
    let tniv = UIImageView()
    tniv.translatesAutoresizingMaskIntoConstraints = false
    tniv.backgroundColor = UIColor.clear
    tniv.contentMode = .scaleAspectFit
    return tniv
}()

let seperatorView: UIView = {
    let sv = UIView()
    sv.translatesAutoresizingMaskIntoConstraints = false
    sv.backgroundColor = UIColor(r: 11, g: 49, b: 68)
    return sv
}()

let clientNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 17)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let openingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let closingTimePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let bookedBarberNamePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 12)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .left
    return fnhp
}()

let servicePricePlaceHolder: UILabel = {
    let fnhp = UILabel()
    fnhp.translatesAutoresizingMaskIntoConstraints = false
    fnhp.font = UIFont(name: "HelveticaNeue-Medium", size: 10)
    fnhp.textColor = UIColor.white
    fnhp.textAlignment = .right
    return fnhp
}()

func setupViews(){
    addSubview(thumbnailImageView)
    addSubview(clientNamePlaceHolder)
    addSubview(openingTimePlaceHolder)
    addSubview(closingTimePlaceHolder)
    addSubview(bookedBarberNamePlaceHolder)
    addSubview(servicePricePlaceHolder)
    addSubview(seperatorView)
    backgroundColor = UIColor(r: 23, g: 69, b: 90)
    addContraintsWithFormat(format: "H:|-16-[v0(90)]|", views: thumbnailImageView)
    addContraintsWithFormat(format: "H:|-116-[v0][v1(50)]-10-|", views: clientNamePlaceHolder, servicePricePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: openingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: closingTimePlaceHolder)
    addContraintsWithFormat(format: "H:|-116-[v0]-60-|", views: bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)][v1(20)][v2(20)][v3(20)]-10-|", views: clientNamePlaceHolder, openingTimePlaceHolder,closingTimePlaceHolder, bookedBarberNamePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0(20)]|", views: servicePricePlaceHolder)
    addContraintsWithFormat(format: "V:|-10-[v0]-10-[v1(5)]|", views: thumbnailImageView,seperatorView)
    addContraintsWithFormat(format: "H:|[v0]|", views: seperatorView)

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

collection view

extension AppointmentsViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.appointments.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! customAppointmentViewCell
    //empty cell data
    //real data

    cell.openingTimePlaceHolder.text = ""
    if let opentime = self.appointments[safe: indexPath.row]?.bookingStartTimeString {
        cell.openingTimePlaceHolder.text = opentime
    } else {
        cell.openingTimePlaceHolder.text = ""
    }

    cell.closingTimePlaceHolder.text = ""
    if let closetime = self.appointments[safe: indexPath.row]?.bookingEndTimeString {
        cell.closingTimePlaceHolder.text = closetime
    } else {
        cell.closingTimePlaceHolder.text = ""
    }

    cell.bookedBarberNamePlaceHolder.text = ""
    if let barberName = self.appointments[safe: indexPath.row]?.bookedBarberName {
        cell.bookedBarberNamePlaceHolder.text = barberName
    } else {
        cell.bookedBarberNamePlaceHolder.text = ""
    }

    cell.servicePricePlaceHolder.text = ""
    if let servicepricee = self.appointments[safe: indexPath.row]?.bookedServicePrice {
        cell.servicePricePlaceHolder.text = servicepricee
    } else {
        cell.servicePricePlaceHolder.text = ""
    }

    cell.thumbnailImageView.image = UIImage()
    if let profileimagess = self.appointments[safe: indexPath.row]?.profileImage {
        cell.thumbnailImageView.image = profileimagess
    } else {
        cell.thumbnailImageView.image = UIImage()
    }

    cell.clientNamePlaceHolder.text = ""
    if let clientnamess = self.appointments[safe: indexPath.row]?.clientName {
        cell.clientNamePlaceHolder.text = clientnamess
    } else {
        cell.clientNamePlaceHolder.text = ""
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectView.frame.width, height: 100)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if let uuidAvail = UserDefaults.standard.object(forKey: "theOriginalBarberShopUUID") as? String{
        if let bookIDDD = self.appointments[safe: indexPath.row]?.bookingUniqueID {
            let orderDetail = OrderDetailViewController()
            orderDetail.specificAppintment = self.appointments[indexPath.row]
            orderDetail.barberShopID = uuidAvail
            orderDetail.bookingUniqueIDDD = bookIDDD
            orderDetail.bookedBarberUUIDAX = self.appointments[indexPath.row].bookedBarberUUID
            orderDetail.appointmentsviewhold = self
            orderDetail.indexPathSelected = indexPath.row
            navigationController?.pushViewController(orderDetail, animated: true)
        }
    }
}
}

thanks

Body:
Try Passing the model object to the UICollectionViewCell class by assigning a property in cell

example:

UICollectionViewCell:

var object: Model? {
  didSet{
    // here do your assignment of text to various labels
  }
}

CellForRow:

let cell = ...
cell.object = self.appointments[indexPath.item]
return cell

I hope this works.


来源: stackexchange

问:
Fragment not showing previous data when coming from another fragment
In my android activity I am using multiple fragments, I am successfully switching these fragments according to my requirement but problem is that when I am switching Fragment 1 to Fragment 2 and back from Fragment 2 to Fragment 1, Fragment 1 not showing previous data Fragment 1 start from stretch, but I want to show previous data same as I was selected.

Here is my code for go Fragment 1 (fragment_search_customerProfile) to Fragment 2 (fragment_CustomerInfo):

```<code>FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, new fragment_Search());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();

transaction.remove(new fragment_search_customerProfile()).commit();
</code>```

Here is my code for back Fragment 1 (fragment_search_customerProfile) fromFragment 2 (fragment_CustomerInfo):

```<code>FragmentManager manager = getActivity().getSupportFragmentManager();

FragmentTransaction transaction = manager.beginTransaction();

Log.d("fragment_Search", fromSearch + "");
transaction.replace(R.id.custIndoFram, new fragment_search_customerProfile());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.custIndoFram);

layout.removeAllViewsInLayout();

transaction.remove(new fragment_CustomerInfo()).commit();
</code>```

Can anyone explain me how can I stay save my fragment data?

答:
You can simple keep the instances of the fragments, so in your Activity you would have fields like that.

```<code>private Fragment fragment1;
private Fragment fragment2;
</code>```

And now you can use the sexy replace() option,

To add Fragment1

```<code>if (fragment1 == null) {
    fragment1 = new fragment_Search();
}
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, fragment1);
</code>```

and same for Fragment2

And you can hold the state of the fragment (data it retrieves) in the Fragment itself, and in your onViewCreated() you check, if the state is not null, you update the view immediately.

```<code>class Fragment1 extends Fragment {
    private State state;

    public void onViewCreated(View v) {
        if (state != null) {
            // Update UI here
        }
    }

}
</code>```

UPDATE

Using your own code

```<code>private Fragment fragment1; // This is a field outside of below method

if (fragment1 == null) {
    fragment1 = new fragment_Search();
}
FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, fragment1).commit();

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();
</code>```

Going to fragment2 should be the same, and this code is used to go to Fragment1 and Fragment2, doesn't matter if you are going back or first time.

ContentLicense: CC BY-SA 3.0

Body:
In my android activity I am using multiple fragments, I am successfully switching these fragments according to my requirement but problem is that when I am switching Fragment 1 to Fragment 2 and back from Fragment 2 to Fragment 1, Fragment 1 not showing previous data Fragment 1 start from stretch, but I want to show previous data same as I was selected.

Here is my code for go Fragment 1 (fragment_search_customerProfile) to Fragment 2 (fragment_CustomerInfo):

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, new fragment_Search());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();

transaction.remove(new fragment_search_customerProfile()).commit();

Here is my code for back Fragment 1 (fragment_search_customerProfile) fromFragment 2 (fragment_CustomerInfo):

FragmentManager manager = getActivity().getSupportFragmentManager();

FragmentTransaction transaction = manager.beginTransaction();

Log.d("fragment_Search", fromSearch + "");
transaction.replace(R.id.custIndoFram, new fragment_search_customerProfile());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.custIndoFram);

layout.removeAllViewsInLayout();

transaction.remove(new fragment_CustomerInfo()).commit();

Can anyone explain me how can I stay save my fragment data?

Body:
You can simple keep the instances of the fragments, so in your Activity you would have fields like that.

private Fragment fragment1;
private Fragment fragment2;

And now you can use the sexy replace() option,

To add Fragment1

if (fragment1 == null) {
    fragment1 = new fragment_Search();
}
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, fragment1);

and same for Fragment2

And you can hold the state of the fragment (data it retrieves) in the Fragment itself, and in your onViewCreated() you check, if the state is not null, you update the view immediately.

class Fragment1 extends Fragment {
    private State state;

    public void onViewCreated(View v) {
        if (state != null) {
            // Update UI here
        }
    }

}

UPDATE

Using your own code

private Fragment fragment1; // This is a field outside of below method

if (fragment1 == null) {
    fragment1 = new fragment_Search();
}
FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, fragment1).commit();

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();

Going to fragment2 should be the same, and this code is used to go to Fragment1 and Fragment2, doesn't matter if you are going back or first time.


问:
Entity Framework 6 with Mysql "System.InvalidOperationException"
I'm new with .net
I'm trying building console app with EF6 and MySql

i always got this error when running it

this is my app.conf

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings>
    <add name="MyContext" providerName="MySql.Data.MySqlClient"
        connectionString="server=192.168.1.212;port=3306;database=zkatt;uid=fanta;password=040506"/>
  </connectionStrings>
  <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="MySql.Data.MySqlClient"
          type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
      <provider invariantName="System.Data.SqlClient"
          type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description="MySQL Database Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
    </DbProviderFactories>
  </system.data>
</configuration>
</code>```

my context class

```<code>[DbConfigurationType(typeof(MySqlEFConfiguration))]
public partial class Entities : DbContext
{
    public Entities()
        : base("name=MyContext")
    {
    }
</code>```

anything i miss?

*edit
this is full report error

答:
Remove the useless node :

```<code><DbProviderFactories>
  <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description="MySQL Database Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
</DbProviderFactories>
</code>```

And specify version of your MySqlClient provider like :

```<code><provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
</code>```

Body:
I'm new with .net
I'm trying building console app with EF6 and MySql

i always got this error when running it

this is my app.conf

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <connectionStrings>
    <add name="MyContext" providerName="MySql.Data.MySqlClient"
        connectionString="server=192.168.1.212;port=3306;database=zkatt;uid=fanta;password=040506"/>
  </connectionStrings>
  <entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="MySql.Data.MySqlClient"
          type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
      <provider invariantName="System.Data.SqlClient"
          type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description="MySQL Database Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
    </DbProviderFactories>
  </system.data>
</configuration>

my context class

[DbConfigurationType(typeof(MySqlEFConfiguration))]
public partial class Entities : DbContext
{
    public Entities()
        : base("name=MyContext")
    {
    }

anything i miss?

*edit
this is full report error

Body:
Remove the useless node :

<DbProviderFactories>
  <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description="MySQL Database Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
</DbProviderFactories>

And specify version of your MySqlClient provider like :

<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>


问:
Filtering a list in python with many key-value pairs
I have a list that looks like this:

```<code>commands = [
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}
]
</code>```

And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.

答:
Use filters
b  = list(filter(lambda x: x['max-threshold']==True, a))

Read more here : http://book.pythontips.com/en/latest/map_filter.html

Body:
I have a list that looks like this:

commands = [
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}
]

And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.


问:
How can I join into insert statement?
Here is my table structure:

```<code>// pages
+----+-----------------------+--------+
| id |         path          | method |
+----+-----------------------+--------+
| 1  | list_role             | get    |
| 2  | make_role             | post   |
| 3  | edit_role/id          | get    |
| 4  | list_voucher/activate | get    |
| 5  | list_voucher/activate | post   |
| 6  | expire_voucher/id     | get    |
+----+-----------------------+--------+

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
</code>```

Now I want to insert multiple rows into role_page table according to this array: (noted that I have $role_id)

```<code>$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example
</code>```

So the expected output is:

```<code>// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4       | 1       |
| 4       | 4       |
+---------+---------+
</code>```

How can I do that by a join?

Currently I do that by a loop on $arr like this:

```<code>$role_id = 4;

foreach($arr as $row) {
    // match the page id
    $page_id = pages::where('path', row[0])->where('method', row[1])->first();

    // insert
    $role_page = new role_page;
    $role_page->role_id = $role_id;
    $role_page->page_id = $page_id;
}
</code>```

答:
```<code>$page_id = pages::where('path', row[0])->where('method', row[1])->first();
</code>```

This returns an object.

```<code>$page_id = pages::where('path', row[0])->where('method', row[1])->first()->id;
</code>```

This will return just the id.

And then in your foreach you can:

```<code>role_page::create([
           'page_id' => $page_id,
           'role_id' => $role_id
       ]);
</code>```

You do have to explicitly state in your role_page model that it's not plural if your not refering to it in a relationship way:

```<code>protected $table = 'role_page';
</code>```

Title: How can I join into insert statement?

Body:
Here is my table structure:

// pages
+----+-----------------------+--------+
| id |         path          | method |
+----+-----------------------+--------+
| 1  | list_role             | get    |
| 2  | make_role             | post   |
| 3  | edit_role/id          | get    |
| 4  | list_voucher/activate | get    |
| 5  | list_voucher/activate | post   |
| 6  | expire_voucher/id     | get    |
+----+-----------------------+--------+

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+

Now I want to insert multiple rows into role_page table according to this array: (noted that I have $role_id)

$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example

So the expected output is:

// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4       | 1       |
| 4       | 4       |
+---------+---------+

How can I do that by a join?

Currently I do that by a loop on $arr like this:

$role_id = 4;

foreach($arr as $row) {
    // match the page id
    $page_id = pages::where('path', row[0])->where('method', row[1])->first();

    // insert
    $role_page = new role_page;
    $role_page->role_id = $role_id;
    $role_page->page_id = $page_id;
}

Body:
$page_id = pages::where('path', row[0])->where('method', row[1])->first();

This returns an object.

$page_id = pages::where('path', row[0])->where('method', row[1])->first()->id;

This will return just the id.

And then in your foreach you can:

role_page::create([
           'page_id' => $page_id,
           'role_id' => $role_id
       ]);

You do have to explicitly state in your role_page model that it's not plural if your not refering to it in a relationship way:

protected $table = 'role_page';


问:
dropdown list always sets modelstate invalid
Whats wrong with this?

```<code>@Html.DropDownListFor(x => x.Post.CategoryId, new SelectList(Model.Categories, "ID", "CategoryName"), "-- Please select --")
@Html.ValidationMessageFor(x => x.Post.CategoryId)
</code>```

When I submit the form the modelstate is invalid and this dropdown list gets flagged as an error, even though i select a value from the dropdown list.

(btw CategoryId is an FK in my Post Table)
I haved added this "buddy" class as a partial

```<code>[MetadataType(typeof(Post_Validation))]
public partial class Post
{

}

class Post_Validation
{

    [Required(ErrorMessage = "Please select a Category")]
    public int CategoryId { get; set; }

}
</code>```

controller:

```<code>// GET: /News/Add
        [Authorize]
        public ActionResult Add()
        {
            var model = new AddPostViewModel() { Categories = categoryRepository.GetAllCategories(), Post = new Post(), IsEditMode=false };
            return View(model);
        }

            //
            // POST: /News/Add
            [Authorize]
            [HttpPost]
            public ActionResult Add(AddPostViewModel model)
            {
              if (!ModelState.IsValid)
              {
              ..etc
              }
            }
</code>```

答:
There is nothing wrong with this particular code you have posted. What might be wrong is the model you are expecting in the controller action which is being posted to. For example if this model is not the same as the model used to render this view:

```<code>[HttpPost]
public ActionResult Index(Post post) { ... }
</code>```

instead of:

```<code>[HttpPost]
public ActionResult Index(ModelContainingPostConmtainingCategoryId post) { ... }
</code>```

The name of the dropdownlist generated will be the following: name="Post.CategoryId" and if your controller action doesn't take a model having a property called Post with a property called CategoryId and this CategoryId property is marked with Required you will get the behavior you are describing.

Other possible reasons is that you have additional properties which are required and which you haven't included in your request. The way to find this out is to analyze the model you are getting back in your controller action and see what's missing. Also looking at the ModelState property itself in debug mode will tell you which properties have validation errors.

UPDATE:

Here's a full working example that could be used as base:

Model:

```<code>[MetadataType(typeof(Post_Validation))]
public class Post
{
    public int CategoryId { get; set; }
}

class Post_Validation
{
    [Required(ErrorMessage = "Please select a Category")]
    public int CategoryId { get; set; }
}

public class AddPostViewModel
{
    public IEnumerable<SelectListItem> Categories { get; set; }
    public Post Post { get; set; }
}
</code>```

Controller:

```<code>public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new AddPostViewModel()
        {
            Categories = Enumerable.Range(1, 5).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = "category " + x
            }),
            Post = new Post()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(AddPostViewModel model)
    {
        if (!ModelState.IsValid)
        {
            ...
        }
        ...
    }
}
</code>```

View:

```<code>@model AppName.Models.AddPostViewModel
@{
    ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.Post.CategoryId, new SelectList(Model.Categories, "Value", "Text"), "-- Please select --")
    @Html.ValidationMessageFor(x => x.Post.CategoryId)
    <input type="submit" value="OK" />
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Whats wrong with this?

@Html.DropDownListFor(x => x.Post.CategoryId, new SelectList(Model.Categories, "ID", "CategoryName"), "-- Please select --")
@Html.ValidationMessageFor(x => x.Post.CategoryId)

When I submit the form the modelstate is invalid and this dropdown list gets flagged as an error, even though i select a value from the dropdown list.

(btw CategoryId is an FK in my Post Table)
I haved added this "buddy" class as a partial

[MetadataType(typeof(Post_Validation))]
public partial class Post
{

}

class Post_Validation
{

    [Required(ErrorMessage = "Please select a Category")]
    public int CategoryId { get; set; }

}

controller:

// GET: /News/Add
        [Authorize]
        public ActionResult Add()
        {
            var model = new AddPostViewModel() { Categories = categoryRepository.GetAllCategories(), Post = new Post(), IsEditMode=false };
            return View(model);
        }

            //
            // POST: /News/Add
            [Authorize]
            [HttpPost]
            public ActionResult Add(AddPostViewModel model)
            {
              if (!ModelState.IsValid)
              {
              ..etc
              }
            }

Body:
There is nothing wrong with this particular code you have posted. What might be wrong is the model you are expecting in the controller action which is being posted to. For example if this model is not the same as the model used to render this view:

[HttpPost]
public ActionResult Index(Post post) { ... }

instead of:

[HttpPost]
public ActionResult Index(ModelContainingPostConmtainingCategoryId post) { ... }

The name of the dropdownlist generated will be the following: name="Post.CategoryId" and if your controller action doesn't take a model having a property called Post with a property called CategoryId and this CategoryId property is marked with Required you will get the behavior you are describing.

Other possible reasons is that you have additional properties which are required and which you haven't included in your request. The way to find this out is to analyze the model you are getting back in your controller action and see what's missing. Also looking at the ModelState property itself in debug mode will tell you which properties have validation errors.

UPDATE:

Here's a full working example that could be used as base:

Model:

[MetadataType(typeof(Post_Validation))]
public class Post
{
    public int CategoryId { get; set; }
}

class Post_Validation
{
    [Required(ErrorMessage = "Please select a Category")]
    public int CategoryId { get; set; }
}

public class AddPostViewModel
{
    public IEnumerable<SelectListItem> Categories { get; set; }
    public Post Post { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new AddPostViewModel()
        {
            Categories = Enumerable.Range(1, 5).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = "category " + x
            }),
            Post = new Post()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(AddPostViewModel model)
    {
        if (!ModelState.IsValid)
        {
            ...
        }
        ...
    }
}

View:

@model AppName.Models.AddPostViewModel
@{
    ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.Post.CategoryId, new SelectList(Model.Categories, "Value", "Text"), "-- Please select --")
    @Html.ValidationMessageFor(x => x.Post.CategoryId)
    <input type="submit" value="OK" />
}


问:
How to remove the coulmn name in Json in c#
For example this is my JSON:

```<code>[
   {
      "id":1,
      "name":"Core"
   },
   {
      "id":2,
      "name":"Moderate"
   },
   {
      "id":3,
      "name":"Remote"
   }
]
</code>```

How can I remove id and name?

My desired output:

```<code>[
  {
    "1":"Core"
  },
  {
    "2":"Moderate"
  },
  {
    "3":"Remote"
  }
]
</code>```

答:
Try like this</p>

```<code>var objs = new[]
{
    new {Id = 1, Name = "Core"},
    new {Id = 2, Name = "Moderate"},
    new {Id = 3, Name = "Remote"},
};

var json1 = JsonConvert.SerializeObject(objs);
Console.WriteLine(json1);

var dict = objs.ToDictionary(k => k.Id.ToString(), v => v.Name);

var json2 = JsonConvert.SerializeObject(dict);
Console.WriteLine(json2);
</code>```

Body:
For example this is my JSON:

[
   {
      "id":1,
      "name":"Core"
   },
   {
      "id":2,
      "name":"Moderate"
   },
   {
      "id":3,
      "name":"Remote"
   }
]

How can I remove id and name?

My desired output:

[
  {
    "1":"Core"
  },
  {
    "2":"Moderate"
  },
  {
    "3":"Remote"
  }
]

Body:
Try like this

var objs = new[]
{
    new {Id = 1, Name = "Core"},
    new {Id = 2, Name = "Moderate"},
    new {Id = 3, Name = "Remote"},
};

var json1 = JsonConvert.SerializeObject(objs);
Console.WriteLine(json1);

var dict = objs.ToDictionary(k => k.Id.ToString(), v => v.Name);

var json2 = JsonConvert.SerializeObject(dict);
Console.WriteLine(json2);


问:
ef core migration insert data
I'd like to insert data into table in migration. Is it possible? Migration needs parameterless constructor available and I'd like to use db context defined in Startup.cs file (best I'd like to get it throught dependency injection). How do that?</p>

答:
Migration is a process of "upgrading" your DB to a new "version". During this, your existing DB tables ("old version") does not required to match your classes (entities) ("new version"), so you can't safely use them.

During migration you should operate only with tables and records using raw SQL commands. You may use migrationBuilder.Sql("UPDATE ..."); for such updates, put them manually into migration Up() code.

If you need perform data modifications using entity classes - you should use "Seed Data" solution (from @itikhomi comment), but remember that it will be run every time your app starts, so you should do some version-check inside it.

Title: ef core migration insert data


问:
Using selenium java need to retrieve data from angularjs
I need to retrieve data from the DB using angularjs to selenium java.

Below steps I tried but I couldn't retrieve data.

Use Selenium code---

HTML page source

```<code>`<div class="col-sm-6">
<input id="LastName" class="form-control ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" type="text" required="" ng-model="UserProfiles.LastName" name="LastName" placeholder="Please Enter Last Name"/>
</div>`
</code>```

Selenium Java code

```<code>WebElement cityField = driver.findElement(By.cssSelector("input[ng-model='UserProfiles.FirstName']"));

cityField.clear();
cityField.sendKeys("Chicago");
System.out.println("Print- "+ cityField.getAttribute("input[ng-model='UserProfiles.FirstName"));

cityField = driver.findElement(By.cssSelector("input[ng-model='UserProfiles.LastName']"));
System.out.println("+++-- "+cityField.getText());`
</code>```

答:
You can used a common function as:

```<code>public String getAttributeValue(WebDriver driver, String locator, String attribute) {
    WebElement element = driver.findElement(By.xpath(locator));
    return element.getAttribute(attribute);
}
</code>```

In test script:

```<code>String idValue = getAttributeValue(driver, "//input[@id='LastName']", "id");
String modelValue = getAttributeValue(driver, "//input[@id='LastName']", "ng-model");
String nameValue = getAttributeValue(driver, "//input[@id='LastName']", "name");
</code>```

The same way for getText of an element.

Body:
I need to retrieve data from the DB using angularjs to selenium java.

Below steps I tried but I couldn't retrieve data.

Use Selenium code---

HTML page source

`

<input id="LastName" class="form-control ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" type="text" required="" ng-model="UserProfiles.LastName" name="LastName" placeholder="Please Enter Last Name"/>

`

Selenium Java code

WebElement cityField = driver.findElement(By.cssSelector("input[ng-model='UserProfiles.FirstName']"));

cityField.clear();
cityField.sendKeys("Chicago");
System.out.println("Print- "+ cityField.getAttribute("input[ng-model='UserProfiles.FirstName"));

cityField = driver.findElement(By.cssSelector("input[ng-model='UserProfiles.LastName']"));
System.out.println("+++-- "+cityField.getText());`

Body:
You can used a common function as:

public String getAttributeValue(WebDriver driver, String locator, String attribute) {
    WebElement element = driver.findElement(By.xpath(locator));
    return element.getAttribute(attribute);
}

In test script:

String idValue = getAttributeValue(driver, "//input[@id='LastName']", "id");
String modelValue = getAttributeValue(driver, "//input[@id='LastName']", "ng-model");
String nameValue = getAttributeValue(driver, "//input[@id='LastName']", "name");

The same way for getText of an element.


问:
Changing instance variables from a method in a class
I've made a class with some variables being set in the ___init____ and I want to be able to change these variables from methods in that class ie.

```<code>class example_class:

    def __init__(self, variable):
        self.thing = 'variable'

    def example_method(self):
        self.thing = 'changed text'

    def different_method(self):
        print(self.thing)
</code>```

So before calling "example_method" the value of self.thing is the string 'variable' and then after calling the method "example_method" self.thing now equals 'changed text'. This must be possible but I don't understand how to do it

答:
You must call the method you've defined into the class to happen.

```<code>class example_class:

    def __init__(self, variable):
        self.thing = 'variable'
        self.example_method()

    def example_method(self):
        self.thing = 'changed text'

    def different_method(self):
</code>```

In this way, when you get/create an instance of the class "example_class", the method "example_method" will be called in the constructor.

You could also do something like:

```<code>if __name__ == '__main__':
    my_class = example_class()
    my_class.example_method()
</code>```

Body:
I've made a class with some variables being set in the ___init____ and I want to be able to change these variables from methods in that class ie.

class example_class:

    def __init__(self, variable):
        self.thing = 'variable'

    def example_method(self):
        self.thing = 'changed text'

    def different_method(self):
        print(self.thing)

So before calling "example_method" the value of self.thing is the string 'variable' and then after calling the method "example_method" self.thing now equals 'changed text'. This must be possible but I don't understand how to do it

Body:
You must call the method you've defined into the class to happen.

class example_class:

    def __init__(self, variable):
        self.thing = 'variable'
        self.example_method()

    def example_method(self):
        self.thing = 'changed text'

    def different_method(self):

In this way, when you get/create an instance of the class "example_class", the method "example_method" will be called in the constructor.

You could also do something like:

if __name__ == '__main__':
    my_class = example_class()
    my_class.example_method()


问:
Way to not use goto loops in vba msgbox
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

```<code>Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub
</code>```

Thanks for any help you are able to provide

答:
I would use a MsgBox instead of an InputBox.

```<code>Sub GetYesNo()
    Dim answer As VbMsgBoxResult

    answer = MsgBox("Yes or No?", vbYesNo)

    If answer = vbYes Then
        'do something
    Else
        'do something else
    End If
End Sub
</code>```

Title: Way to not use goto loops in vba msgbox

Body:
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub

Thanks for any help you are able to provide

Body:
I would use a MsgBox instead of an InputBox.

Sub GetYesNo()
    Dim answer As VbMsgBoxResult

    answer = MsgBox("Yes or No?", vbYesNo)

    If answer = vbYes Then
        'do something
    Else
        'do something else
    End If
End Sub


问:
how to rotate a "triangle down" to a "triangle up" using css and jquery
i have the following triangle

created by the following css:

```<code>.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}
</code>```

html:

```<code><div class=triangle></div>
</code>```

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

```<code>.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}
</code>```

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

答:
Here You can use the follwing snippet using css transition ,by toggling a css  class :

$(".triangle").click(function() {
  $(this).toggleClass("triangle-up");

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin:20px;
}
.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s ease;

}

.triangle-up {
 transform:rotate(180deg);
 transform-origin: 50% 40%;
}</code>```

```

Body:
i have the following triangle

created by the following css:

.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;

}

html:

when i click on the triangle i want it to rotate and become a triangle facing up.Can you guide me on how to achieve this?

this the code tried for triangle up

.triangle-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 10px solid #555;
    margin-left: -10px;
}

im not sure how to get it to rotate when triangle down is clicked to triangle up,and then when triangle up is clicked it must rotate back to triangle down

Body:
Here You can use the follwing snippet using css transition ,by toggling a css  class :

$(".triangle").click(function() {
  $(this).toggleClass("triangle-up");

})

body {
  margin:20px;
}
.triangle {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 10px solid #cecece;
    margin-left: -10px;
    transition: .5s ease;

}

.triangle-up {
 transform:rotate(180deg);
 transform-origin: 50% 40%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="triangle"></div>


问:
Unable to send more than the first user data
I am making an admin page. I want to edit the user data if there is anything wrong.

Below is my table where admin can click "Edit" to edit the information.

I manage to get the data from this activity to second activity, but the data will only follow the first row.

When I click Edit for second row (BI14110391, Totalmarks:3), the data still remains to the first row data(BI14110104, Total Marks=8)

My code:

```<code>    public class assessment_table_edit extends AppCompatActivity {
        Toolbar toolbar;
        String data = "";
        TableLayout tlAssessment;
        TableRow tr;
        TextView stuID,totalmarks,marks,edit;
        ArrayList<Assessment_Information> users;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_assessment_table_edit);
            toolbar=(Toolbar)findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("Percentage of the Marks");
            tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);

            final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    data =getdb.getDataFromDB();
                    System.out.println(data);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            users=parseJSON(data);
                            addData(users);
                        }
                    });
                }
            }).start();

        }

        View.OnClickListener onClickListener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.assessment_id:
 //Problem is here
                        Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
                        Bundle b=new Bundle();
                        b.putString("stuID", users.get(0).getStuID());
                        b.putString("totalmarks",users.get(1).getTotalmarks());
                        iChange.putExtras(b);
                        // iChange.putExtra("stuID",user.getStuID());
                        startActivity(iChange);
                        break;
                }
            }
        };
</code>```

答:
The code below refers to wrong position when fetching data from row.

```<code>Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
                    Bundle b=new Bundle();
                    b.putString("stuID", **users.get(0).getStuID()**);
                    b.putString("totalmarks",**users.get(1).getTotalmarks()**);
                    iChange.putExtras(b);
                    // iChange.putExtra("stuID",user.getStuID());
                    startActivity(iChange);
</code>```

Please use proper position value.

Body:
I am making an admin page. I want to edit the user data if there is anything wrong.

Below is my table where admin can click "Edit" to edit the information.

I manage to get the data from this activity to second activity, but the data will only follow the first row.

When I click Edit for second row (BI14110391, Totalmarks:3), the data still remains to the first row data(BI14110104, Total Marks=8)

My code:

    public class assessment_table_edit extends AppCompatActivity {
        Toolbar toolbar;
        String data = "";
        TableLayout tlAssessment;
        TableRow tr;
        TextView stuID,totalmarks,marks,edit;
        ArrayList<Assessment_Information> users;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_assessment_table_edit);
            toolbar=(Toolbar)findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("Percentage of the Marks");
            tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);

            final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    data =getdb.getDataFromDB();
                    System.out.println(data);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            users=parseJSON(data);
                            addData(users);
                        }
                    });
                }
            }).start();

        }

        View.OnClickListener onClickListener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.assessment_id:
 //Problem is here
                        Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
                        Bundle b=new Bundle();
                        b.putString("stuID", users.get(0).getStuID());
                        b.putString("totalmarks",users.get(1).getTotalmarks());
                        iChange.putExtras(b);
                        // iChange.putExtra("stuID",user.getStuID());
                        startActivity(iChange);
                        break;
                }
            }
        };

Body:
The code below refers to wrong position when fetching data from row.

Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
                    Bundle b=new Bundle();
                    b.putString("stuID", **users.get(0).getStuID()**);
                    b.putString("totalmarks",**users.get(1).getTotalmarks()**);
                    iChange.putExtras(b);
                    // iChange.putExtra("stuID",user.getStuID());
                    startActivity(iChange);

Please use proper position value.


问:
Visual Studio 2010 SP1 Beta slow install
Started the SP1 beta install at 8 am today and at 11 am decided that the progress bar looked decidedly hung at about 5%. I pushed cancel which gives a message saying its rolling back but leaves the progress bar hung at the same location for the last hour.

Is the SP1 beta installer just really slow or is there something wrong with my specific setup?

The PC itself is half decent (win7, x64, dual core, 4gb ram, etc...). Did your install go quicker?

答: I had the same problem. "VS 2010 Slowlly installation, win 7 x64"(sic) solved it for me. </p>


问:
Show div using button and hide it if click outside the div
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new-shipping'">Open Div</button>
<div id="add-shipping-modal" style="display:none">
  <button id="close-add">Close Div</button>
  <p> Show Me </p>
</div></code>```

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

答:
try this </p>

```<code>$('#close-add').on('click', function () {
            $("#add-shipping-modal").hide();
        });

        $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });
        $("#add-shipping-modal").click(function () { return false; });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });
</code>```

Body:
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});

<button id="new-shipping'">Open Div</button>

  <button id="close-add">Close Div</button>

 Show Me

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

Body:
try this

$('#close-add').on('click', function () {
            $("#add-shipping-modal").hide();
        });

        $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });
        $("#add-shipping-modal").click(function () { return false; });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });


问:
Removing white spacing between stacked elements in CSS
I am trying to remove spacing between elements stacked on each other.

This is what i have:

input[type="text"] {
  width: 40%;
  height: 30px;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  border-width: 0;
}

input[type="submit"] {
  margin-left: -100px;
  height: 30px;
  width: 100px;
  border-width: 0;
  border-radius: 29px;
  background: blue;
  color: white;
  -webkit-appearance: none;
}

body {
  background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br/>
<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname" placeholder="Enter your email"><input type="submit">
</form></code>```

I have tried top:0; and bottom:0; but it does not seem to solve my problem in this example.

答:
Remove the top bottom padding of input[type="text"].</p>

```<code>input[type="text"] {
  width: 40%;
  height: 30px;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</code>```

Body:
I am trying to remove spacing between elements stacked on each other.

This is what i have:

input[type="text"] {
  width: 40%;
  height: 30px;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  border-width: 0;
}

input[type="submit"] {
  margin-left: -100px;
  height: 30px;
  width: 100px;
  border-width: 0;
  border-radius: 29px;
  background: blue;
  color: white;
  -webkit-appearance: none;
}

body {
  background-color: black;
}

<form>
  First Name
  <input type="text" id="fname" name="fname" placeholder="Enter your email"><input type="submit">
</form>

I have tried top:0; and bottom:0; but it does not seem to solve my problem in this example.

Body:
Remove the top bottom padding of input[type="text"].

input[type="text"] {
  width: 40%;
  height: 30px;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  padding-top: 0;
  padding-bottom: 0;
}


问:
MSTest/Visual Studio parallel test running
Ran into a problem recently with VS/MSTest and wondering if anyone has had a similar issue.

I'm currently working on a UI framework in c# using MSTest and over the past few weeks I've been implementing selenium grid/Jenkins for CI.

Selenium grid facilitates parallel test running but the running is done by MSTest. in the past few weeks parallel test running with VS has stopped working.

No changes have been made to how the tests are structured or created but when multiple driver instances are created Driver A works until Driver B is created then Driver B runs while Driver A stops executing steps.

I'm beginning to think it's a bug with WebDriver or MSTest itself as it's weird for something that was working to stop working without any code changes. Wondering if anyone else has had similar problems.

It had been working for me for months and I had found some issues by running in parallel so it's strange that it has suddenly stopped working with no changes. It was last working around 2 months ago.

I tried changing every static method/variable in the solution to not being static as I've read statics can cause problems but it didn't help.

setup is
Unit Test solution using Seleno (Webdriver Nuget Package)
Tests written as unit tests using in MSTest. Page Object approach.

Driver:Chromedriver 2.33

Chrome version:  Version 62.0.3202.75 (Official Build) (64-bit)

Parallel test running enabled using a .Testsettings file in the solution

same thing happening with latest version of IE/IEDriverServer which makes me think it may be WebDriver that is an issue.

Any help or thoughts would be much appreciated.

Thanks,

G

答:
I'm having exactly the same issue. In my case, it's the first time I implement Selenium grid and try to run tests in parallel. They run sequentially.

I've found this:

http://colinsalmcorner.com/post/parallel-testing-in-a-selenium-grid-with-vsts

Apparently the only way to solve it is putting tests in separate .csproj files, or maybe running multiple mstest processes with appropriate list of tests as arguments on each one (with some utility you can create). Please keep me posted.


问:
convert multilevel nested array using into json using javascript
I have the code, where I load data from a csv file and get the data by grouping data using D3.

The code I wrote is:

```<code>                d3.csv("data/data2.csv", function(data1) {

                  var workStation =
                                {"key":"Data","values":
                                d3.nest()
                                .key(function(d) { return d.WorkStation_Id; })
                                .key(function(d) { return d.Order_Id; })
                                .rollup(function(v) {
                                    return v.map(function(c){
                                        return { "actualStart": convertscheduledtime(c.ScheduledTime),"rowHeight": 30, "actualEnd":c.Duration*1000+convertscheduledtime(c.ScheduledTime), "name":c.Order_Id};
                                    });
                                }).entries(data1)};

                var d2= [{"name":"Data", "children":workStation.values.map( function(major){
                        return {
                            "name": major.key,
                            "children":major.values.map( function(Order_Id){
                                return{
                                    "name" : Order_Id.key,
                                    "actualStart" : Order_Id.values.actualStart,
                                    "actualEnd" : Order_Id.values.actualEnd
                                };
                            })
                            };
                        })
                    }];

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

What I was trying to do was convert the obtained result to json format using the following code which I found online:
These are the following I am trying to do:

1) I am trying to get the Start Time End Time. I am calculating the Start time by adding the Duration.
2) The array that is obtained is coming as nested key values pair. I am trying to convert them to JSON data so that I can just pass this into the var treeData Gantt chart of anychart.js.

The following is the JSON data what I am trying to achieve and I got the data that I want till children's name:1, for actualStart and actualEnd I am getting undefined as the value:
         parent : 10A,
        children:[{
                        name:1,
                        actualStart:18332233333,
                        actualEnd:12343434444},
                      {
                        name:2,
                        actualStart:18332233898,
                        actualEnd:12343434998},
                        ....
                ],
        parent : 10B,
        children: [{
                        name:1,
                        actualStart:18332233333,
                        actualEnd:12343434444},
                      {
                        name:2,
                        actualStart:18332233898,
                        actualEnd:12343434998},
                        ....
        ]
....
Could someone kindly suggest what I need to change to get the actualStart and actualEnd data.

Thank you.

I have included the sample csv data:

```<code>ScheduledTime,WorkStation_Id,Order_Id,Duration(seconds)
</code>```

01.01.2016  00:00:00,10A,1,15

        01.01.2016  00:00:15,10A,1,25

        01.01.2016  00:00:35,10A,1,10

        01.01.2016  00:00:45,10A,2,10

        01.01.2016  00:00:55,10A,2,10

        01.01.2016  00:01:05,10B,1,20

        01.01.2016  00:01:25,10B,1,10

        01.01.2016  00:01:35,10B,2,20

        .....

答:
In this case, you need some custom data formatting. Below you may find the code which takes the .csv data you provided us before, then parses it, groups and formats. After that creates gantt project chart. This code helps to get the data structure you want.

```<code>//parse .csv data and group by WorkStation_Id
d3.csv("data.csv", function (data1) {
    var workStation = d3.nest()
        .key(function (d) {
            return d.WorkStation_Id;
        })
        .entries(data1);

    //get formatted data as a tree
    var formattedData = formatData(workStation);
    console.log(formattedData);

    //set formatted data as a tree
    var treeData = anychart.data.tree(formattedData, "as-tree");
    // chart type
    chart = anychart.ganttProject();

    // set data for the chart
    chart.data(treeData);

    // set container id for the chart
    chart.container('container').draw();

    // Fit all visible data to timeline.
    chart.fitAll();
});

//helper function to format data in apropriate way
//to set to the gantt chart
function formatData(data) {

    var outputData = [];

    data.forEach(function (item) {
        var itemObj = {};
        itemObj['name'] = item['key'];
        itemObj['children'] = [];

        var childs = item['values'];

        for (var i = 0; i < childs.length; i++) {
            var childObj = {};
            childObj['name'] = 'Order ID: ' + childs[i]['Order_Id'] + '-' + i;
            childObj['actualStart'] = new Date(childs[i]['ScheduledTime']).getTime();
            childObj['actualEnd'] = childObj['actualStart'] + childs[i]['Duration(seconds)'] * 1000;
            childObj['Order_Id'] = childs[i]['Order_Id'];
            itemObj['children'].push(childObj);
        }
        outputData.push(itemObj);
    });
    return outputData;
}
</code>```

Below is a screenshot of the chart which is built by this code.

Body:
I have the code, where I load data from a csv file and get the data by grouping data using D3.

The code I wrote is:

                d3.csv("data/data2.csv", function(data1) {

                  var workStation =
                                {"key":"Data","values":
                                d3.nest()
                                .key(function(d) { return d.WorkStation_Id; })
                                .key(function(d) { return d.Order_Id; })
                                .rollup(function(v) {
                                    return v.map(function(c){
                                        return { "actualStart": convertscheduledtime(c.ScheduledTime),"rowHeight": 30, "actualEnd":c.Duration*1000+convertscheduledtime(c.ScheduledTime), "name":c.Order_Id};
                                    });
                                }).entries(data1)};

                var d2= [{"name":"Data", "children":workStation.values.map( function(major){
                        return {
                            "name": major.key,
                            "children":major.values.map( function(Order_Id){
                                return{
                                    "name" : Order_Id.key,
                                    "actualStart" : Order_Id.values.actualStart,
                                    "actualEnd" : Order_Id.values.actualEnd
                                };
                            })
                            };
                        })
                    }];

    });
    console.log(d2);

What I was trying to do was convert the obtained result to json format using the following code which I found online:
These are the following I am trying to do:

1) I am trying to get the Start Time End Time. I am calculating the Start time by adding the Duration.
2) The array that is obtained is coming as nested key values pair. I am trying to convert them to JSON data so that I can just pass this into the var treeData Gantt chart of anychart.js.

The following is the JSON data what I am trying to achieve and I got the data that I want till children's name:1, for actualStart and actualEnd I am getting undefined as the value:
         parent : 10A,
        children:[{
                        name:1,
                        actualStart:18332233333,
                        actualEnd:12343434444},
                      {
                        name:2,
                        actualStart:18332233898,
                        actualEnd:12343434998},
                        ....
                ],
        parent : 10B,
        children: [{
                        name:1,
                        actualStart:18332233333,
                        actualEnd:12343434444},
                      {
                        name:2,
                        actualStart:18332233898,
                        actualEnd:12343434998},
                        ....
        ]
....
Could someone kindly suggest what I need to change to get the actualStart and actualEnd data.

Thank you.

I have included the sample csv data:

ScheduledTime,WorkStation_Id,Order_Id,Duration(seconds)

01.01.2016  00:00:00,10A,1,15

        01.01.2016  00:00:15,10A,1,25

        01.01.2016  00:00:35,10A,1,10

        01.01.2016  00:00:45,10A,2,10

        01.01.2016  00:00:55,10A,2,10

        01.01.2016  00:01:05,10B,1,20

        01.01.2016  00:01:25,10B,1,10

        01.01.2016  00:01:35,10B,2,20

        .....

Body:
In this case, you need some custom data formatting. Below you may find the code which takes the .csv data you provided us before, then parses it, groups and formats. After that creates gantt project chart. This code helps to get the data structure you want.

//parse .csv data and group by WorkStation_Id
d3.csv("data.csv", function (data1) {
    var workStation = d3.nest()
        .key(function (d) {
            return d.WorkStation_Id;
        })
        .entries(data1);

    //get formatted data as a tree
    var formattedData = formatData(workStation);
    console.log(formattedData);

    //set formatted data as a tree
    var treeData = anychart.data.tree(formattedData, "as-tree");
    // chart type
    chart = anychart.ganttProject();

    // set data for the chart
    chart.data(treeData);

    // set container id for the chart
    chart.container('container').draw();

    // Fit all visible data to timeline.
    chart.fitAll();
});

//helper function to format data in apropriate way
//to set to the gantt chart
function formatData(data) {

    var outputData = [];

    data.forEach(function (item) {
        var itemObj = {};
        itemObj['name'] = item['key'];
        itemObj['children'] = [];

        var childs = item['values'];

        for (var i = 0; i < childs.length; i++) {
            var childObj = {};
            childObj['name'] = 'Order ID: ' + childs[i]['Order_Id'] + '-' + i;
            childObj['actualStart'] = new Date(childs[i]['ScheduledTime']).getTime();
            childObj['actualEnd'] = childObj['actualStart'] + childs[i]['Duration(seconds)'] * 1000;
            childObj['Order_Id'] = childs[i]['Order_Id'];
            itemObj['children'].push(childObj);
        }
        outputData.push(itemObj);
    });
    return outputData;
}

Below is a screenshot of the chart which is built by this code.


问:
Turn id back into a reference object in AppScript objective-c
I'm writing an app that talks to Mail using Objective-C-appscript (objc-appscript). I want to make a copy of the currently selected mail messages and perform some processing on it at a later -- at which time the current selection may have changed.

```<code>MLApplication *mail = [[MLApplication alloc] initWithBundleID: @"com.apple.mail"];
MLReference *ref = [mail selection];
id theSelection = [[ref getItem] copy];

// Do something here, which may change the contents of ref,
// but that's okay since I made a copy in theSelection

MLMoveCommand *cmd = [[theSelection move] to: [[mail mailboxes] byName:@"test"]];

// This command should move the selected messages to the mailbox but fails
// because theSelection

MLReference *ref2 = nil; // Need to turn theSelection into an MLReference *
MLMoveCommand *cmd = [[ref2 move] to: [[mail mailboxes] byName:@"test"]];
</code>```

I need to turn theSelection back into an MLReference *. I'm sure this should be a simple operation, but I am new to appscript and require some guidance. Thanks!

答:
You're assuming Apple event IPC uses proxy objects like Distributed Objects, but that's not the case: it's RPC + queries. (Think XPath over XML-RPC as a rough analogy.) It's a common misconception - Apple themselves totally fail at explaining it - but grasping Apple events' query-based nature is essential to controlling scriptable apps effectively.

Anyway, here's where you're going wrong:

```<code>id theSelection = [[ref getItem] copy];
</code>```

This line copies an MLReference object identifying Mail's selection property, but as a reference is basically analogous to a URL that's effectively a no-op.

```<code>MLMoveCommand *cmd = [[theSelection move] to: [[mail mailboxes] byName:@"test"]];
</code>```

This line tells Mail to move the object(s) it finds at the referenced location. That command may or may not work depending on how capable Mail's scripting support is (some apps may be capable of manipulating multiple objects with a single command; others are limited to a single object per command). But even if it does work, it will be operating on whatever's selected at the time the command is sent - which isn't what you're after.

The correct solution in this case is to use a get command to retrieve a list of references (in this case, an NSArray of MLReference instances), which you can later iterate over to move each of the referenced messages in turn. Fortunately, the references that Mail returns identify messages by id, which means that they should continue pointing to the original message objects even if they're moved in the meantime. (By-index and by-name references are much less stable, so you need to be a lot more careful working with apps that use those.)

For example (error checking omitted for clarity):

```<code>MLApplication *mail = [MLApplication applicationWithBundleID: @"com.apple.mail"];
NSArray *messageRefs = [[mail selection] getItem];
// do other stuff here
MLReference *message;
for (message in messageRefs) {
    MLMoveCommand *cmd = [[mail move: message] to: [[mail mailboxes] byName: @"test"]];
    id result = [cmd send];
}
</code>```

See the appscript manual for more information. Also, ASTranslate is your friend.

Body:
I'm writing an app that talks to Mail using Objective-C-appscript (objc-appscript). I want to make a copy of the currently selected mail messages and perform some processing on it at a later -- at which time the current selection may have changed.

MLApplication *mail = [[MLApplication alloc] initWithBundleID: @"com.apple.mail"];
MLReference *ref = [mail selection];
id theSelection = [[ref getItem] copy];

// Do something here, which may change the contents of ref,
// but that's okay since I made a copy in theSelection

MLMoveCommand *cmd = [[theSelection move] to: [[mail mailboxes] byName:@"test"]];

// This command should move the selected messages to the mailbox but fails
// because theSelection

MLReference *ref2 = nil; // Need to turn theSelection into an MLReference *
MLMoveCommand *cmd = [[ref2 move] to: [[mail mailboxes] byName:@"test"]];

I need to turn theSelection back into an MLReference *. I'm sure this should be a simple operation, but I am new to appscript and require some guidance. Thanks!

Body:
You're assuming Apple event IPC uses proxy objects like Distributed Objects, but that's not the case: it's RPC + queries. (Think XPath over XML-RPC as a rough analogy.) It's a common misconception - Apple themselves totally fail at explaining it - but grasping Apple events' query-based nature is essential to controlling scriptable apps effectively.

Anyway, here's where you're going wrong:

id theSelection = [[ref getItem] copy];

This line copies an MLReference object identifying Mail's selection property, but as a reference is basically analogous to a URL that's effectively a no-op.

MLMoveCommand *cmd = [[theSelection move] to: [[mail mailboxes] byName:@"test"]];

This line tells Mail to move the object(s) it finds at the referenced location. That command may or may not work depending on how capable Mail's scripting support is (some apps may be capable of manipulating multiple objects with a single command; others are limited to a single object per command). But even if it does work, it will be operating on whatever's selected at the time the command is sent - which isn't what you're after.

The correct solution in this case is to use a get command to retrieve a list of references (in this case, an NSArray of MLReference instances), which you can later iterate over to move each of the referenced messages in turn. Fortunately, the references that Mail returns identify messages by id, which means that they should continue pointing to the original message objects even if they're moved in the meantime. (By-index and by-name references are much less stable, so you need to be a lot more careful working with apps that use those.)

For example (error checking omitted for clarity):

MLApplication *mail = [MLApplication applicationWithBundleID: @"com.apple.mail"];
NSArray *messageRefs = [[mail selection] getItem];
// do other stuff here
MLReference *message;
for (message in messageRefs) {
    MLMoveCommand *cmd = [[mail move: message] to: [[mail mailboxes] byName: @"test"]];
    id result = [cmd send];
}

See the appscript manual for more information. Also, ASTranslate is your friend.


答:
I removed the height property from both elements and added it to the container, the form. Then added display: flex to the form.

form {
  height: 30px;
  display: flex;
}

input[type="text"] {
  width: 40%;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  border-width: 0;
}

input[type="submit"] {
  margin-left: -100px;
  width: 100px;
  border-width: 0;
  border-radius: 29px;
  background: blue;
  color: white;
  -webkit-appearance: none;
}

body {
  background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br/>
<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname" placeholder="Enter your email"><input type="submit">
</form></code>```

Title: Removing white spacing between stacked elements in CSS

Body:
I removed the height property from both elements and added it to the container, the form. Then added display: flex to the form.

form {
  height: 30px;
  display: flex;
}

input[type="text"] {
  width: 40%;
  border-radius: 29px;
  border-style: none;
  padding-right: 100px;
  padding-left: 30px;
  border-width: 0;
}

input[type="submit"] {
  margin-left: -100px;
  width: 100px;
  border-width: 0;
  border-radius: 29px;
  background: blue;
  color: white;
  -webkit-appearance: none;
}

body {
  background-color: black;
}

<br/>
<form>
  <label for="fname">First Name</label>
  <input type="text" id="fname" name="fname" placeholder="Enter your email"><input type="submit">
</form>


问:
How can I make variables accessible to all the functions within the class in php
I want my variables to be accessible to all the functions within the class in php.
I am giving a sample code of what Im trying to achieve. Please help me out.

```<code>class ClassName extends AnotherClass {

    function __construct(argument)
    {

    }

    $name = $this->getName();
    $city = $this->getCity();
    $age = 24;

    public function getName() {
        return 'foo';
    }

    public function getCity() {
        return 'kolkata';
    }

    public function fun1() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun2() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun3() {
        echo $name;
        echo $city;
        echo $age;
    }
}
</code>```

Or if there is any other way to have least overhead .Please suggest

答:
You have to set your variables as class attributes:

```<code>class ClassName extends AnotherClass {
    private $name;
    private $city;
    private $age;

    //Here we do our setters and getters
    public function setName($name)
    {$this->name = $name;}
    public function getName()
    {return $this->name;}

   // you call the setters in your construct, and you set the values there
</code>```

Of course you can set them as private, public or protected, depends if you want them to be accessible only from this class or others.

Body:
I want my variables to be accessible to all the functions within the class in php.
I am giving a sample code of what Im trying to achieve. Please help me out.

class ClassName extends AnotherClass {

    function __construct(argument)
    {

    }

    $name = $this->getName();
    $city = $this->getCity();
    $age = 24;

    public function getName() {
        return 'foo';
    }

    public function getCity() {
        return 'kolkata';
    }

    public function fun1() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun2() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun3() {
        echo $name;
        echo $city;
        echo $age;
    }
}

Or if there is any other way to have least overhead .Please suggest

Body:
You have to set your variables as class attributes:

class ClassName extends AnotherClass {
    private $name;
    private $city;
    private $age;

    //Here we do our setters and getters
    public function setName($name)
    {$this->name = $name;}
    public function getName()
    {return $this->name;}

   // you call the setters in your construct, and you set the values there

Of course you can set them as private, public or protected, depends if you want them to be accessible only from this class or others.


问:
Firebase onMessageReceived not called when app in background
I'm working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appears on the notification centre of the device, but when the notification appears or even if I click on it, the onMessageReceived method inside my FCMessagingService is never called.

When I tested this while my app was in the foreground, the onMessageReceived method was called and everything worked fine. The problem occurs when the app is running in the background.

Is this intended behaviour, or is there a way I can fix this?

Here is my FBMessagingService:

```<code>import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FBMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i("PVL", "MESSAGE RECEIVED!!");
        if (remoteMessage.getNotification().getBody() != null) {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody());
        } else {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message"));
        }
    }
}
</code>```

答:
If app is in background Fire-base by default handling notification But if we want to our custom notification than we have to change our server side, which is responsible for to send our custom data(data payload)

Remove notification payload completely from your server request. Send only Data and handle it in onMessageReceived() otherwise your onMessageReceived will not be triggered when app is in background or killed.

now,your server side code format look like,

```<code>{
  "collapse_key": "CHAT_MESSAGE_CONTACT",
  "data": {
    "loc_key": "CHAT_MESSAGE_CONTACT",
    "loc_args": ["John Doe", "Contact Exchange"],
    "text": "John Doe shared a contact in the group Contact Exchange",
    "custom": {
      "chat_id": 241233,
      "msg_id": 123
    },
    "badge": 1,
    "sound": "sound1.mp3",
    "mute": true
  }
}
</code>```

NOTE: see this line in above code

"text": "John Doe shared a contact in the group Contact Exchange"
in Data payload you should use "text" parameter instead of "body" or "message" parameters for message description or whatever you want to use text.

onMessageReceived()

```<code>@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getData().toString());

        if (remoteMessage == null)
            return;

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
           /* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
            Log.e(TAG, "Data Payload: " + remoteMessage);

            try {

                Map<String, String> params = remoteMessage.getData();
                JSONObject json = new JSONObject(params);
                Log.e("JSON_OBJECT", json.toString());

                Log.e(TAG, "onMessageReceived: " + json.toString());

                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }
</code>```

Body:
I'm working with Firebase and testing sending notifications to my app from my server while the app is in the background. The notification is sent successfully, it even appears on the notification centre of the device, but when the notification appears or even if I click on it, the onMessageReceived method inside my FCMessagingService is never called.

When I tested this while my app was in the foreground, the onMessageReceived method was called and everything worked fine. The problem occurs when the app is running in the background.

Is this intended behaviour, or is there a way I can fix this?

Here is my FBMessagingService:

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FBMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.i("PVL", "MESSAGE RECEIVED!!");
        if (remoteMessage.getNotification().getBody() != null) {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getNotification().getBody());
        } else {
            Log.i("PVL", "RECEIVED MESSAGE: " + remoteMessage.getData().get("message"));
        }
    }
}

Body:
If app is in background Fire-base by default handling notification But if we want to our custom notification than we have to change our server side, which is responsible for to send our custom data(data payload)

Remove notification payload completely from your server request. Send only Data and handle it in onMessageReceived() otherwise your onMessageReceived will not be triggered when app is in background or killed.

now,your server side code format look like,

{
  "collapse_key": "CHAT_MESSAGE_CONTACT",
  "data": {
    "loc_key": "CHAT_MESSAGE_CONTACT",
    "loc_args": ["John Doe", "Contact Exchange"],
    "text": "John Doe shared a contact in the group Contact Exchange",
    "custom": {
      "chat_id": 241233,
      "msg_id": 123
    },
    "badge": 1,
    "sound": "sound1.mp3",
    "mute": true
  }
}

NOTE: see this line in above code

"text": "John Doe shared a contact in the group Contact Exchange"
in Data payload you should use "text" parameter instead of "body" or "message" parameters for message description or whatever you want to use text.

onMessageReceived()

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getData().toString());

        if (remoteMessage == null)
            return;

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
           /* Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());*/
            Log.e(TAG, "Data Payload: " + remoteMessage);

            try {

                Map<String, String> params = remoteMessage.getData();
                JSONObject json = new JSONObject(params);
                Log.e("JSON_OBJECT", json.toString());

                Log.e(TAG, "onMessageReceived: " + json.toString());

                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }


问:
Are there different libraries of Windows system calls?
From looking at traces of system calls in Windows, I am very confused by the different types of these. Here are some different types I've encountered:

```<code>NtQueryPerformanceCounter( Counter=0xbcf6c8 [1.45779e+009], Freq=null ) => 0
NtProtectVirtualMemory( ProcessHandle=-1, BaseAddress=0xbcf6f4 …
NtProtectVirtualMemory( ProcessHandle=-1, BaseAddress=0xbcf6f4 [0x7702e000]…
NtQuerySystemInformation( SystemInformationClass=0 [SystemBasicInformation]
NtQueryVirtualMemory( ProcessHandle=-1, BaseAddress=0x76f20000, MemoryInformationClass=6, MemoryInformation=0xbcf440, Length=0xc, ReturnLength=null ) => 0
</code>```

I know that these are referred to as API system calls. My untrained eye classify these as system calls that start with "Nt".

But I've also encountered these:

```<code>"CreateSemaphoreW","CreateSemaphoreA","GlobalAddAtomW","lstrcpynW","LoadLibraryExW","SearchPathW",
"CreateFileW","CreateFileMappingW","MapViewOfFileEx","GetSystemMetrics","RegisterClipboardFormatW","SystemParametersInfoW",
"GetDC","GetDeviceCaps","ReleaseDC","LocalAlloc"
</code>```

Although I may be wrong, I assume that these are system calls that are lower in level than those that start with Nt.

And this is another trace that I've encountered:

```<code>  HeapAlloc HeapAlloc HeapFree HeapFree HeapAlloc HeapAlloc HeapFree
HeapFree NtOpenKey GetProcessHeap HeapAlloc NtOpenKey HeapAlloc NtOpenKey
 NtQueryValueKey NtQueryValueKey HeapFree HeapAlloc HeapAlloc NtOpenKey
NtQueryValueKey HeapAlloc HeapAlloc RegOpenKeyExW
</code>```

This trace contains both Nt and those without... I understand that I may sound too unknowledgeable in this field but I really would like to develop a better general idea of what these are.

These traces make me assume that there are different sets of system calls that people seem to refer to them in the same name ("system calls"), in Windows. Could somebody tell me if I am wrong? And if I am right, are there names for these different sets of system calls?

Thank you

答:
The top snippet shows native api function names, the actual api of the operating system.  The api you'd target when you write drivers.  But that is rarely the api you use when you write your own programs.  Windows NT originally included three distinct api layers, Win32, OS/2 and Posix.

The second snippet shows function names from the Win32 api layer, by far the most common one you target when you write a Windows program.  The OS/2 subsystem was retired a long time ago.  Posix fell out of use and was discontinued at Win8 and Server2012, but is back in Win10 with the new Linux subsystem.

Such a subsystem is implemented by translating its api functions into equivalent native api functions, if any.  Most of the Win32 subsystem code lives in kernel32.dll, gdi32.dll, user32.dll and advapi.dll.  ntdll.dll is the native api wrapper that calls into the kernel when necessary.  Native api function names start with Nt or Zw.  There is a glue layer that marries the two that gets exposed occasionally, its function names start with Rtl.

Primary advantage of this layering is that Microsoft can innovate on the OS without breaking existing programs.  Code that was written 30 years ago is still pretty likely to compile and run correctly on a current OS, in spite of two very drastic architecture changes and many Windows releases.  The last big change to the native api was at Vista, major version 6.

Body:
From looking at traces of system calls in Windows, I am very confused by the different types of these. Here are some different types I've encountered:

NtQueryPerformanceCounter( Counter=0xbcf6c8 [1.45779e+009], Freq=null ) => 0
NtProtectVirtualMemory( ProcessHandle=-1, BaseAddress=0xbcf6f4 …
NtProtectVirtualMemory( ProcessHandle=-1, BaseAddress=0xbcf6f4 [0x7702e000]…
NtQuerySystemInformation( SystemInformationClass=0 [SystemBasicInformation]
NtQueryVirtualMemory( ProcessHandle=-1, BaseAddress=0x76f20000, MemoryInformationClass=6, MemoryInformation=0xbcf440, Length=0xc, ReturnLength=null ) => 0

I know that these are referred to as API system calls. My untrained eye classify these as system calls that start with "Nt".

But I've also encountered these:

"CreateSemaphoreW","CreateSemaphoreA","GlobalAddAtomW","lstrcpynW","LoadLibraryExW","SearchPathW",
"CreateFileW","CreateFileMappingW","MapViewOfFileEx","GetSystemMetrics","RegisterClipboardFormatW","SystemParametersInfoW",
"GetDC","GetDeviceCaps","ReleaseDC","LocalAlloc"

Although I may be wrong, I assume that these are system calls that are lower in level than those that start with Nt.

And this is another trace that I've encountered:

  HeapAlloc HeapAlloc HeapFree HeapFree HeapAlloc HeapAlloc HeapFree
HeapFree NtOpenKey GetProcessHeap HeapAlloc NtOpenKey HeapAlloc NtOpenKey
 NtQueryValueKey NtQueryValueKey HeapFree HeapAlloc HeapAlloc NtOpenKey
NtQueryValueKey HeapAlloc HeapAlloc RegOpenKeyExW

This trace contains both Nt and those without... I understand that I may sound too unknowledgeable in this field but I really would like to develop a better general idea of what these are.

These traces make me assume that there are different sets of system calls that people seem to refer to them in the same name ("system calls"), in Windows. Could somebody tell me if I am wrong? And if I am right, are there names for these different sets of system calls?

Thank you