问:
How to use UIPickerView inside UITableViewController
Hi I have a Table view Controller Name as MyTableViewController. In MyTableViewController, i am using different UIPickerView inside different cell of table which is name as headerCell which is set by the following function and in that i am not using any UIPickerView

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyTableViewCell
    headerCell.contentView.backgroundColor = UIColor.white
    return headerCell
}
</code>```

MyTableViewCell is class of UITableViewCell type in which, I have attached all table layouts like Label, TextField, Button,UIPickerView and etc.

My Second cell is middleCell an footerCell which is as

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : SubscriptionTableViewCell?
    if indexPath.row == 1 {
        cell = tableView.dequeueReusableCell(withIdentifier: "footer", for: indexPath) as? SubscriptionTableViewCell
        cell!.cardTypePicker.delegate = self
        cell!.expMonth.delegate = self
        cell!.expYear.delegate = self
        cell!.countryPicker.delegate = self
        cell!.shippingMethodPicker.delegate = self

        cell!.cardTypePicker.dataSource = self
        cell!.expMonth.dataSource = self
        cell!.expYear.dataSource = self
        cell!.countryPicker.dataSource = self
        cell!.shippingMethodPicker.dataSource = self

    }else {
        cell = tableView.dequeueReusableCell(withIdentifier: "middle", for: indexPath) as? SubscriptionTableViewCell
        cell!.variantPicker.delegate = self
        cell!.variantPicker.dataSource = self
    }
    return cell!
}
</code>```

as you can see there are different UIPickerView.
So now i am not able to understand how should i use UIPickerView delegates inside UITableViewController.

Please help for that thanks.

答:
class TableViewCell: UITableViewCell {

```<code>@IBOutlet var pickerView: UIPickerView!

var arrCountryName : [String] = []

override func awakeFromNib() {
    super.awakeFromNib()

    arrCountryName = ["India" , "Australia"]
    pickerView.delegate = self
    pickerView.dataSource = self
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
</code>```

}

extension TableViewCell : UIPickerViewDataSource , UIPickerViewDelegate {

```<code>func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return arrCountryName.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return arrCountryName[row]
}
</code>```

}

Body:
Hi I have a Table view Controller Name as MyTableViewController. In MyTableViewController, i am using different UIPickerView inside different cell of table which is name as headerCell which is set by the following function and in that i am not using any UIPickerView

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCell(withIdentifier: "header") as! MyTableViewCell
    headerCell.contentView.backgroundColor = UIColor.white
    return headerCell
}

MyTableViewCell is class of UITableViewCell type in which, I have attached all table layouts like Label, TextField, Button,UIPickerView and etc.

My Second cell is middleCell an footerCell which is as

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : SubscriptionTableViewCell?
    if indexPath.row == 1 {
        cell = tableView.dequeueReusableCell(withIdentifier: "footer", for: indexPath) as? SubscriptionTableViewCell
        cell!.cardTypePicker.delegate = self
        cell!.expMonth.delegate = self
        cell!.expYear.delegate = self
        cell!.countryPicker.delegate = self
        cell!.shippingMethodPicker.delegate = self

        cell!.cardTypePicker.dataSource = self
        cell!.expMonth.dataSource = self
        cell!.expYear.dataSource = self
        cell!.countryPicker.dataSource = self
        cell!.shippingMethodPicker.dataSource = self

    }else {
        cell = tableView.dequeueReusableCell(withIdentifier: "middle", for: indexPath) as? SubscriptionTableViewCell
        cell!.variantPicker.delegate = self
        cell!.variantPicker.dataSource = self
    }
    return cell!
}

as you can see there are different UIPickerView.
So now i am not able to understand how should i use UIPickerView delegates inside UITableViewController.

Please help for that thanks.

Body:
class TableViewCell: UITableViewCell {

@IBOutlet var pickerView: UIPickerView!

var arrCountryName : [String] = []

override func awakeFromNib() {
    super.awakeFromNib()

    arrCountryName = ["India" , "Australia"]
    pickerView.delegate = self
    pickerView.dataSource = self
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

extension TableViewCell : UIPickerViewDataSource , UIPickerViewDelegate {

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return arrCountryName.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return arrCountryName[row]
}

}


来源: stackexchange

问:
Postsharp MethodInterceptionAspect get method return value
I have an implementation of MethodInterceptionAspect(PostSharp)
but when I in the override OnInvoke method, the args.Method is null,
I need to know the method return value type,

anyone know about?

```<code>[PSerializable]
public class PSHandleRequestAttribute : MethodInterceptionAspect
{
    public PSHandleRequestAttribute(bool readOnly = true) : base()
    {
        ReadOnly = readOnly;
    }

    #region Properties

    protected bool ReadOnly { get; set; }

    #endregion Properties

    #region Public Methods

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        var instance = args.Instance as IBusinessTransaction;
        var method = args.Method;
        if (instance.IsNull())
        {
            throw new Exception("Use PSHandleRequestAttribute only for IBusinessTransaction");
        }

        instance.OpenTransaction();

        try
        {
            args.Proceed();
            //base.OnInvoke(args);
            instance.CommitTransaction();
            return;
        }
        catch (Exception ex)
        {
            var errorMessage = instance.RollbackTransaction(ex);

            return;
        }
    }

    #endregion Public Methods
}
</code>```

答:
PostSharp optimizes the resulting code, so when the value of args.Method is not used anywhere, the optimizer skips some operations and passes null as the value.

Once you use the value in your code, the value should appear.

I'd also recommend you to do the usage validation in CompileTimeValidate method and emit a build time error message. This way you would catch a possible error in build time. See http://doc.postsharp.net/aspect-validation.

ContentLicense: CC BY-SA 3.0

Body:
I have an implementation of MethodInterceptionAspect(PostSharp)
but when I in the override OnInvoke method, the args.Method is null,
I need to know the method return value type,

anyone know about?

[PSerializable]
public class PSHandleRequestAttribute : MethodInterceptionAspect
{
    public PSHandleRequestAttribute(bool readOnly = true) : base()
    {
        ReadOnly = readOnly;
    }

    #region Properties

    protected bool ReadOnly { get; set; }

    #endregion Properties

    #region Public Methods

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        var instance = args.Instance as IBusinessTransaction;
        var method = args.Method;
        if (instance.IsNull())
        {
            throw new Exception("Use PSHandleRequestAttribute only for IBusinessTransaction");
        }

        instance.OpenTransaction();

        try
        {
            args.Proceed();
            //base.OnInvoke(args);
            instance.CommitTransaction();
            return;
        }
        catch (Exception ex)
        {
            var errorMessage = instance.RollbackTransaction(ex);

            return;
        }
    }

    #endregion Public Methods
}


问:
The type List is not generic; it cannot be parameterized with arguments
Iv read that I should be able to create an ArrayList by using the following code:

```<code>List<String> myList = new ArrayList<>();
</code>```

however; when I do i get the error: "The type List is not generic; it cannot be parameterized with arguments  "

```<code>import java.awt.List;
import java.util.ArrayList;

public class Euler1 {

    public static void main(String[] args) {
        List<String> nuList = new ArrayList<>();

    }

}
</code>```

答: What you've read is for java.util.List not the awt-list. You need to change your import.

ContentLicense: CC BY-SA 4.0

Body:
Iv read that I should be able to create an ArrayList by using the following code:

List<String> myList = new ArrayList<>();

however; when I do i get the error: "The type List is not generic; it cannot be parameterized with arguments  "

import java.awt.List;
import java.util.ArrayList;

public class Euler1 {

    public static void main(String[] args) {
        List<String> nuList = new ArrayList<>();

    }

}


问:
Check if an item exists in an observableArray
Why is the check for duplicate Artist always returning false?

See this JSFiddle for a runnable demo.

Knockout Code

```<code>$(function() {

  function Artist(name) {
    this.name = name;
  }

  function ViewModel() {
    var self = this;
    self.favoriteArtists = ko.observableArray([]);
    self.artistToAdd = ko.observableArray("");
    self.addArtist = function () {
      var newFavoriteArtist = new Artist(self.artistToAdd());
      console.log("New Favorite Artist: " + newFavoriteArtist.name);
      var artistExists = self.favoriteArtists.indexOf(newFavoriteArtist) > 0;
      console.log("Artist Exists: " + artistExists);
      if(!artistExists) {
          self.favoriteArtists.push(newFavoriteArtist);
          console.log("A new artist has been added:" + self.artistToAdd());
      } else {
        console.log("Artist already in favorites.");
      }
    };
  }
  ko.applyBindings(new ViewModel());
});
</code>```

HTML

Favorite Artists

Currently, your favorite artists include:

Enter the name of a new artist:

<input data-bind="value: artistToAdd" />
<button data-bind="click: addArtist">Add</button>
```

答:
Better is to stop iterating after first element is found instead of go through all collection (so use find, not filter):</p>

```<code>return favoriteArtists.find(function(data) {
  return data === newFavoriteArtist;
}) !== null;
</code>```

Body:
Why is the check for duplicate Artist always returning false?

See this JSFiddle for a runnable demo.

Knockout Code

$(function() {

  function Artist(name) {
    this.name = name;
  }

  function ViewModel() {
    var self = this;
    self.favoriteArtists = ko.observableArray([]);
    self.artistToAdd = ko.observableArray("");
    self.addArtist = function () {
      var newFavoriteArtist = new Artist(self.artistToAdd());
      console.log("New Favorite Artist: " + newFavoriteArtist.name);
      var artistExists = self.favoriteArtists.indexOf(newFavoriteArtist) > 0;
      console.log("Artist Exists: " + artistExists);
      if(!artistExists) {
          self.favoriteArtists.push(newFavoriteArtist);
          console.log("A new artist has been added:" + self.artistToAdd());
      } else {
        console.log("Artist already in favorites.");
      }
    };
  }
  ko.applyBindings(new ViewModel());
});

HTML

Favorite Artists

Currently, your favorite artists include:

Enter the name of a new artist:

<input data-bind="value: artistToAdd" />
<button data-bind="click: addArtist">Add</button>

Body:
Better is to stop iterating after first element is found instead of go through all collection (so use find, not filter):

return favoriteArtists.find(function(data) {
  return data === newFavoriteArtist;
}) !== null;


问:
Why, when i get the coordinates of an image in android, it changes according to the device?
Why, when i get the coordinates of an image in android, it changes according to the device ?
@Override

```<code>public boolean onTouch(View v, MotionEvent event) {
ImageView image = (ImageView) findViewById(R.id.monimage);
Log.d("", event.getX())
</code>```

Why when i change of device, Nexus 4 prints 44 when i click on the sun of the image, and when I use nexus 5X, when i click on the sun of the image, it prints me an another number (77 for example) ?

答: event.getX() gives you the coordinates of the screen according to the your screen Resolution. For example, nexus 4 has 768x1280 and 5x has 1080x1920. So x and Y position will change according to the device resolution.</p>

Body:
Why, when i get the coordinates of an image in android, it changes according to the device ?
@Override

public boolean onTouch(View v, MotionEvent event) {
ImageView image = (ImageView) findViewById(R.id.monimage);
Log.d("", event.getX())

Why when i change of device, Nexus 4 prints 44 when i click on the sun of the image, and when I use nexus 5X, when i click on the sun of the image, it prints me an another number (77 for example) ?


问:
How to get the previous url using PHP
Suppose my site's url is given as hyperlink on some page on the internet; that page could be anything on internet - blog, orkut, yahoo, even stackoverflow etc, and someone clicks on it,and visited my site. So can we know, using php, the previous url from which the visitor came to my page? </p>

答:
I can't add a comment yet, so I wanted to share that HTTP_REFERER is not always sent.

Notice: Undefined index: HTTP_REFERER

ContentLicense: CC BY-SA 2.5

Title: How to get the previous url using PHP


问:
Hibernate Join Columns with enum
I have the following setup

```<code>table: table1
| id | name |
|  1 | test |

table: table2
| id | table1_id | value |
| 1  |    1      | ENUM1 |
| 2  |    1      | ENUM2 |
</code>```

And then, I have the following Java code:

```<code>@Entity
public class Table1 {

    @Id
    @GeneratedValue
    private Long id;

    @NotEmpty
    @Column(unique = true)
    private String name;

    @OneToMany
    @JoinTable(
        name = "TABLE2",
        joinColumns = @JoinColumn(name = "table1_id")
    )
    @Enumerated(EnumType.STRING)
    private Set<TheEnum> enumValues;

}
</code>```

But, when I am trying to run my Spring boot app I get the following error:

Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: ${package}.Table1.enumValues

Do you know what I have to do?

答:
@Enumerated says whether TheEnum object is stored as int or string in database.

You want to map collection enumValues to join table TABLE2. Use this code:

```<code>@ElementCollection(targetClass = TheEnum.class)
@JoinTable(name = "TABLE2", joinColumns = @JoinColumn(name = "table1_id"))
@Column(name = "enumValues", nullable = false)
@Enumerated(EnumType.STRING)
Set<TheEnum> enumValues;
</code>```

Title: Hibernate Join Columns with enum

Body:
I have the following setup

table: table1
| id | name |
|  1 | test |

table: table2
| id | table1_id | value |
| 1  |    1      | ENUM1 |
| 2  |    1      | ENUM2 |

And then, I have the following Java code:

@Entity
public class Table1 {

    @Id
    @GeneratedValue
    private Long id;

    @NotEmpty
    @Column(unique = true)
    private String name;

    @OneToMany
    @JoinTable(
        name = "TABLE2",
        joinColumns = @JoinColumn(name = "table1_id")
    )
    @Enumerated(EnumType.STRING)
    private Set<TheEnum> enumValues;

}

But, when I am trying to run my Spring boot app I get the following error:

Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: ${package}.Table1.enumValues

Do you know what I have to do?

Body:
@Enumerated says whether TheEnum object is stored as int or string in database.

You want to map collection enumValues to join table TABLE2. Use this code:

@ElementCollection(targetClass = TheEnum.class)
@JoinTable(name = "TABLE2", joinColumns = @JoinColumn(name = "table1_id"))
@Column(name = "enumValues", nullable = false)
@Enumerated(EnumType.STRING)
Set<TheEnum> enumValues;


答:
There is a property on UIView called tag that you can use for any purpose you want.  You could assign the table's row number to it and then check for that in the delegate.

You need to be careful if you can insert or delete rows -- you need to reload affected rows and update the tag.

EDIT (another way):

You do not need to assign the same delegate to every picker.  You could make new classes that implement the delegate protocol.

So,

```<code>class CountryPickerDelegate: UIPickerDelegate {

// do what the country picker needs
// The init can take the VC if you need that.
// add a weak var viewController: MyTableViewController? = nil

}

class CardTypePickerDelegate: UIPickerDelegate {

// do what the card picker needs
// The init can take the VC if you need that.
// add a weak var viewController: MyTableViewController = nil

}
</code>```

Then,

```<code>cell!.countryPicker.delegate = CountryPickerDelegate(viewController: self)
</code>```

Title: How to use UIPickerView inside UITableViewController

Body:
There is a property on UIView called tag that you can use for any purpose you want.  You could assign the table's row number to it and then check for that in the delegate.

You need to be careful if you can insert or delete rows -- you need to reload affected rows and update the tag.

EDIT (another way):

You do not need to assign the same delegate to every picker.  You could make new classes that implement the delegate protocol.

So,

class CountryPickerDelegate: UIPickerDelegate {

// do what the country picker needs
// The init can take the VC if you need that.
// add a weak var viewController: MyTableViewController? = nil

}

class CardTypePickerDelegate: UIPickerDelegate {

// do what the card picker needs
// The init can take the VC if you need that.
// add a weak var viewController: MyTableViewController = nil

}

Then,

cell!.countryPicker.delegate = CountryPickerDelegate(viewController: self)


问:
How to delete duplicate records in a table using Orientdb
```<code>Select * from table
cola colb
a     b
a     c
a     b
a     b
</code>```

How to delete duplicate records excluding the first entry in a table.Expected result :

```<code> Select * from table
cola colb
a     b
a     c
</code>```

答:
As a workaround, you can try the following solution:

1. Create new (temporary) class

```<code>create class table_temp
</code>```

Insert grouped (distinct) values to new class table

insert into table_temp from select cola, colb from your_table
group by cola, colb

Clean your table delete from your_table

Insert data from new table

insert into your_table from select cola, colb from table_temp
group by cola, colb

Ideally, these steps should be done within single transaction.

Body:
Select * from table
cola colb
a     b
a     c
a     b
a     b

How to delete duplicate records excluding the first entry in a table.Expected result :

 Select * from table
cola colb
a     b
a     c

Body:
As a workaround, you can try the following solution:

1. Create new (temporary) class

create class table_temp

Insert grouped (distinct) values to new class table

insert into table_temp from select cola, colb from your_table
group by cola, colb

Clean your table delete from your_table

Insert data from new table

insert into your_table from select cola, colb from table_temp
group by cola, colb

Ideally, these steps should be done within single transaction.


问:
Django ORM: Override related_name of Field in Child Class
I get this exception:

django.core.exceptions.FieldError:

Local field 'ticket' in class 'SpecialPlugin' clashes with field of similar name from base class 'BasePlugin'

Here are my models:

```<code>class BasePlugin(models.Model):
    ticket = models.OneToOneField('foobar.ticket', primary_key=True,
                                  related_name='%(app_label)s_%(class)s')

    class Meta(IndexImplementation.Meta):
        abstract = True

    # .. Other stuff which should be available for SpecialPlugin
    #    and other child classes.

class SpecialPlugin(BasePlugin):
    ticket = models.OneToOneField('foobar.ticket', primary_key=True,
                                  related_name='special')
</code>```

I only found this note, but in my case the parent class is abstract. I am unsure if it applies here.

I want to give the child class SpecialPlugin the related name "special" since the related name (%(app_label)s_%(class)s) of the BasePlugin would break old code.

Is there a way to give SpecialPlugin.ticket the related_name "special"?

答:
Update:

Similar thing can be done using django's default_related_name meta option.

It might look like an ugly hack, but you can set a function call to the related_name argument instead of string. And then override that function in the child class/model.

```<code>class BasePlugin(models.Model):

    @staticmethod
    def get_ticket_related_name():
        return '%(app_label)s_%(class)s'

    ticket = models.OneToOneField('foobar.ticket', primary_key=True,
                                  related_name=get_ticket_related_name.__func__())

    class Meta(IndexImplementation.Meta):
        abstract = True

class SpecialPlugin(BasePlugin):
    @staticmethod
    def get_ticket_related_name():
        return 'special'
</code>```

Body:
I get this exception:

django.core.exceptions.FieldError:

Local field 'ticket' in class 'SpecialPlugin' clashes with field of similar name from base class 'BasePlugin'

Here are my models:

class BasePlugin(models.Model):
    ticket = models.OneToOneField('foobar.ticket', primary_key=True,
                                  related_name='%(app_label)s_%(class)s')

    class Meta(IndexImplementation.Meta):
        abstract = True

    # .. Other stuff which should be available for SpecialPlugin
    #    and other child classes.

class SpecialPlugin(BasePlugin):
    ticket = models.OneToOneField('foobar.ticket', primary_key=True,
                                  related_name='special')

I only found this note, but in my case the parent class is abstract. I am unsure if it applies here.

I want to give the child class SpecialPlugin the related name "special" since the related name (%(app_label)s_%(class)s) of the BasePlugin would break old code.

Is there a way to give SpecialPlugin.ticket the related_name "special"?

Body:
Update:

Similar thing can be done using django's default_related_name meta option.

It might look like an ugly hack, but you can set a function call to the related_name argument instead of string. And then override that function in the child class/model.

class BasePlugin(models.Model):

    @staticmethod
    def get_ticket_related_name():
        return '%(app_label)s_%(class)s'

    ticket = models.OneToOneField('foobar.ticket', primary_key=True,
                                  related_name=get_ticket_related_name.__func__())

    class Meta(IndexImplementation.Meta):
        abstract = True

class SpecialPlugin(BasePlugin):
    @staticmethod
    def get_ticket_related_name():
        return 'special'


问:
Excluding files in Path::Tiny using negative lookahead regex
Using Path::Tiny. It has a method: children which could be used as:

```<code>@paths = path("/tmp")->children( qr/\.txt$/ );
</code>```

If an optional qr// argument is provided, it only returns objects for
  child names that match the given regular expression. Only the base
  name is used for matching

So the

```<code>@paths = path("/tmp")->children( qr/\A(foo|bar|baz)\z/ );
</code>```

will return either foo bar baz files found in the /tmp.

I need the opposite, want any file but NOT the (foo|bar|baz) ones.

The following could filter out the unwanted ones,

```<code>@paths = grep { $_->basename !~ /^(foo|bar|baz)$/ } path("/tmp")->children;
</code>```

but wondering how to write the qr for it.

So, the question: How to create the qr expression for: any file but not foo|bar|baz?

I tried the negative lookahead

```<code>path(...)->children( qr/\A (?!(foo|bar|baz)) \z/x );
</code>```

but, it doesn't do what I think it should do  :) - e.g. my regex is wrong.

答:
Put the \z inside the negative look-ahead

```<code>qr/\A(?!(?:foo|bar|baz)\z)/
</code>```

Body:
Using Path::Tiny. It has a method: children which could be used as:

@paths = path("/tmp")->children( qr/\.txt$/ );

If an optional qr// argument is provided, it only returns objects for
  child names that match the given regular expression. Only the base
  name is used for matching

So the

@paths = path("/tmp")->children( qr/\A(foo|bar|baz)\z/ );

will return either foo bar baz files found in the /tmp.

I need the opposite, want any file but NOT the (foo|bar|baz) ones.

The following could filter out the unwanted ones,

@paths = grep { $_->basename !~ /^(foo|bar|baz)$/ } path("/tmp")->children;

but wondering how to write the qr for it.

So, the question: How to create the qr expression for: any file but not foo|bar|baz?

I tried the negative lookahead

path(...)->children( qr/\A (?!(foo|bar|baz)) \z/x );

but, it doesn't do what I think it should do  :) - e.g. my regex is wrong.

Body:
Put the \z inside the negative look-ahead

qr/\A(?!(?:foo|bar|baz)\z)/


问:
how to get the date from string in C#
I have a string like

```<code> string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");
</code>```

want the output only 2017-03-10

答:
Change you code as below

```<code>  DateTime firstdate = DateTime.ParseExact(startdatestring,
                                 "yyyy-MM-ddTHH:mm:ss.fff",
                                 CultureInfo.InvariantCulture);
</code>```

Title: how to get the date from string in C#

Body:
I have a string like

 string startdatestring = "2017-03-10T07:19:28.907";
 DateTime firstdate = DateTime.ParseExact(startdatestring,
                                          "yyyy/MM/dd hh:mm:ss",
                                          CultureInfo.InvariantCulture);
 var firstDateString = firstdate.ToString("yyyy-MM-dd");

want the output only 2017-03-10

Body:
Change you code as below

  DateTime firstdate = DateTime.ParseExact(startdatestring,
                                 "yyyy-MM-ddTHH:mm:ss.fff",
                                 CultureInfo.InvariantCulture);


答:
You imported the wrong class.

```<code>import java.awt.List;
</code>```

It should be:

```<code>import java.util.List;
</code>```

Title: The type List is not generic; it cannot be parameterized with arguments

Body:
You imported the wrong class.

import java.awt.List;

It should be:

import java.util.List;


问:
HTML picture in div won't fill out body completely
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

```<code><!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">
  </head>
  <body>
   <div id="backgroundWallpaper">
    <img src=".../img/1.jpg" alt="image could not be loaded">
   </div>
  </body>
 </html>
</code>```

This is my css file

```<code>body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}
</code>```

答:
You are using max-width: 100%; , but this will not fill the DIV if your image is smaller than the DIV. Use width: 100%. Still, this does not guarantee that the heigth will fill the window height since it will stay in its original proportion.

Better would be to use the image as a background image for body and set background-size: cover for it

Body:
I want to use a picture (jpg) as a background for my page.

This is how I tried to tackle the problem :
Create the body, inside the body put a div with the id backgroundWallpaper.
Inside the div i put the image.
The problem is though that it's completely filled out to the site (horizontal) and also to the top but at the bottom there is a small gap between the picture and the browser. I changed the body background to crimson red to demonstrate you the gap. I use the latest version of safari as my browser. This is my code :
index.html

<!DOCTYPE html>

   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">

This is my css file

body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}


问:
POSTing data from angularJS to Express using $http
I'm trying so send some json data from angularjs to express/nodejs

AngularJS code:

```<code>$http({
      method: 'POST',
      url: 'http://localhost:8000/api/auth',
      data: {
         name: user,
         password: passwd
      },
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
      }
   })
   .success(function(data, status, headers, config) {
      $scope.loginStatus = data;
   })
   .error(function(data, status, headers, config) {
      $scope.lloginStatusogin = data;
   });
</code>```

ExpressJS code:

```<code>var express = require('express');
var app = express();

var config = require('./config'); // get our config file

var port = process.env.PORT || 8000; // used to create, sign, and verify tokens

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: true
}));

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

var apiRoutes = express.Router();

apiRoutes.post('/auth', function(req, res) {

   console.log(req.body)
});

app.use('/api', apiRoutes);
app.listen(port);
</code>```

but at express when log the req.body i get this object
{ '{"name":"Nick","password":"password"}': '' }  the whole json object is taken as a property having an empty value i don't understand or see what am doing wrong.

答:
In the header part : it should be

```<code>{'Content-Type': 'application/json'}
</code>```

instead of

```<code>{'Content-Type': 'application/x-www-form-urlencoded'}
</code>```

Body:
I'm trying so send some json data from angularjs to express/nodejs

AngularJS code:

$http({
      method: 'POST',
      url: 'http://localhost:8000/api/auth',
      data: {
         name: user,
         password: passwd
      },
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
      }
   })
   .success(function(data, status, headers, config) {
      $scope.loginStatus = data;
   })
   .error(function(data, status, headers, config) {
      $scope.lloginStatusogin = data;
   });

ExpressJS code:

var express = require('express');
var app = express();

var config = require('./config'); // get our config file

var port = process.env.PORT || 8000; // used to create, sign, and verify tokens

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: true
}));

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

var apiRoutes = express.Router();

apiRoutes.post('/auth', function(req, res) {

   console.log(req.body)
});

app.use('/api', apiRoutes);
app.listen(port);

but at express when log the req.body i get this object
{ '{"name":"Nick","password":"password"}': '' }  the whole json object is taken as a property having an empty value i don't understand or see what am doing wrong.

Body:
In the header part : it should be

{'Content-Type': 'application/json'}

instead of

{'Content-Type': 'application/x-www-form-urlencoded'}


问:
Unable to push to github: repository not found
Whenever I try to push changes to a remote github repository from the command-line, I receive the following error:

```<code>> git push
remote: Repository not found.
fatal: repository 'https://github.com/MyOrg/MyRepo.git' not found
</code>```

(I've replaced org and repo name, but they are definitely the correct names).

I have checked I have write access to the repository. I'm able to create branches and write to files through the github website, and pull these changes back down locally.

I am authenticating with github using the Git Credential Manager for Windows (GCM), and I have the following in gitconfig:

```<code>[credential]
    helper = manager
</code>```

I'm running on Windows 10, git version 2.10.2.windows.1.

答: In my case the problem was with Git Credential Manager, I deleted the saved credential from Windows through Control Panel > User Accounts > Credential Manager > Windows Credentials. The next time I tried to push it popped up a dialog prompting for the github username and password. On entering these it seems to have sorted itself out.</p>

Body:
Whenever I try to push changes to a remote github repository from the command-line, I receive the following error:

> git push
remote: Repository not found.
fatal: repository 'https://github.com/MyOrg/MyRepo.git' not found

(I've replaced org and repo name, but they are definitely the correct names).

I have checked I have write access to the repository. I'm able to create branches and write to files through the github website, and pull these changes back down locally.

I am authenticating with github using the Git Credential Manager for Windows (GCM), and I have the following in gitconfig:

[credential]
    helper = manager

I'm running on Windows 10, git version 2.10.2.windows.1.


问:
Performant way to convert adjacency list to links for undirected graph
I have an adjacency list like below:

```<code>const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];
</code>```

I need to create a set of links for an undirected graph without duplicates (example bellow).
Such links as [0,1] and [1,0] are considered duplicates.

```<code>const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]
</code>```

Right now I do it this way:

```<code>const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})
</code>```

I am wondering if there is a better pattern to solve this kind of task on massive arrays.

答: You could sort your link tuple values, skip the check skip.indexOf(j) and let Set take care of the duplicates.

Body:
I have an adjacency list like below:

const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];

I need to create a set of links for an undirected graph without duplicates (example bellow).
Such links as [0,1] and [1,0] are considered duplicates.

const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]

Right now I do it this way:

const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})

I am wondering if there is a better pattern to solve this kind of task on massive arrays.


问:
Create 1 list in Excel from 2 other lists
I have two lists in Excel, one with the columns Code, Company, Email and Invoice (sheet 1) and another list with the columns Code, Company and Invoice (sheet 2).
Now, how can I create a new list that only contains rows where the value in the column Code in sheet 1 is identical to the value in the column Invoice in sheet 2?

EDIT: OK, so I used MATCH in Sheet1 as suggested like this:
=MATCH(A3,Sheet2!D:D,0)
However this only returns the row number when there is a match. But I need to return a specific cell value in Sheet2 for every row where there is a match. How can I do that?

答:
Not sure I get exactly but I suppose you want to import from sheet2 to sheet1 some columns where there's match sheet1/code = sheet2/invoice. You can try this formula in Sheet1 E3 then copy/paste it in all cells that you want to import:

```<code>  =IFERROR(INDEX(Sheet2!E:E, MATCH($A3,Sheet2!$D:$D,0)), "")
</code>```

Body:
Not sure I get exactly but I suppose you want to import from sheet2 to sheet1 some columns where there's match sheet1/code = sheet2/invoice. You can try this formula in Sheet1 E3 then copy/paste it in all cells that you want to import:

  =IFERROR(INDEX(Sheet2!E:E, MATCH($A3,Sheet2!$D:$D,0)), "")


问:
Django model inheritance: override restrictions in child classes
I will try to abstract my problem:

I need to create two model classes for IPv4 and IPv6.
I want to do it via inheritance; namely, to create a model class, and then to inherit from this class, but with the additional (different) limit for each of the child classes:

```<code>class IP(models.Model):
    ip = models.GenericIPAddressField()

    class Meta:
        abstract = True

class IPv4(IP):
    ip = models.GenericIPAddressField(protocol='ipv4')

class IPv6(IP):
    ip = models.GenericIPAddressField(protocol='ipv6')
</code>```

I'm not sure whether or not this is the correct way to do that, and I would like to know which problems might be caused due to such a model.

答:
The Abstract Model is usually used to define a model with common fields.
If you define the same field in two models, that field is unnecessary for the base model.
However, in your code, that field('IP.ip') will be virtually absent, so it will not be an operational problem.</p>

Body:
I will try to abstract my problem:

I need to create two model classes for IPv4 and IPv6.
I want to do it via inheritance; namely, to create a model class, and then to inherit from this class, but with the additional (different) limit for each of the child classes:

class IP(models.Model):
    ip = models.GenericIPAddressField()

    class Meta:
        abstract = True

class IPv4(IP):
    ip = models.GenericIPAddressField(protocol='ipv4')

class IPv6(IP):
    ip = models.GenericIPAddressField(protocol='ipv6')

I'm not sure whether or not this is the correct way to do that, and I would like to know which problems might be caused due to such a model.


答:
when I add the css file directly to the html file, I do not see any spaces in firefox or chrome, but I do get that the image could not be loaded.  What size is the photo.  Without the photo dimensions, it may be difficult to resolve.

<!DOCTYPE html>

   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">

 ```

Title: HTML picture in div won't fill out body completely

Body:
when I add the css file directly to the html file, I do not see any spaces in firefox or chrome, but I do get that the image could not be loaded.  What size is the photo.  Without the photo dimensions, it may be difficult to resolve.

<!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <title>name</title>
   <linkrel="stylesheet"
   href"http://meyerweb.com/eric/tools/css/reset/reset.css">
   <link rel="stylesheet" href="main.css">
  </head>
  <body>
   <div id="backgroundWallpaper">
    <img src=".../img/1.jpg" alt="image could not be loaded">
   </div>

<style>
body {
 background: crimson;
 margin: 0;
 padding: 0;
}

#backgroundWallpaper img {
 max-width: 100%;
}
</style>
  </body>
 </html>


问:
What are the proper and complete steps to deploy a .NET application from Visual Studio for public use?
I usually write C# programs for myself, or just parts of other applications.  Now, I have been working on a project that I would like to eventually commercialize and I am interested in the easiest way to deploy a simple application from VS 2008 that will primarily be downloaded and installed.  I am not just interested in installer choices, but build options, exception handling settings, and any other essential details.

The documentation on MSDN is a little overwhelming.  Just the section on deployment how-to's has over 100 topics!

http://msdn.microsoft.com/en-us/library/ms184415.aspx

What should I focus on and in what order?  Does anyone have a personal checklist that they run through just to make sure all of the bases are covered?

答:
Get your licensing mechanism figured out. Serial numbers, activation, whatever. Test it.

Build your assemblies and obfuscate them. If the assemblies are small, I'd actually ILMerge them too - makes the whole thing more manageable.

Make an installer. ClickOnce is an option, albeit for the brave. Its major feature is that it self-updates. Which is problematic if you want to charge money for updates. I'd just use WiX and code self-updating myself - not exactly hard.

OwnerDisplayName: Ben

OwnerDisplayName: Dmitri Nesteruk


问:
Find in (HTML) Page Script
I would like to add a Find box in an html page that has a long list of names. This would be similar to a browser Find in page feature.  I will be using this on iOS devices within a UIWebView and so there is no Find in Page feature.

Linda

答:
I found a solution here.
http://www.seabreezecomputers.com/tips/find.htm</p>

Title: Find in (HTML) Page Script


问:
Hibernate database schema validation fails for H2 database when entity contains UUID
For a H2 database schema mapping to an entity with a UUID, the Hibernate ddl validation fails with the exception:

Root cause: org.hibernate.tool.schema.spi.SchemaManagementException:
  Schema-validation: wrong column type encountered in column [testuuid]
  in table [TEST.dummy]; found [varbinary (Types#VARBINARY)], but
  expecting [binary (Types#BINARY)]

Setup:

Hibernate 5.2.9.Final

H2 1.4.194

further hibernate settings:

hibernate.hbm2ddl.auto=validate

Database dialect is not set explicitly.

The H2 DDL is initially generated with hibernate resulting in the UUID being represented by 'binary' in the H2 database schema.

Disabling the validation works, but is not an option.

How can I solve this issue?

答:
The root cause is that in the H2 database some data types are synonym, but hibernate currently does not handle this fact.

There is another stackoverflow question targeting a similar issue with H2 returning a synonym type instead of the expected one.

A workaround is proposed in the related hibernate bugtracker ticket. Just implement a custom hibernate H2 dialect which may look like this:

```<code>package your.pckg.name;

import java.sql.Types;
import org.hibernate.dialect.H2Dialect;

public class H2DialectCustom extends H2Dialect {

    public H2DialectCustom() {
        super();
        registerColumnType(Types.BINARY, "varbinary");
    }

}
</code>```

and register it in your hibernate/JPA settings:

spring.jpa.properties.hibernate.dialect = your.pckg.name.H2DialectCustom

Body:
The root cause is that in the H2 database some data types are synonym, but hibernate currently does not handle this fact.

There is another stackoverflow question targeting a similar issue with H2 returning a synonym type instead of the expected one.

A workaround is proposed in the related hibernate bugtracker ticket. Just implement a custom hibernate H2 dialect which may look like this:

package your.pckg.name;

import java.sql.Types;
import org.hibernate.dialect.H2Dialect;

public class H2DialectCustom extends H2Dialect {

    public H2DialectCustom() {
        super();
        registerColumnType(Types.BINARY, "varbinary");
    }

}

and register it in your hibernate/JPA settings:

spring.jpa.properties.hibernate.dialect = your.pckg.name.H2DialectCustom


问:
How to pass Ajax Json object to the Controller Class in .Net Core?
We are trying to make a Ajax request to our Core Web API and get the data Json result back to the Controller for further processing, Which include Deserialization of the Json object result, Ajax request is working fine and we are able to get the required Json data in data.

Can anyone here please advise the changes or the alternatives to achieve this?

View (Ajax Request)

```<code>@section scripts
{
<script type="text/javascript">
    $(document).ready(function () {
    GetEventDetails('@Url.Content("~/")');
    });

    function GetEventDetails(contextRoot) {
    $.ajax({
    type: "GET",
    url: contextRoot + "api/EventsAPI",
    dataType: "json",
    success: function (data) {
        debugger;
        var datavalue = data;
        contentType: "application/json";
        //Send data to controller ???
        console.log(data);
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
    });
    }
</script>
}
</code>```

Controller.cs

```<code>public ActionResult Index()
{
    /*Do all stuff before returning view
    1. Get Json Data from Ajax request
    2. Deserialize the obtained Json Data
    3. return to view
    */
    return View("Index");
}
</code>```

Update:

I have tried the solution given by @J. Doe, but still unable to get the result set. Please check the screenshot and below code..

Ajax Request:

```<code>function GetEventDetails(contextRoot) {
        $.ajax({
            type: "GET",
            url: contextRoot + "api/EventsAPI",
            dataType: "json",
            success: function (data) {
                debugger;
                var datavalue = data;
                contentType: "application/json; charset=utf-8";
                console.log(data);
                var EventJson = data;
                console.log(EventJson);
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("Index")",
                    dataType: "json",
                    data: EventJson,
                    contentType: "application/json; charset=utf-8",
                        //data: EventJson,
                    success: function (data) {
                        alert(data.responseText);
                        console.log('Data received: ');
                        console.log(data.responseText);
                    },
                    failure: function (errMsg) {
                        console.log(errMsg);
                }
            });
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
});
}
</code>```

Class Properties:

```<code>public class RootObject
{
    public Embedded _embedded { get; set; }
    public Links _links { get; set; }
    public Page page { get; set; }
}
</code>```

Here is Action Result Controller:

```<code>public ActionResult Index(RootObject model)
{
    if (model != null)
    {
        return Json("Success");
    }
    else
    {
        return Json("An Error Has occoured");
    }
    //return View("Index");
}
</code>```

Error Snapshot:

enter image description here

答:
We are trying

Hello soviet sojuz!

But back to question - A 2 months ago i created sample on GitHub with ajax with .Net Core - https://github.com/CShepartd/ASP.Net_Core_-_Ajax_Example

In short:

Make action with objects in controller:

```<code>    public IActionResult Ajax(string name1, string name2)
    {
        return View();
    }
</code>```

Next in view send name1 and name2 to action

```<code>$('form').submit(function(event) {
            event.preventDefault();
            var data = {
                name1: $("input[name='name1']", this).val(),
                name2: $("input[name='name2']",this).val()
            };

            $.ajax({
                type: 'POST',
                url: '/Home/Ajax',
                dataType: 'json',
                data: data,
                success: function(response) {
                    alert(response);
                    console.log('Data received: ');
                    console.log(response);
                },
                failure: function(response) {
                    //...
                },
                error: function(response) {
                    //...
                }
            });
        });
</code>```

Body:
We are trying to make a Ajax request to our Core Web API and get the data Json result back to the Controller for further processing, Which include Deserialization of the Json object result, Ajax request is working fine and we are able to get the required Json data in data.

Can anyone here please advise the changes or the alternatives to achieve this?

View (Ajax Request)

@section scripts
{

}

Controller.cs

public ActionResult Index()
{
    /*Do all stuff before returning view
    1. Get Json Data from Ajax request
    2. Deserialize the obtained Json Data
    3. return to view
    */
    return View("Index");
}

Update:

I have tried the solution given by @J. Doe, but still unable to get the result set. Please check the screenshot and below code..

Ajax Request:

function GetEventDetails(contextRoot) {
        $.ajax({
            type: "GET",
            url: contextRoot + "api/EventsAPI",
            dataType: "json",
            success: function (data) {
                debugger;
                var datavalue = data;
                contentType: "application/json; charset=utf-8";
                console.log(data);
                var EventJson = data;
                console.log(EventJson);
                $.ajax({
                    type: "POST",
                    url: "@Url.Action("Index")",
                    dataType: "json",
                    data: EventJson,
                    contentType: "application/json; charset=utf-8",
                        //data: EventJson,
                    success: function (data) {
                        alert(data.responseText);
                        console.log('Data received: ');
                        console.log(data.responseText);
                    },
                    failure: function (errMsg) {
                        console.log(errMsg);
                }
            });
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
});
}

Class Properties:

public class RootObject
{
    public Embedded _embedded { get; set; }
    public Links _links { get; set; }
    public Page page { get; set; }
}

Here is Action Result Controller:

public ActionResult Index(RootObject model)
{
    if (model != null)
    {
        return Json("Success");
    }
    else
    {
        return Json("An Error Has occoured");
    }
    //return View("Index");
}

Error Snapshot:

enter image description here

Body:
We are trying

Hello soviet sojuz!

But back to question - A 2 months ago i created sample on GitHub with ajax with .Net Core - https://github.com/CShepartd/ASP.Net_Core_-_Ajax_Example

In short:

Make action with objects in controller:

    public IActionResult Ajax(string name1, string name2)
    {
        return View();
    }

Next in view send name1 and name2 to action

$('form').submit(function(event) {
            event.preventDefault();
            var data = {
                name1: $("input[name='name1']", this).val(),
                name2: $("input[name='name2']",this).val()
            };

            $.ajax({
                type: 'POST',
                url: '/Home/Ajax',
                dataType: 'json',
                data: data,
                success: function(response) {
                    alert(response);
                    console.log('Data received: ');
                    console.log(response);
                },
                failure: function(response) {
                    //...
                },
                error: function(response) {
                    //...
                }
            });
        });


答:
Send Content-Type: application/json if you try to send an object. application/x-www-form-urlencoded expects an urlEncoded string as body property. The following both solutions should work for you, choose one.

Send JSON object as body with application/json content-type

```<code>$http({
    method  : 'POST',
    url     : 'http://localhost:8000/api/auth',
    data    : {
        name: user,
        password: passwd
    },
    headers : {'Content-Type': 'application/json'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});
</code>```

Send urlEncoded sring in body with application/x-www-form-urlencoded content-type.

transformRequest will create a urlEncoded string based on data before the request will be send.

```<code>$http({
    method: 'POST',
    url: 'http://localhost:8000/api/auth',
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    },
    data: {
        name: user,
        password: passwd
    },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});
</code>```

Title: POSTing data from angularJS to Express using $http

Body:
Send Content-Type: application/json if you try to send an object. application/x-www-form-urlencoded expects an urlEncoded string as body property. The following both solutions should work for you, choose one.

Send JSON object as body with application/json content-type

$http({
    method  : 'POST',
    url     : 'http://localhost:8000/api/auth',
    data    : {
        name: user,
        password: passwd
    },
    headers : {'Content-Type': 'application/json'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});

Send urlEncoded sring in body with application/x-www-form-urlencoded content-type.

transformRequest will create a urlEncoded string based on data before the request will be send.

$http({
    method: 'POST',
    url: 'http://localhost:8000/api/auth',
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
    },
    data: {
        name: user,
        password: passwd
    },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config){
    $scope.loginStatus=data;
})
.error(function(data, status, headers, config){
    $scope.lloginStatusogin=data;
});


问:
What is the typical speed that PHP connects to MySQL?
Say I have very standard mysql connection code:

```<code>$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);
</code>```

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?

答:
2 seconds does seem slow, but it depends on your server and database server. Depending on what else they are doing, where they are located and many other factors it could actually be fast.

I usually get times of less than a second.

Body:
Say I have very standard mysql connection code:

$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?


问:
DataHandler structure for creating parent/child record relations
I'm trying to create nested record structures using TYPO3's DataHandler data structures (tested with TYPO3 v7). However relations are not created as expected. Consider the following data structure:

        $data = array(
                'sys_category' =>
                        array(
                                'NEW_1' =>
                                        array(
                                                'title' => 'Category 1',
                                                'pid' => $pid,
                                        ),
                                'NEW_2' =>
                                        array(
                                                'title' => 'Category 3',
                                                'pid' => $pid,
                                        ),
                                'NEW_3' =>
                                        array(
                                                'title' => 'Category 2',
                                                'pid' => $pid,
                                        ),
                                'NEW_4' =>
                                        array(
                                                'title' => 'Category 1.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_5' =>
                                        array(
                                                'title' => 'Category 1.2',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_6' =>
                                        array(
                                                'title' => 'Category 3.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_2',
                                        ),
                        ),
        );
```

<p>This gives the following result in the database:</p>

```uid title           parent
1   Category 1      0
2   Category 3      0
3   Category 2      0
4   Category 1.1    0
5   Category 1.2    0
6   Category 3.1    0
```

Note the "0" value for all "parent" fields. Why is it that the "NEW_*" values are not interpreted for the "parent" fields set in the data structure?

答:
As far as I see only the pid-value is checked for the "NEW"-keyword.
But you could use some of the included hooks for enabling the assignment for "parent" too.

EDIT:
I'm referring to TYPO3\CMS\Core\DataHandling\DataHandler::process_datamap()

Body:
I'm trying to create nested record structures using TYPO3's DataHandler data structures (tested with TYPO3 v7). However relations are not created as expected. Consider the following data structure:

        $data = array(
                'sys_category' =>
                        array(
                                'NEW_1' =>
                                        array(
                                                'title' => 'Category 1',
                                                'pid' => $pid,
                                        ),
                                'NEW_2' =>
                                        array(
                                                'title' => 'Category 3',
                                                'pid' => $pid,
                                        ),
                                'NEW_3' =>
                                        array(
                                                'title' => 'Category 2',
                                                'pid' => $pid,
                                        ),
                                'NEW_4' =>
                                        array(
                                                'title' => 'Category 1.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_5' =>
                                        array(
                                                'title' => 'Category 1.2',
                                                'pid' => $pid,
                                                'parent' => 'NEW_1',
                                        ),
                                'NEW_6' =>
                                        array(
                                                'title' => 'Category 3.1',
                                                'pid' => $pid,
                                                'parent' => 'NEW_2',
                                        ),
                        ),
        );

This gives the following result in the database:

uid title           parent
1   Category 1      0
2   Category 3      0
3   Category 2      0
4   Category 1.1    0
5   Category 1.2    0
6   Category 3.1    0

Note the "0" value for all "parent" fields. Why is it that the "NEW_*" values are not interpreted for the "parent" fields set in the data structure?


问:
How to set some type of highlight to a button when it's default button or when it's mouse over button?
Here is a button which I styled, but I realized that there is no way for someone who uses the application to notice when button is mouse over / selected or something like that?
I just want some kind of notification when button is selected or whatever?
Any kind of solution will be acceptable for me so in case button is mouse hovered, or in case button is selected to notice user
that is that button!

Here is my current button:

```<code> <Button x:Name="btnOk"
                    SnapsToDevicePixels="True"
                    UseLayoutRounding="True"
                    IsDefault="True"
                    Grid.Row="2"
                    Grid.Column="1"
                    FontSize="15"
                    Width="140"
                    BorderThickness="1"
                    HorizontalContentAlignment="Center"
                    VerticalContentAlignment="Center"
                    Foreground="#0091EA"
                    Background="White"
                    Content="Ok!"
                    BorderBrush="#0091EA" Margin="5,10,0,10" HorizontalAlignment="Left" Click="btnPotvrdi_Click">
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="BlueViolet"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
            <Button.Template>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border BorderThickness="{TemplateBinding BorderThickness}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                    </Border>
                </ControlTemplate>

            </Button.Template>

        </Button>
</code>```

答:
Specify the default background (White) in the Style and your trigger will work as expected:

```<code><Button x:Name="btnOk"
                    SnapsToDevicePixels="True"
                    UseLayoutRounding="True"
                    IsDefault="True"
                    Grid.Row="2"
                    Grid.Column="1"
                    FontSize="15"
                    Width="140"
                    BorderThickness="1"
                    HorizontalContentAlignment="Center"
                    VerticalContentAlignment="Center"
                    Foreground="#0091EA"
                    Content="Ok!"
                    BorderBrush="#0091EA" Margin="5,10,0,10" HorizontalAlignment="Left" Click="btnPotvrdi_Click">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="White" />
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Background" Value="Green"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="BlueViolet"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Border BorderThickness="{TemplateBinding BorderThickness}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}">
                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
            </Border>
        </ControlTemplate>
    </Button.Template>
</Button>
</code>```

A "local" value takes precedence over a value set by a Setter in a Style: https://msdn.microsoft.com/en-us/library/ms743230(v=vs.110).aspx

Body:
Here is a button which I styled, but I realized that there is no way for someone who uses the application to notice when button is mouse over / selected or something like that?
I just want some kind of notification when button is selected or whatever?
Any kind of solution will be acceptable for me so in case button is mouse hovered, or in case button is selected to notice user
that is that button!

Here is my current button:

 <Button x:Name="btnOk"
                    SnapsToDevicePixels="True"
                    UseLayoutRounding="True"
                    IsDefault="True"
                    Grid.Row="2"
                    Grid.Column="1"
                    FontSize="15"
                    Width="140"
                    BorderThickness="1"
                    HorizontalContentAlignment="Center"
                    VerticalContentAlignment="Center"
                    Foreground="#0091EA"
                    Background="White"
                    Content="Ok!"
                    BorderBrush="#0091EA" Margin="5,10,0,10" HorizontalAlignment="Left" Click="btnPotvrdi_Click">
            <Button.Style>

                </Style>
            </Button.Style>
            <Button.Template>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border BorderThickness="{TemplateBinding BorderThickness}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                    </Border>
                </ControlTemplate>

            </Button.Template>

        </Button>

Body:
Specify the default background (White) in the Style and your trigger will work as expected:

<Button x:Name="btnOk"
                    SnapsToDevicePixels="True"
                    UseLayoutRounding="True"
                    IsDefault="True"
                    Grid.Row="2"
                    Grid.Column="1"
                    FontSize="15"
                    Width="140"
                    BorderThickness="1"
                    HorizontalContentAlignment="Center"
                    VerticalContentAlignment="Center"
                    Foreground="#0091EA"
                    Content="Ok!"
                    BorderBrush="#0091EA" Margin="5,10,0,10" HorizontalAlignment="Left" Click="btnPotvrdi_Click">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="White" />
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Background" Value="Green"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="BlueViolet"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <Border BorderThickness="{TemplateBinding BorderThickness}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}">
                <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
            </Border>
        </ControlTemplate>
    </Button.Template>
</Button>

A "local" value takes precedence over a value set by a Setter in a Style: https://msdn.microsoft.com/en-us/library/ms743230(v=vs.110).aspx


问:
How to use the DB connection config in java or groovy component?
I have an requirement where i want to use the db connection configuration defined in mule config file.I want to use it in JAVA or Groovy code.
How i can do that?

Thanks,
Anurag Kumar Dwivedi

答:
In java you could pattern it like this.</p>

```<code>  <component>
     <singleton-object class="com.alex.v1.jdbc.SQLServerSPExecutor">
        <property key="dataSource" value="" value-ref="SData_Source"/>
      </singleton-object>
  </component>

  public class SQLServerSPExecutor implements Callable {
      private DataSource dataSource;

      public void setDataSource(DataSource dataSource) {
          this.dataSource = dataSource;
      }

      @Override
      public Object onCall(MuleEventContext eventContext) throws Exception {

      }
}
</code>```

Body:
In java you could pattern it like this.

  <component>
     <singleton-object class="com.alex.v1.jdbc.SQLServerSPExecutor">
        <property key="dataSource" value="" value-ref="SData_Source"/>
      </singleton-object>
  </component>

  public class SQLServerSPExecutor implements Callable {
      private DataSource dataSource;

      public void setDataSource(DataSource dataSource) {
          this.dataSource = dataSource;
      }

      @Override
      public Object onCall(MuleEventContext eventContext) throws Exception {

      }
}


问:
How to display icon using font ? ios
I got a file(please find attached file) which contain font, this font supposed to display icons according to code number.
but i didn't succeed to display any icon with this font. here is my code:

```<code>    iconTest = UILabel();
    iconTest.frame = CGRectMake(0, 0, 100, 100);
    onTest.center = self.view.center;

    iconTest.font = UIFont(name: "icomoon", size:16.0);
    iconTest.text = "e906";
</code>```

what's the correct way to display icons using font !

download font svg file

答:
Follow these steps:

Install fonts by double clicking on them.

Drag and drop fonts in Xcode and make sure they are added to target. (check copy items if needed)

In info.plist, set key Fonts provided by application and add font name for item(under key)

Set font type custom in storyboard for your controls or programatically assign font to UILabel

Code:

```<code>   //In swift 3
   let font = UIFont(name: "iconmoon", size: 15)
    btnSignout.setTitle("\u{e913}", for: UIControlState.normal) // set font icon on UIButton
    btnSignout.titleLabel!.font =  font

   // In objectiveC
   _lbl.text =  [NSString stringWithUTF8String:"\ue92e"]; // set font icon on UILabel
   _lbl.font =  [UIFont fontWithName:@"iconmoon" size:16];
</code>```

Note: \u prefix is mandatory, Example for unicode e626, the label text should be \ue626 or \u{e626}

Title: How to display icon using font ? ios

Body:
I got a file(please find attached file) which contain font, this font supposed to display icons according to code number.
but i didn't succeed to display any icon with this font. here is my code:

    iconTest = UILabel();
    iconTest.frame = CGRectMake(0, 0, 100, 100);
    onTest.center = self.view.center;

    iconTest.font = UIFont(name: "icomoon", size:16.0);
    iconTest.text = "e906";

what's the correct way to display icons using font !

download font svg file

Body:
Follow these steps:

Install fonts by double clicking on them.

Drag and drop fonts in Xcode and make sure they are added to target. (check copy items if needed)

In info.plist, set key Fonts provided by application and add font name for item(under key)

Set font type custom in storyboard for your controls or programatically assign font to UILabel

Code:

   //In swift 3
   let font = UIFont(name: "iconmoon", size: 15)
    btnSignout.setTitle("\u{e913}", for: UIControlState.normal) // set font icon on UIButton
    btnSignout.titleLabel!.font =  font

   // In objectiveC
   _lbl.text =  [NSString stringWithUTF8String:"\ue92e"]; // set font icon on UILabel
   _lbl.font =  [UIFont fontWithName:@"iconmoon" size:16];

Note: \u prefix is mandatory, Example for unicode e626, the label text should be \ue626 or \u{e626}


问:
Nested loops with conditions in javascript
I am working on a project where I want to create an array named full_day[] to be have an exactly equal length with an array time_plan[] after passing through my day_schedule().

Here is  my code:

function day_schedule(){

var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

var day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

var key1 = 'lesson_start';
var key2 = 'lesson_end';
var full_day = [];

for (var d = 0; d < day.length; d++) {
                var start_time = day[d].lesson_start;
                var end_time = day[d].lesson_end;

                for (var i = 0; i < time_plan.length; i++) {
                        var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
                        if (search_key == true) {
                            document.writeln('day matched == ' + day[d],'
');
                            full_day.push(day[d]);
                        } else {
                            full_day.push({
                                lesson_start: ' ',
                                lesson_end: ' ',
                                subject_name: ' '
                            });
                        }

                    }

                console.log('full day',full_day.length, full_day);

            }
}

day_schedule();```
</div>
</div>
</p>

<p>i'm expecting a result of</p>

```full day 7 [
  {
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  },
  {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  }
];
```

but i cant figure how to do it.

答:
First, don't use document.write. That only works on the first render of the page, is a blocking operation, and an accidental use after the page has rendered will wipe off the page. Consider using DOM manipulation. document.createElement and node.appendChild will be your friends. And avoid nested loops if possible, it's a bad habit to make. Use adjacent loops if possible.

If your ultimate goal is to find the subjects in day that are found in your time_plan, then what you could do is convert day into an object with the time as key using array.reduce. It's the only thing that makes your day items unique, as well as the only data that could identify it from time_plan. Then use array.map to convert time_plan into an array of subjects.

It's just simple array/object transformations, nothing fancy.

const time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

const day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

// Convert day into time-day element pairs
// { "08:00-09:00": { "subject_name": "..." }, ... }
const dayMap = day.reduce((c, v) => Object.assign(c, {[`${v.lesson_start}-${v.lesson_end}`] : v }), {});

// Convert time_plan to its corresponding day element using time
// as key.
const full_day = time_plan.map(v => dayMap[`${v.lesson_start}-${v.lesson_end}`]).filter(v => !!v);

console.log(full_day);```

There's an array.filter at the end of full_day to remove entries that do not have a corresponding day item.

Body:
I am working on a project where I want to create an array named full_day[] to be have an exactly equal length with an array time_plan[] after passing through my day_schedule().

Here is  my code:

function day_schedule(){

var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

var day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

var key1 = 'lesson_start';
var key2 = 'lesson_end';
var full_day = [];

for (var d = 0; d < day.length; d++) {
                var start_time = day[d].lesson_start;
                var end_time = day[d].lesson_end;

                for (var i = 0; i < time_plan.length; i++) {
                        var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
                        if (search_key == true) {
                            document.writeln('day matched == ' + day[d],'
');
                            full_day.push(day[d]);
                        } else {
                            full_day.push({
                                lesson_start: ' ',
                                lesson_end: ' ',
                                subject_name: ' '
                            });
                        }

                    }

                console.log('full day',full_day.length, full_day);

            }
}

day_schedule();

i'm expecting a result of

full day 7 [
  {
    "subject_name": "Math-1",
    "lesson_start": "08:00",
    "lesson_end": "09:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "subject_name": "Phy",
    "lesson_start": "11:00",
    "lesson_end": "12:00"
  },
  {
    "subject_name": "Engl",
    "lesson_start": "12:00",
    "lesson_end": "13:00"
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  },
  {
    "lesson_start": " ",
    "lesson_end": " ",
    "subject_name": " "
  }
];

but i cant figure how to do it.

Body:
First, don't use document.write. That only works on the first render of the page, is a blocking operation, and an accidental use after the page has rendered will wipe off the page. Consider using DOM manipulation. document.createElement and node.appendChild will be your friends. And avoid nested loops if possible, it's a bad habit to make. Use adjacent loops if possible.

If your ultimate goal is to find the subjects in day that are found in your time_plan, then what you could do is convert day into an object with the time as key using array.reduce. It's the only thing that makes your day items unique, as well as the only data that could identify it from time_plan. Then use array.map to convert time_plan into an array of subjects.

It's just simple array/object transformations, nothing fancy.

const time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];

const day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];

// Convert day into time-day element pairs
// { "08:00-09:00": { "subject_name": "..." }, ... }
const dayMap = day.reduce((c, v) => Object.assign(c, {[`${v.lesson_start}-${v.lesson_end}`] : v }), {});

// Convert time_plan to its corresponding day element using time
// as key.
const full_day = time_plan.map(v => dayMap[`${v.lesson_start}-${v.lesson_end}`]).filter(v => !!v);

console.log(full_day);

There's an array.filter at the end of full_day to remove entries that do not have a corresponding day item.


问:
How to enable/disable select tag and post it (even if disabled) with knockout
I have a complex form with many selects whose state (enabled/disabled) depends on the value of some other controls, so it could happen that these selects are disabled when submitting the form (and the select value is not posted). I need to post the selected value even in the case the user is not allowed to change the select.

I saw some solutions here HTML form readonly SELECT tag/input (mainly the solution is to have an hidden field synchronized with the disabled select).

I am thinking to taking a slightly different approach: I want to use knockout (already used in the project) to display the select only when the data is editable, and display a readonly input (or a div/span) otherwise.

How can I use knockout to simplify this approach?

答: You could just bind the knockout view model variable "IsDisable" to the select list


问:
how to add new entries in struct which is member of class using inheritance
```<code>class A
{
    public:
        typedef struct st
        {
            int x;
            int y;
        }st;
};
</code>```

I have class A which has a structure as public member variable. I want to add some new entries in above struct st. I used inheritance. is it possible to add new entries in that structure without changing it's name (st).

```<code>class B:public A
{
};
</code>```

Please help me out.

答:
You cannot add additional members to the original struct within A (btw: why that C-style typedef? You simply don't need it in C++...).

The only thing you can do is extending your struct within B by creating a new data type:

class A
{
public:
    struct st
    {
        int x;
        int y;
    };
};

class B : public A
{
public:
    struct st : A::st
    {
        int z;
    };
};
```

<p>Be aware, however, that that these are different data types and you risk type erasure under certain circumstances:</p>

<pre class="lang-cpp prettyprint-override"><code>B::st instance;
A::st& reference      = instance;  // OK
A::st* pointer        = &instance; // OK
A::st anotherInstance = instance;  // works, but z gets erased!!!
</code>```

Body:
class A
{
    public:
        typedef struct st
        {
            int x;
            int y;
        }st;
};

I have class A which has a structure as public member variable. I want to add some new entries in above struct st. I used inheritance. is it possible to add new entries in that structure without changing it's name (st).

class B:public A
{
};

Please help me out.

Body:
You cannot add additional members to the original struct within A (btw: why that C-style typedef? You simply don't need it in C++...).

The only thing you can do is extending your struct within B by creating a new data type:

class A
{
public:
    struct st
    {
        int x;
        int y;
    };
};

class B : public A
{
public:
    struct st : A::st
    {
        int z;
    };
};

Be aware, however, that that these are different data types and you risk type erasure under certain circumstances:

B::st instance;
A::st& reference      = instance;  // OK
A::st* pointer        = &instance; // OK
A::st anotherInstance = instance;  // works, but z gets erased!!!


问:
Wordpress and buddypress advice
I have a website that I want to setup so that users can register for the site but the administrator of the site will have the final say on whether or not they can be a member of the site or not.

I am running Wordpress 3.0.1 and Buddypress 1.2.5, buddypress is used to register the user, so I assume it will need to be a buddypress plugin that is used to allow or deny the user. I have searched and searched and cannot come up with any plugin that replicates this functionality. Are there any out there, or anything that gives a similar experience?

Many Thanks To Anyone That Helps,

sea_1987

答:
I have just completed a thorough research exercise on this, with the same requirement in mind.  The sad truth of the matter is that most of the plugins that supposedly give you this functionality do not work fully and properly.  I tried a number of plugins including:

Buddypress Registration Options

Absolute Privacy

Angsuman’s Authenticated WordPress Plugin

BuddyPress Private Community

All of these failed to give me bulletproof security. They largely seemed to block standard WordPress pages, but didn't block public access to the Activity, Members, Groups and other sections.  Other issues were simply getting it to work with WP 3.0.1. I found I had to dig into the plugin code and hack it to get a decent result.

Finally, I settled on a plugin called "registered-users-only-2".  This totally blocks users who are not registered.  However, it doesn't give you moderation functionality.

I hope this helps your quest.

Title: Wordpress and buddypress advice


问:
Edittext password is always showing the password
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

```<code><EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>
</code>```

drawable file ss:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />
</code>```

Complete Layout:

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>
</code>```

答:
I have tested this is working fine

```<code> <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textWebPassword"
        android:layout_height="40dp"
        android:hint="Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15" />
</code>```

change your inputType from

```<code>android:inputType="textPassword"
</code>```

to

```<code>android:inputType="textWebPassword"
</code>```

Body:
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

<EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>

drawable file ss:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />

Complete Layout:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>

Body:
I have tested this is working fine

 <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textWebPassword"
        android:layout_height="40dp"
        android:hint="Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15" />

change your inputType from

android:inputType="textPassword"

to

android:inputType="textWebPassword"