问:
How to write CouchDB view to get currently active servers given start timestamp and end timestamp of each server?
I have set of documents which has the server name, with the start timestamp and end timestamp of that server. eg.

```<code>[
    {
        serverName: "Houston",
        startTimestamp: "2018/03/07 17:52:13 +000",
        endTimestamp: "2018/03/07 18:50:10 +000"
    },
    {
        serverName: "Canberra",
        startTimestamp: "2018/03/07 18:48:09 +000",
        endTimestamp: "2018/03/07 20:10:00 +000"
    },
    {
        serverName: "Melbourne",
        startTimestamp: "2018/03/08 01:43:13 +000",
        endTimestamp: "2018/03/08 12:09:10 +000"
    }
]
</code>```

With this data, given a Timestamp I need to get the list of active servers at that point of time.

For example. for TS="2018/03/07 18:50:00 +000" from the above data the list of active servers are ["Huston", "Canberra"]

Is it possible to achieve this using only CouchDB views. If so how to go about it?

Note: Initially I tried the following approach. In the map function I emit  two documents

1 with key=doc.startTimestsamp and value={"station_add": doc.station}

1 with key=doc.startEndtsamp and value={"station_rem": doc.station}

My intention was to iterate through these in the reduce function adding stations present in "station_add" and removing stations in "stations_rem". But I found that CouchDB does not mention anything about the ordering of values in the reduce function.

答:
If you can live with fixed periods and don't mind the extra disk space that might be needed for the view results, you can create a view of active servers per hour, for example.

Iterate over the periods between start and end and emit the time that each server was online during this period:

```<code>function(doc) {
  var start = new Date(doc.startTimestamp).getTime()
  var end = new Date(doc.endTimestamp).getTime()
  var msPerPeriod = 60*60*1000
  var msOfflineInFirstPeriod = start % msPerPeriod
  var firstPeriod = start - msOfflineInFirstPeriod

  var msOnlineInLastPeriod = end % msPerPeriod
  var lastPeriod = end - msOnlineInLastPeriod

  if (firstPeriod === lastPeriod) {
    // The server was only online within one period.
    emit([new Date(firstPeriod), doc.serverName], [1, msOnlineInLastPeriod - msOfflineInFirstPeriod])
  } else {
    // The server was online over multiple periods.
    emit([new Date(firstPeriod), doc.serverName], [1,msPerPeriod - msOfflineInFirstPeriod])
    for (var period = firstPeriod + msPerPeriod; period < lastPeriod; period += msPerPeriod) {
      emit([new Date(period), doc.serverName], [1, msPerPeriod])
    }
    emit([new Date(lastPeriod), doc.serverName], [1,msOnlineInLastPeriod])
  }
}
</code>```

If you want the total without the server names, just add a reduce function with the built-in shortcut _sum. You'll get the number of servers online during the period as the first number and the milliseconds that the servers were online in that period as the second number.

You can play with the view if you emit the year, month and day as the first keys. Then you can use the group_level at query time to get a finer or more coarse overview.

Bear in mind that this view might get large on disk, as each row has to be stored, and also the intermediate results for each group level are stored. So you shouldn't set the period duration too small – emitting a row for each second would take a lot of disk space, for example.

Body:
I have set of documents which has the server name, with the start timestamp and end timestamp of that server. eg.

[
    {
        serverName: "Houston",
        startTimestamp: "2018/03/07 17:52:13 +000",
        endTimestamp: "2018/03/07 18:50:10 +000"
    },
    {
        serverName: "Canberra",
        startTimestamp: "2018/03/07 18:48:09 +000",
        endTimestamp: "2018/03/07 20:10:00 +000"
    },
    {
        serverName: "Melbourne",
        startTimestamp: "2018/03/08 01:43:13 +000",
        endTimestamp: "2018/03/08 12:09:10 +000"
    }
]

With this data, given a Timestamp I need to get the list of active servers at that point of time.

For example. for TS="2018/03/07 18:50:00 +000" from the above data the list of active servers are ["Huston", "Canberra"]

Is it possible to achieve this using only CouchDB views. If so how to go about it?

Note: Initially I tried the following approach. In the map function I emit  two documents

1 with key=doc.startTimestsamp and value={"station_add": doc.station}

1 with key=doc.startEndtsamp and value={"station_rem": doc.station}

My intention was to iterate through these in the reduce function adding stations present in "station_add" and removing stations in "stations_rem". But I found that CouchDB does not mention anything about the ordering of values in the reduce function.

Body:
If you can live with fixed periods and don't mind the extra disk space that might be needed for the view results, you can create a view of active servers per hour, for example.

Iterate over the periods between start and end and emit the time that each server was online during this period:

function(doc) {
  var start = new Date(doc.startTimestamp).getTime()
  var end = new Date(doc.endTimestamp).getTime()
  var msPerPeriod = 60*60*1000
  var msOfflineInFirstPeriod = start % msPerPeriod
  var firstPeriod = start - msOfflineInFirstPeriod

  var msOnlineInLastPeriod = end % msPerPeriod
  var lastPeriod = end - msOnlineInLastPeriod

  if (firstPeriod === lastPeriod) {
    // The server was only online within one period.
    emit([new Date(firstPeriod), doc.serverName], [1, msOnlineInLastPeriod - msOfflineInFirstPeriod])
  } else {
    // The server was online over multiple periods.
    emit([new Date(firstPeriod), doc.serverName], [1,msPerPeriod - msOfflineInFirstPeriod])
    for (var period = firstPeriod + msPerPeriod; period < lastPeriod; period += msPerPeriod) {
      emit([new Date(period), doc.serverName], [1, msPerPeriod])
    }
    emit([new Date(lastPeriod), doc.serverName], [1,msOnlineInLastPeriod])
  }
}

If you want the total without the server names, just add a reduce function with the built-in shortcut _sum. You'll get the number of servers online during the period as the first number and the milliseconds that the servers were online in that period as the second number.

You can play with the view if you emit the year, month and day as the first keys. Then you can use the group_level at query time to get a finer or more coarse overview.

Bear in mind that this view might get large on disk, as each row has to be stored, and also the intermediate results for each group level are stored. So you shouldn't set the period duration too small – emitting a row for each second would take a lot of disk space, for example.


来源: stackexchange

问:
iTunes Search API - HTTPS artworkUrl?
When I run a query against the iTunes Search API over SSL, most of the URL's returned are provided via HTTPS:

https://itunes.apple.com/search?term=rihanna

However, the artworkUrl results are served over HTTP and updating them manually throws an error since the SSL certificate doesn't match on the domain they're using.

Is there a way to grab these images over HTTPS instead of HTTP?

答:
New to SO and Swift - stumbled over this problem until finding this Q, and the answers above.  The following worked for me:

```<code>func withHTTPS() -> URL? {
  var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
  components?.scheme = "https"
  let host = (components?.host)!
  components?.host = host.replacingOccurrences(of: ".", with: "-ssl.", options: .caseInsensitive, range: host.range(of: "."))
  return components?.url
}
</code>```

called using:

```<code>guard let url = item.artworkURL.withHTTPS() else { return }
</code>```

ContentLicense: CC BY-SA 3.0

Title: iTunes Search API - HTTPS artworkUrl?

Body:
New to SO and Swift - stumbled over this problem until finding this Q, and the answers above.  The following worked for me:

func withHTTPS() -> URL? {
  var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
  components?.scheme = "https"
  let host = (components?.host)!
  components?.host = host.replacingOccurrences(of: ".", with: "-ssl.", options: .caseInsensitive, range: host.range(of: "."))
  return components?.url
}

called using:

guard let url = item.artworkURL.withHTTPS() else { return }


问:
Replace random value in string with random value
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

```<code>def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)
</code>```

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

答:
You can do sth. like the following:</p>

```<code>def mutate(virus):
    # choose random index to change
    index = random.randint(0, len(virus) - 1)

    # make sure you are not using the previous char by removing it from
    # the mutations to choose from
    mutations = [c for c in 'ATCG' if c != virus[index]]

    # swap out the char at index with a random mutation
    return virus[:index] + random.choice(mutations) + virus[index+1:]
</code>```

Body:
virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

Body:
You can do sth. like the following:

def mutate(virus):
    # choose random index to change
    index = random.randint(0, len(virus) - 1)

    # make sure you are not using the previous char by removing it from
    # the mutations to choose from
    mutations = [c for c in 'ATCG' if c != virus[index]]

    # swap out the char at index with a random mutation
    return virus[:index] + random.choice(mutations) + virus[index+1:]


问:
Various problems when retrieving frames from IP cameras
I have 2 IP cameras and they are different models and both from the same manufacturer. Lets call them Cam1 and Cam2. I want to retrieve frames from these cameras by their network address but there are some problems.

Cam1:

When using frame = capture.RetrieveBgrFrame(); frame is always null.

When using frame = capture.QueryFrame(); frame is OK.

Cam2(in the same network with my PC):

When using frame = capture.RetrieveBgrFrame(); frame is always null.

When using frame = capture.QueryFrame(); WinForm is frozen and computer(i7 3,3GHz, 6GB RAM) freezes.

Both stream addresses are OK. I tried to open them with VLC and also with OpenCV C++ platform.

What could be a problem here?

Here is the code:

```<code>using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.UI;

namespace IPcamera
{
    public partial class Form1 : Form
    {
        private Capture capture;
        private Image<Bgr, Byte> frame;

        public Form1()
        {
            InitializeComponent();

            try
            {
                capture = new Capture(camera_address);
            }
            catch (NullReferenceException exception)
            {
                MessageBox.Show(exception.Message);
            }

            if (capture != null)
            {
                Application.Idle += ProcessFrame;
            }
        }

        void ProcessFrame(object sender, EventArgs e)
        {
            frame = capture.RetrieveBgrFrame();
            if (frame != null)
            {
                pictureBox1.Image = frame.ToBitmap();
            }
        }
    }
}
</code>```

答:
Could you replace

```<code> Application.Idle += ProcessFrame;
</code>```

with

```<code> capture.ImageGrabbed += ProcessFrame;
</code>```

And then RetrieveBgrFrame() method may retrurn the frame. That is how I normally do it and I have not had any problems. You may need to assign image to pictureBox1.Image using invoke.

```<code> pictureBox1.Invoke((MethodInvoker) (() => pictureBox1.Image = frame.ToBitmap()));
</code>```

Body:
I have 2 IP cameras and they are different models and both from the same manufacturer. Lets call them Cam1 and Cam2. I want to retrieve frames from these cameras by their network address but there are some problems.

Cam1:

When using frame = capture.RetrieveBgrFrame(); frame is always null.

When using frame = capture.QueryFrame(); frame is OK.

Cam2(in the same network with my PC):

When using frame = capture.RetrieveBgrFrame(); frame is always null.

When using frame = capture.QueryFrame(); WinForm is frozen and computer(i7 3,3GHz, 6GB RAM) freezes.

Both stream addresses are OK. I tried to open them with VLC and also with OpenCV C++ platform.

What could be a problem here?

Here is the code:

using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.UI;

namespace IPcamera
{
    public partial class Form1 : Form
    {
        private Capture capture;
        private Image<Bgr, Byte> frame;

        public Form1()
        {
            InitializeComponent();

            try
            {
                capture = new Capture(camera_address);
            }
            catch (NullReferenceException exception)
            {
                MessageBox.Show(exception.Message);
            }

            if (capture != null)
            {
                Application.Idle += ProcessFrame;
            }
        }

        void ProcessFrame(object sender, EventArgs e)
        {
            frame = capture.RetrieveBgrFrame();
            if (frame != null)
            {
                pictureBox1.Image = frame.ToBitmap();
            }
        }
    }
}

Body:
Could you replace

 Application.Idle += ProcessFrame;

with

 capture.ImageGrabbed += ProcessFrame;

And then RetrieveBgrFrame() method may retrurn the frame. That is how I normally do it and I have not had any problems. You may need to assign image to pictureBox1.Image using invoke.

 pictureBox1.Invoke((MethodInvoker) (() => pictureBox1.Image = frame.ToBitmap()));


问:
Angular - Route only on condition (Based on localStorage)
I have an Angular application using basic Routing module. The below shows my defined routes:

```<code>...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];
...
</code>```

Now I want to protect my dashboard route. I want to route only when I have a localStorage object named token. How can I do it?

```<code>var local = JSON.parse(localStorage.getItem('token'));
</code>```

Something like:

```<code>...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', checkLogin, component: DashboardComponent }
];
...
function checkLogin(){
    // do the logic
}
</code>```

答:
You should use Angular Route Guards. Like this:

import { CanActivate } from '@angular/router';

class DashBoardGuard implements CanActivate {
  canActivate() {
    if (// your condition)  {
      return true; // all fine
    } else {//maybe redirect somwhere}
  }

}

// in your routes
...
{path: 'dashboard', canActivate: {[DashBoardGuard]}```

Read more about guards here

Body:
I have an Angular application using basic Routing module. The below shows my defined routes:

...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];
...

Now I want to protect my dashboard route. I want to route only when I have a localStorage object named token. How can I do it?

var local = JSON.parse(localStorage.getItem('token'));

Something like:

...
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', checkLogin, component: DashboardComponent }
];
...
function checkLogin(){
    // do the logic
}

Body:
You should use Angular Route Guards. Like this:

import { CanActivate } from '@angular/router';

class DashBoardGuard implements CanActivate {
  canActivate() {
    if (// your condition)  {
      return true; // all fine
    } else {//maybe redirect somwhere}
  }

}

// in your routes
...
{path: 'dashboard', canActivate: {[DashBoardGuard]}

Read more about guards here


问:
Filter Grid: getElementsByTagName is not a function
I am trying to make a function to filter a grid.
For this I am using a input type text with a onkeyup event Filter()

```<code>  <label>Filter:</label><input type="text" id="filterTextBox" onkeyup="Filter()" style="margin-left: 5px;  border: 1px solid #cccccc; border-radius: 4px;"/>
</code>```

The JS:

```<code>function Filter() {
    // Declare variables
    var input, filter, table, tr, column, td, i;
    input = document.getElementById("filterTextBox");
    filter = input.value.toUpperCase();
    table = document.getElementsByClassName("table");
    tr = table.getElementsByTagName("tr");
    // column = Document.getElementsByClassName("td-tc");

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByClassName("td-tc")[0];
        if (td) {
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}
</code>```

I've been trying to debug but honestly, I have no idea why I get the error:

```<code>Uncaught TypeError: table.getElementsByTagName is not a function
</code>```

What do I miss here?

I've tried to google on the error, but I have no idea what could be wrong.

答:
You tried to find TR on element collection, not single element.

First define correctly the table variable.

```<code>table = document.getElementsByClassName("table")[0];
</code>```

Than tr definition should be okay.

```<code>tr = table.getElementsByTagName("tr");
</code>```

Body:
I am trying to make a function to filter a grid.
For this I am using a input type text with a onkeyup event Filter()

  Filter:<input type="text" id="filterTextBox" onkeyup="Filter()" style="margin-left: 5px;  border: 1px solid #cccccc; border-radius: 4px;"/>

The JS:

function Filter() {
    // Declare variables
    var input, filter, table, tr, column, td, i;
    input = document.getElementById("filterTextBox");
    filter = input.value.toUpperCase();
    table = document.getElementsByClassName("table");
    tr = table.getElementsByTagName("tr");
    // column = Document.getElementsByClassName("td-tc");

    for (i = 0; i
 -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}

I've been trying to debug but honestly, I have no idea why I get the error:

Uncaught TypeError: table.getElementsByTagName is not a function

What do I miss here?

I've tried to google on the error, but I have no idea what could be wrong.

Body:
You tried to find TR on element collection, not single element.

First define correctly the table variable.

table = document.getElementsByClassName("table")[0];

Than tr definition should be okay.

tr = table.getElementsByTagName("tr");


问:
this.setState is not clear out array on first attempt of onClick event and have to do it twice to clear out array
Working on a document upload section of a component. User can drop their file to upload and below the drop area is a submit, cancel button, and the list of files they are going to submit. The cancel button should clear the files array.

However, the first time you click, it still prints out the file name due to the file still being there. Click it again and it erases the file. Not sure why this happens.

The function in question is the handleClick(event).

Interestingly, it does clear the list of files being rendered on the page, but the array still shows as populated view the console.log in the handleClick(event).

```<code>import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { submitDocument } from '../../actions/documents';
import Dropzone from 'react-dropzone';

class SubmitDocuments extends Component {

    constructor() {
        super();
        this.state = {
            files: []
        }

        this.handleClick = this.handleClick.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.onDrop = this.onDrop.bind(this);
    }

    handleClick(event) {
        this.setState({
            files: []
        })
        console.log(this.state.files);

    }

    handleSubmit(event) {
        event.preventDefault();
        // console.log(this.state.files);
        // filesToBeSent.pus
    }

    onDrop(files) {
        // console.log(files);
        // files.push(this.state.files);
        this.setState({
            files
        });
    }

    render() {

        return (
            <form onSubmit={this.handleSubmit}>
                <div className='panel panel-default'>
                    <div className='panel-heading'>
                        <h4><strong>Submit Documents</strong></h4>
                    </div>

                    <div className='panel-body'>
                        <Dropzone className='dropzone' onDrop={this.onDrop}>
                            <h3>Click to add files or drag files here to upload</h3>
                        </Dropzone>
                        <div>
                            {_.map(this.state.files, f =>
                                <h5 key={f.name}>{f.name} - {f.size} bytes</h5>
                            )}
                        </div>
                        <button type='submit' className='btn btn-primary'>Submit</button>
                        <button type='button' className='btn btn-danger' onClick={this.handleClick}>Cancel</button>
                    </div>
                </div>
            </form>
        );
    }
}

function mapStateToProps(state) {
    return {
        documents: state.home.documents
    }
}

export default connect(mapStateToProps, { submitDocument })(SubmitDocuments);
</code>```

答:
setState can run asynchronously.

Try changing your handler to:

```<code>handleClick(event) {
    this.setState({
        files: []
    }, () => console.log(this.state.files));
}
</code>```

Your console statement should now print what you expect on the first click.

Body:
Working on a document upload section of a component. User can drop their file to upload and below the drop area is a submit, cancel button, and the list of files they are going to submit. The cancel button should clear the files array.

However, the first time you click, it still prints out the file name due to the file still being there. Click it again and it erases the file. Not sure why this happens.

The function in question is the handleClick(event).

Interestingly, it does clear the list of files being rendered on the page, but the array still shows as populated view the console.log in the handleClick(event).

import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { submitDocument } from '../../actions/documents';
import Dropzone from 'react-dropzone';

class SubmitDocuments extends Component {

    constructor() {
        super();
        this.state = {
            files: []
        }

        this.handleClick = this.handleClick.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.onDrop = this.onDrop.bind(this);
    }

    handleClick(event) {
        this.setState({
            files: []
        })
        console.log(this.state.files);

    }

    handleSubmit(event) {
        event.preventDefault();
        // console.log(this.state.files);
        // filesToBeSent.pus
    }

    onDrop(files) {
        // console.log(files);
        // files.push(this.state.files);
        this.setState({
            files
        });
    }

    render() {

        return (
            <form onSubmit={this.handleSubmit}>

Submit Documents

                        <Dropzone className='dropzone' onDrop={this.onDrop}>

Click to add files or drag files here to upload

                        </Dropzone>

                            {_.map(this.state.files, f =>

{f.name} - {f.size} bytes

                            )}

                        <button type='submit' className='btn btn-primary'>Submit</button>
                        <button type='button' className='btn btn-danger' onClick={this.handleClick}>Cancel</button>

            </form>
        );
    }
}

function mapStateToProps(state) {
    return {
        documents: state.home.documents
    }
}

export default connect(mapStateToProps, { submitDocument })(SubmitDocuments);

Body:
setState can run asynchronously.

Try changing your handler to:

handleClick(event) {
    this.setState({
        files: []
    }, () => console.log(this.state.files));
}

Your console statement should now print what you expect on the first click.


问:
How to distinguish negative number from subtraction?
I want to create a very simple math calculator which could give me results of simple equations, like 5*(5-9).

In the first step I split the equation into meaningful tokens, eg.:

```<code>5
*
(
5
-
9
)
</code>```

Now how can I (algorithmically) tell the difference between a negative number (eg. -5) and subtraction (x - 5)?

Edit: I won't have variables (like x) in my equations but I can have functions (like sin, abs).

答:
I think you could do something like this:

```<code><?php
function splitEq($a) {
    $split = array();

    // count al the minuses:
    $c = substr_count($a, "-");

    // when 0, its save!
    if ($c == 0) {
        // split string in chars:
        for ($i = 0; $i < strlen($a); $i++) $split[] = substr($a, $i, 1);

        return $split;
    } else {
        // check them:
        $offset = 0;
        $good = 0;

        //  loop through the minuses:
        for ($i = 0; $i < $c; $i++) {
            $p = strpos($a, "-", $offset);

            // before there is a number == good
            if ($p > 0) {
                if (is_numeric(substr($a, $p - 1,1))) $good++;
            }
            $offset = $p + 1;
        }

        // everything is good, no negative numbers:
        if ($good == $c) {
            for ($i = 0; $i < strlen($a); $i++) $split[] = substr($a, $i, 1);

            return $split;
        } else {
            // split needs a bit of special attention:
            $split = array();
            $ex = explode("-", $a);

            // loop through all the parts

            // make the array:
            for ($y = 0; $y < strlen($a); $y++) $split[] = substr($a, $y, 1);

            // calculate the offset
            $o = strlen($ex[0]);
            for ($i = 1; $i < count($ex); $i++) {
                // if the previous $i is empty, then add it to the first item.
                if ($ex[$i - 1] == "") {
                    array_splice($split, 0,1);
                    $split[0] = "-" . $split[0];
                }

                // if the previous last char is not numeric
                $last = substr($ex[$i - 1], -1, 1);
                if (!is_numeric($last) AND $last) {
                    array_splice($split, $o, 1);
                    $split[$o] = "-" . $split[$o];
                }
                // update offset
                $o += strlen($ex[$i]);

            }
            return $split;
        }
    }
}

$ex[0] = "abs(5*-9)";
$ex[1] = "5*(1-9)";
$ex[2] = "-1*(5-9)";
$ex[3] = "5*(-1-9)";
$ex[5] = "-3+2(-5-9)";
$ex[6] = "5*3";
$ex[7] = "5*(-1-9)";

foreach($ex as $e) {
    echo "<h2>" . $e . "</h2>";
    echo "```";
    print_r(splitEq($e));
    echo "```";
    echo "<hr>";
}
</code>```

There are some limitations; you can't use double digits like 15 at this moment.

Body:
I want to create a very simple math calculator which could give me results of simple equations, like 5*(5-9).

In the first step I split the equation into meaningful tokens, eg.:

5
*
(
5
-
9
)

Now how can I (algorithmically) tell the difference between a negative number (eg. -5) and subtraction (x - 5)?

Edit: I won't have variables (like x) in my equations but I can have functions (like sin, abs).

Body:
I think you could do something like this:

<?php
function splitEq($a) {
    $split = array();

    // count al the minuses:
    $c = substr_count($a, "-");

    // when 0, its save!
    if ($c == 0) {
        // split string in chars:
        for ($i = 0; $i < strlen($a); $i++) $split[] = substr($a, $i, 1);

        return $split;
    } else {
        // check them:
        $offset = 0;
        $good = 0;

        //  loop through the minuses:
        for ($i = 0; $i < $c; $i++) {
            $p = strpos($a, "-", $offset);

            // before there is a number == good
            if ($p > 0) {
                if (is_numeric(substr($a, $p - 1,1))) $good++;
            }
            $offset = $p + 1;
        }

        // everything is good, no negative numbers:
        if ($good == $c) {
            for ($i = 0; $i < strlen($a); $i++) $split[] = substr($a, $i, 1);

            return $split;
        } else {
            // split needs a bit of special attention:
            $split = array();
            $ex = explode("-", $a);

            // loop through all the parts

            // make the array:
            for ($y = 0; $y < strlen($a); $y++) $split[] = substr($a, $y, 1);

            // calculate the offset
            $o = strlen($ex[0]);
            for ($i = 1; $i < count($ex); $i++) {
                // if the previous $i is empty, then add it to the first item.
                if ($ex[$i - 1] == "") {
                    array_splice($split, 0,1);
                    $split[0] = "-" . $split[0];
                }

                // if the previous last char is not numeric
                $last = substr($ex[$i - 1], -1, 1);
                if (!is_numeric($last) AND $last) {
                    array_splice($split, $o, 1);
                    $split[$o] = "-" . $split[$o];
                }
                // update offset
                $o += strlen($ex[$i]);

            }
            return $split;
        }
    }
}

$ex[0] = "abs(5*-9)";
$ex[1] = "5*(1-9)";
$ex[2] = "-1*(5-9)";
$ex[3] = "5*(-1-9)";
$ex[5] = "-3+2(-5-9)";
$ex[6] = "5*3";
$ex[7] = "5*(-1-9)";

foreach($ex as $e) {
    echo "<h2>" . $e . "</h2>";
    echo "<pre>";
    print_r(splitEq($e));
    echo "</pre>";
    echo "<hr>";
}

There are some limitations; you can't use double digits like 15 at this moment.


问:
Angular4 always require Browsers Cache Clean
I have a web application in production environment. The users are using it every day, when I publish an update and a user comes back to the web application he/she views the old version of the web application. He needs to refresh the browser to load the new version. How can I solve this problem? I cannot tell hundreds of users to refresh the page every time I publish an update (3-4 times a week).
I have used following to build my front end application : Angular4 with angular-cli</p>

答:
As noted in the angular-cli docs, there are 2 ways of enabling cache busting.

--prod or --target=production will set a number of flags, including --output-hashing=all which is what triggers the cache-busting

You can also set --output-hashing itself on the command line with one of its possible values of [none|all|media|bundles]. This is useful for testing/staging builds.


问:
Color RDA vectors by groups in R
I'm plotting a series of RDAs in R, each of which has 10+ environmental vectors. The environmental variables each fall in to one of 5 categories. I'd like the vector colors to reflect these categories. I did it in a somewhat ghetto fashion by producing the raw black and white plot, then tracing it in Powerpoint (super time consuming), but there are ALOT of inherent issues with this but it looks good at least.
Here's that plot, note the vector colors.

I'd like to have my output be an R native plot. The plot I use to make the base plot is currently:

```<code>#download the data#
env<- read.csv("environmenta data.csv")
bio<- read.csv("bio data.csv")

#break out the groups of environmental vectors#
#these are purley for example#
group1<-as.matrix(subset(env,select=c(a,b,c))
group2<-as.matrix(subset(env,select=c(d,e,f,h))
group3<-as.matrix(subset(env,select=c(g))
group4<-as.matrix(subset(env,select=c(j,k,l,o))
group5<-as.matrix(subset(env,select=c(m,n,))

#run the RDA#
rda1<-rda(bio,env)

#Plot it#
plot(rda1,type="n",bty="n",main="",
     xlab="XX% variance explained",
     ylab="XX% variance explained",
     col.main="black",col.lab="black", col.axis="white",
     xaxt="n",yaxt="n")
#points(rda1,display="species",col="gray",pch=20)
#option to display species points
#text(rda2,display="species",col="gray")
#option for species labels

points(rda1,display="cn",col="black",lwd=2)#<<< guessing this is the key statement for my issue, but not sure
text(rda1,display="cn",col="black",cex=0.5)
</code>```

I'm assuming the answer falls in this points--> col="..." command, but I'm not sure how to tell it to subset by groups. Any and all help would be appreciated.

答:
```<code>library(vegan)

#DATA
data(varespec)
data(varechem)
env = varechem
bio = varespec
rm(list = c("varechem", "varespec"))

#Assign colors based on groups for the columns of env
groups = rep(c("red", "blue"), length.out = NCOL(env))

rda1 = rda(X = bio, Y = env)
plot(rda1, type = "n")
points(rda1)
text(rda1, display = "bp", col = groups)
</code>```

Title: Color RDA vectors by groups in R

Body:
I'm plotting a series of RDAs in R, each of which has 10+ environmental vectors. The environmental variables each fall in to one of 5 categories. I'd like the vector colors to reflect these categories. I did it in a somewhat ghetto fashion by producing the raw black and white plot, then tracing it in Powerpoint (super time consuming), but there are ALOT of inherent issues with this but it looks good at least.
Here's that plot, note the vector colors.

I'd like to have my output be an R native plot. The plot I use to make the base plot is currently:

#download the data#
env<- read.csv("environmenta data.csv")
bio<- read.csv("bio data.csv")

#break out the groups of environmental vectors#
#these are purley for example#
group1<-as.matrix(subset(env,select=c(a,b,c))
group2<-as.matrix(subset(env,select=c(d,e,f,h))
group3<-as.matrix(subset(env,select=c(g))
group4<-as.matrix(subset(env,select=c(j,k,l,o))
group5<-as.matrix(subset(env,select=c(m,n,))

#run the RDA#
rda1<-rda(bio,env)

#Plot it#
plot(rda1,type="n",bty="n",main="",
     xlab="XX% variance explained",
     ylab="XX% variance explained",
     col.main="black",col.lab="black", col.axis="white",
     xaxt="n",yaxt="n")
#points(rda1,display="species",col="gray",pch=20)
#option to display species points
#text(rda2,display="species",col="gray")
#option for species labels

points(rda1,display="cn",col="black",lwd=2)#<<< guessing this is the key statement for my issue, but not sure
text(rda1,display="cn",col="black",cex=0.5)

I'm assuming the answer falls in this points--> col="..." command, but I'm not sure how to tell it to subset by groups. Any and all help would be appreciated.


问:
What setting in vim counteracts smartindent's refusal to indent # comments in shell scripts?
I recently started using vim 7 (previously vim 6) and the smartindent setting.  For the most part, it works well, though I'm so used to typing a tab after an open brace that it is almost counter-productive.

However, there is one piece of maniacal behaviour.  When editing a shell script, I try to create a comment at the current indent level, but smartindent will have nothing to do with it.  It insists that the comment must be at level 0 (no indent).  What's worse, it breaks shift-right ('>>' and friends) so that they do not work.  This is outright insubordination, and I'd like to know what's the best way to fix it?

(I'm also not keen on smartindent's ideas about indenting then after if.)

Preferred solutions will save me manual bashing - I'm being lazy.  One option would be 'turn off smartindent when editing shell scripts (leave it on for the rest)'.  Another option would be guidelines on how to find the control script for smartindent and what to edit to change the characteristics I don't like.  The final option (which I don't need advice on how to do - just the hint that it is the best, or only, way to restore sanity) is to leave smartindent unset.

I saw the vaguely related question on "(PHP and) annoying vim unindent rules"; it doesn't provide me with the direct answer, though maybe the cindent and related items mentioned in there are in fact part of the answer.

答:
Yes that is very annoying. smartindent is really only for C like languages.
See how I enable the appropriate indenting based on language at:
http://www.pixelbeat.org/settings/.vimrc

OwnerDisplayName: Jonathan Leffler

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: pixelbeat


问:
Un responsive two columns
I Using bootstrap and have this structure in a report:

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
        <h2>I want Two Equal Columns when printing a Portrait A4 Report </h2>
        <div class="container>
            <div class="row">
                  <div class="col-sm-6">
                        <h2>Left Column</h2>
                        <p>This is a test with a large information that I would like to have two columns even if printed in portrait mode.</p>
                  </div>
                  <div class="col-sm-6">
                        <h2>Right Column</h2>
                        <p>This is a test with a large information that I would like to have two columns even if printed in portrait mode.</p>
                  </div>
            </div>
        </div>
    </body>
</code>```

When I print in Landscape format all is right:

But when I print in Portrait:

How do I make the two columns side by side even in portrait mode?

答:
 body {
    margin: 0;
    padding: 0;
  }
  * {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
  }
  .page {
    width: 21cm;
    min-height: 29.7cm;
    padding: 2cm;
    margin: 1cm auto;
    border-radius: 5px;
    background: white;
  }

  @page {
    size: A4;
    margin: 0;
  }
  @media print {
    .page {
      margin: 0;
      border: initial;
      border-radius: initial;
      width: initial;
      min-height: initial;
      box-shadow: initial;
      background: initial;
      page-break-after: always;
    }
  }
  table {
    background-color: transparent;
    width: 100% !important;
    margin-bottom: 0px;
  }

h2{
  font-size: 23px;
  margin-top: 10px;
    margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Bootstrap -->
  <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
   <!-- Normalize or reset CSS with your favorite library -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">

   <div class="page">
<table>
      <tr>
        <td style="width: 100%"><h2>I want Two Equal Columns when printing a Portrait A4 Report </h2></td>
      </tr>
    </table>

<table>
      <tr>
        <td style="width: 50%"><h2>Left Column</h2></td>
        <td style="width: 50%"><h2>Right Column</h2></td>
      </tr>
    </table>

 <table>
      <tr>
        <td style="width: 50%"><p>This is a test with a large information that I would like to have two columns even if printed in portrait mode.</p></td>
         <td style="width: 50%"><p>This is a test with a large information that I would like to have two columns even if printed in portrait mode.</p></td>
      </tr>
    </table>

</div></code>```

Title: Un responsive two columns

Body:
I Using bootstrap and have this structure in a report:

<!DOCTYPE html>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

I want Two Equal Columns when printing a Portrait A4 Report

Left Column

This is a test with a large information that I would like to have two columns even if printed in portrait mode.

Right Column

This is a test with a large information that I would like to have two columns even if printed in portrait mode.

When I print in Landscape format all is right:

But when I print in Portrait:

How do I make the two columns side by side even in portrait mode?

Body:
 body {
    margin: 0;
    padding: 0;
  }
  * {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
  }
  .page {
    width: 21cm;
    min-height: 29.7cm;
    padding: 2cm;
    margin: 1cm auto;
    border-radius: 5px;
    background: white;
  }

  @page {
    size: A4;
    margin: 0;
  }
  @media print {
    .page {
      margin: 0;
      border: initial;
      border-radius: initial;
      width: initial;
      min-height: initial;
      box-shadow: initial;
      background: initial;
      page-break-after: always;
    }
  }
  table {
    background-color: transparent;
    width: 100% !important;
    margin-bottom: 0px;
  }

h2{
  font-size: 23px;
  margin-top: 10px;
    margin-bottom: 10px;
}

<!-- Bootstrap -->
  <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
   <!-- Normalize or reset CSS with your favorite library -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css">

   <div class="page">
<table>
      <tr>
        <td style="width: 100%"><h2>I want Two Equal Columns when printing a Portrait A4 Report </h2></td>
      </tr>
    </table>

<table>
      <tr>
        <td style="width: 50%"><h2>Left Column</h2></td>
        <td style="width: 50%"><h2>Right Column</h2></td>
      </tr>
    </table>

 <table>
      <tr>
        <td style="width: 50%"><p>This is a test with a large information that I would like to have two columns even if printed in portrait mode.</p></td>
         <td style="width: 50%"><p>This is a test with a large information that I would like to have two columns even if printed in portrait mode.</p></td>
      </tr>
    </table>

</div>


问:
Exporting Google Firebase to Bigquery
I am trying to export my Google Firebase database to Google Bigquery but have not found a solution besides manually exporting everything. I have found multiple ways to export firebase analytics but this is not what I want. Any help or anything that would point me in the right direction would be greatly appreciated. Thanks to all!

Wes

答:
Manual export/import

If you wish to do a one-time export/import, you can do this manually. When viewing the Firebase Database console, click on the three-dot icon for more options. One of those options is "Export JSON", which will download a file to your computer.  You may also be able to use the REST API to perform the same operation if you'd prefer to download the file to a server.

After downloading the database export, you can try following the documentation for loading data into BigQuery from a file.  Depending on your Database structure, you may need to reformat/restructure the data to be compatible with what BigQuery expects.

Streaming export/import

If you need to stream data from your Database into BigQuery, you can use Firebase Cloud Functions. For example, you can write a function triggered by a Database-event which uses the BigQuery NodeJS client to stream that data to your BigQuery table.

Be sure to familiarize yourself with the associated costs & quotas, as well as the docs about streaming data into BigQuery.

Title: Exporting Google Firebase to Bigquery


答:
Try setting the state in handleClick(event) method as below.

```<code>handleClick(event) {
    this.setState({
        ...this.state, files: []
    })
}
</code>```

Title: this.setState is not clear out array on first attempt of onClick event and have to do it twice to clear out array

Body:
Try setting the state in handleClick(event) method as below.

handleClick(event) {
    this.setState({
        ...this.state, files: []
    })
}


问:
how do you generate random numbers from a bimodal Gaussian Probability Density Function in MATLAB?
How do you generate numbers from a bimodal Gaussian PDF in MATLAB?

For a unimodal symmetric Gaussian PDF it is really easy:

```<code>x=randn(1000,1);
</code>```

But now I want to draw 1000 numbers from a Gaussian PDF that has two peaks (or two means).  How do I do this?

答:
I propose you an alternative that uses gmdistribution:</p>

```<code>% Means (X1 -> -0.5 and X2 -> 1.2)
m = [-0.5; 1.2];

% Standard Deviations (X1 -> 2.1 and X2 -> 1.3)
s = cat(3,2.1,1.3);

% Weights (X1 and X2 Equally Weighted 0.5)
w = ones(1,2) / 2;

% Create the Gaussian Mixture Model...
gmd = gmdistribution(m,s,w);

% Draw 1000 random numbers from it...
x = random(gmd,1000);

% Plot a histogram...
histogram(x,100);
</code>```

Body:
How do you generate numbers from a bimodal Gaussian PDF in MATLAB?

For a unimodal symmetric Gaussian PDF it is really easy:

x=randn(1000,1);

But now I want to draw 1000 numbers from a Gaussian PDF that has two peaks (or two means).  How do I do this?

Body:
I propose you an alternative that uses gmdistribution:

% Means (X1 -> -0.5 and X2 -> 1.2)
m = [-0.5; 1.2];

% Standard Deviations (X1 -> 2.1 and X2 -> 1.3)
s = cat(3,2.1,1.3);

% Weights (X1 and X2 Equally Weighted 0.5)
w = ones(1,2) / 2;

% Create the Gaussian Mixture Model...
gmd = gmdistribution(m,s,w);

% Draw 1000 random numbers from it...
x = random(gmd,1000);

% Plot a histogram...
histogram(x,100);


问:
Django Forms Showing No Input Fields
instead of the whole form i am just seeing the submit button not the form fields

Goal: get form fields to load and be able to submit form.

views.py file

```<code>from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views import generic
from friendsbook.models import Status,User
from django.views.generic.edit import CreateView
from .forms import CreatePost

class IndexView(generic.ListView):
    template_name='uposts/home.html'
    context_object_name='status_object'

    def get_queryset(self):
        return Status.objects.all()

class  post_detail(generic.DetailView):
    model=Status
    context_object_name='user_profile'
    template_name='uposts/detail.html'

    def get_queryset(self):
        abc=Status.objects.all()
        return abc;

def create_post(request):
    form=CreatePost()
    return render(request,"uposts/createpost.html",{'form':form})
</code>```

forms.py file

```<code>from django import forms
from friendsbook.models import Status

class CreatePost(forms.Form):

    class meta:
        model=Status
        fields = ("title","username" )
</code>```

createpost.html file inside designated folder

```<code>{% extends "friendsbook/structure.html" %}
{% block content %}
<form action="" method="post">{%csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="Save">
</form>

{% endblock %}
</code>```

i also try by python shell but it's of no use.
look at this it's giving me empty string instead of form fields.

please help me.

答:
You have a couple of errors here.

First, to create fields from a model your form needs to inherit from forms.ModelForm, not forms.Form.

Secondly, the inner class needs to be called Meta, not meta.

Title: Django Forms Showing No Input Fields

Body:
instead of the whole form i am just seeing the submit button not the form fields

Goal: get form fields to load and be able to submit form.

views.py file

from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views import generic
from friendsbook.models import Status,User
from django.views.generic.edit import CreateView
from .forms import CreatePost

class IndexView(generic.ListView):
    template_name='uposts/home.html'
    context_object_name='status_object'

    def get_queryset(self):
        return Status.objects.all()

class  post_detail(generic.DetailView):
    model=Status
    context_object_name='user_profile'
    template_name='uposts/detail.html'

    def get_queryset(self):
        abc=Status.objects.all()
        return abc;

def create_post(request):
    form=CreatePost()
    return render(request,"uposts/createpost.html",{'form':form})

forms.py file

from django import forms
from friendsbook.models import Status

class CreatePost(forms.Form):

    class meta:
        model=Status
        fields = ("title","username" )

createpost.html file inside designated folder

{% extends "friendsbook/structure.html" %}
{% block content %}
<form action="" method="post">{%csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="Save">
</form>

{% endblock %}

i also try by python shell but it's of no use.
look at this it's giving me empty string instead of form fields.

please help me.


问:
file link doesn't work
I can't achieve working linking between my index.html and main.css/img.pgn files.

File tree: HTML file(not working): /home/user/Desktop/vswd/index.html

           CSS file: /home/user/Desktop/vswd/en/css/main.css

           IMG file: /home/user/Desktop/vswd/en/img/img.png

```<code><link rel="stylesheet" type="text/css" href="../en/css/main.css"/>  doesn't work

<img class="img" src="../en/img/img.png"> doesn't work
</code>```

BUT

if I move the file one folder below linking work fine.

File tree: HTML file(not working): /home.user/Desktop/vswd/en/index.html

```<code><link rel="stylesheet" type="text/css" href="../css/main.css"/>  work fine

<img class="img" src="../img/img.png"> work fine
</code>```

I tried everything but didn't find a solution.

答:
Your index.html and en/ are in the vswd directory, so you don't need to go up a directory using ../. Instead, use ./:

```<code><link rel="stylesheet" type="text/css" href="./en/css/main.css"/>
<img class="img" src="./en/img/img.png">
</code>```

Title: file link doesn't work

Body:
I can't achieve working linking between my index.html and main.css/img.pgn files.

File tree: HTML file(not working): /home/user/Desktop/vswd/index.html

           CSS file: /home/user/Desktop/vswd/en/css/main.css

           IMG file: /home/user/Desktop/vswd/en/img/img.png

<link rel="stylesheet" type="text/css" href="../en/css/main.css"/>  doesn't work

 doesn't work

BUT

if I move the file one folder below linking work fine.

File tree: HTML file(not working): /home.user/Desktop/vswd/en/index.html

<link rel="stylesheet" type="text/css" href="../css/main.css"/>  work fine

 work fine

I tried everything but didn't find a solution.

Body:
Your index.html and en/ are in the vswd directory, so you don't need to go up a directory using ../. Instead, use ./:

<link rel="stylesheet" type="text/css" href="./en/css/main.css"/>
<img class="img" src="./en/img/img.png">


问:
How to expand the tree view in protractor tests. Below is the code snippet
Below is the code snippet. The code represents one item and I have multiple of these. All these are distinguished by ng-reflect-index. I want to write a test case by expanding these nodes one by one but could not expand the node by using protractor. I am able to go till ng-reflect-index by using css function (element(by.css('[ng-reflect-index="1"]'))). Now i would like to click on the span class  would be really thankful if anyone can help me in fixing this.

```<code><tree-node ng-reflect-node="[object Object]" ng-reflect-index="0" ng-reflect-templates="[object Object]" class="ng-star-inserted">
    <!--bindings={
  "ng-reflect-mobx-autorun": null
}--><!---->
      <!--bindings={
  "ng-reflect-ng-if": "true"
}--><div class="tree-node-level-1 tree-node ng-star-inserted tree-node-active tree-node-focused tree-node-collapsed">

        <!--bindings={
  "ng-reflect-ng-if": "true"
}--><tree-node-drop-slot ng-reflect-node="[object Object]" ng-reflect-drop-index="0" class="ng-star-inserted">
    <div class="node-drop-slot" ng-reflect-tree-allow-drop="function () { [native code] }">
    </div>
  </tree-node-drop-slot>

        <tree-node-wrapper ng-reflect-node="[object Object]" ng-reflect-index="0" ng-reflect-templates="[object Object]">
      <!--bindings={
  "ng-reflect-ng-if": "true"
}--><div class="node-wrapper ng-star-inserted" style="padding-left: 0px;">
        <tree-node-expander ng-reflect-node="[object Object]">
    <!--bindings={
  "ng-reflect-mobx-autorun": null
}--><!---->
      <!--bindings={
  "ng-reflect-ng-if": "true"
}-->
<span class="toggle-children-wrapper ng-star-inserted toggle-children-wrapper-collapsed">

        <span class="toggle-children"></span>
      </span>
      <!--bindings={
  "ng-reflect-ng-if": "false"
}-->

  </tree-node-expander>
        <div class="node-content-wrapper node-content-wrapper-active node-content-wrapper-focused" ng-reflect-tree-allow-drop="function (element, $event) {
 " draggable="true" ng-reflect-dragged-element="[object Object]" ng-reflect-tree-drag-enabled="true">

          <tree-node-content ng-reflect-node="[object Object]" ng-reflect-index="0" ng-reflect-template="[object Object]">
  <!--bindings={
  "ng-reflect-ng-if": "false"
}-->
  <!--bindings={
  "ng-reflect-ng-template-outlet-context": "[object Object]",
  "ng-reflect-ng-template-outlet": "[object Object]"
}-->
      <span _ngcontent-c5="" class="ui-treenode-parent ng-star-inserted"></span>
      <span _ngcontent-c5="" title="Title" class="ng-star-inserted">Assets</span>
      <span _ngcontent-c5="" class="pull-right ng-star-inserted">(7)</span>

  </tree-node-content>
        </div>
      </div>
      <!--bindings={
  "ng-reflect-ng-template-outlet-context": "[object Object]"
}-->

    </tree-node-wrapper>

        <tree-node-children ng-reflect-node="[object Object]" ng-reflect-templates="[object Object]">
    <!--bindings={
  "ng-reflect-mobx-autorun": null
}--><!---->
      <!--bindings={
  "ng-reflect-animate-speed": "true",
  "ng-reflect-animate-acceleration": "1.2",
  "ng-reflect-is-enabled": "true",
  "ng-reflect-is-open": "false"
}-->

  </tree-node-children>
        <tree-node-drop-slot ng-reflect-node="[object Object]" ng-reflect-drop-index="1">
    <div class="node-drop-slot" ng-reflect-tree-allow-drop="function () { [native code] }">
    </div>
  </tree-node-drop-slot>
      </div>
      <!--bindings={
  "ng-reflect-ng-template-outlet-context": "[object Object]"
}-->

    </tree-node>
</code>```

答:
You can select that element and click it: </p>

```<code>element(by.css('toggle-children-wrapper.ng-star-inserted.toggle-children-wrapper-collapsed')).click()
</code>```

Body:
Below is the code snippet. The code represents one item and I have multiple of these. All these are distinguished by ng-reflect-index. I want to write a test case by expanding these nodes one by one but could not expand the node by using protractor. I am able to go till ng-reflect-index by using css function (element(by.css('[ng-reflect-index="1"]'))). Now i would like to click on the span class  would be really thankful if anyone can help me in fixing this.

<tree-node ng-reflect-node="[object Object]" ng-reflect-index="0" ng-reflect-templates="[object Object]" class="ng-star-inserted">

        <tree-node-drop-slot ng-reflect-node="[object Object]" ng-reflect-drop-index="0" class="ng-star-inserted">

  </tree-node-drop-slot>

        <tree-node-wrapper ng-reflect-node="[object Object]" ng-reflect-index="0" ng-reflect-templates="[object Object]">

        <tree-node-expander ng-reflect-node="[object Object]">

  </tree-node-expander>

          <tree-node-content ng-reflect-node="[object Object]" ng-reflect-index="0" ng-reflect-template="[object Object]">

      Assets
      (7)

  </tree-node-content>

    </tree-node-wrapper>

        <tree-node-children ng-reflect-node="[object Object]" ng-reflect-templates="[object Object]">

  </tree-node-children>
        <tree-node-drop-slot ng-reflect-node="[object Object]" ng-reflect-drop-index="1">

  </tree-node-drop-slot>

    </tree-node>

Body:
You can select that element and click it:

element(by.css('toggle-children-wrapper.ng-star-inserted.toggle-children-wrapper-collapsed')).click()


问:
two-way binding - nested object - angular - Cannot read property of undefined
I want to use [(ngModel)] for a nested object, but is giving me an error

Cannot read property 'mxn' of undefined

these are the data structure of my models:

company.model.ts

```<code>import Currency from './currency.model';

class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency;
date: Date;

constructor() {
    this.name = '';
    this.date = new Date();
    this.maxLimit = 0;
    this.source = [''];
    this.deliveryMethod = [''];
    this.currency.mxn = 0;
    this.currency.php = 0;
    }
}

export default Company;
</code>```

currency.model.ts

```<code>class Currency {
mxn: number;
php: number;

constructor() {
    this.mxn = 0;
    this.php = 0;
}
}

export default Currency;
</code>```

and this is part of company.ts

```<code>public newCompany: Company = new Company();
companiesList: Company[];
editcompanies: Company[] = [];
</code>```

and HTML

in HTML page I'm able to show the mxn value by just using :

```<code><tr class="companies" *ngFor="let company of companiesList">
{{company.currency.mxn}}
</code>```

but when I want to use it with ngModel two-way binding for updating the value and sending it to the database it doesn't work.

[(ngModel)] = "newCompany.currency.mxn"
it produces the mentioned error above.
if I use
[(ngModel)] = "newCompany.currency" it doesn't give me an error but the code it's useless since i can't assign any value to mxn.

I have to say that [(ngModel)] = "newCompany.name" it works fine with this and I can update the name.

the backend works fine as I tried it with Postman. the problem is angular side.

so the question is if my data structure is correct how can I use two-way binding for the nested object?

答:
It looks like you're not instantiating the currency field in your constructor. Try by changing the

```<code>currency: Currency;
</code>```

to

```<code>currency = new Currency();
</code>```

It's probably working with your companiesList because probably (I'm guessing here) your backend instantiate them for you. And when you instantiate the newCompany which I assume you do by yourself it's not working cause of the missing new Currency()

Body:
I want to use [(ngModel)] for a nested object, but is giving me an error

Cannot read property 'mxn' of undefined

these are the data structure of my models:

company.model.ts

import Currency from './currency.model';

class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency;
date: Date;

constructor() {
    this.name = '';
    this.date = new Date();
    this.maxLimit = 0;
    this.source = [''];
    this.deliveryMethod = [''];
    this.currency.mxn = 0;
    this.currency.php = 0;
    }
}

export default Company;

currency.model.ts

class Currency {
mxn: number;
php: number;

constructor() {
    this.mxn = 0;
    this.php = 0;
}
}

export default Currency;

and this is part of company.ts

public newCompany: Company = new Company();
companiesList: Company[];
editcompanies: Company[] = [];

and HTML

in HTML page I'm able to show the mxn value by just using :

{{company.currency.mxn}}

but when I want to use it with ngModel two-way binding for updating the value and sending it to the database it doesn't work.

[(ngModel)] = "newCompany.currency.mxn"
it produces the mentioned error above.
if I use
[(ngModel)] = "newCompany.currency" it doesn't give me an error but the code it's useless since i can't assign any value to mxn.

I have to say that [(ngModel)] = "newCompany.name" it works fine with this and I can update the name.

the backend works fine as I tried it with Postman. the problem is angular side.

so the question is if my data structure is correct how can I use two-way binding for the nested object?

Body:
It looks like you're not instantiating the currency field in your constructor. Try by changing the

currency: Currency;

to

currency = new Currency();

It's probably working with your companiesList because probably (I'm guessing here) your backend instantiate them for you. And when you instantiate the newCompany which I assume you do by yourself it's not working cause of the missing new Currency()


问:
How to echo results with join names from another table using nl2br
I know how to echo results that are in an array using the following

```<code>nl2br(str_replace(',', "\n", $row['column-name']))
</code>```

I now have a column in which the listed items (separated by commas) are id numbers that correspond to another table.

How can I echo these results and apply the name associated to that item relative to its id?

I have tried INNER JOIN but I seem to be missing how to perform this correctly.

```<code>'SELECT * FROM Table1
 INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnID
 INNER JOIN Table3 ON Table1.ColumnID2 = Table3.ColumnID2 <-- This needs to apply names to the number-ids split by the nl2br
 ORDER BY OrderColumn'

<span>'.nl2br(str_replace(',', "\n", $row['table3-column-name-to-replace-table1-columnID2'])).'</span>
</code>```

Thanks for your help.

This is the expected result. https://drive.google.com/file/d/1ChGv9qHeJPgtwVcxbqj8ey-1RjVTah28/view?usp=sharing

答:
To get all Table3 rows that appear in the list of Table1 you need to change your JOIN accordingly:

```<code>SELECT
    Table1.CoverageArea,
    Table2.stateName as State,
    GROUP_CONCAT(Table3.CountName SEPARATOR '\n') as County
FROM
    Table1
    INNER JOIN Table2
        ON Table1.State = Table2.ID
    INNER JOIN Table3
        ON Table1.Counties LIKE Table3.ID+ ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID+ ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID
        OR Table1.Counties = Table3.ID
GROUP BY TABLE1.CoverageArea
ORDER BY TABLE1.CoverageArea ASC;
</code>```

Result would be:

```<code>[
    ['John Doe', 'Missouri', 'Apple County
                              Orange County
                              Grape County
                              Banana County']
]
</code>```

The down side to this is, that the DB needs to perform multiple text comparisons on each row, meaning that this is a very slow way to do the JOIN's.

The better solution would be to edit Table3 to hold not only the own ID, but the ID of Table1 aswell, as a foreign key / parent reference.

```<code>START TRANSACTION;
ALTER TABLE Table3 ADD coverageAreaID INT NOT NULL;
ALTER TABLE Table3 ADD CONSTRAINT fk_covarea_state FOREIGN KEY (coverageAreaID) REFERENCES Table1(ID);
UPDATE Table3 SET coverageAreaID = (
    SELECT
        Table1.ID
    FROM
        Table1
    WHERE
        Table1.Counties LIKE Table3.ID + ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID + ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID
        OR Table1.Counties = Table3.ID
    LIMIT 1;
);
COMMIT;
</code>```

Like this you can use the following SQL query:

```<code>SELECT
    Table1.CoverageArea,
    Table2.stateName as State,
    GROUP_CONCAT(Table3.CountName SEPARATOR '\n') as County
FROM
    Table1
    INNER JOIN Table2
        ON Table1.State = Table2.ID
    INNER JOIN Table3
        ON Table1.ID = Table3.coverageAreaID
GROUP BY TABLE1.CoverageArea
ORDER BY TABLE1.CoverageArea ASC;
</code>```

This query will now export the same result as above, but it will be much faster, because it can join the tables with a simple numeric comparison.

Now you should have no problem using your code:

nl2br($row['County'])

Body:
I know how to echo results that are in an array using the following

nl2br(str_replace(',', "\n", $row['column-name']))

I now have a column in which the listed items (separated by commas) are id numbers that correspond to another table.

How can I echo these results and apply the name associated to that item relative to its id?

I have tried INNER JOIN but I seem to be missing how to perform this correctly.

'SELECT * FROM Table1
 INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnID
 INNER JOIN Table3 ON Table1.ColumnID2 = Table3.ColumnID2 <-- This needs to apply names to the number-ids split by the nl2br
 ORDER BY OrderColumn'

'.nl2br(str_replace(',', "\n", $row['table3-column-name-to-replace-table1-columnID2'])).'

Thanks for your help.

This is the expected result. https://drive.google.com/file/d/1ChGv9qHeJPgtwVcxbqj8ey-1RjVTah28/view?usp=sharing

Body:
To get all Table3 rows that appear in the list of Table1 you need to change your JOIN accordingly:

SELECT
    Table1.CoverageArea,
    Table2.stateName as State,
    GROUP_CONCAT(Table3.CountName SEPARATOR '\n') as County
FROM
    Table1
    INNER JOIN Table2
        ON Table1.State = Table2.ID
    INNER JOIN Table3
        ON Table1.Counties LIKE Table3.ID+ ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID+ ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID
        OR Table1.Counties = Table3.ID
GROUP BY TABLE1.CoverageArea
ORDER BY TABLE1.CoverageArea ASC;

Result would be:

[
    ['John Doe', 'Missouri', 'Apple County
                              Orange County
                              Grape County
                              Banana County']
]

The down side to this is, that the DB needs to perform multiple text comparisons on each row, meaning that this is a very slow way to do the JOIN's.

The better solution would be to edit Table3 to hold not only the own ID, but the ID of Table1 aswell, as a foreign key / parent reference.

START TRANSACTION;
ALTER TABLE Table3 ADD coverageAreaID INT NOT NULL;
ALTER TABLE Table3 ADD CONSTRAINT fk_covarea_state FOREIGN KEY (coverageAreaID) REFERENCES Table1(ID);
UPDATE Table3 SET coverageAreaID = (
    SELECT
        Table1.ID
    FROM
        Table1
    WHERE
        Table1.Counties LIKE Table3.ID + ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID + ',%'
        OR Table1.Counties LIKE '%,' + Table3.ID
        OR Table1.Counties = Table3.ID
    LIMIT 1;
);
COMMIT;

Like this you can use the following SQL query:

SELECT
    Table1.CoverageArea,
    Table2.stateName as State,
    GROUP_CONCAT(Table3.CountName SEPARATOR '\n') as County
FROM
    Table1
    INNER JOIN Table2
        ON Table1.State = Table2.ID
    INNER JOIN Table3
        ON Table1.ID = Table3.coverageAreaID
GROUP BY TABLE1.CoverageArea
ORDER BY TABLE1.CoverageArea ASC;

This query will now export the same result as above, but it will be much faster, because it can join the tables with a simple numeric comparison.

Now you should have no problem using your code:

nl2br($row['County'])


问:
Java - Remove keys matching regex from JsonObject
I'm able to remove the key from JsonObject using:

```<code>String prop = "test";
JsonObject o = parser.parse(props).getAsJsonObject();
o.remove(prop);
</code>```

I need to remove all the keys matching certain pattern from the JsonObject, like anything that starts with "test.*". Instead of iterating over the keys and find a match, is there any other way to remove the keys matching a given pattern?

```<code>input: {"test":"0","test_1": "1","test_10":"10", "site":"abc.com"}
expected output: {"site":"abc.com"}
</code>```

Thanks!

答:
There isn't.

The best you can do is compile the regex before the loop to improve performance:

```<code>Pattern pattern = Pattern.compile(prop);
Iterator<Entry<...>> it = o.entrySet().iterator();
while (it.hasNext()) {
    Entry<...> entry = it.next();
    if (pattern.matcher(entry.getKey()).matches()) {
        i.remove();
    }
}
</code>```

Body:
I'm able to remove the key from JsonObject using:

String prop = "test";
JsonObject o = parser.parse(props).getAsJsonObject();
o.remove(prop);

I need to remove all the keys matching certain pattern from the JsonObject, like anything that starts with "test.*". Instead of iterating over the keys and find a match, is there any other way to remove the keys matching a given pattern?

input: {"test":"0","test_1": "1","test_10":"10", "site":"abc.com"}
expected output: {"site":"abc.com"}

Thanks!

Body:
There isn't.

The best you can do is compile the regex before the loop to improve performance:

Pattern pattern = Pattern.compile(prop);
Iterator<Entry<...>> it = o.entrySet().iterator();
while (it.hasNext()) {
    Entry<...> entry = it.next();
    if (pattern.matcher(entry.getKey()).matches()) {
        i.remove();
    }
}


问:
Why doesn't FB.login delete the logout cookie?
I have a problem with Facebook authentication logic:

On home page load, I call getLoginStatus() and if I get "connected", I redirect the user to his account page. If not, the user can click the login button that calls FB.login().

If the user is logged in and then navigates back to home page (full page load), getLoginStatus() there returns "connected" as expected and user gets bounced back to account page.

However, when the logged in user calls FB.logout() and repeats steps 1-2, the 2nd step will always yield "unknown" login status. So, FB.logout() basically breaks my bouncing logic.

I checked the mechanics of login/logout calls and it appears FB.logout() creates a fblo_<appId> cookie with 1 year expiration that blocks getLoginStatus() from returning the proper status. This seems to be the actual mechanism for keeping people logged out, which I can understand. What I can't understand, though, is: why this cookie is not deleted on a successful FB.login() call?

答:
I was experiencing this a few days ago but I'm not seeing the issue any more.

In either case make sure you consider these different scenarios when testing:

A person logs into Facebook, then logs into your app. Upon logging out from your app, the person is still logged into Facebook.

A person logs into your app and into Facebook as part of your app's login flow. Upon logging out from your app, the user is also logged out of Facebook.

A person logs into another app and into Facebook as part of the other app's login flow, then logs into your app. Upon logging out from either app, the user is logged out of Facebook.

https://developers.facebook.com/docs/reference/javascript/FB.logout/

Debugging tip:

In the Application tab in Chrome you can select Cookies in the left panel and then type fblo into the search box to filter by that name. When I call FB.login and successfully authenticate I see that the fblo cookie disappears - so I believe this issue fixed.


问:
scala: how to make a superclass' variable implicit in the scope of the subclass
Imagine I had some function that takes a String explicitly and an T implicitly:

```<code>object SomeNamespace {
  def myFunction(arg: String)(implicit t: T)
}
</code>```

And I had a superclass which provides the T

```<code>trait TProvider {
  val t: T = ...
}
</code>```

And in a subclass I use extends TProvider and try to use the function

```<code>class Child extends TProvider {
   SomeNamespace.myFunction("somestring")
}
</code>```

I would get an error "could not find implicit value for parameter t". My workaround is to reassign the superclass val to a new implicit one in the subclass like:

```<code> implicit val subclassImplicitT = t
</code>```

and that works ... but is kind of ugly. Is there some better way to "implicitify" a variable?

答:
FWIW, I ended up solving this problem in my own project by simply making another class where the t was implicit -- so like

```<code>trait ImplicitTProvider {
  implicit val t: T = ...
}
</code>```

And then extended from that class instead of the TProvider.

This made sense for this project since I don't see either of these classes changing much. But not a great general solution perhaps.

Body:
Imagine I had some function that takes a String explicitly and an T implicitly:

object SomeNamespace {
  def myFunction(arg: String)(implicit t: T)
}

And I had a superclass which provides the T

trait TProvider {
  val t: T = ...
}

And in a subclass I use extends TProvider and try to use the function

class Child extends TProvider {
   SomeNamespace.myFunction("somestring")
}

I would get an error "could not find implicit value for parameter t". My workaround is to reassign the superclass val to a new implicit one in the subclass like:

 implicit val subclassImplicitT = t

and that works ... but is kind of ugly. Is there some better way to "implicitify" a variable?

Body:
FWIW, I ended up solving this problem in my own project by simply making another class where the t was implicit -- so like

trait ImplicitTProvider {
  implicit val t: T = ...
}

And then extended from that class instead of the TProvider.

This made sense for this project since I don't see either of these classes changing much. But not a great general solution perhaps.


问:
create an array of time jobs based on customer weekly schedule
My customer specified weekly schedules (mondays at 2pm, fridays at 3pm, fridays also at 4pm, etc.). My function foo() needs to be called at these times. They will then say "Call foo() using this schedule" but only for a number of specified months.

So I have their chosen schedule (day is 1-7 for mon-sun):

```<code>const scheduleArray = [{day: '1', hour: '11', minute: '34'},{...}]
</code>```

Which I need to convert into an array of real days in the format I'm thinking:

```<code> const scheduleArrayForFooFunction = [{
    month: '3',
    date: '16',
    hour: '11',
    minute: '34'},{...}]
</code>```

Any recommendations on how to convert this? I'm having difficulties. Or is there a javascript library that will do it for me?

答:
momentjs.com is what you need.

To get first Monday of the current month for instance

```<code>moment().startOf('month').add(1, 'week').add(-1, 'day').day('1')
</code>```

(Last call in the chain day('1') for Monday I used string because of your format but it can be just a number)

Then you can use add(1, 'week') to get other Mondays. And check range of months as you need.

UPDATE

RobG asked if there is simpler way. Obviously it could be simplified

```<code>moment().startOf('month').add(6, 'day').day('1')
</code>```

But I think it's not so clear why we add 6 days.

Body:
My customer specified weekly schedules (mondays at 2pm, fridays at 3pm, fridays also at 4pm, etc.). My function foo() needs to be called at these times. They will then say "Call foo() using this schedule" but only for a number of specified months.

So I have their chosen schedule (day is 1-7 for mon-sun):

const scheduleArray = [{day: '1', hour: '11', minute: '34'},{...}]

Which I need to convert into an array of real days in the format I'm thinking:

 const scheduleArrayForFooFunction = [{
    month: '3',
    date: '16',
    hour: '11',
    minute: '34'},{...}]

Any recommendations on how to convert this? I'm having difficulties. Or is there a javascript library that will do it for me?

Body:
momentjs.com is what you need.

To get first Monday of the current month for instance

moment().startOf('month').add(1, 'week').add(-1, 'day').day('1')

(Last call in the chain day('1') for Monday I used string because of your format but it can be just a number)

Then you can use add(1, 'week') to get other Mondays. And check range of months as you need.

UPDATE

RobG asked if there is simpler way. Obviously it could be simplified

moment().startOf('month').add(6, 'day').day('1')

But I think it's not so clear why we add 6 days.


问:
Create objective-c class instance by name?
Is it possible to create an instance of a class by name? Something like:

```<code>NSString* className = @"Car";
id* p = [Magic createClassByName:className];
[p turnOnEngine];
</code>```

I don't know if this is possible in objective-c but seems like it would be,

答:
If you are working with Objective-C without the NeXTstep (OS X, iOS, GNUstep etc) system  or you just think this method is cleaner, then you could utilize the Objective-C language runtime library's API.  Under Objective-C 2.0:

```<code>#import <objc/runtime.h>
//Declaration in the above named file
id objc_getClass(const char* name);
//Usage
id c = objc_getClass("Object");
[ [ c alloc ] free ];
</code>```

Under the Objective-C (1.0 or unnamed version) you would utilize the following:

```<code>#import <objc/objc-api.h>
//Declaration within the above named file
Class objc_get_class( const char* name);
//Usage
Class cls = objc_get_class( "Test" );
id obj = class_create_instance( cls );
[ obj free ];
</code>```

I haven't tested the 1.0 version, however I have used the 2.0 function in code that is now in production.  I personally believe utilizing the 2.0 function is cleaner if available than the NS function as it consumes less space: the length of the name in bytes + 1 ( null terminator ) for the 2.0 API versus the sum of two pointers (isa, cstring), a size_t length (cstring_length), and the length of the string in bytes + 1 for the NeXTSTEP API.

Body:
Is it possible to create an instance of a class by name? Something like:

NSString* className = @"Car";
id* p = [Magic createClassByName:className];
[p turnOnEngine];

I don't know if this is possible in objective-c but seems like it would be,

Body:
If you are working with Objective-C without the NeXTstep (OS X, iOS, GNUstep etc) system  or you just think this method is cleaner, then you could utilize the Objective-C language runtime library's API.  Under Objective-C 2.0:

#import <objc/runtime.h>
//Declaration in the above named file
id objc_getClass(const char* name);
//Usage
id c = objc_getClass("Object");
[ [ c alloc ] free ];

Under the Objective-C (1.0 or unnamed version) you would utilize the following:

#import <objc/objc-api.h>
//Declaration within the above named file
Class objc_get_class( const char* name);
//Usage
Class cls = objc_get_class( "Test" );
id obj = class_create_instance( cls );
[ obj free ];

I haven't tested the 1.0 version, however I have used the 2.0 function in code that is now in production.  I personally believe utilizing the 2.0 function is cleaner if available than the NS function as it consumes less space: the length of the name in bytes + 1 ( null terminator ) for the 2.0 API versus the sum of two pointers (isa, cstring), a size_t length (cstring_length), and the length of the string in bytes + 1 for the NeXTSTEP API.


问:
programmatically highlight UIBarButtonItem
after tapping the 'record' BarButtonItem I would like to keep it programmatically highlighted until the recording is over. The highlighting graphics of iOS are very good, therefor I would like to remain or set that state.

Up to now I found 'setSelected' and 'setHighlighted' but these do not work on a UIBarButtonItem.
Any suggestions on how to solve this? Thank you in advance, Koen.

答:
p.a.'s answer, converted for Xcode 9, Swift 4.

The idea is that the .done style highlights - or bolds, in Swift 4 - the button text.

Initialize the button item in an un-highlighted state:

```<code>let toggleButtonItem = UIBarButtonItem(title: "MyButton",
                                       style: .plain,
                                       target: self,
                                       action: #selector(doSomething))
</code>```

Toggle the button item to a highlighted state using a ternary operator, like so:

```<code>toggleButtonItem.style = (toggleButtonItem.style == .plain) ?
                         toggleButtonItem.style = .done : toggleButtonItem.style = .plain
</code>```

Or, alternatively, toggle the highlight state with a regular if/else statement like this instead:

```<code>if toggleButtonItem.style == .plain {
    toggleButtonItem.style = .done
}
else {
    toggleButtonItem.style = .plain
}
</code>```

And, to set up a boolean value to check if the button item is highlighted:

```<code>var isHighlighted: Bool = (toggleButtonItem.style == .done)
</code>```

Notes:

The bordered style was deprecated in iOS 8, so I used .plain here instead. They both present the button item's text in an unhighlighted state.

The #selector function must either be an @IBAction, or it must be prefixed with @objc, to avoid "Objective-C inference" issues. For example:

```<code>@objc func doSomething() { ... }
</code>```

or, if you've connected an action to the button item:

```<code>@IBAction func doSomething() { ... }
</code>```

Both of these function declarations tell the compiler that they're using Objective-C-based functionality. This is required because #selector is an Objective-C thing under the hood, and in Swift 4 you have to state this, rather than letting the compiler infer what's going on as it has done previously.

Body:
p.a.'s answer, converted for Xcode 9, Swift 4.

The idea is that the .done style highlights - or bolds, in Swift 4 - the button text.

Initialize the button item in an un-highlighted state:

let toggleButtonItem = UIBarButtonItem(title: "MyButton",
                                       style: .plain,
                                       target: self,
                                       action: #selector(doSomething))

Toggle the button item to a highlighted state using a ternary operator, like so:

toggleButtonItem.style = (toggleButtonItem.style == .plain) ?
                         toggleButtonItem.style = .done : toggleButtonItem.style = .plain

Or, alternatively, toggle the highlight state with a regular if/else statement like this instead:

if toggleButtonItem.style == .plain {
    toggleButtonItem.style = .done
}
else {
    toggleButtonItem.style = .plain
}

And, to set up a boolean value to check if the button item is highlighted:

var isHighlighted: Bool = (toggleButtonItem.style == .done)

Notes:

The bordered style was deprecated in iOS 8, so I used .plain here instead. They both present the button item's text in an unhighlighted state.

The #selector function must either be an @IBAction, or it must be prefixed with @objc, to avoid "Objective-C inference" issues. For example:

@objc func doSomething() { ... }

or, if you've connected an action to the button item:

@IBAction func doSomething() { ... }

Both of these function declarations tell the compiler that they're using Objective-C-based functionality. This is required because #selector is an Objective-C thing under the hood, and in Swift 4 you have to state this, rather than letting the compiler infer what's going on as it has done previously.


问:
How do you group social network nodes?
A graph is made up of nodes/vertexes connected by edges/arcs. Multiple sub groups of nodes often exist (colored below). These can be people in a social network, items and purchase records, travel data, or many other things.

How do you:

Split the nodes into groups based on edges

find the leader (most connected node) in each subgroup?

答:
To answer your first question, you can use one of several community structure algorithms, such as:

Minimum-cut method

Hierarchical clustering

Girvan–Newman algorithm

Modularity maximization

Among others.

As for your second question, once you know the members within a group you can rank them by number of connections.

Title: How do you group social network nodes?


问:
Jms Configuration Ready Api 2.2
i am trying to manually configure JMS in Ready API 2.2 . I want to use Apache ActiveMQ , for that i need valid inputs for : </p>

```<code>Initial Context Class
Provider Url
Connection Factory JNDI name
</code>```

<p>I have checked many sources , but i am not getting exact values for these . Can anyone provide them. And what are basic Jar files required ? </p>

答: Take a look at the ActiveMQ documentation on this subject.  It should answer most if not all your questions.</p>

Title: Jms Configuration Ready Api 2.2

Body:
i am trying to manually configure JMS in Ready API 2.2 . I want to use Apache ActiveMQ , for that i need valid inputs for :

Initial Context Class
Provider Url
Connection Factory JNDI name

I have checked many sources , but i am not getting exact values for these . Can anyone provide them. And what are basic Jar files required ?


问:
What made i = i++ + 1; legal in C++17?
Before you start yelling undefined behaviour, this is explicitly listed in N4659 (C++17)

```<code>  i = i++ + 1;        // the value of i is incremented
</code>```

Yet in N3337 (C++11)

```<code>  i = i++ + 1;        // the behavior is undefined
</code>```

What changed?

From what I can gather, from [N4659 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined.

Where value is defined at [N4659 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values

From [N3337 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Likewise, value is defined at [N3337 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.

They are identical except mention of concurrency which doesn't matter, and with the usage of memory location instead of scalar object, where

Arithmetic types, enumeration types, pointer types, pointer to member types, std::nullptr_t, and cv-qualified versions of these types are collectively called scalar types.

Which doesn't affect the example.

From [N4659 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

From [N3337 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

The only difference being the last sentence being absent in N3337.

The last sentence however, shouldn't have any importance as the left operand i is neither "another side effect" nor "using the value of the same scalar object" as the id-expression is a lvalue.

答:
In C++11 the act of "assignment", i.e. the side-effect of modifying the LHS, is sequenced after the value computation of the right operand. Note that this is a relatively "weak" guarantee: it produces sequencing only with relation to value computation of the RHS. It says nothing about the side-effects that might be present in the RHS, since occurrence of side-effects is not part of value computation. The requirements of C++11 establish no relative sequencing between the act of assignment and any side-effects of the RHS. This is what creates the potential for UB.

The only hope in this case is any additional guarantees made by specific operators used in RHS. If the RHS used a prefix ++, sequencing properties specific to the prefix form of ++ would have saved the day in this example. But postfix ++ is a different story: it does not make such guarantees. In C++11 the side-effects of = and postfix ++ end up unsequenced with relation to each other in this example. And that is UB.

In C++17 an extra sentence is added to the specification of assignment operator:

The right operand is sequenced before the left operand.

In combination with the above it makes for a very strong guarantee. It sequences everything that happens in the RHS (including any side-effects) before everything that happens in the LHS. Since the actual assignment is sequenced after LHS (and RHS), that extra sequencing completely isolates the act of assignment from any side-effects present in RHS. This stronger sequencing is what eliminates the above UB.

(Updated to take into account @John Bollinger's comments.)

Title: What made i = i++ + 1; legal in C++17?

Body:
Before you start yelling undefined behaviour, this is explicitly listed in N4659 (C++17)

  i = i++ + 1;        // the value of i is incremented

Yet in N3337 (C++11)

  i = i++ + 1;        // the behavior is undefined

What changed?

From what I can gather, from [N4659 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined.

Where value is defined at [N4659 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values

From [N3337 basic.exec]

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Likewise, value is defined at [N3337 basic.type]

For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.

They are identical except mention of concurrency which doesn't matter, and with the usage of memory location instead of scalar object, where

Arithmetic types, enumeration types, pointer types, pointer to member types, std::nullptr_t, and cv-qualified versions of these types are collectively called scalar types.

Which doesn't affect the example.

From [N4659 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

From [N3337 expr.ass]

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand. The result in all cases is a bit-field if the left operand is a bit-field. In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

The only difference being the last sentence being absent in N3337.

The last sentence however, shouldn't have any importance as the left operand i is neither "another side effect" nor "using the value of the same scalar object" as the id-expression is a lvalue.