答: You couldn't add multiple actions in the form action, You should send the form to a PHP file and then after validating, send the email by PHP mail function or other libraries like PHPmailer etc.</p>

Title: Multipe action="" attribute urls

Body:
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?

HTML:

<form action="<?php echo htmlspecialchars($_server['php_self']);?>
    , mailto:example@gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> First Name:
    <input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><?php echo $fnameErr;?>

    Last Name:
    <input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><?php echo $lnameErr;?>

    Email:
    <input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><?php echo
    $emailErr;?>

    Year Level:
    <select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
        <option>Year 8</option>
        <option>Year 9</option>
        <option>Year 10</option>
        <option>Year 11</option>
        <option>Year 12</option>
        <option>Uni Student</option>
        <option>Other</option>
    </select>
    Comment:
    <textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
    </textarea>

    <input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>

PHP:

<?php
//feedback form validation code
//start

//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";

//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["fname"])) {
        $fnameErr = "* Your first name is required!";
    } else {
        $firstName = test_input($_POST["fname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
            $fnameErr = "* Only letters and white space allowed!";
        }
    }

    if (empty($_POST["lname"])) {
        $lnameErr = "* Your last name is required!";
    } else {
        $lastName = test_input($_POST["lname"]);
        if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
            $lnameErr = "* Only letters and white space allowed!";
        }
    }

    if(empty($_POST["comment"])) {
        $comment = "* the comment box is required!";
    } else {
        $comment = test_input($_post["comment"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "* Your email is required!";
    } else {
        $email = test_input($_POST["email"]);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
           $emailErr = "* Invalid Email Format!";
        }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
//end
?>

JS script for a confirm when the user clicks submit. so it makes sense to the form.


来源: stackexchange

问:
calling a promise within a promise , with $q.all
I have multiple api requests which can run in parallel.

getlocations, getstates, get territories can make a request in parallel. however once i have the states list from getstates() call, i need to make an api request for each individual state and parse the state object.

Here is the code that i have so far, Is it ok to call a promise within a promise this way ?

```<code>  getAllLocations() {
    //make a promise call for all here .
    var promise = [];
    //first prmise
    promise.push(this.getAllLocations(Id).then(
        (locationsData) => {
            this.locations = locationsData;
        }));
    //second promise
    promise.push(this.getAllStates(Id).then(
        (resp) => {
            this.states = resp.data;
            //for each state , need to make an api call and add to the state info
            angular.forEach(this.states, function(state){
                var nodeId = state.Id;
                this.getStateSummary(nodeId).then((resp) => {
                    state.healthStatus = resp.data.operationalStatus;
                });
            },this)
        }));
    //third promise
    promise.push(this.getAllterritories(Id).then(
        (resp) => {
            this.territories = resp.data;
        }));
    //after all promises parse teh location data
    $q.all(promise).then(() => {
        for (var i = 0; i < this.locations.length; i++) {
            //do something with with location here
        }
        this.gridData = this.locations;
    });
}
</code>```

if not , whats the best way to make teh getStatesummary() call ?

答:
I'd simplify each of the 3 promises (especially 1 and 3), so that this.locations, this.states and this.territories are all updated in the $q.all .then - you don't have to, but I think it makes the code a little more readable

Next, assign all 3 promises to a variable (p1, p2, p3 in the code below)

The next issue is waiting on all the states API calls to complete - another $q.all required there

All up, with a little extra ES6 goodness, you get

```<code>getAllLocations() {
    //first prmise
    const p1 = this.getAllLocations(Id);
    //second promise
    const p2 = this.getAllStates(Id).then(resp =>
        //for each state , need to make an api call and add to the state info
        $q.all(resp.map(state => this.getStateSummary(state.Id).then(resp => state.healthStatus = resp.data.operationalStatus)))
        .then(() => resp) // so we return data for this.states
    );
    //third promise
    const p3 = this.getAllterritories(Id).then(resp => resp.data);
    //after all promises parse teh location data
    $q.all([p1, p2, p3]).then(([locations, states, territories]) => {
        this.locations = locations;
        this.states = states;
        this.territories = territories;
        for (var i = 0; i < locations.length; i++) {
            //do something with with location here
        }
        this.gridData = this.locations;
    });
}
</code>```

If the getAllStates promise returns a Object instead of my assumption that it's an array - then replace the inner $q.all with

```<code>        $q.all(Object.entries(resp).map(([key, state]) => this.getStateSummary(state.Id).then(resp => state.healthStatus = resp.data.operationalStatus)))
</code>```

Actually, the above code would work for Array or Object equally :p

ContentLicense: CC BY-SA 3.0

Body:
I have multiple api requests which can run in parallel.

getlocations, getstates, get territories can make a request in parallel. however once i have the states list from getstates() call, i need to make an api request for each individual state and parse the state object.

Here is the code that i have so far, Is it ok to call a promise within a promise this way ?

  getAllLocations() {
    //make a promise call for all here .
    var promise = [];
    //first prmise
    promise.push(this.getAllLocations(Id).then(
        (locationsData) => {
            this.locations = locationsData;
        }));
    //second promise
    promise.push(this.getAllStates(Id).then(
        (resp) => {
            this.states = resp.data;
            //for each state , need to make an api call and add to the state info
            angular.forEach(this.states, function(state){
                var nodeId = state.Id;
                this.getStateSummary(nodeId).then((resp) => {
                    state.healthStatus = resp.data.operationalStatus;
                });
            },this)
        }));
    //third promise
    promise.push(this.getAllterritories(Id).then(
        (resp) => {
            this.territories = resp.data;
        }));
    //after all promises parse teh location data
    $q.all(promise).then(() => {
        for (var i = 0; i < this.locations.length; i++) {
            //do something with with location here
        }
        this.gridData = this.locations;
    });
}

if not , whats the best way to make teh getStatesummary() call ?

Body:
I'd simplify each of the 3 promises (especially 1 and 3), so that this.locations, this.states and this.territories are all updated in the $q.all .then - you don't have to, but I think it makes the code a little more readable

Next, assign all 3 promises to a variable (p1, p2, p3 in the code below)

The next issue is waiting on all the states API calls to complete - another $q.all required there

All up, with a little extra ES6 goodness, you get

getAllLocations() {
    //first prmise
    const p1 = this.getAllLocations(Id);
    //second promise
    const p2 = this.getAllStates(Id).then(resp =>
        //for each state , need to make an api call and add to the state info
        $q.all(resp.map(state => this.getStateSummary(state.Id).then(resp => state.healthStatus = resp.data.operationalStatus)))
        .then(() => resp) // so we return data for this.states
    );
    //third promise
    const p3 = this.getAllterritories(Id).then(resp => resp.data);
    //after all promises parse teh location data
    $q.all([p1, p2, p3]).then(([locations, states, territories]) => {
        this.locations = locations;
        this.states = states;
        this.territories = territories;
        for (var i = 0; i < locations.length; i++) {
            //do something with with location here
        }
        this.gridData = this.locations;
    });
}

If the getAllStates promise returns a Object instead of my assumption that it's an array - then replace the inner $q.all with

        $q.all(Object.entries(resp).map(([key, state]) => this.getStateSummary(state.Id).then(resp => state.healthStatus = resp.data.operationalStatus)))

Actually, the above code would work for Array or Object equally :p


问:
SQL - char field with date - how to search between two dates
I have simple problem with SQL query.. I would like to search fields, where dates begin and ends in specific date and time.

Field is defined as CHAR and have structure: DD.MM.YYYY hh:mm:ss and I cannot change it.

I tried to declare some variables and search by this, also tried by Converting.

This is what I tried and didn't work:

```<code>SELECT date FROM table WHERE date BETWEEN '1.01.2017 00:00:00' AND '1.02.2017 23:59:59'

SELECT date FROM table WHERE date >= '1.01.2017 00:00:00' AND date <= '1.02.2017 00:00:00'

SELECT date FROM table WHERE date >= Convert(DATETIME, '1.01.2017', 104) AND date <= Convert(DATETIME, '1.02.2017', 104)
</code>```

Always after this query I get all dates, not this what I asked.

答:
Your field is not in a format that can be compared lexicographically as strings, so you need to convert it to a date. But it's not in the format that MySQL can parse by default (it expects dates in the format YYYY-MM-DD). So use STR_TO_DATE() to parse it with a format string.

```<code>SELECT date
FROM table
WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN '2017-01-01 00:00' AND '2017-01-02 23:59:59'
</code>```

Body:
I have simple problem with SQL query.. I would like to search fields, where dates begin and ends in specific date and time.

Field is defined as CHAR and have structure: DD.MM.YYYY hh:mm:ss and I cannot change it.

I tried to declare some variables and search by this, also tried by Converting.

This is what I tried and didn't work:

SELECT date FROM table WHERE date BETWEEN '1.01.2017 00:00:00' AND '1.02.2017 23:59:59'

SELECT date FROM table WHERE date >= '1.01.2017 00:00:00' AND date <= '1.02.2017 00:00:00'

SELECT date FROM table WHERE date >= Convert(DATETIME, '1.01.2017', 104) AND date <= Convert(DATETIME, '1.02.2017', 104)

Always after this query I get all dates, not this what I asked.

Body:
Your field is not in a format that can be compared lexicographically as strings, so you need to convert it to a date. But it's not in the format that MySQL can parse by default (it expects dates in the format YYYY-MM-DD). So use STR_TO_DATE() to parse it with a format string.

SELECT date
FROM table
WHERE STR_TO_DATE(date, '%d.%m.%Y %H:%i:%s') BETWEEN '2017-01-01 00:00' AND '2017-01-02 23:59:59'


问:
Variable init in Go
I see following code (I simplified it a bit).

```<code>func getEndpoints(db *sqlx.DB) s.Endpoints {
    var endpoints s.Endpoints
    {
        repository := acl.NewRepository(db)
        service := stat.NewService(repository)
        endpoints = s.Endpoints{
            GetEndpoint: s.MakeEndpoint(service),
        }
    }

    return endpoints
}
</code>```

If I understand this code correctly, code inside var endpoints s.Endpoints{...} is executed line by line and endpoints = s.Endpoints ... line initialises var endpoints variable declared above.

I suppose that it's correct to rewrite it like this (correct me if I'm wrong):

```<code>func getEndpoints(db *sqlx.DB) s.Endpoints {

    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints := s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }

    return endpoints
}
</code>```

So can somebody explain me why initialisation is written inside var endpoints s.Endpoints{...}. Is there any idea to do it like this? Am I missing something?

答:
Adding a new block will create a new variable scope, and variables declared in that block will not be available outside of it:

```<code>var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

// service and repository  variables are not defined here!
</code>```

In your specific simplified example it makes little sense, but if you have other blocks with the same variables it makes more sense. For example:

```<code>var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

 // Get another repository
{
    repository := otherRepo.NewRepository(db)
    repository.DoSomething()
}
</code>```

Some people consider this "good hygiene". Personally, I don't think it's worth the decrease in readability.

Title: Variable init in Go

Body:
I see following code (I simplified it a bit).

func getEndpoints(db *sqlx.DB) s.Endpoints {
    var endpoints s.Endpoints
    {
        repository := acl.NewRepository(db)
        service := stat.NewService(repository)
        endpoints = s.Endpoints{
            GetEndpoint: s.MakeEndpoint(service),
        }
    }

    return endpoints
}

If I understand this code correctly, code inside var endpoints s.Endpoints{...} is executed line by line and endpoints = s.Endpoints ... line initialises var endpoints variable declared above.

I suppose that it's correct to rewrite it like this (correct me if I'm wrong):

func getEndpoints(db *sqlx.DB) s.Endpoints {

    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints := s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }

    return endpoints
}

So can somebody explain me why initialisation is written inside var endpoints s.Endpoints{...}. Is there any idea to do it like this? Am I missing something?

Body:
Adding a new block will create a new variable scope, and variables declared in that block will not be available outside of it:

var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

// service and repository  variables are not defined here!

In your specific simplified example it makes little sense, but if you have other blocks with the same variables it makes more sense. For example:

var endpoints s.Endpoints
{
    repository := acl.NewRepository(db)
    service := stat.NewService(repository)
    endpoints = s.Endpoints{
        GetEndpoint: s.MakeEndpoint(service),
    }
}

 // Get another repository
{
    repository := otherRepo.NewRepository(db)
    repository.DoSomething()
}

Some people consider this "good hygiene". Personally, I don't think it's worth the decrease in readability.


问:
iOS keyboard with "Go" button instead of return
Is there a way to use the keyboard with "Go" key instead of the "Return" key like when you are accessing login fields in Safari? I'm guessing this should be something trivial but my searches aren't turning up anything. :(

Thanks in advance.

答:
For a UITextField or editable UITextView:

```<code>[myTextField setReturnKeyType:UIReturnKeyGo];
</code>```

You can also configure this in Interface Builder, under Text Input Traits for your text field/view:

ContentLicense: CC BY-SA 2.5

Body:
For a UITextField or editable UITextView:

[myTextField setReturnKeyType:UIReturnKeyGo];

You can also configure this in Interface Builder, under Text Input Traits for your text field/view:


问:
Add strechable space in WPF
I have this XAML:

```<code><Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="400" Width="400" >

    <StackPanel Margin="10, 10, 10, 10">

        <CheckBox Content="CheckBox" Margin="0, 0, 0, 10"/>
        <Button Content="Button" Height="30" Click="OnClick"/>

    </StackPanel>

</Window>
</code>```

which gives this output:

How can I add a stretchable space between the combo box and the button to keep one on the top, and the other on the bottom?

Thanks,
Massimo

答:
Use a DockPanel (the LastChildFill is important in this case):</p>

```<code><DockPanel Margin="10, 10, 10, 10" LastChildFill="False">
    <CheckBox DockPanel.Dock="Top"  Content="CheckBox" Margin="0, 0, 0, 10"/>
    <Button DockPanel.Dock="Bottom" Content="Button" Height="30" Click="OnClick"/>
</DockPanel>
</code>```

Title: Add strechable space in WPF

Body:
I have this XAML:

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="400" Width="400" >

    <StackPanel Margin="10, 10, 10, 10">

        <CheckBox Content="CheckBox" Margin="0, 0, 0, 10"/>
        <Button Content="Button" Height="30" Click="OnClick"/>

    </StackPanel>

</Window>

which gives this output:

How can I add a stretchable space between the combo box and the button to keep one on the top, and the other on the bottom?

Thanks,
Massimo

Body:
Use a DockPanel (the LastChildFill is important in this case):

<DockPanel Margin="10, 10, 10, 10" LastChildFill="False">
    <CheckBox DockPanel.Dock="Top"  Content="CheckBox" Margin="0, 0, 0, 10"/>
    <Button DockPanel.Dock="Bottom" Content="Button" Height="30" Click="OnClick"/>
</DockPanel>


问:
Android- How to create 4 square buttons in one row with icons on top of them?
Im trying to create an app which will have 4 square buttons in one row with an icon on top of these buttons. Which is the best way to approach this? I'm trying to do something like this as shown in the image

Thank You

答: Have you Tried Table Layout? Although you can use any Layout, I suggest you stick to one Parent layout like the relative layout and then multiple child layouts to manage to UI elements.</p>


问:
Azure service call to server under firewall
I have an azure app service.
I want to call to a private(under firewall) service from the app service and receive a response.

What to set on private service's firewall to ba able to call from app service and get response?

答:
On Azure Web App properties panel, you could get a list of outbound IP addresses. To enable your app service to call your private service, you need to configure these IP addresses to the inbound security of private service's firewall.

Please note that only app service hosted in App Service Environment has a static outbound IP address. For other app services, the outbound IP addresses may be changed due to following reasons. We need to change the inbound security of private service's firewall if the outbound IP addresses are changed.

It becomes necessary for Azure infrastructure to increase the number of outbound IP addresses. In that case the existing IP addresses will be preserved but there will be some new ones. So far there hasn't been a need to increase number of IP addresses and if there ever be the need for that there will be an early notice about it.

The Web App gets relocated to a different scale unit. Prior to that the subscription owner gets an email notification one month in advance.


问:
Intergrating firebase real time database to android app
App doesn't receive data from firebase console.

I have set up INTERNET permission in the manifest file.
I have also have one listview in my layout file.
Firebase assistant also shows my app is connected to Firebase,dependencies set up correctly

Here's my java class:

```<code>public class Todaytips extends Activity implements ValueEventListener {
    DatabaseReference dref;
    ListView listView;
    ArrayList<String> list=new ArrayList<>();
    ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todaytips);
        listView=(ListView)findViewById(R.id.listview);
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list);
        dref= FirebaseDatabase.getInstance().getReference();
        dref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
             String value= dataSnapshot.getValue(String.class);
                list.add(value);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                String value= dataSnapshot.getValue(String.class);
                list.remove(value);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_activity_one, menu);
        return true;
    }

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }

}
</code>```

答:
I had different project IDs because my android studio and firebase were logged in
on different google accounts. </p>

Body:
App doesn't receive data from firebase console.

I have set up INTERNET permission in the manifest file.
I have also have one listview in my layout file.
Firebase assistant also shows my app is connected to Firebase,dependencies set up correctly

Here's my java class:

public class Todaytips extends Activity implements ValueEventListener {
    DatabaseReference dref;
    ListView listView;
    ArrayList<String> list=new ArrayList<>();
    ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todaytips);
        listView=(ListView)findViewById(R.id.listview);
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list);
        dref= FirebaseDatabase.getInstance().getReference();
        dref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
             String value= dataSnapshot.getValue(String.class);
                list.add(value);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                String value= dataSnapshot.getValue(String.class);
                list.remove(value);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_activity_one, menu);
        return true;
    }

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }

}


问:
Minimum and maximum date in UIDatePicker
I want to get the minimum and maximum date from a date picker, but minimum date should be "- 18" of the current date and the maximum date should be "- 100" of current date.

Suppose current year is 2018 then I want minimum date 2000 and maximum date 1918.

What I have done so far is :

```<code>NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSInteger year = [components year];

int mindt = year - 18;

int maxdt = year -100;

   // NSDate * MinDate = [components year] - 18;

   // NSDate * MaxDate =  [components year] - 100;

   // self.datePicker.minimumDate = MinDate;

   // self.datePicker.maximumDate = MaxDate;
</code>```

but I cant get this integer to my date format..

答:
**Minimum and maximum date in UIDatePicker: #Swift

**if you want to select the min and max date between two date value use below simple code: **

for Example :  Min Date : 01-04-2017 and Max Date : 31-03-2018

```<code>let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
minDateComponent.day = 01
minDateComponent.month = 04
minDateComponent.year = 2017

let minDate = calendar.date(from: minDateComponent)
print(" min date : \(String(describing: minDate))")

var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
maxDateComponent.day = 0
maxDateComponent.month = 03 + 1
maxDateComponent.year = 2018

let maxDate = calendar.date(from: maxDateComponent)
print("max date : \(String(describing: maxDate))")

picker.minimumDate = minDate! as Date
picker.maximumDate =  maxDate! as Date
</code>```

Body:
I want to get the minimum and maximum date from a date picker, but minimum date should be "- 18" of the current date and the maximum date should be "- 100" of current date.

Suppose current year is 2018 then I want minimum date 2000 and maximum date 1918.

What I have done so far is :

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];

NSInteger year = [components year];

int mindt = year - 18;

int maxdt = year -100;

   // NSDate * MinDate = [components year] - 18;

   // NSDate * MaxDate =  [components year] - 100;

   // self.datePicker.minimumDate = MinDate;

   // self.datePicker.maximumDate = MaxDate;

but I cant get this integer to my date format..

Body:
**Minimum and maximum date in UIDatePicker: #Swift

**if you want to select the min and max date between two date value use below simple code: **

for Example :  Min Date : 01-04-2017 and Max Date : 31-03-2018

let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
minDateComponent.day = 01
minDateComponent.month = 04
minDateComponent.year = 2017

let minDate = calendar.date(from: minDateComponent)
print(" min date : \(String(describing: minDate))")

var maxDateComponent = calendar.dateComponents([.day,.month,.year], from: Date())
maxDateComponent.day = 0
maxDateComponent.month = 03 + 1
maxDateComponent.year = 2018

let maxDate = calendar.date(from: maxDateComponent)
print("max date : \(String(describing: maxDate))")

picker.minimumDate = minDate! as Date
picker.maximumDate =  maxDate! as Date


问:
window.open("url","_self") works well on localhost url, but not when I put it on a server
I have an angularJS frontend that I redirect to a third party payment gateway when a customer clicks on the Pay button.

I am currently using the following function to redirect to the payment gateway:

```<code>if(status.data.result == "true"){
var ref = window.open(url,'_self');
}
};
</code>```

This code works well when I try it on localhost. But does not work when I put it on the ubuntu server.

Any ideas on why?

Regards,
Galeej

答:
Try adding return false after var ref = window.open(url,'_self'); like

```<code>var ref = window.open(url,'_self');
return false;
</code>```

return false will prevent from page submit and it may work this way to properly redirect on the same page.

Body:
I have an angularJS frontend that I redirect to a third party payment gateway when a customer clicks on the Pay button.

I am currently using the following function to redirect to the payment gateway:

if(status.data.result == "true"){
var ref = window.open(url,'_self');
}
};

This code works well when I try it on localhost. But does not work when I put it on the ubuntu server.

Any ideas on why?

Regards,
Galeej

Body:
Try adding return false after var ref = window.open(url,'_self'); like

var ref = window.open(url,'_self');
return false;

return false will prevent from page submit and it may work this way to properly redirect on the same page.


问:
Python How to find average of columns using dataframes apply method
This is a question on Udacity Data Science Nanodegree and I can't figure it out. The instructions are:

Using the dataframe's apply method, create a new Series called avg_medal_count that indicates the average number of gold, silver, and bronze medals earned amongst countries who earned at least one medal of any kind at the 2014 Sochi Olympics.

The code I have currently is:

```<code>import numpy
from pandas import DataFrame, Series

def avg_medal_count():

 countries = ['Russian Fed.', 'Norway', 'Canada', 'United States',
                 'Netherlands', 'Germany', 'Switzerland', 'Belarus',
                 'Austria', 'France', 'Poland', 'China', 'Korea',
                 'Sweden', 'Czech Republic', 'Slovenia', 'Japan',
                 'Finland', 'Great Britain', 'Ukraine', 'Slovakia',
                 'Italy', 'Latvia', 'Australia', 'Croatia', 'Kazakhstan']

    gold = [13, 11, 10, 9, 8, 8, 6, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
    silver = [11, 5, 10, 7, 7, 6, 3, 0, 8, 4, 1, 4, 3, 7, 4, 2, 4, 3, 1, 0, 0, 2, 2, 2, 1, 0]
    bronze = [9, 10, 5, 12, 9, 5, 2, 1, 5, 7, 1, 2, 2, 6, 2, 4, 3, 1, 2, 1, 0, 6, 2, 1, 0, 1]

    olympic_medal_counts = {'country_name':countries,
                            'gold': Series(gold),
                            'silver': Series(silver),
                            'bronze': Series(bronze)}
    df = DataFrame(olympic_medal_counts)

# YOUR CODE HERE

    return avg_medal_count
</code>```

I have tried a couple different things such as:

avg_medal_count = df.apply(numpy.mean), but get the error saying it could not convert the first column to numeric which makes sense because the first column is a list of countries. How can I use df.apply on only gold, silver and bronze columns? I have tried other variations, but nothing worked. I am pretty sure that I need to use a combination of df.apply and numpy.mean, because that is what I just learned about. Any thoughts?

Thanks!

答:
Neither solution above uses apply as stated in the problem. Use the following:

```<code># YOUR CODE HERE

sub_series = {'gold': df.gold,
              'silver': df.silver,
              'bronze': df.bronze
             }

sub_df = DataFrame(sub_series)

avg_medal_count = sub_df.apply(numpy.mean)

return avg_medal_count
</code>```

The applying numpy.mean on the original df will always return errors due to the text column 'countries'

Body:
This is a question on Udacity Data Science Nanodegree and I can't figure it out. The instructions are:

Using the dataframe's apply method, create a new Series called avg_medal_count that indicates the average number of gold, silver, and bronze medals earned amongst countries who earned at least one medal of any kind at the 2014 Sochi Olympics.

The code I have currently is:

import numpy
from pandas import DataFrame, Series

def avg_medal_count():

 countries = ['Russian Fed.', 'Norway', 'Canada', 'United States',
                 'Netherlands', 'Germany', 'Switzerland', 'Belarus',
                 'Austria', 'France', 'Poland', 'China', 'Korea',
                 'Sweden', 'Czech Republic', 'Slovenia', 'Japan',
                 'Finland', 'Great Britain', 'Ukraine', 'Slovakia',
                 'Italy', 'Latvia', 'Australia', 'Croatia', 'Kazakhstan']

    gold = [13, 11, 10, 9, 8, 8, 6, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
    silver = [11, 5, 10, 7, 7, 6, 3, 0, 8, 4, 1, 4, 3, 7, 4, 2, 4, 3, 1, 0, 0, 2, 2, 2, 1, 0]
    bronze = [9, 10, 5, 12, 9, 5, 2, 1, 5, 7, 1, 2, 2, 6, 2, 4, 3, 1, 2, 1, 0, 6, 2, 1, 0, 1]

    olympic_medal_counts = {'country_name':countries,
                            'gold': Series(gold),
                            'silver': Series(silver),
                            'bronze': Series(bronze)}
    df = DataFrame(olympic_medal_counts)

# YOUR CODE HERE

    return avg_medal_count

I have tried a couple different things such as:

avg_medal_count = df.apply(numpy.mean), but get the error saying it could not convert the first column to numeric which makes sense because the first column is a list of countries. How can I use df.apply on only gold, silver and bronze columns? I have tried other variations, but nothing worked. I am pretty sure that I need to use a combination of df.apply and numpy.mean, because that is what I just learned about. Any thoughts?

Thanks!

Body:
Neither solution above uses apply as stated in the problem. Use the following:

# YOUR CODE HERE

sub_series = {'gold': df.gold,
              'silver': df.silver,
              'bronze': df.bronze
             }

sub_df = DataFrame(sub_series)

avg_medal_count = sub_df.apply(numpy.mean)

return avg_medal_count

The applying numpy.mean on the original df will always return errors due to the text column 'countries'


问:
Why doesn't this ES6 default argument value give the desired result?
I found this ES6 code in a book:

```<code>let value = 5;

function getValue() {
    return value++;
}

function add(first, second = getValue()) {
    return first + second;
}

console.log(add(1, 1));     // 2
console.log(add(1));        // 6
</code>```

Why does running console.log(add(1)); return 6 as the value, which means it is taking the parameter second as 5 although my code explicitly specifies that the getValue function should return value++ - which means the first time it is run, the getValue function should be returning 6 and add should be returning 7. I am running this code in the Firefox console - am I missing something?

答:
Because you use the postfix expression, if you use prefix expression then you will get 7.

Airthmetic operators

"If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.
If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing".

Body:
I found this ES6 code in a book:

let value = 5;

function getValue() {
    return value++;
}

function add(first, second = getValue()) {
    return first + second;
}

console.log(add(1, 1));     // 2
console.log(add(1));        // 6

Why does running console.log(add(1)); return 6 as the value, which means it is taking the parameter second as 5 although my code explicitly specifies that the getValue function should return value++ - which means the first time it is run, the getValue function should be returning 6 and add should be returning 7. I am running this code in the Firefox console - am I missing something?


答:
I believe your problem is not related to ecmascript-6, but in not understand the ++ operator correctly.

According to the documentation:

Unary operator. Adds one to its operand. If used as a prefix operator
  (++x), returns the value of its operand after adding one; if used as a
  postfix operator (x++), returns the value of its operand before adding
  one.

Replacing value++ with either ++value or value + 1 should solve your issue.

Title: Why doesn't this ES6 default argument value give the desired result?


问:
PHP header location function not working in form
I'm trying to make a registration form for my website. I'm using the code below. All the error handlers work fine since it's adding the users into my database. I've trid to add ob_start. I removed all white spaces using a plugin for sublime text. I tried to use javascript instead of php (top.window). I also tried to use full url instead of just directories. But when I click submit it doesnt redirect me to the address I put after Location. When I click the button it takes me to this php file but doesnt redirect me back to the registration page which is a seperate file(I know there are a lot of similar questions that have been asked but they dont seem to work for my situation).
Does anyone know how to fix that?

```<code>if (isset($_POST['submit'])){

include_once 'db.php';

$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

//error handlers
//Check for empty fields
if (empty($uid) || empty($pwd) || empty($email)) {

    header("Location : /login/register.php?signup=empty");
    exit();

} else{

    //Check if input characters are valid
    if (!preg_match("/^[a-zA-Z]*$/", $uid)) {

        header('Location: /login/register.php?signup=invalid');
        exit();

    } else {

        //Check if email is valid
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            header('Location : /login/register.php?signup=email');
            exit();
        } else {
            $sql = "SELECT * FROM users WHERE user_uid='$uid'";
            $result = mysqli_query($conn, $sql);
            $resultCheck = mysqli_num_rows($result);

            if ($resultCheck > 0) {
                header('Location : /login/register.php?signup=usertaken');
            exit();
            } else {
                //Hashing the password
                $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
                //Insert the user into the databse
                $sql = "INSERT INTO users (user_uid, user_pwd, user_email) VALUES ('$uid', '$hashedPwd', '$email');";
                mysqli_query($conn, $sql);
                header('Location : /login/register.php?signup=success');
                exit();
            }
        }

    }

}

} else {
    header('Location : /login/register.php');
    exit();
}
</code>```

Solved - Removing space after "location" answer by Nigel Ren

答:
replace all header to location.assign

```<code>header('Location : /login/register.php');
</code>```

replace to

```<code>echo "<script>location.assign('/login/register.php')</script>";
</code>```

after use location assign , maybe problem sol..

Body:
I'm trying to make a registration form for my website. I'm using the code below. All the error handlers work fine since it's adding the users into my database. I've trid to add ob_start. I removed all white spaces using a plugin for sublime text. I tried to use javascript instead of php (top.window). I also tried to use full url instead of just directories. But when I click submit it doesnt redirect me to the address I put after Location. When I click the button it takes me to this php file but doesnt redirect me back to the registration page which is a seperate file(I know there are a lot of similar questions that have been asked but they dont seem to work for my situation).
Does anyone know how to fix that?

if (isset($_POST['submit'])){

include_once 'db.php';

$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

//error handlers
//Check for empty fields
if (empty($uid) || empty($pwd) || empty($email)) {

    header("Location : /login/register.php?signup=empty");
    exit();

} else{

    //Check if input characters are valid
    if (!preg_match("/^[a-zA-Z]*$/", $uid)) {

        header('Location: /login/register.php?signup=invalid');
        exit();

    } else {

        //Check if email is valid
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            header('Location : /login/register.php?signup=email');
            exit();
        } else {
            $sql = "SELECT * FROM users WHERE user_uid='$uid'";
            $result = mysqli_query($conn, $sql);
            $resultCheck = mysqli_num_rows($result);

            if ($resultCheck > 0) {
                header('Location : /login/register.php?signup=usertaken');
            exit();
            } else {
                //Hashing the password
                $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
                //Insert the user into the databse
                $sql = "INSERT INTO users (user_uid, user_pwd, user_email) VALUES ('$uid', '$hashedPwd', '$email');";
                mysqli_query($conn, $sql);
                header('Location : /login/register.php?signup=success');
                exit();
            }
        }

    }

}

} else {
    header('Location : /login/register.php');
    exit();
}

Solved - Removing space after "location" answer by Nigel Ren

Body:
replace all header to location.assign

header('Location : /login/register.php');

replace to

echo "<script>location.assign('/login/register.php')</script>";

after use location assign , maybe problem sol..


问:
Android unit testing, says I have no tests inside my class, although I have 1
This is how my ApplicationTest class looks like:

```<code>  /**
 * <a href="http://d.android.com/tools/testing/testing_android.html">Testing
Fundamentals</a>
 */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class ApplicationTest {
@Rule
public ActivityTestRule mActivityRule =
        new ActivityTestRule(VMBaseActivity.class,
                false /* Initial touch mode */, false /*  launch activity */) {

            @Override
            protected void afterActivityLaunched() {
                // Enable JavaScript.
                Log.i("","activity has been started");
            }
        };

@Test
public void enterPin() {
    // Type text and then press the button.
    onView(withId(R.id.button0)).perform(click());
    onView(withId(R.id.button0)).perform(click());
    onView(withId(R.id.button0)).perform(click());
    onView(withId(R.id.button0)).perform(click());
}
}
</code>```

I have this in my build.gradle

```<code>    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
</code>```

But when I run I get this error:

```<code> Client not ready yet..
 Started running tests

 junit.framework.AssertionFailedError: No tests found in com.vidyo.vidyomod.ApplicationTest
 at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
 at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
 at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
 at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1893)

 Tests ran to completion.
</code>```

Why doesn't the app find my tests?

答:
Add the following line to your app.gradle:

defaultConfig {
          testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
      }

Body:
This is how my ApplicationTest class looks like:

  /**
 * Testing
Fundamentals
 */
@RunWith(AndroidJUnit4.class)
@LargeTest
public class ApplicationTest {
@Rule
public ActivityTestRule mActivityRule =
        new ActivityTestRule(VMBaseActivity.class,
                false /* Initial touch mode */, false /*  launch activity */) {

            @Override
            protected void afterActivityLaunched() {
                // Enable JavaScript.
                Log.i("","activity has been started");
            }
        };

@Test
public void enterPin() {
    // Type text and then press the button.
    onView(withId(R.id.button0)).perform(click());
    onView(withId(R.id.button0)).perform(click());
    onView(withId(R.id.button0)).perform(click());
    onView(withId(R.id.button0)).perform(click());
}
}

I have this in my build.gradle

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

But when I run I get this error:

 Client not ready yet..
 Started running tests

 junit.framework.AssertionFailedError: No tests found in com.vidyo.vidyomod.ApplicationTest
 at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
 at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
 at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
 at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1893)

 Tests ran to completion.

Why doesn't the app find my tests?


问:
What's a simple way to convert between an am/pm time to 24 hour time in javascript
I've been playing with jquery and I've run myself into a time problem. I've got 3 time input select boxes, one for hours, one for minutes, and one for the Meridian. I need to convert this time into a 24 hour string format and then stick it into a hidden input.

```<code>var time = "";
time += $("#EventCloseTimeHour option:selected").text();
time += ":" + $("#EventCloseTimeMin option:selected").text() + ":00";
time += " " + $("#EventCloseTimeMeridian option:selected").text();

$("#ConditionValue").val(time);
</code>```

This gives me "1:30:00 pm" where I need "13:30:00". Any quick javascript time tips?

答:
Just to add a plain JS answer, the following will format the time based on the length of the initial string. If h:mm returns HH:mm, if h:mm:ss returns HH:mm:ss.

If HH:mm:ss is always required, it's simple to add default seconds of ":00" if not present in initial string.

// Change time in h:mm:ss ap to  HH:mm:ss time
// If time missing seconds, returns HH:mm
function timeToHHmm(time) {
  var nums = time.match(/\d+/g);
  var am   = /am/i.test(time);
  nums[0] = ('0' + ((nums[0]%12) + (am? 0 : 12))).slice(-2);
  // If HH:mm:ss required, use following line instead of last
  // return nums.join(':') + (nums.length == 2? ':00' : '');
  return nums.join(':');
}

// Some tests
['2:45am',     // hh:mm only
 '5:15:45pm',  // hh:mm:ss
 '5:15:45 pm', // space before am/pm
 '05:15:45 pm',// leading zero on hour
 '12:02am',
 '12:02 pm',
 '12:02:00am'
 ].forEach(function(time) {
  console.log(time + ' => ' + timeToHHmm(time));
});```

OwnerDisplayName: wizard

Body:
I've been playing with jquery and I've run myself into a time problem. I've got 3 time input select boxes, one for hours, one for minutes, and one for the Meridian. I need to convert this time into a 24 hour string format and then stick it into a hidden input.

var time = "";
time += $("#EventCloseTimeHour option:selected").text();
time += ":" + $("#EventCloseTimeMin option:selected").text() + ":00";
time += " " + $("#EventCloseTimeMeridian option:selected").text();

$("#ConditionValue").val(time);

This gives me "1:30:00 pm" where I need "13:30:00". Any quick javascript time tips?


问:
Unable to change value at edit time with codeIgniter validation
Here i have a list of categories and user can add a new category as well as edit them.

Now at the edit time i'm using server-side validation by codeigniter for reduce redundancies . but the issue is the, whenever i edit an existing category then it can't update it because it compare with their original value, that is wrong. i trying to many time but unable to fix this issue.

Here is my code

```<code>public function category_upd()
{
    extract($_POST);
    $userId = $this->session->userdata('id');
    $original_value = $this->db->query("SELECT cat_name FROM category WHERE user_id=".$userId." and  cat_name ='".$_POST['cat_name']."'") ;

    $original_value  = $original_value->result_array();
    $original_value = $original_value[0]['cat_name'];

    $original_value2 = $this->db->query("SELECT cat_name FROM category WHERE user_id=".$userId." and  cat_name ='".$_POST['cat_name']."'") ;

    $original_value2  = $original_value2->result_array();

    $original_value2 = $original_value2[0]['cat_name'];

    if(ucwords($_POST['cat_name']) != $original_value) {
        $this->session->set_flashdata('cat_failed','Category must be unique.');
        $is_unique =  '|is_unique[category.cat_name]';
    } else if(ucwords($original_value2 == "")){

        echo "go";
        exit;

        $this->session->set_flashdata('cat_failed','Category must be unique.');
        $is_unique =  '|is_unique[category.cat_name]';
    } else {
        $is_unique =  '';
    }
    $this->form_validation->set_rules('cat_name','Category','trim|required'.$is_unique);
    if($this->form_validation->run() ) {
</code>```

A snap with error

I need your kind efforts. Thanks

答:
Set validation Rules like this and you need to pass category id value

```<code> $this->form_validation->set_rules('cat_name', 'cat_name', 'required|trim|edit_unique[category.category_name.' . $_POST['category_id'].'.'.$_POST['user_id']. ']', array('edit_unique' => 'Category must be unique.'));
</code>```

And developed one function edit_unique on Form_validation.php like this
  Filepath system/libraries/Form_validation.php

```<code> public function edit_unique($str, $field)
    {

        sscanf($field, '%[^.].%[^.].%[^.].%[^.]', $table, $field,$id, $field2);
        return isset($this->CI->db)
            ? ($this->CI->db->limit(1)->get_where($table, array($field => $str, 'id !=' => $id,'user_id'=>$field2))->num_rows() === 0)
            : FALSE;

    }
</code>```

Body:
Here i have a list of categories and user can add a new category as well as edit them.

Now at the edit time i'm using server-side validation by codeigniter for reduce redundancies . but the issue is the, whenever i edit an existing category then it can't update it because it compare with their original value, that is wrong. i trying to many time but unable to fix this issue.

Here is my code

public function category_upd()
{
    extract($_POST);
    $userId = $this->session->userdata('id');
    $original_value = $this->db->query("SELECT cat_name FROM category WHERE user_id=".$userId." and  cat_name ='".$_POST['cat_name']."'") ;

    $original_value  = $original_value->result_array();
    $original_value = $original_value[0]['cat_name'];

    $original_value2 = $this->db->query("SELECT cat_name FROM category WHERE user_id=".$userId." and  cat_name ='".$_POST['cat_name']."'") ;

    $original_value2  = $original_value2->result_array();

    $original_value2 = $original_value2[0]['cat_name'];

    if(ucwords($_POST['cat_name']) != $original_value) {
        $this->session->set_flashdata('cat_failed','Category must be unique.');
        $is_unique =  '|is_unique[category.cat_name]';
    } else if(ucwords($original_value2 == "")){

        echo "go";
        exit;

        $this->session->set_flashdata('cat_failed','Category must be unique.');
        $is_unique =  '|is_unique[category.cat_name]';
    } else {
        $is_unique =  '';
    }
    $this->form_validation->set_rules('cat_name','Category','trim|required'.$is_unique);
    if($this->form_validation->run() ) {

A snap with error

I need your kind efforts. Thanks

Body:
Set validation Rules like this and you need to pass category id value

 $this->form_validation->set_rules('cat_name', 'cat_name', 'required|trim|edit_unique[category.category_name.' . $_POST['category_id'].'.'.$_POST['user_id']. ']', array('edit_unique' => 'Category must be unique.'));

And developed one function edit_unique on Form_validation.php like this
  Filepath system/libraries/Form_validation.php

 public function edit_unique($str, $field)
    {

        sscanf($field, '%[^.].%[^.].%[^.].%[^.]', $table, $field,$id, $field2);
        return isset($this->CI->db)
            ? ($this->CI->db->limit(1)->get_where($table, array($field => $str, 'id !=' => $id,'user_id'=>$field2))->num_rows() === 0)
            : FALSE;

    }


问:
wp_insert_post() database changes
I need to repeat all sql requests that occurs during wp_insert_post() execution. Also I need to create categories (also create new if not exists) and custom fields. Is it possible?</p>

答:
When you go to the Wordpress documentation for the wp_insert_post() you will find there section called "source" - you can see there all that is done when function wp_insert_post() is executed.

You see it's a lot of things. For most cases it is much better to use the built in Wordpress functions.

Title: wp_insert_post() database changes


问:
HTML5 audio problems
I have a HTML5 audio player on my website, it is not working, however it works in all browsers except chrome.

```<code><audio controls>
     <source src="http://www.mywebsite.com/path/2015-09-27.mp3" type="audio/mpeg">
</audio>
</code>```

However a week or more ago the audio files did work, and I didn't change anything, they just stopped being able to be played.

答:
I had the same problem with a mp3 file. I converted the *.mp3 file to *.ogg (e.g. with Audacity) and added a second source to the audio tag:

```<code><audio controls>
  <source src="file.mp3" type="audio/mpeg">
  <source src="file.ogg" type="audio/ogg">
  Your browser does not support the audio element.
</audio>
</code>```

Now everything works fine.

(found at W3Schools)

Title: HTML5 audio problems

Body:
I have a HTML5 audio player on my website, it is not working, however it works in all browsers except chrome.

<audio controls>
     <source src="http://www.mywebsite.com/path/2015-09-27.mp3" type="audio/mpeg">
</audio>

However a week or more ago the audio files did work, and I didn't change anything, they just stopped being able to be played.

Body:
I had the same problem with a mp3 file. I converted the *.mp3 file to *.ogg (e.g. with Audacity) and added a second source to the audio tag:

<audio controls>
  <source src="file.mp3" type="audio/mpeg">
  <source src="file.ogg" type="audio/ogg">
  Your browser does not support the audio element.
</audio>

Now everything works fine.

(found at W3Schools)


问:
Angular 4 async data storage
I'm creating a testing application that has 1000s of questions hosted on firebase. To prevent downloading the questions multiple times, I've implemented a questions service where in the constructor I download the questions:

```<code>this.db.list("questions/", { preserveSnapshot: true}).subscribe(snapshots => {...}
</code>```

This downloads the questions and pushes them to a questions array so that I don't have to re download until the next session. I also have a function to serve the questions:

```<code>getQuestion(){
    return this.questions[0];
}
</code>```

However, because of the asynchronous nature of firebase, often times the data is not yet downloaded before getQuestion() is called, so it returns  undefined.

Is there a proper way to implement this data store type pattern in angular, and make sure the async call in the constructor finishes before getQuestion() gets called?

I've tried adding a variable ready, initializing it to false, and setting it to true when the async call returns. Then, getQuestions() is modified to look like:

```<code>getQuestion(){
    while(!this.ready()){}
    return this.questions[0];
}
</code>```

However this just causes the app to hang.

答:
It's almost never necessary to use preserveSnapshot. Not having to worry about snapshots is one of the main benefits of using AngularFire. Just write this.db.list(PATH).subscribe(list =>.

You're confusing "downloading" with "subscribing". It is hardly ever a good idea to subscribe inside a service, and store the data locally--you'll never be exactly sure when the subscribe handler has run, as you have found.

Instead, the service should provide an observable, which consumers--usually components-will consume. Those consumers can subscribe to the observable and do whatever they want, include storing the data statically, or, preferably, you can subscribe to the observable directly within a template using the async pipe.

The general rule is to subscribe as late as possible--ideally in the template. Write your code as a set of observables which you map and filter and compose.

Firebase caches results and in general you don't need to worry about caching yourself.

Title: Angular 4 async data storage

Body:
I'm creating a testing application that has 1000s of questions hosted on firebase. To prevent downloading the questions multiple times, I've implemented a questions service where in the constructor I download the questions:

this.db.list("questions/", { preserveSnapshot: true}).subscribe(snapshots => {...}

This downloads the questions and pushes them to a questions array so that I don't have to re download until the next session. I also have a function to serve the questions:

getQuestion(){
    return this.questions[0];
}

However, because of the asynchronous nature of firebase, often times the data is not yet downloaded before getQuestion() is called, so it returns  undefined.

Is there a proper way to implement this data store type pattern in angular, and make sure the async call in the constructor finishes before getQuestion() gets called?

I've tried adding a variable ready, initializing it to false, and setting it to true when the async call returns. Then, getQuestions() is modified to look like:

getQuestion(){
    while(!this.ready()){}
    return this.questions[0];
}

However this just causes the app to hang.


问:
"Unmerging" merged google calendar data with jq
I have ical data containing a calendar owner's events (UID contains google.com) and events imported from hebcal.com (UID contains hebcal). I'd like to use jq to to make two separate and complete ical files. ical2json converts the .ics to .json . So far I have managed to isolate the data with

```<code>cat basic.json | jq '.VCALENDAR[].VEVENT[] | select(.UID | contains("google.com"))'
</code>```

How do I recreate the original structure including just the google.com or hebal.com data?

Here's sample json of the whole structure with two events, one from google, one from hebcal. So imagine producing the same structure, but with just google events.

```<code>{
  "VCALENDAR": [
    {
      "PRODID": "-//Google Inc//Google Calendar 70.9054//EN",
      "VERSION": "2.0",
      "CALSCALE": "GREGORIAN",
      "METHOD": "PUBLISH",
      "X-WR-CALNAME": "Events - TS Cinnaminson",
      "X-WR-TIMEZONE": "America/New_York",
      "VTIMEZONE": [
        {
          "TZID": "America/New_York",
          "X-LIC-LOCATION": "America/New_York",
          "DAYLIGHT": [
            {
              "TZOFFSETFROM": "-0500",
              "TZOFFSETTO": "-0400",
              "TZNAME": "EDT",
              "DTSTART": "19700308T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=3;BYDAY=2SU"
            }
          ],
          "STANDARD": [
            {
              "TZOFFSETFROM": "-0400",
              "TZOFFSETTO": "-0500",
              "TZNAME": "EST",
              "DTSTART": "19701101T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=11;BYDAY=1SU"
            }
          ]
        }
      ],
      "VEVENT": [
        {
          "DTSTART;VALUE=DATE": "20170930",
          "DTEND;VALUE=DATE": "20171001",
          "DTSTAMP": "20170626T155902Z",
          "UID": "hebcal-20170930-6d1036bc2e3a7c743225174c4feb5d1f",
          "URL": "http://hebcal.com/h/yom-kippur",
          "CLASS": "PUBLIC",
          "CREATED": "20170603T024831Z",
          "DESCRIPTION": "Day of Atonement\\n\\nhttp://hebcal.com/h/yom-kippur",
          "LAST-MODIFIED": "20170626T153742Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Yom Kippur",
          "TRANSP": "OPAQUE",
          "X-MICROSOFT-CDO-BUSYSTATUS": "OOF"
        },
        {
          "DTSTART": "20170731T233000Z",
          "DTEND": "20170801T003000Z",
          "DTSTAMP": "20170626T155902Z",
          "UID": "va6vhj4qba2rll8epdmccnjs@google.com",
          "CREATED": "20170523T010707Z",
          "DESCRIPTION": "",
          "LAST-MODIFIED": "20170523T010707Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Service",
          "TRANSP": "OPAQUE"
        }
      ]
    }
  ]
}
</code>```

Desired output is:

```<code>{
  "VCALENDAR": [
    {
      "PRODID": "-//Google Inc//Google Calendar 70.9054//EN",
      "VERSION": "2.0",
      "CALSCALE": "GREGORIAN",
      "METHOD": "PUBLISH",
      "X-WR-CALNAME": "Events - TS Cinnaminson",
      "X-WR-TIMEZONE": "America/New_York",
      "VTIMEZONE": [
        {
          "TZID": "America/New_York",
          "X-LIC-LOCATION": "America/New_York",
          "DAYLIGHT": [
            {
              "TZOFFSETFROM": "-0500",
              "TZOFFSETTO": "-0400",
              "TZNAME": "EDT",
              "DTSTART": "19700308T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=3;BYDAY=2SU"
            }
          ],
          "STANDARD": [
            {
              "TZOFFSETFROM": "-0400",
              "TZOFFSETTO": "-0500",
              "TZNAME": "EST",
              "DTSTART": "19701101T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=11;BYDAY=1SU"
            }
          ]
        }
      ],
      "VEVENT": [
        {
          "DTSTART": "20170731T233000Z",
          "DTEND": "20170801T003000Z",
          "DTSTAMP": "20170626T155902Z",
          "UID": "va6vhj4qba2rll8epdmccnjs@google.com",
          "CREATED": "20170523T010707Z",
          "DESCRIPTION": "",
          "LAST-MODIFIED": "20170523T010707Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Service",
          "TRANSP": "OPAQUE"
        }
      ]
    }
  ]
}
</code>```

答:
Use update-assignment operator |=:

```<code>jq '.VCALENDAR[0].VEVENT |= map(select(.UID | contains("google.com")))' base.json
</code>```

The output:

```<code>{
  "VCALENDAR": [
    {
      "PRODID": "-//Google Inc//Google Calendar 70.9054//EN",
      "VERSION": "2.0",
      "CALSCALE": "GREGORIAN",
      "METHOD": "PUBLISH",
      "X-WR-CALNAME": "Events - TS Cinnaminson",
      "X-WR-TIMEZONE": "America/New_York",
      "VTIMEZONE": [
        {
          "TZID": "America/New_York",
          "X-LIC-LOCATION": "America/New_York",
          "DAYLIGHT": [
            {
              "TZOFFSETFROM": "-0500",
              "TZOFFSETTO": "-0400",
              "TZNAME": "EDT",
              "DTSTART": "19700308T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=3;BYDAY=2SU"
            }
          ],
          "STANDARD": [
            {
              "TZOFFSETFROM": "-0400",
              "TZOFFSETTO": "-0500",
              "TZNAME": "EST",
              "DTSTART": "19701101T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=11;BYDAY=1SU"
            }
          ]
        }
      ],
      "VEVENT": [
        {
          "DTSTART": "20170731T233000Z",
          "DTEND": "20170801T003000Z",
          "DTSTAMP": "20170626T155902Z",
          "UID": "va6vhj4qba2rll8epdmccnjs@google.com",
          "CREATED": "20170523T010707Z",
          "DESCRIPTION": "",
          "LAST-MODIFIED": "20170523T010707Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Service",
          "TRANSP": "OPAQUE"
        }
      ]
    }
  ]
}
</code>```

Body:
I have ical data containing a calendar owner's events (UID contains google.com) and events imported from hebcal.com (UID contains hebcal). I'd like to use jq to to make two separate and complete ical files. ical2json converts the .ics to .json . So far I have managed to isolate the data with

cat basic.json | jq '.VCALENDAR[].VEVENT[] | select(.UID | contains("google.com"))'

How do I recreate the original structure including just the google.com or hebal.com data?

Here's sample json of the whole structure with two events, one from google, one from hebcal. So imagine producing the same structure, but with just google events.

{
  "VCALENDAR": [
    {
      "PRODID": "-//Google Inc//Google Calendar 70.9054//EN",
      "VERSION": "2.0",
      "CALSCALE": "GREGORIAN",
      "METHOD": "PUBLISH",
      "X-WR-CALNAME": "Events - TS Cinnaminson",
      "X-WR-TIMEZONE": "America/New_York",
      "VTIMEZONE": [
        {
          "TZID": "America/New_York",
          "X-LIC-LOCATION": "America/New_York",
          "DAYLIGHT": [
            {
              "TZOFFSETFROM": "-0500",
              "TZOFFSETTO": "-0400",
              "TZNAME": "EDT",
              "DTSTART": "19700308T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=3;BYDAY=2SU"
            }
          ],
          "STANDARD": [
            {
              "TZOFFSETFROM": "-0400",
              "TZOFFSETTO": "-0500",
              "TZNAME": "EST",
              "DTSTART": "19701101T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=11;BYDAY=1SU"
            }
          ]
        }
      ],
      "VEVENT": [
        {
          "DTSTART;VALUE=DATE": "20170930",
          "DTEND;VALUE=DATE": "20171001",
          "DTSTAMP": "20170626T155902Z",
          "UID": "hebcal-20170930-6d1036bc2e3a7c743225174c4feb5d1f",
          "URL": "http://hebcal.com/h/yom-kippur",
          "CLASS": "PUBLIC",
          "CREATED": "20170603T024831Z",
          "DESCRIPTION": "Day of Atonement\\n\\nhttp://hebcal.com/h/yom-kippur",
          "LAST-MODIFIED": "20170626T153742Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Yom Kippur",
          "TRANSP": "OPAQUE",
          "X-MICROSOFT-CDO-BUSYSTATUS": "OOF"
        },
        {
          "DTSTART": "20170731T233000Z",
          "DTEND": "20170801T003000Z",
          "DTSTAMP": "20170626T155902Z",
          "UID": "va6vhj4qba2rll8epdmccnjs@google.com",
          "CREATED": "20170523T010707Z",
          "DESCRIPTION": "",
          "LAST-MODIFIED": "20170523T010707Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Service",
          "TRANSP": "OPAQUE"
        }
      ]
    }
  ]
}

Desired output is:

{
  "VCALENDAR": [
    {
      "PRODID": "-//Google Inc//Google Calendar 70.9054//EN",
      "VERSION": "2.0",
      "CALSCALE": "GREGORIAN",
      "METHOD": "PUBLISH",
      "X-WR-CALNAME": "Events - TS Cinnaminson",
      "X-WR-TIMEZONE": "America/New_York",
      "VTIMEZONE": [
        {
          "TZID": "America/New_York",
          "X-LIC-LOCATION": "America/New_York",
          "DAYLIGHT": [
            {
              "TZOFFSETFROM": "-0500",
              "TZOFFSETTO": "-0400",
              "TZNAME": "EDT",
              "DTSTART": "19700308T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=3;BYDAY=2SU"
            }
          ],
          "STANDARD": [
            {
              "TZOFFSETFROM": "-0400",
              "TZOFFSETTO": "-0500",
              "TZNAME": "EST",
              "DTSTART": "19701101T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=11;BYDAY=1SU"
            }
          ]
        }
      ],
      "VEVENT": [
        {
          "DTSTART": "20170731T233000Z",
          "DTEND": "20170801T003000Z",
          "DTSTAMP": "20170626T155902Z",
          "UID": "va6vhj4qba2rll8epdmccnjs@google.com",
          "CREATED": "20170523T010707Z",
          "DESCRIPTION": "",
          "LAST-MODIFIED": "20170523T010707Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Service",
          "TRANSP": "OPAQUE"
        }
      ]
    }
  ]
}

Body:
Use update-assignment operator |=:

jq '.VCALENDAR[0].VEVENT |= map(select(.UID | contains("google.com")))' base.json

The output:

{
  "VCALENDAR": [
    {
      "PRODID": "-//Google Inc//Google Calendar 70.9054//EN",
      "VERSION": "2.0",
      "CALSCALE": "GREGORIAN",
      "METHOD": "PUBLISH",
      "X-WR-CALNAME": "Events - TS Cinnaminson",
      "X-WR-TIMEZONE": "America/New_York",
      "VTIMEZONE": [
        {
          "TZID": "America/New_York",
          "X-LIC-LOCATION": "America/New_York",
          "DAYLIGHT": [
            {
              "TZOFFSETFROM": "-0500",
              "TZOFFSETTO": "-0400",
              "TZNAME": "EDT",
              "DTSTART": "19700308T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=3;BYDAY=2SU"
            }
          ],
          "STANDARD": [
            {
              "TZOFFSETFROM": "-0400",
              "TZOFFSETTO": "-0500",
              "TZNAME": "EST",
              "DTSTART": "19701101T020000",
              "RRULE": "FREQ=YEARLY;BYMONTH=11;BYDAY=1SU"
            }
          ]
        }
      ],
      "VEVENT": [
        {
          "DTSTART": "20170731T233000Z",
          "DTEND": "20170801T003000Z",
          "DTSTAMP": "20170626T155902Z",
          "UID": "va6vhj4qba2rll8epdmccnjs@google.com",
          "CREATED": "20170523T010707Z",
          "DESCRIPTION": "",
          "LAST-MODIFIED": "20170523T010707Z",
          "LOCATION": "",
          "SEQUENCE": "0",
          "STATUS": "CONFIRMED",
          "SUMMARY": "Service",
          "TRANSP": "OPAQUE"
        }
      ]
    }
  ]
}


问:
Multipe action="" attribute urls
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?

HTML:

```<code><form action="<?php echo htmlspecialchars($_server['php_self']);?>
    , mailto:example@gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> <label for="first">First Name:</label>
    <input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><span class="error"><?php echo $fnameErr;?>
    </span><br/>
    <label for="last">Last Name:</label>
    <input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><span class="error"><?php echo $lnameErr;?>
    </span><br/>
    <label for="mail">Email:</label>
    <input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><span class="error"><?php echo
    $emailErr;?>
    </span><br/>
    <label for="yearLevel">Year Level:</label>
    <select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
        <option>Year 8</option>
        <option>Year 9</option>
        <option>Year 10</option>
        <option>Year 11</option>
        <option>Year 12</option>
        <option>Uni Student</option>
        <option>Other</option>
    </select>
    <label for"comment">Comment:</label>
    <textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
    </textarea><br/><br/>
    <input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>
</code>```

PHP:

```<code><?php
//feedback form validation code
//start

//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";

//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["fname"])) {
        $fnameErr = "* Your first name is required!";
    } else {
        $firstName = test_input($_POST["fname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
            $fnameErr = "* Only letters and white space allowed!";
        }
    }

    if (empty($_POST["lname"])) {
        $lnameErr = "* Your last name is required!";
    } else {
        $lastName = test_input($_POST["lname"]);
        if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
            $lnameErr = "* Only letters and white space allowed!";
        }
    }

    if(empty($_POST["comment"])) {
        $comment = "* the comment box is required!";
    } else {
        $comment = test_input($_post["comment"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "* Your email is required!";
    } else {
        $email = test_input($_POST["email"]);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
           $emailErr = "* Invalid Email Format!";
        }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
//end
?>
</code>```

JS script for a confirm when the user clicks submit. so it makes sense to the form.

```<code><script type="text/javascript">
//confrim before submitting.
function ask() {
    var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
    if (box == true) {
        document.getElementById('firstPart').style.display = "none";
        document.getElementById('nextPart').style.display = "block";
        console.log("Thanks for sending your feedback");
        return true;
    } else {
        console.log("edit!");
        return false;
    }
}

</script>
</code>```

答:
You can't do it, but you can call mailto inside your ask() like,

```<code>function ask() {
    var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
    if (box == true) {
        document.getElementById('firstPart').style.display = "none";
        document.getElementById('nextPart').style.display = "block";
        console.log("Thanks for sending your feedback");
        // add mailto here
        myWindow=window.open("mailto:example@gmail.com");
        myWindow.close();
        return true;
    } else {
        console.log("edit!");
        return false;
    }
}
</code>```

And change form action like,

```<code><form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" ...>
  ....
</form>
</code>```

Title: Multipe action="" attribute urls

Body:
I am wanting to know if you can add more than one url in the action attribute in the form element? I know a lot of people are asking that but the ones I am adding in are: a php self and a mailto action. This is a feedback form so when any one sends some feedback it should check the php of validation of it and send a email at the same time once the submit button is clicked. But I tested that but when I clicked the submit button it came up as an error page. Can any one please help me?

HTML:

<form action="<?php echo htmlspecialchars($_server['php_self']);?>
    , mailto:example@gmail.com" method="post" name="feedbackForm" id="ff" class="feedback"> First Name:
    <input type="text" id="first" name="fname" class="namef" placeholder="First Name" required="required"/><?php echo $fnameErr;?>

    Last Name:
    <input type="text" id="last" name="lname" class="namel" placeholder="Last Name" required="required"/><?php echo $lnameErr;?>

    Email:
    <input type="email" id="mail" name="email" class="u-email" placeholder="any email is fine!" required="required"/><?php echo
    $emailErr;?>

    Year Level:
    <select name="yearLevel" id="yearLevel" onchange="MM_jumpMenu('parent',this,0)">
        <option>Year 8</option>
        <option>Year 9</option>
        <option>Year 10</option>
        <option>Year 11</option>
        <option>Year 12</option>
        <option>Uni Student</option>
        <option>Other</option>
    </select>
    Comment:
    <textarea id="comment" name="comment" class="userComment" rows="12" cols="" "55" ">
    </textarea>

    <input type="submit" name="submitFeed" id="subff" class="sub" onclick="ask()" style="margin-left:20%;"/>
</form>

PHP:

<?php
//feedback form validation code
//start

//variables
$fnameErr = $lnameErr = $yearleErr = $emailErr = "";
$firstName = $lastName = $comment = $yearLevel = $email = "";

//the function of validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["fname"])) {
        $fnameErr = "* Your first name is required!";
    } else {
        $firstName = test_input($_POST["fname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $firstName)) {
            $fnameErr = "* Only letters and white space allowed!";
        }
    }

    if (empty($_POST["lname"])) {
        $lnameErr = "* Your last name is required!";
    } else {
        $lastName = test_input($_POST["lname"]);
        if (!preg_match("/^[a-zA-Z]*$/", $lastName)) {
            $lnameErr = "* Only letters and white space allowed!";
        }
    }

    if(empty($_POST["comment"])) {
        $comment = "* the comment box is required!";
    } else {
        $comment = test_input($_post["comment"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "* Your email is required!";
    } else {
        $email = test_input($_POST["email"]);
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
           $emailErr = "* Invalid Email Format!";
        }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
//end
?>

JS script for a confirm when the user clicks submit. so it makes sense to the form.

Body:
You can't do it, but you can call mailto inside your ask() like,

function ask() {
    var box = confirm("Are you sure you want to send this feeback? If yes
that you are sure click ok or if not then click canel to edit it.");
    if (box == true) {
        document.getElementById('firstPart').style.display = "none";
        document.getElementById('nextPart').style.display = "block";
        console.log("Thanks for sending your feedback");
        // add mailto here
        myWindow=window.open("mailto:example@gmail.com");
        myWindow.close();
        return true;
    } else {
        console.log("edit!");
        return false;
    }
}

And change form action like,

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post" ...>
  ....
</form>


问:
enum vs separate table for storing roles?
I have to implement a role system in my app for authorization. We have around 5 kind of roles in our system.

To maintain these roles we have 2 options,

Alternative #1

1.Create an enum in rails Role model,

enum role: {super_admin: 1, translator: 2, approver: 3, sales_admin: 4, marketing_admin: 5, guest: 6}

2.In the Roles table , now we will have ID user_id role_id

Alternative #2

1.Create 2 models Role and Role_User.

Role table will only contain ID | role_name and Role_User will contain ID | user_id | role_id

Which should be preferred?

答:
It depends how baked into your code the roles are. Some systems have a very rigid concept of "admin" or "moderator" or "user" and introducing roles that don't fit those slots can cause chaos. In those cases they're better off left hard-coded. You might have a table simply to convert the internal name into a label, something especially important when translation's involved. "admin" becomes "Administrator", or whatever that means in the other languages your system employs.

If you've got a system that's a lot more adaptable, where the roles table can define arbitrary permissions, then it makes a lot more sense. You can create custom roles that will work within the structure of the system because the system was deliberately engineered for it. A "role" in this cases is just a set of permissions.


问:
how to display specific data from sub-array using jquery?
hello guys im confused and don't have more idea, how to append specific json string to select tag from sub-array. i have already searched over the internet but some answer and problem didn't match my issue.

```<code>array (size=6)
  0 =>
    array (size=16)
      'id' => int 7
      'receive_purchase_series_id' => null
      'lumber_processing_series_id' => int 174
      'items_series_code' => string 'LP-001-id_1-001-001' (length=19)
      'quantity' => int 50
      'type_id' => int 7
      'supplier_id' => null
      'status' => int 0
      'created_by_id' => int 49
      'scanned_by_id' => int 49
      'receive_purchase_code_from' => null
      'lumber_processing_code_from' => string '191589764523' (length=12)
      'item_id' => int 40
      'created_at' => string '2017-06-30 08:40:17' (length=19)
      'updated_at' => string '2017-06-30 08:40:17' (length=19)
      'nail_items' =>
        array (size=6)
          'id' => int 40
          'type_id' => int 7
          'code' => string 'LI-7' (length=4)
          'description' => string '90X120X200' (length=10)
          'created_at' => string '2017-05-15 11:29:12' (length=19)
          'updated_at' => string '2017-05-15 11:29:12' (length=19)
  1 =>
    array (size=16)
      'id' => int 8
      'receive_purchase_series_id' => null
      'lumber_processing_series_id' => int 175
      'items_series_code' => string 'LP-001-id_1-001-002' (length=19)
      'quantity' => int 50
      'type_id' => int 7
      'supplier_id' => null
      'status' => int 0
      'created_by_id' => int 49
      'scanned_by_id' => int 49
      'receive_purchase_code_from' => null
      'lumber_processing_code_from' => string '191589764523' (length=12)
      'item_id' => int 40
      'created_at' => string '2017-07-03 08:57:47' (length=19)
      'updated_at' => string '2017-07-03 08:57:47' (length=19)
      'nail_items' =>
        array (size=6)
          'id' => int 40
          'type_id' => int 7
          'code' => string 'LI-7' (length=4)
          'description' => string '90X120X200' (length=10)
          'created_at' => string '2017-05-15 11:29:12' (length=19)
          'updated_at' => string '2017-05-15 11:29:12' (length=19)
  2 =>
    array (size=16)
      'id' => int 9
      'receive_purchase_series_id' => null
      'lumber_processing_series_id' => int 176
      'items_series_code' => string 'LP-001-id_1-002-001' (length=19)
      'quantity' => int 60
      'type_id' => int 8
      'supplier_id' => null
      'status' => int 0
      'created_by_id' => int 49
      'scanned_by_id' => int 49
      'receive_purchase_code_from' => null
      'lumber_processing_code_from' => string '430159790249' (length=12)
      'item_id' => int 38
      'created_at' => string '2017-07-03 09:01:23' (length=19)
      'updated_at' => string '2017-07-03 09:01:23' (length=19)
      'nail_items' =>
        array (size=6)
          'id' => int 38
          'type_id' => int 8
          'code' => string 'LI-5' (length=4)
          'description' => string '18X127X1000' (length=11)
          'created_at' => string '2017-05-09 16:41:39' (length=19)
          'updated_at' => string '2017-05-15 10:37:13' (length=19)
  3 =>
    array (size=4)
      'nail_id' => int 27
      'code' => string 'NI-1' (length=4)
      'description' => string 'NAIL ITEM 1' (length=11)
      'type' => null
  4 =>
    array (size=4)
      'nail_id' => int 28
      'code' => string 'NI-2' (length=4)
      'description' => string 'NAIL ITEM 2' (length=11)
      'type' => null
  5 =>
    array (size=4)
      'nail_id' => int 29
      'code' => string 'NI-3' (length=4)
      'description' => string 'NAIL ITEM 3' (length=11)
      'type' => null
</code>```

This is my existing code...

```<code>$.each(active_items, function(key,value){
  rowTemp1 += "<option value='"+ value['nail_id'] +"'>"+ value['code'] +" "+         value['description'] +"</option>";
      $.each(value['nail_items']  , function(key2,item){
         rowTemp1 += "<option >"+ item['code'] +"</option>";
     });
});
</code>```

答:
check if the key exist in first array if not then search in sub-array.Try below code :

```<code>var rowTemp1 ="";
$.each(active_items, function(key,value){
      if('nail_id' in value){
         rowTemp1 += "<option value='"+ value['nail_id'] +"'>"+value['code'] +" "+value['description'] +"</option>";
      }else{

           rowTemp1 += "<option >"+ value['nail_items']['code']  +"</option>";

     }
});
</code>```

Working demo

Body:
hello guys im confused and don't have more idea, how to append specific json string to select tag from sub-array. i have already searched over the internet but some answer and problem didn't match my issue.

array (size=6)
  0 =>
    array (size=16)
      'id' => int 7
      'receive_purchase_series_id' => null
      'lumber_processing_series_id' => int 174
      'items_series_code' => string 'LP-001-id_1-001-001' (length=19)
      'quantity' => int 50
      'type_id' => int 7
      'supplier_id' => null
      'status' => int 0
      'created_by_id' => int 49
      'scanned_by_id' => int 49
      'receive_purchase_code_from' => null
      'lumber_processing_code_from' => string '191589764523' (length=12)
      'item_id' => int 40
      'created_at' => string '2017-06-30 08:40:17' (length=19)
      'updated_at' => string '2017-06-30 08:40:17' (length=19)
      'nail_items' =>
        array (size=6)
          'id' => int 40
          'type_id' => int 7
          'code' => string 'LI-7' (length=4)
          'description' => string '90X120X200' (length=10)
          'created_at' => string '2017-05-15 11:29:12' (length=19)
          'updated_at' => string '2017-05-15 11:29:12' (length=19)
  1 =>
    array (size=16)
      'id' => int 8
      'receive_purchase_series_id' => null
      'lumber_processing_series_id' => int 175
      'items_series_code' => string 'LP-001-id_1-001-002' (length=19)
      'quantity' => int 50
      'type_id' => int 7
      'supplier_id' => null
      'status' => int 0
      'created_by_id' => int 49
      'scanned_by_id' => int 49
      'receive_purchase_code_from' => null
      'lumber_processing_code_from' => string '191589764523' (length=12)
      'item_id' => int 40
      'created_at' => string '2017-07-03 08:57:47' (length=19)
      'updated_at' => string '2017-07-03 08:57:47' (length=19)
      'nail_items' =>
        array (size=6)
          'id' => int 40
          'type_id' => int 7
          'code' => string 'LI-7' (length=4)
          'description' => string '90X120X200' (length=10)
          'created_at' => string '2017-05-15 11:29:12' (length=19)
          'updated_at' => string '2017-05-15 11:29:12' (length=19)
  2 =>
    array (size=16)
      'id' => int 9
      'receive_purchase_series_id' => null
      'lumber_processing_series_id' => int 176
      'items_series_code' => string 'LP-001-id_1-002-001' (length=19)
      'quantity' => int 60
      'type_id' => int 8
      'supplier_id' => null
      'status' => int 0
      'created_by_id' => int 49
      'scanned_by_id' => int 49
      'receive_purchase_code_from' => null
      'lumber_processing_code_from' => string '430159790249' (length=12)
      'item_id' => int 38
      'created_at' => string '2017-07-03 09:01:23' (length=19)
      'updated_at' => string '2017-07-03 09:01:23' (length=19)
      'nail_items' =>
        array (size=6)
          'id' => int 38
          'type_id' => int 8
          'code' => string 'LI-5' (length=4)
          'description' => string '18X127X1000' (length=11)
          'created_at' => string '2017-05-09 16:41:39' (length=19)
          'updated_at' => string '2017-05-15 10:37:13' (length=19)
  3 =>
    array (size=4)
      'nail_id' => int 27
      'code' => string 'NI-1' (length=4)
      'description' => string 'NAIL ITEM 1' (length=11)
      'type' => null
  4 =>
    array (size=4)
      'nail_id' => int 28
      'code' => string 'NI-2' (length=4)
      'description' => string 'NAIL ITEM 2' (length=11)
      'type' => null
  5 =>
    array (size=4)
      'nail_id' => int 29
      'code' => string 'NI-3' (length=4)
      'description' => string 'NAIL ITEM 3' (length=11)
      'type' => null

This is my existing code...

$.each(active_items, function(key,value){
  rowTemp1 += "<option value='"+ value['nail_id'] +"'>"+ value['code'] +" "+         value['description'] +"</option>";
      $.each(value['nail_items']  , function(key2,item){
         rowTemp1 += "<option >"+ item['code'] +"</option>";
     });
});

Body:
check if the key exist in first array if not then search in sub-array.Try below code :

var rowTemp1 ="";
$.each(active_items, function(key,value){
      if('nail_id' in value){
         rowTemp1 += "<option value='"+ value['nail_id'] +"'>"+value['code'] +" "+value['description'] +"</option>";
      }else{

           rowTemp1 += "<option >"+ value['nail_items']['code']  +"</option>";

     }
});

Working demo


问:
extracting indexes regex, with python
I am trying to get certain strings and their indexes.But I always get only the index of the first one. Could anyone maybe tell me what am I doing wrong?
Thnks

here is what I have written:

```<code>import re

f = open("topology_seq.txt")

strToSearch = ""
for line in f:
    strToSearch += line

patFinder = re.compile("I(L|p)")

findpattern = re.search(patFinder, strToSearch)

findpattern1 = re.findall(patFinder, strToSearch)

for i in findpattern1:
    print(i),
    print (findpattern.end())
</code>```

Output:
L
143
p
143
L
143

答:
You can use the finditer method.

```<code>itr = re.finditer(patFinder, strToSearch)
indexes = [match.start(0) for match in itr]
</code>```

re.finditer(pattern, string, flags=0)

Return an iterator yielding MatchObject instances over all non-overlapping >matches for the RE pattern in string

Title: extracting indexes regex, with python

Body:
I am trying to get certain strings and their indexes.But I always get only the index of the first one. Could anyone maybe tell me what am I doing wrong?
Thnks

here is what I have written:

import re

f = open("topology_seq.txt")

strToSearch = ""
for line in f:
    strToSearch += line

patFinder = re.compile("I(L|p)")

findpattern = re.search(patFinder, strToSearch)

findpattern1 = re.findall(patFinder, strToSearch)

for i in findpattern1:
    print(i),
    print (findpattern.end())

Output:
L
143
p
143
L
143

Body:
You can use the finditer method.

itr = re.finditer(patFinder, strToSearch)
indexes = [match.start(0) for match in itr]

re.finditer(pattern, string, flags=0)

Return an iterator yielding MatchObject instances over all non-overlapping >matches for the RE pattern in string


问:
Function is not working when called with AJAX
I have:

call.php:

```<code>function ajaxnotify(){
   notify('hello');
}
function notify($a){
echo "
    <script src=\"/js/jquery.min.js\"></script>
    <script src=\"//cdn.socket.io/socket.io-1.4.5.js\"></script>
    <script>
    $(function(){
        socket = io.connect(\"MY IP AND PORT\",{secure: true});
        socket.emit('say', {'msg': '$a'})
    });
    </script>
    ";
}
switch($_GET["do"]){
case "1":
     ajaxnotify();
     break;
case "2":
     notify();
     break;
}
</code>```

and this code absolutely works when I directly go to mysite/call.php. But when I use:

```<code>$.ajax({
            type: "POST",
            url: "call.php?do=1",
            data: "",
            success: function(html){

            }
        });
</code>```

It just doesn't work. it works when I'm directly going to page, but it doesn't work when I call ajax function from html.

Where is my mistake, guys?

答:
You're sending the request using POST, yet using $_GET to retrieve the variable in PHP.

Change the type: "POST" in jQuery, to type: 'GET'. Here's a complete example:

```<code>$.ajax({
  type: 'GET',
  url: 'call.php',
  data: { do = 1 },
  success: function(html) {
    console.log(html); // to at least verify the response
  }
});
</code>```

Body:
I have:

call.php:

function ajaxnotify(){
   notify('hello');
}
function notify($a){
echo "

    ";
}
switch($_GET["do"]){
case "1":
     ajaxnotify();
     break;
case "2":
     notify();
     break;
}

and this code absolutely works when I directly go to mysite/call.php. But when I use:

$.ajax({
            type: "POST",
            url: "call.php?do=1",
            data: "",
            success: function(html){

            }
        });

It just doesn't work. it works when I'm directly going to page, but it doesn't work when I call ajax function from html.

Where is my mistake, guys?

Body:
You're sending the request using POST, yet using $_GET to retrieve the variable in PHP.

Change the type: "POST" in jQuery, to type: 'GET'. Here's a complete example:

$.ajax({
  type: 'GET',
  url: 'call.php',
  data: { do = 1 },
  success: function(html) {
    console.log(html); // to at least verify the response
  }
});


问:
Eclipse running out of memory when starting Minecraft client
I have been following a mod tutorial and have finally gotten to the point where we are supposed to launch a Minecraft instance inside of Eclipse to test the mod. Whenever I try to do that I keep getting this error:
java.lang.OutOfMemoryError: Java heap space
(Full Error log: https://pastebin.com/t7AbTguS). I have tried giving Eclipse more memory but that doesn't seem to work. I have tried everything I have seen online but nothing works. I am on OSX with 8GB of RAM. Here's my eclipse.ini: https://pastebin.com/Ybi2jsx8.

答:
The memory settings in the eclipse.ini control how much memory Eclipse itself uses. They do not control the memory used when you launch another program (such as minecraft) from within Eclipse.

To change the settings for a launched program open the 'Run > Run Configurations' dialog.

Find the entry for your program in the tree on the left.

Put your settings in the 'VM arguments' section on the 'Arguments' tab.


问:
Echo php with echoed html php
I currently have a php which echo my html template.

However in that HTML template there is another echo which calls from another php script.

Just wondering how do I do that? Because once I echo my html template the other it doesn't seems to echo my content from the other php script.

HTML TEMPLATE

```<code><php? $html = '<span>name:<?php echo $name; ?></span><span>email:<?php echo $email; ?></span>' ?>
</code>```

CONTACT TEMPLATE

```<code><php? $name = "hello world"; $email = "hello@world.com"; ?>
</code>```

答:
I can see what you're trying to do, and it's a simple error. You can't escape php like that whilst inside setting a variable.

Also, I must add that you are declaring php incorrectly.

This is preferred

```<code><?php
</code>```

not

```<code><php?
</code>```

So make sure for your contact template you use the correct tag.

Also to include a file you have to call it/require it.

Back to the original question - Here is your method

```<code><php? $html = '<span>name:<?php echo $name; ?></span><span>email:<?php echo $email; ?></span>' ?>
</code>```

Here is the correct method

```<code><?php
 require('contact.php');
 $html = '<span>name:'.$name.'</span><span>email:'.$email.'</span>';
 echo $html;
?>
</code>```

First I created the variable. And when doing so I insert the existing variables by escaping the php. Only once this final variable is created do I echo it.

Hope this helps you on your way.

Title: Echo php with echoed html php

Body:
I currently have a php which echo my html template.

However in that HTML template there is another echo which calls from another php script.

Just wondering how do I do that? Because once I echo my html template the other it doesn't seems to echo my content from the other php script.

HTML TEMPLATE

<php? $html = 'name:<?php echo $name; ?>email:<?php echo $email; ?>' ?>

CONTACT TEMPLATE

<php? $name = "hello world"; $email = "hello@world.com"; ?>

Body:
I can see what you're trying to do, and it's a simple error. You can't escape php like that whilst inside setting a variable.

Also, I must add that you are declaring php incorrectly.

This is preferred

<?php

not

<php?

So make sure for your contact template you use the correct tag.

Also to include a file you have to call it/require it.

Back to the original question - Here is your method

<php? $html = '<span>name:<?php echo $name; ?></span><span>email:<?php echo $email; ?></span>' ?>

Here is the correct method

<?php
 require('contact.php');
 $html = '<span>name:'.$name.'</span><span>email:'.$email.'</span>';
 echo $html;
?>

First I created the variable. And when doing so I insert the existing variables by escaping the php. Only once this final variable is created do I echo it.

Hope this helps you on your way.

ContentLicense: CC BY-SA 4.0


问:
PHP/MySQL Show first X results, hide the rest
Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? I just need to know how to show only the first X results in one page, then the rest in a seperate page using href.

My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.Thanks

答:
You need pagination look at the some tutorial to do this. there are lot of code examples on this do googling

here are some links

http://www.codediesel.com/php/simple-pagination-in-php/ -

http://php.about.com/od/phpwithmysql/ss/php_pagination.htm