问:
Was Form.create() from antd replaced?
i am trying to create a login page in react using antd. I found a tutorial for doing this,but i belive that it is outdated, because it gives an error. I read on a forum that form.create() is not available anymore, but i don't know how to replace it.Here is my code:

```<code>import { Form, Icon, Input, Button, Spin } from 'antd';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import * as actions from '../store/actions/auth';

const FormItem = Form.Item;
const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onAuth(values.userName, values.password);
        this.props.history.push('/');
      }
    });
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (
            <p>{this.props.error.message}</p>
        );
    }

    const { getFieldDecorator } = this.props.form;
    return (
        <div>
            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onSubmit={this.handleSubmit} className="login-form">

                    <FormItem>
                    {getFieldDecorator('userName', {
                        rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    )}
                    </FormItem>

                    <FormItem>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    )}
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }
      </div>
    );
  }
}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(WrappedNormalLoginForm);
</code>```

When i try to run it, i get an error that says:

```<code>TypeError: _antd.Form.create(...) is not a function
</code>```

How can i rewrite the code in order to make it run?

答:
I think you are using Antd v4.*. Form.create({}) is no more in latest version, so you have to your code as follow to make it working. V4 has. major changes so you have to go through migration guidelines

```<code>import { Form, Input, Button, Spin } from 'antd';
import { LoadingOutlined, UserOutlined, LockOutlined } from "@ant-design/icons";
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import * as actions from '../store/actions/auth';

const FormItem = Form.Item;
const antIcon = <LoadingOutlined style={{ fontSize: 24 }} />;

class NormalLoginForm extends React.Component {
  handleFinish = (values) => {
    this.props.onAuth(values.userName, values.password);
    this.props.history.push('/');
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (
            <p>{this.props.error.message}</p>
        );
    }

    return (
        <div>
            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onFinish={this.handleFinish} className="login-form">

                    <FormItem name="userName" rules={[{ required: true, message: 'Please input your username!' }]}>
                    <Input prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    )}
                    </FormItem name="password" rules={[{ required: true, message: 'Please input your Password!' }]}>

                    <FormItem>
<Input prefix={<LockOutlined style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    )}
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }
      </div>
    );
  }
}

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(NormalLoginForm);

</code>```

Title: Was Form.create() from antd replaced?

Body:
i am trying to create a login page in react using antd. I found a tutorial for doing this,but i belive that it is outdated, because it gives an error. I read on a forum that form.create() is not available anymore, but i don't know how to replace it.Here is my code:

import { Form, Icon, Input, Button, Spin } from 'antd';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import * as actions from '../store/actions/auth';

const FormItem = Form.Item;
const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onAuth(values.userName, values.password);
        this.props.history.push('/');
      }
    });
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (

{this.props.error.message}

        );
    }

    const { getFieldDecorator } = this.props.form;
    return (

            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onSubmit={this.handleSubmit} className="login-form">

                    <FormItem>
                    {getFieldDecorator('userName', {
                        rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    )}
                    </FormItem>

                    <FormItem>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    )}
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }

    );
  }
}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(WrappedNormalLoginForm);

When i try to run it, i get an error that says:

TypeError: _antd.Form.create(...) is not a function

How can i rewrite the code in order to make it run?

Body:
I think you are using Antd v4.*. Form.create({}) is no more in latest version, so you have to your code as follow to make it working. V4 has. major changes so you have to go through migration guidelines

import { Form, Input, Button, Spin } from 'antd';
import { LoadingOutlined, UserOutlined, LockOutlined } from "@ant-design/icons";
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import * as actions from '../store/actions/auth';

const FormItem = Form.Item;
const antIcon = <LoadingOutlined style={{ fontSize: 24 }} />;

class NormalLoginForm extends React.Component {
  handleFinish = (values) => {
    this.props.onAuth(values.userName, values.password);
    this.props.history.push('/');
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (
            <p>{this.props.error.message}</p>
        );
    }

    return (
        <div>
            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onFinish={this.handleFinish} className="login-form">

                    <FormItem name="userName" rules={[{ required: true, message: 'Please input your username!' }]}>
                    <Input prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    )}
                    </FormItem name="password" rules={[{ required: true, message: 'Please input your Password!' }]}>

                    <FormItem>
<Input prefix={<LockOutlined style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    )}
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }
      </div>
    );
  }
}

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(NormalLoginForm);


来源: stackexchange

问:
Loop through a object, organize keys from Z - A reverse alphabetical
I'm looking for a way to reverse alphabetical the object keys. Currently, it stores correctly in alphabetical order, what would be the best approach to ensure it reverses the keys correctly? I see there are a lot of options for arrays to reverse loop but not seeing anything for objects. Is it possible to 'unshift' the keys that the reduce exports?</p>

```<code>var alph = Object.keys(feedData)
    .sort()
    .reduce(function (acc, key) {
        acc[key] = feedData[key];
        return acc;
    }, {});

    console.log(alph);

var config = {
    "size": [{
      "F2-1_largerLegal-input": "",
      "F3-1_copy-font": "",
      "Frame-Three": "",
      "_assetKey": "",
      "F3-2_copy-fontSize": "",
      "_jvxRtnWeight": "",
      "CTA-1_copy-fontSize": "",
      "F2-1_copy-font": "",
      "EF-1_largerLegal-fontSize": "",
      "reportingName": "",
      "EF-2_copy-fontSize": "",
      "EF-2_copy-font": "",
      "F2-3_copy-fontSize": "",
      "Frame-One": "",
      "assetVarient": "",
      "F3-1_largerLegal-fontSize": "",
      "EF-1_product-src": "",
      "F3-1_frameLegal-input": "",
      "F3-1_frameLegal-fontSize": "",
      "F3-1_copy-input": "",
      "F2-1_copy-input": "",
      "EF-3_copy-fontSize": "",
      "F2-1_frameLegal-input": "",
      "F3-3_copy-fontSize": "",
      "F3-2_bg-src": "",
      "EF-1_copy-input": "",
      "F2-1_frameLegal-fontSize": "",
      "F2-2_copy-input": "",
      "F2-3_copy-input": "",
      "F3-3_copy-input": "",
      "EF-1_largerLegal-input": "",
      "EF-1_copy-font": "",
      "EF-1_frameLegal-fontSize": "",
      "F3-3_copy-font": "",
      "RO-1_legal-input": "",
      "EF-1_frameLegal-input": "",
      "F2-3_copy-font": "",
      "EF-2_copy-input": "",
      "End-Frame": "",
      "F3-2_copy-input": "",
      "F2-1_copy-fontSize": "",
      "F2-1_product-src": "",
      "F2-2_copy-font": "",
      "rotation": "",
      "F3-2_copy-font": "",
      "exitUrl": "",
      "EF-3_copy-input": "",
      "CTA-1_copy-input": "",
      "F3-1_copy-fontSize": "",
      "EF-1_copy-fontSize": "",
      "Frame-Two": "",
      "F3-1_bg-src": "",
      "EF-3_copy-font": "",
      "weighTag": "",
      "F3-1_largerLegal-input": "",
      "F2-2_copy-fontSize": "",
      "dimensions": "",
      "F2-1_largerLegal-fontSize": ""
    }]
  };
</code>```

答:
You cannot ensure the order of keys added with a normal object, as stated in the comments.

You could use an array of sorted Keys, as stated in the comments, or we could use a Map object, and this can be iterated over natively, in the order of key addition.

Here is an example:

const initObj = {
  "a": 1,
  "c": 3,
  "b": 2,
  "e": 5,
  "d": 4
}

//Option 1, created a sorted array of keys:
const sortedKeys = Object.keys(initObj).sort((a,b) => b.localeCompare(a));
console.log(sortedKeys);

//now loop over your initObj using our sortedKeys:
console.log("using sortedKeys:");
for (let key of sortedKeys){
  console.log(key, initObj[key]);
}

//Option 2, use a Map object:
const mapObj = new Map(Object.entries(initObj).sort(([key_a, a],[key_b, b]) => key_b.localeCompare(key_a)));

//now loop over your Map Object directly:
console.log("using mapObj:");
for (let [key, val] of mapObj){
  console.log(key, val);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a way to reverse alphabetical the object keys. Currently, it stores correctly in alphabetical order, what would be the best approach to ensure it reverses the keys correctly? I see there are a lot of options for arrays to reverse loop but not seeing anything for objects. Is it possible to 'unshift' the keys that the reduce exports?

var alph = Object.keys(feedData)
    .sort()
    .reduce(function (acc, key) {
        acc[key] = feedData[key];
        return acc;
    }, {});

    console.log(alph);

var config = {
    "size": [{
      "F2-1_largerLegal-input": "",
      "F3-1_copy-font": "",
      "Frame-Three": "",
      "_assetKey": "",
      "F3-2_copy-fontSize": "",
      "_jvxRtnWeight": "",
      "CTA-1_copy-fontSize": "",
      "F2-1_copy-font": "",
      "EF-1_largerLegal-fontSize": "",
      "reportingName": "",
      "EF-2_copy-fontSize": "",
      "EF-2_copy-font": "",
      "F2-3_copy-fontSize": "",
      "Frame-One": "",
      "assetVarient": "",
      "F3-1_largerLegal-fontSize": "",
      "EF-1_product-src": "",
      "F3-1_frameLegal-input": "",
      "F3-1_frameLegal-fontSize": "",
      "F3-1_copy-input": "",
      "F2-1_copy-input": "",
      "EF-3_copy-fontSize": "",
      "F2-1_frameLegal-input": "",
      "F3-3_copy-fontSize": "",
      "F3-2_bg-src": "",
      "EF-1_copy-input": "",
      "F2-1_frameLegal-fontSize": "",
      "F2-2_copy-input": "",
      "F2-3_copy-input": "",
      "F3-3_copy-input": "",
      "EF-1_largerLegal-input": "",
      "EF-1_copy-font": "",
      "EF-1_frameLegal-fontSize": "",
      "F3-3_copy-font": "",
      "RO-1_legal-input": "",
      "EF-1_frameLegal-input": "",
      "F2-3_copy-font": "",
      "EF-2_copy-input": "",
      "End-Frame": "",
      "F3-2_copy-input": "",
      "F2-1_copy-fontSize": "",
      "F2-1_product-src": "",
      "F2-2_copy-font": "",
      "rotation": "",
      "F3-2_copy-font": "",
      "exitUrl": "",
      "EF-3_copy-input": "",
      "CTA-1_copy-input": "",
      "F3-1_copy-fontSize": "",
      "EF-1_copy-fontSize": "",
      "Frame-Two": "",
      "F3-1_bg-src": "",
      "EF-3_copy-font": "",
      "weighTag": "",
      "F3-1_largerLegal-input": "",
      "F2-2_copy-fontSize": "",
      "dimensions": "",
      "F2-1_largerLegal-fontSize": ""
    }]
  };

Body:
You cannot ensure the order of keys added with a normal object, as stated in the comments.

You could use an array of sorted Keys, as stated in the comments, or we could use a Map object, and this can be iterated over natively, in the order of key addition.

Here is an example:

const initObj = {
  "a": 1,
  "c": 3,
  "b": 2,
  "e": 5,
  "d": 4
}

//Option 1, created a sorted array of keys:
const sortedKeys = Object.keys(initObj).sort((a,b) => b.localeCompare(a));
console.log(sortedKeys);

//now loop over your initObj using our sortedKeys:
console.log("using sortedKeys:");
for (let key of sortedKeys){
  console.log(key, initObj[key]);
}

//Option 2, use a Map object:
const mapObj = new Map(Object.entries(initObj).sort(([key_a, a],[key_b, b]) => key_b.localeCompare(key_a)));

//now loop over your Map Object directly:
console.log("using mapObj:");
for (let [key, val] of mapObj){
  console.log(key, val);
}

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
RxSwift Differ library crash `NSInternalInconsistencyException`
I am trying to use Diffing with RxSwift in a basic example for now. I am using the Differ library.

Here is my Interactor + ViewModels associated:

import Foundation
import RxSwift
import RxCocoa

class Interactor {

    var items = [
            [1,5,6,7,4,6,7,1,5],
            [1,5,2,1,0,6,7],
    ]

    let viewModel: BehaviorRelay<ViewModel>

    var currentObjects: Int = 0 {
        didSet {
            viewModel.accept(.init(with: .loaded(items[currentObjects])))
        }
    }

    init() {
        viewModel = BehaviorRelay(value: .init(with: .initialized))
    }

    func fetchValue() {
        currentObjects = currentObjects == 0 ? 1 : 0
    }

}

struct ViewModel {

    enum ViewModelType: Equatable {
        case cell(CellViewModel)
    }

    enum State {
        case initialized
        case loaded([Int])
    }

    let state: State
    let viewModels: [ViewModelType]

    init(with state: State) {
        self.state = state
        switch state {
        case .initialized: viewModels = []
        case .loaded(let values):
            viewModels = CellViewModel.from(values).map(ViewModelType.cell)
        }
    }
}

extension ViewModel: Equatable {

    static func ==(left: ViewModel, right: ViewModel) -> Bool {
        return left.state == left.state
    }
}

extension ViewModel.State: Equatable {

    static func ==(left: ViewModel.State, right: ViewModel.State) -> Bool {
        switch (left, right) {
        case (.initialized, .initialized): return true
        case let (.loaded(l), .loaded(r)): return l == r
        default: return false
        }
    }
}

struct CellViewModel {
    let description: String
}

extension CellViewModel {

    static func from(_ values: [Int]) -> [CellViewModel] {
        return values.map { CellViewModel(description: String($0)) }
    }
}

extension CellViewModel: Equatable {

    static func ==(left: CellViewModel, right: CellViewModel) -> Bool {
        return left.description == right.description
    }
}
```

<p>Now for the view I am using a simple `UITableView</p>

<pre class="lang-swift prettyprint-override"><code>import UIKit
import Differ
import RxSwift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        ...

        interactor
            .viewModel
            .asObservable()
            .scan([], accumulator: { (previous, current) in
              Array(previous + [current]).suffix(2)
            })
            .map({ (arr) -> (previous: ViewModel?, current: ViewModel) in
              (arr.count > 1 ? arr.first : nil, arr.last!)
            }).subscribe(onNext: { [weak self] (previous, current) in
                if let prev = previous {
                    print("Previous => State: \(prev.state) | ViewModelType.count: \(prev.viewModels.count)")
                } else {
                    print("Previous => State: nil | ViewModelType.count: nil")
                }
                print("Current => State: \(current.state) | ViewModelType.count: \(current.viewModels.count)")
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    strongSelf.tableView.animateRowChanges(oldData: previous?.viewModels ?? [], newData: current.viewModels)
                }
            }).disposed(by: disposeBag)

        interactor.fetchValue()
    }

    @objc
    func onRefresh() {
        interactor.fetchValue()
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return interactor.viewModel.value.viewModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellViewModel = interactor.viewModel.value.viewModels[indexPath.row]
        switch cellViewModel {
        case .cell(let viewModel):
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = viewModel.description
            return cell
        }
    }
}
</code>```

With everything conforming to Equatable, I thought the job would be done but I got an NSInternalInconsistencyException exception.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (7 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

The prints I put to check what came from Rx before the crash show:

Previous => State: nil | ViewModelType.count: nil
Current => State: initialized | ViewModelType.count: 0
Previous => State: initialized | ViewModelType.count: 0
Current => State: loaded([1, 5, 2, 1, 0, 6, 7]) | ViewModelType.count: 7
```

<p>The flow looks good to me in a logic stand point. Am I missing something?</p>

<hr>

<h1>Edit 2019/10/29</h1>

<p>I have made another version without using <code>RxSwift</code> to know if the problem was du to <code>RxSwift</code>:</p>

<pre class="lang-swift prettyprint-override"><code>protocol InteractorDelegate: class {
    func viewModelDidChange(_ old: ViewModel?, _ new: ViewModel)
}

class Interactor {

    weak var delegate: InteractorDelegate?

    var items = [
            [1,5,6,7,4,6,7,1,5],
            [1,5,2,1,0,6,7],
    ]

    var viewModel: ViewModel? {
        didSet {
            delegate?.viewModelDidChange(oldValue, viewModel!)
        }
    }

    var currentObjects: Int = 0 {
        didSet {
            viewModel = .init(with: .loaded(items[currentObjects]))
        }
    }

    init() {
        viewModel = .init(with: .initialized)
    }

    func fetchValue() {
        currentObjects = currentObjects == 0 ? 1 : 0
    }
}
</code>```

For the ViewController:

extension ViewController: InteractorDelegate {

    func viewModelDidChange(_ old: ViewModel?, _ new: ViewModel) {

        if let prev = old {
            print("Previous => State: \(prev.state) | ViewModelType.count: \(prev.viewModels.count)")
        } else {
            print("Previous => State: nil | ViewModelType.count: nil")
        }
        print("Current => State: \(new.state) | ViewModelType.count: \(new.viewModels.count)")
        DispatchQueue.main.async {
            self.tableView.animateRowChanges(oldData: old?.viewModels ?? [], newData: new.viewModels)
        }
    }
}
```

<p>Seems that the issue is still same without <code>RxSwift</code>:</p>

<pre class="lang-none prettyprint-override"><code>Previous => State: initialized | ViewModelType.count: 0
Current => State: loaded([1, 5, 2, 1, 0, 6, 7]) | ViewModelType.count: 7
2019-10-29 13:45:56.636678+0900 TestDiffer[93631:21379549] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (7 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
</code>```

Is there a problem with my Equatables conformance?

Edit 2019/10/29 #2

After new tests, I saw that the crash occurred only when the previous value is empty.

Everything is working fine with with changing the code like this:

extension ViewController: InteractorDelegate {

    func viewModelDidChange(_ old: ViewModel?, _ new: ViewModel) {

        DispatchQueue.main.async {
            guard old != nil && !old!.viewModels.isEmpty else {
                self.tableView.reloadData()
                return
            }
            self.tableView.animateRowChanges(oldData: old!.viewModels, newData: new.viewModels)
        }
    }
}
```

Same success when putting back RxSwift instead of the delegate.

Even if it is working as expected now. I am still questioning why the diffing isn't working when the array is empty. Having an previous value empty and a new value with 2 elements should be analyzed as 2 inserts no? What is going on here?

答:
It is difficult to tell what exactly is going on with just the code you posted here. Could you maybe provide a self-contained sample app showcasing the issue?

By the looks of the error message you are getting, I have faced a similar issue in the past. I believe this can happen if you don't use the API correctly and you schedule a transition before the UITableView had a chance to query its data source. I'm going to try to reproduce this issue in a sample app.

When the underlying data has changed, you call animateRowChanges(oldData:newData:).
This diffs the data and determines where rows need to be inserted, deleted, and moved — in your case simply 7 insertions. animateRowChanges(oldData:newData:) then delegates to beginUpdates() and endUpdates(). In the scenario where the UITableView hasn't queried its data source before, beginUpdates() does just that and finds out that the UITableView is currently showing 7 rows. But after inserting 7 extra rows and calling endUpdates(), the data source still reports only 7 rows, hence the internal inconsistency exception.

Scheduling the transition when the underlying data has already changed is simply too late.
A didSet property observer or your method viewModelDidChange(_:_:) is not the place to do so. Really, scheduling the transition when the data has already changed is always wrong and only usually works because the UITableView caches its numberOfSections etc.

So how can you work around this issue?

The correct way to use these APIs is updating your data source between beginUpdates() and endUpdates() or in the closure passed to performBatchUpdates(_:completion:), not prior to these calls. The UICollectionView documentation also states that

[i]f the collection view's layout is not up to date before you call this method, a reload may occur. To avoid problems, you should update your data model inside the updates block or ensure the layout is updated before you call performBatchUpdates(_:completion:).

Differ supports this since release 1.4.3 in the form of an additional updateData: parameters on the UICollectionView family of the transitioning methods, but not on the UITableView family. I'm working on a pull request to bring this feature to UITableView as well.

Once that feature lands, you should be able to resolve your issue by changing the viewModelDidChange(_:_:) callback to something like viewModelWillChange(from:to:updateData:). You should probably also make var viewModel a private(set) because as described above, the didSet property observer is too late to call these methods. Instead, you'll want to add a setter method that calls the delegate like so:

```<code>func setViewModel(_ newValue: ViewModel) {
    if let delegate = self.delegate {
        delegate?.viewModelWillChange(from: viewModel, to: newValue, updateData: { self.viewModel = newValue })
    } else {
        self.viewModel = newValue
    }
}
</code>```

Your implementation of InteractorDelegate could then look like so:

```<code>func viewModelWillChange(from oldValue: ViewModel?, to newValue: ViewModel, updateData: () -> Void) {
    self.tableView.animateRowChanges(oldData: oldValue.viewModels ?? [], newData: newValue.viewModels ?? [], updateData: updateData)
}
</code>```

Alternatively, you can write a custom wrapper to animateRowChanges(oldData:newData:) today that checks if oldData is compatible with the current state of the UITableView by comparing to its numberOfSections and numberOfItems(inSection:). If oldData is compatible, you can delegate to Differ, otherwise you could call reloadData().

Body:
I am trying to use Diffing with RxSwift in a basic example for now. I am using the Differ library.

Here is my Interactor + ViewModels associated:

import Foundation
import RxSwift
import RxCocoa

class Interactor {

    var items = [
            [1,5,6,7,4,6,7,1,5],
            [1,5,2,1,0,6,7],
    ]

    let viewModel: BehaviorRelay<ViewModel>

    var currentObjects: Int = 0 {
        didSet {
            viewModel.accept(.init(with: .loaded(items[currentObjects])))
        }
    }

    init() {
        viewModel = BehaviorRelay(value: .init(with: .initialized))
    }

    func fetchValue() {
        currentObjects = currentObjects == 0 ? 1 : 0
    }

}

struct ViewModel {

    enum ViewModelType: Equatable {
        case cell(CellViewModel)
    }

    enum State {
        case initialized
        case loaded([Int])
    }

    let state: State
    let viewModels: [ViewModelType]

    init(with state: State) {
        self.state = state
        switch state {
        case .initialized: viewModels = []
        case .loaded(let values):
            viewModels = CellViewModel.from(values).map(ViewModelType.cell)
        }
    }
}

extension ViewModel: Equatable {

    static func ==(left: ViewModel, right: ViewModel) -> Bool {
        return left.state == left.state
    }
}

extension ViewModel.State: Equatable {

    static func ==(left: ViewModel.State, right: ViewModel.State) -> Bool {
        switch (left, right) {
        case (.initialized, .initialized): return true
        case let (.loaded(l), .loaded(r)): return l == r
        default: return false
        }
    }
}

struct CellViewModel {
    let description: String
}

extension CellViewModel {

    static func from(_ values: [Int]) -> [CellViewModel] {
        return values.map { CellViewModel(description: String($0)) }
    }
}

extension CellViewModel: Equatable {

    static func ==(left: CellViewModel, right: CellViewModel) -> Bool {
        return left.description == right.description
    }
}

Now for the view I am using a simple `UITableView

import UIKit
import Differ
import RxSwift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        ...

        interactor
            .viewModel
            .asObservable()
            .scan([], accumulator: { (previous, current) in
              Array(previous + [current]).suffix(2)
            })
            .map({ (arr) -> (previous: ViewModel?, current: ViewModel) in
              (arr.count > 1 ? arr.first : nil, arr.last!)
            }).subscribe(onNext: { [weak self] (previous, current) in
                if let prev = previous {
                    print("Previous => State: \(prev.state) | ViewModelType.count: \(prev.viewModels.count)")
                } else {
                    print("Previous => State: nil | ViewModelType.count: nil")
                }
                print("Current => State: \(current.state) | ViewModelType.count: \(current.viewModels.count)")
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    strongSelf.tableView.animateRowChanges(oldData: previous?.viewModels ?? [], newData: current.viewModels)
                }
            }).disposed(by: disposeBag)

        interactor.fetchValue()
    }

    @objc
    func onRefresh() {
        interactor.fetchValue()
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return interactor.viewModel.value.viewModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellViewModel = interactor.viewModel.value.viewModels[indexPath.row]
        switch cellViewModel {
        case .cell(let viewModel):
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = viewModel.description
            return cell
        }
    }
}

With everything conforming to Equatable, I thought the job would be done but I got an NSInternalInconsistencyException exception.

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (7 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

The prints I put to check what came from Rx before the crash show:

Previous => State: nil | ViewModelType.count: nil
Current => State: initialized | ViewModelType.count: 0
Previous => State: initialized | ViewModelType.count: 0
Current => State: loaded([1, 5, 2, 1, 0, 6, 7]) | ViewModelType.count: 7

The flow looks good to me in a logic stand point. Am I missing something?

Edit 2019/10/29

I have made another version without using RxSwift to know if the problem was du to RxSwift:

protocol InteractorDelegate: class {
    func viewModelDidChange(_ old: ViewModel?, _ new: ViewModel)
}

class Interactor {

    weak var delegate: InteractorDelegate?

    var items = [
            [1,5,6,7,4,6,7,1,5],
            [1,5,2,1,0,6,7],
    ]

    var viewModel: ViewModel? {
        didSet {
            delegate?.viewModelDidChange(oldValue, viewModel!)
        }
    }

    var currentObjects: Int = 0 {
        didSet {
            viewModel = .init(with: .loaded(items[currentObjects]))
        }
    }

    init() {
        viewModel = .init(with: .initialized)
    }

    func fetchValue() {
        currentObjects = currentObjects == 0 ? 1 : 0
    }
}

For the ViewController:

extension ViewController: InteractorDelegate {

    func viewModelDidChange(_ old: ViewModel?, _ new: ViewModel) {

        if let prev = old {
            print("Previous => State: \(prev.state) | ViewModelType.count: \(prev.viewModels.count)")
        } else {
            print("Previous => State: nil | ViewModelType.count: nil")
        }
        print("Current => State: \(new.state) | ViewModelType.count: \(new.viewModels.count)")
        DispatchQueue.main.async {
            self.tableView.animateRowChanges(oldData: old?.viewModels ?? [], newData: new.viewModels)
        }
    }
}

Seems that the issue is still same without RxSwift:

Previous => State: initialized | ViewModelType.count: 0
Current => State: loaded([1, 5, 2, 1, 0, 6, 7]) | ViewModelType.count: 7
2019-10-29 13:45:56.636678+0900 TestDiffer[93631:21379549] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (7), plus or minus the number of rows inserted or deleted from that section (7 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

Is there a problem with my Equatables conformance?

Edit 2019/10/29 #2

After new tests, I saw that the crash occurred only when the previous value is empty.

Everything is working fine with with changing the code like this:

extension ViewController: InteractorDelegate {

    func viewModelDidChange(_ old: ViewModel?, _ new: ViewModel) {

        DispatchQueue.main.async {
            guard old != nil && !old!.viewModels.isEmpty else {
                self.tableView.reloadData()
                return
            }
            self.tableView.animateRowChanges(oldData: old!.viewModels, newData: new.viewModels)
        }
    }
}

Same success when putting back RxSwift instead of the delegate.

Even if it is working as expected now. I am still questioning why the diffing isn't working when the array is empty. Having an previous value empty and a new value with 2 elements should be analyzed as 2 inserts no? What is going on here?

Body:
It is difficult to tell what exactly is going on with just the code you posted here. Could you maybe provide a self-contained sample app showcasing the issue?

By the looks of the error message you are getting, I have faced a similar issue in the past. I believe this can happen if you don't use the API correctly and you schedule a transition before the UITableView had a chance to query its data source. I'm going to try to reproduce this issue in a sample app.

When the underlying data has changed, you call animateRowChanges(oldData:newData:).
This diffs the data and determines where rows need to be inserted, deleted, and moved — in your case simply 7 insertions. animateRowChanges(oldData:newData:) then delegates to beginUpdates() and endUpdates(). In the scenario where the UITableView hasn't queried its data source before, beginUpdates() does just that and finds out that the UITableView is currently showing 7 rows. But after inserting 7 extra rows and calling endUpdates(), the data source still reports only 7 rows, hence the internal inconsistency exception.

Scheduling the transition when the underlying data has already changed is simply too late.
A didSet property observer or your method viewModelDidChange(_:_:) is not the place to do so. Really, scheduling the transition when the data has already changed is always wrong and only usually works because the UITableView caches its numberOfSections etc.

So how can you work around this issue?

The correct way to use these APIs is updating your data source between beginUpdates() and endUpdates() or in the closure passed to performBatchUpdates(_:completion:), not prior to these calls. The UICollectionView documentation also states that

[i]f the collection view's layout is not up to date before you call this method, a reload may occur. To avoid problems, you should update your data model inside the updates block or ensure the layout is updated before you call performBatchUpdates(_:completion:).

Differ supports this since release 1.4.3 in the form of an additional updateData: parameters on the UICollectionView family of the transitioning methods, but not on the UITableView family. I'm working on a pull request to bring this feature to UITableView as well.

Once that feature lands, you should be able to resolve your issue by changing the viewModelDidChange(_:_:) callback to something like viewModelWillChange(from:to:updateData:). You should probably also make var viewModel a private(set) because as described above, the didSet property observer is too late to call these methods. Instead, you'll want to add a setter method that calls the delegate like so:

func setViewModel(_ newValue: ViewModel) {
    if let delegate = self.delegate {
        delegate?.viewModelWillChange(from: viewModel, to: newValue, updateData: { self.viewModel = newValue })
    } else {
        self.viewModel = newValue
    }
}

Your implementation of InteractorDelegate could then look like so:

func viewModelWillChange(from oldValue: ViewModel?, to newValue: ViewModel, updateData: () -> Void) {
    self.tableView.animateRowChanges(oldData: oldValue.viewModels ?? [], newData: newValue.viewModels ?? [], updateData: updateData)
}

Alternatively, you can write a custom wrapper to animateRowChanges(oldData:newData:) today that checks if oldData is compatible with the current state of the UITableView by comparing to its numberOfSections and numberOfItems(inSection:). If oldData is compatible, you can delegate to Differ, otherwise you could call reloadData().


问:
What are you using for Distributed Caching in web farms running ASP.NET?
I am curious as to what others are using in this situation.  I know a couple of the options that are out there like a memcached port or ScaleOutSoftware.  The memcached ports don't seem to be actively worked on (correct me if I'm wrong).  ScaleOutSoftware is too expensive for me (I don't doubt it is worth it).  This is not to say that I don't want to hear about people using memcached or ScaleOutSoftware.  I'm just stating what I "know" at this point.

So my question is basically this: for those of you ACTIVELY using distributed caching, what are you using, are you happy with it, and what should I look out for?

I am moving to two servers very soon...both will be at the same location.  I use caching fairly heavily (but carefully) to reduce the load on my database server.

Edit: I downloaded Scaleout Software's solution.  I've coded for it and it seems to work real well.  I just have to decide if my wallet will part with the cash for it.  :)  Anyone have experiences good or bad with ScaleoutSoftware?

Edit Again: It's been a little while since I asked this?  Any more thoughts on it?  We ended up buying the solution from ScaleOutSoftware and have been happy with it, but I'm curious what others are doing.

答:
There is a 100% native .NET, well documented open source (LGPL) project called Shared Cache. Looks like it is not yet mentioned on SO, but it's promising and should be able to do what most people expect from a distributed cache. It even supports different strategies like distributed or replicated caching etc.

I will update this post with more details as soon as I had a chance to try it on a real project.

OwnerDisplayName: mmcquade

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Micky McQuade

OwnerDisplayName: markus


问:
Mauritus national flag problem
I've made a solution for the Dutch national flag problem already.

But this time, I want to try something more difficult: the Mauritus national flag problem - 4 colours, instead of 3. Any suggestions for an effective algorithm?

Basically, The Mauritius National Flag Problem focuses on how you would be able to sort the given list of pairs based on the order of colors in the Mauritius National Flag (Red, Blue, Yellow, Green). And the numbers must be sorted in ascending order too.

Scheme Programming Sample Input:

( (R . 3) (G . 6) (Y . 1) (B . 2) (Y . 7) (G . 3) (R . 1) (B . 8) )

Output:

( (R . 1) (R . 3) (B . 2) (B . 8) (Y . 1) (Y . 7) (G . 3) (G . 6) )

答:
I do have a similar kind of code but insted of</p>

```<code>function sort(a:string[]){
         let low = 0;
         let mid1 = 0;
         let mid2 = a.length-1;
         let high = a.length-1;

        while(mid1 <= mid2){
             switch(a[mid1]){

                 case '0':

                        [a[mid1],a[low]] = [a[low],a[mid1]];
                        mid1++;
                        low++;
                        break;

                 case '1':mid1++;break;

                 case '2':
                 case '3':[a[mid1],a[mid2]] = [a[mid2],a[mid1]];
                            mid2--;
                            break;

                 }
         }
    //sort 2 and 3
         while(mid1 <= high){
          switch(a[mid1]){
                 case '2': mid1++; break;
                 case '3': [a[mid1],a[high]] = [a[high],a[mid1]]
                            high--;
                            break;

           }
        }

}
</code>```

Title: Mauritus national flag problem

Body:
I do have a similar kind of code but insted of

function sort(a:string[]){
         let low = 0;
         let mid1 = 0;
         let mid2 = a.length-1;
         let high = a.length-1;

        while(mid1 <= mid2){
             switch(a[mid1]){

                 case '0':

                        [a[mid1],a[low]] = [a[low],a[mid1]];
                        mid1++;
                        low++;
                        break;

                 case '1':mid1++;break;

                 case '2':
                 case '3':[a[mid1],a[mid2]] = [a[mid2],a[mid1]];
                            mid2--;
                            break;

                 }
         }
    //sort 2 and 3
         while(mid1 <= high){
          switch(a[mid1]){
                 case '2': mid1++; break;
                 case '3': [a[mid1],a[high]] = [a[high],a[mid1]]
                            high--;
                            break;

           }
        }

}


问:
Read values from multiple YAML files in spring boot
spring.config.location can accept a list of directories which host the yaml files for a spring boot application.

But the listed directories must have file named as applicaion.yml, else they are not picked up.

if my application allows users to place yaml files with any names then I can't use this option.

I have then manually add the file names to the property like below

spring.config.location=/location1/file1.yml,/location2/file2.yml

Every time a new file is added, I have to modify this property.

I was able to use YamlPropertySourceLoader to read all the files and put all properties into a Map, but is there another, more elegant, way of doing this which allows me to bind these values directly into the @Value annotation.

updating with the code snippet that I am currently using, but looking for any other better alternatives.

```<code>Resource[] resources = applicationContext.getResources("classpath*:*.properties");

        Map<Object, Object> map = new HashMap<>();

        Arrays.stream(resources).forEach(res -> {
            try {
                propertiesPropertySourceLoader.load("resources", res)
                        .forEach(prop -> map.putAll((Map<?, ?>) prop.getSource()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
</code>```

答:
You can configure multiple configuration files using PropertyPlaceholderConfigurer for example:

```<code><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
  <list>
    <value>${YOUR_HOME}/global.properties</value>
    <value>${YOUR_HOME}/second-level.properties</value>
  </list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="fileEncoding" value="UTF8"/>
</code>```

Or you can use @PropertySource annotation for example:

```<code>@PropertySource(value = {"classpath:global.properties", "file://${YOUR_HOME}/second-level.properties"}, ignoreResourceNotFound = true)
</code>```

Body:
spring.config.location can accept a list of directories which host the yaml files for a spring boot application.

But the listed directories must have file named as applicaion.yml, else they are not picked up.

if my application allows users to place yaml files with any names then I can't use this option.

I have then manually add the file names to the property like below

spring.config.location=/location1/file1.yml,/location2/file2.yml

Every time a new file is added, I have to modify this property.

I was able to use YamlPropertySourceLoader to read all the files and put all properties into a Map, but is there another, more elegant, way of doing this which allows me to bind these values directly into the @Value annotation.

updating with the code snippet that I am currently using, but looking for any other better alternatives.

Resource[] resources = applicationContext.getResources("classpath*:*.properties");

        Map<Object, Object> map = new HashMap<>();

        Arrays.stream(resources).forEach(res -> {
            try {
                propertiesPropertySourceLoader.load("resources", res)
                        .forEach(prop -> map.putAll((Map<?, ?>) prop.getSource()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

Body:
You can configure multiple configuration files using PropertyPlaceholderConfigurer for example:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
  <list>
    <value>${YOUR_HOME}/global.properties</value>
    <value>${YOUR_HOME}/second-level.properties</value>
  </list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="fileEncoding" value="UTF8"/>

Or you can use @PropertySource annotation for example:

@PropertySource(value = {"classpath:global.properties", "file://${YOUR_HOME}/second-level.properties"}, ignoreResourceNotFound = true)


问:
Unwanted new line returned after AJAX request
I'm using an ajax request to send comments to DB. Succesful response is marked by

```<code>1. OK
</code>```

The problem actually is that the response from the php script is

```<code>1.
2. OK
</code>```

So I debugged the script and noted that the newline character si being added when the script executes the following line:

```<code>require_once($ABS_APPS."/quotes/classQuote.php");
</code>```

After some searches i read that it could be a BOM (Byte Order Mark) problem. So I just downloaded and opened the classQuote.php file with an hex editor and noticed that there's no BOM... can someone help me?

P.S. All files in my project are encoted in UTF-8, and I'm currently usint NetBeans which doesn't add BOM to files.

This is the incriminated script:

```<code>// Send new comment to DB
case "send":
    $notification = new Notification();
    if($comment->insert($_POST["username"], $_POST["comment"], $_POST["app"], $_POST["entryId"])){
        switch ($_POST["app"]) {
            case "quotes":
                require_once($ABS_APPS."/quotes/classQuote.php");
                $quote = new Quote();
                $quoteData = $quote->get($_POST["entryId"]);
                // If user comments his own entry we don't have to send the notification
                if($quoteData["UserAuthor"] != $_SESSION["User"]){
                    $notification->newComment($_POST["username"], $quoteData["UserAuthor"], $_POST["entryId"], $_POST["app"]);
                }
                break;
            default:
                break;
        }
        echo "OK";
    } else {
        echo "ERROR";
    }
    break;
</code>```

答:
I also faced the same problem.
The final solution I figured out is following

Check all the files which are loaded into the file to which you are sending AJAX request

Remove the extra white spaces from the very first <? line and PHP starting tag If your file starts from line number 1, the first ever character should be this <?.

If they are PHP files, then don't add   ?>  at the end.

Try to keep the last line marker only up to the last line of code written. means that do not add extra spaces at the end of the file. If code finishes at line 32, do not go to line number 33 via editor. In fact, press the back button and clear everything below up to line number 32.

If you are using any PHP framework, then make sure that the hierarchy of all files loaded should not have the same problem. e.g. if you are using codeigniter framework them make sure that the calling function's controller and all the models loaded into that controller should not have the same problem.

ContentLicense: CC BY-SA 3.0

Body:
I'm using an ajax request to send comments to DB. Succesful response is marked by

1. OK

The problem actually is that the response from the php script is

1.
2. OK

So I debugged the script and noted that the newline character si being added when the script executes the following line:

require_once($ABS_APPS."/quotes/classQuote.php");

After some searches i read that it could be a BOM (Byte Order Mark) problem. So I just downloaded and opened the classQuote.php file with an hex editor and noticed that there's no BOM... can someone help me?

P.S. All files in my project are encoted in UTF-8, and I'm currently usint NetBeans which doesn't add BOM to files.

This is the incriminated script:

// Send new comment to DB
case "send":
    $notification = new Notification();
    if($comment->insert($_POST["username"], $_POST["comment"], $_POST["app"], $_POST["entryId"])){
        switch ($_POST["app"]) {
            case "quotes":
                require_once($ABS_APPS."/quotes/classQuote.php");
                $quote = new Quote();
                $quoteData = $quote->get($_POST["entryId"]);
                // If user comments his own entry we don't have to send the notification
                if($quoteData["UserAuthor"] != $_SESSION["User"]){
                    $notification->newComment($_POST["username"], $quoteData["UserAuthor"], $_POST["entryId"], $_POST["app"]);
                }
                break;
            default:
                break;
        }
        echo "OK";
    } else {
        echo "ERROR";
    }
    break;


问:
navbar-right is not working on list
I'm new to bootstrap and in my application I want to have a navbar at the top of the page. The navbar should contain the brand name and then to the right of it it should have some options. But whenever I use navbar-right it doesn't work and the page I get looks like this

As you can see everything is squashed together with the brand name on the left hand side. What I have tried to fix this is by using pull-right which does work perfectly but I want to know why navbar-right isn't.

homeTemplate.html

```<code><body>
<nav class="navbar navbar-default">
    <div class="navbar-inner">
       <div class="container-fluid">
           <div class="navbar-header">
               <a href="#" class="navbar-brand">MyApp</a>
           </div>
           <ul class="nav navbar-nav navbar-right">
               <li><a href="#">Profile</a></li>
               <li><a href="#">Notifications</a></li>
               <li><a href="#">Messages</a></li>
               <li><a href="#">Options</a></li>
           </ul>
       </div>
   </div>
</nav>
</body>
</code>```

答:
There might be a version issue. For Bootstrap version 4, Use
 for moving element to the right.

Title: navbar-right is not working on list

Body:
I'm new to bootstrap and in my application I want to have a navbar at the top of the page. The navbar should contain the brand name and then to the right of it it should have some options. But whenever I use navbar-right it doesn't work and the page I get looks like this

As you can see everything is squashed together with the brand name on the left hand side. What I have tried to fix this is by using pull-right which does work perfectly but I want to know why navbar-right isn't.

homeTemplate.html

               MyApp

Profile

Notifications

Messages

Options

Body: There might be a version issue. For Bootstrap version 4, Use <ul class="nav navbar-nav ml-auto"> for moving element to the right.


问:
Conditional passing of a default argument to a function (using the '?' operator)
There be a function declared as

```<code>CalculateTimeSilence(float SilenceThresholdOverride = -1.f);
</code>```

Is there a way to call it, so that I can utilize the conditional '?' operator to either choose a value for SilenceThresholdOverride or leave it at the default value?

Expressed as pseudo-code:

```<code>CalculateTimeSilence(bUseOverride ? OverrideValue : default);
</code>```

, where 'default' would be replaced by the compiler, by the value the argument was defaulted to in it's declaration (-1.f in this instance).
If there were such a way, it would remove the need to match the default value or to write an If-Else statement.

Thanks,
Sebastian

答:
When you are calling the function with out specifiying the parameter, then the default is added at the call site, so when you call

```<code>CalculateTimeSilence();
</code>```

Then you are actually calling

```<code>CalculateTimeSilence(-1.f);
</code>```

There is no default or similar mechanism to get the default argument, but you can do that "manually"

```<code>const float default_value = -1.f;

CalculateTimeSilence(float SilenceThresholdOverride = default_value);
</code>```

and then you can call it as desired:

```<code>CalculateTimeSilence(bUseOverride ? OverrideValue : default_value);
</code>```

However, while the conditional operator comes in handy sometimes, often it obfuscates code and makes it difficult to read. In this case I'd perhaps rather write

```<code>auto x = bUseOverride ? OverrideValue : default_value;
CalculateTimeSilence(x);
</code>```

Body:
There be a function declared as

CalculateTimeSilence(float SilenceThresholdOverride = -1.f);

Is there a way to call it, so that I can utilize the conditional '?' operator to either choose a value for SilenceThresholdOverride or leave it at the default value?

Expressed as pseudo-code:

CalculateTimeSilence(bUseOverride ? OverrideValue : default);

, where 'default' would be replaced by the compiler, by the value the argument was defaulted to in it's declaration (-1.f in this instance).
If there were such a way, it would remove the need to match the default value or to write an If-Else statement.

Thanks,
Sebastian

Body:
When you are calling the function with out specifiying the parameter, then the default is added at the call site, so when you call

CalculateTimeSilence();

Then you are actually calling

CalculateTimeSilence(-1.f);

There is no default or similar mechanism to get the default argument, but you can do that "manually"

const float default_value = -1.f;

CalculateTimeSilence(float SilenceThresholdOverride = default_value);

and then you can call it as desired:

CalculateTimeSilence(bUseOverride ? OverrideValue : default_value);

However, while the conditional operator comes in handy sometimes, often it obfuscates code and makes it difficult to read. In this case I'd perhaps rather write

auto x = bUseOverride ? OverrideValue : default_value;
CalculateTimeSilence(x);


问:
Adding DIV Element Into IFRAME Using JavaScript
Summernote textarea change YouTube URL into  using this code :

```<code>    $video = $('<iframe>')
      .attr('src', '//www.youtube.com/embed/' + youtubeId)
      .attr('width', '640').attr('height', '360');
</code>```

and it turns the YouTube URL into this :

```<code><iframe src="//www.youtube.com/embed/_qxxxxxxc" width="640" height="360" frameborder="0"></iframe>
</code>```

but I want to insert bootstrap responsive class, so it will end like this :

```<code><div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="//www.youtube.com/embed/_qxxxxxxc" frameborder="0"></iframe>
</code>```

I tried to modify the javascript like this :

```<code>$video =
    $('<div>').attr('class','embed-responsive embed-responsive-16by9');
    $('<iframe>')
    .attr('class', 'embed-responsive-item')
    .attr('src', '//www.youtube.com/embed/' + youtubeId)
    .attr('width', '640').attr('height', '360');
</code>```

and it end up like this as result :

```<code><div class="embed-responsive embed-responsive-16by9" frameborder="0"></div>
</code>```

how to keep the iframe and add div element? thank you.

答:
As for today's date if you're using summernote v0.8.16

you may refer below code for youtube specific

```<code>$video = external_root_jQuery_commonjs2_jquery_commonjs_jquery_amd_jquery_default()('<iframe allowfulscreen allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture">').attr('frameborder', 0).attr('src', 'https://www.youtube.com/embed/' + youtubeId + (start > 0 ? '?start=' + start : ''));

$video.addClass('note-video-clip embed-responsive-item');
$video = $('<div class="embed-responsive embed-responsive-16by9"></div>').append($video);
return $video[0];
</code>```

You'll find this code line somewhere around 9000 to 9100 or you may just search for $video = hope this helps

Body:
Summernote textarea change YouTube URL into  using this code :

    $video = $('')
      .attr('src', '//www.youtube.com/embed/' + youtubeId)
      .attr('width', '640').attr('height', '360');

and it turns the YouTube URL into this :

but I want to insert bootstrap responsive class, so it will end like this :

I tried to modify the javascript like this :

$video =
    $('
').attr('class','embed-responsive embed-responsive-16by9');
    $('')
    .attr('class', 'embed-responsive-item')
    .attr('src', '//www.youtube.com/embed/' + youtubeId)
    .attr('width', '640').attr('height', '360');

and it end up like this as result :

how to keep the iframe and add div element? thank you.

Body:
As for today's date if you're using summernote v0.8.16

you may refer below code for youtube specific

$video = external_root_jQuery_commonjs2_jquery_commonjs_jquery_amd_jquery_default()('<iframe allowfulscreen allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture">').attr('frameborder', 0).attr('src', 'https://www.youtube.com/embed/' + youtubeId + (start > 0 ? '?start=' + start : ''));

$video.addClass('note-video-clip embed-responsive-item');
$video = $('<div class="embed-responsive embed-responsive-16by9"></div>').append($video);
return $video[0];

You'll find this code line somewhere around 9000 to 9100 or you may just search for $video = hope this helps


问:
Mouse not drawing in pyglet
My custom mouse image is not showing up in pyglet. It loads normally(When you create the window outside a class), but when i make the window in a class and try yo add the custom mouse cursor nothing happens

```<code>class x:
    def __init__(self):
        self.game_window = pyglet.window.Window()
        self.on_mouse_press = self.game_window.event(self.on_mouse_press)

        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.game_window.set_mouse_cursor(self.cursor)
</code>```

I have tried printing every one of the lines of code (for mouse image loading)

When i print - self.game_cursor = pyglet.image.load('image.png') - This is the result:
ImageData 85x82

When i print - self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70) - This is the result:
pyglet.window.ImageMouseCursor object at 0x7f4dad76b390

When i print - self.game_window.set_mouse_cursor(self.cursor) - This is the result:
None

How do I fix make the mouse show?

答:
I strongly suggest you inherit the window class in to your class instead of keeping it as a internal value if possible. So you can use override hooks to replace the on_ functions. Perhaps this is an outdated approach, but for the time I've learned to work with these things - it's reommended.

```<code>class x(pyglet.window.Window):
    def __init__(self):
        super(x, self).__init__()
        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.set_mouse_cursor(self.cursor)

    def on_mouse_press():
        # Your code handling on_mouse_press
</code>```

Here's a working example:

from pyglet import *
from pyglet.gl import *

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.set_mouse_cursor(self.cursor)

        self.x, self.y = 0, 0

        self.keys = {}

        self.mouse_x = 0
        self.mouse_y = 0

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_mouse_motion(self, x, y, dx, dy):
        self.mouse_x = x

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        self.keys[symbol] = True

    def render(self):
        self.clear()

        ## Add stuff you want to render here.
        ## Preferably in the form of a batch.

        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

if __name__ == '__main__':
    x = main()
    x.run()
```

Title: Mouse not drawing in pyglet

Body:
My custom mouse image is not showing up in pyglet. It loads normally(When you create the window outside a class), but when i make the window in a class and try yo add the custom mouse cursor nothing happens

class x:
    def __init__(self):
        self.game_window = pyglet.window.Window()
        self.on_mouse_press = self.game_window.event(self.on_mouse_press)

        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.game_window.set_mouse_cursor(self.cursor)

I have tried printing every one of the lines of code (for mouse image loading)

When i print - self.game_cursor = pyglet.image.load('image.png') - This is the result:
ImageData 85x82

When i print - self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70) - This is the result:
pyglet.window.ImageMouseCursor object at 0x7f4dad76b390

When i print - self.game_window.set_mouse_cursor(self.cursor) - This is the result:
None

How do I fix make the mouse show?

Body:
I strongly suggest you inherit the window class in to your class instead of keeping it as a internal value if possible. So you can use override hooks to replace the on_ functions. Perhaps this is an outdated approach, but for the time I've learned to work with these things - it's reommended.

class x(pyglet.window.Window):
    def __init__(self):
        super(x, self).__init__()
        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.set_mouse_cursor(self.cursor)

    def on_mouse_press():
        # Your code handling on_mouse_press

Here's a working example:

from pyglet import *
from pyglet.gl import *

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.set_mouse_cursor(self.cursor)

        self.x, self.y = 0, 0

        self.keys = {}

        self.mouse_x = 0
        self.mouse_y = 0

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_mouse_motion(self, x, y, dx, dy):
        self.mouse_x = x

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        self.keys[symbol] = True

    def render(self):
        self.clear()

        ## Add stuff you want to render here.
        ## Preferably in the form of a batch.

        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

if __name__ == '__main__':
    x = main()
    x.run()


问:
Using ProjectDelegate `gradle` within the `plugins` DSL
As titled, this:

```<code>plugins {
   if (gradle.gradleVersion < "6.0")
      id("ru.vyarus.quality").version("4.3.0")
}
</code>```

returns:

Unresolved reference: gradle

gradle is also marked as an error, and hovering the mouse above I get:

'val Build_gradle.gradle: Gradle' can't be called in this context by implicit receiver. Use the explicit one if necessary

Googling around, I tried specifying the receiver:

```<code>plugins {
   if (this@Build_gradle.gradle.gradleVersion < "6.0")
      id("ru.vyarus.quality").version("4.3.0")
}
</code>```

But it fires:

Unresolved reference: getGradle

Is there a way? (other than declaring an outside variable just for that)

答:
From Limitations of the plugins DSL:

This requires that plugins be specified in a way that Gradle can easily and quickly extract, before executing the rest of the build script. It also requires that the definition of plugins to use be somewhat static.

The plugins {} block does not support arbitrary code. It is constrained, in order to be idempotent (produce the same result every time) and side effect free (safe for Gradle to execute at any time).

In fact, your build script is evaluated against CompiledKotlinPluginsBlock for the plugins block, and CompiledKotlinBuildScript for the rest. So this@Build_gradle doesn't always refer to the same object. You can see this by printing the superclass at different places:

```<code>println(this@Build_gradle::class.java.superclass)
</code>```

And as it turns out CompiledKotlinPluginsBlock doesn't have a getGradle() method.

It's great to know why that happens, but finding a solution wasn't so easy. You can't add a variable outside of plugins {} because it won't be reachable. One way would be to have a static field in your buildSrc folder, but it would be weird needing it only for that.

Here's something I found that works. In your root build.gradle.kts add:

```<code>plugins {
    id("ru.vyarus.quality") version "4.3.0" apply false
}

project(":yourModule") {
    if (gradle.gradleVersion < "6.0") {
        apply(plugin = "ru.vyarus.qualit")
    }
}
</code>```

I wish it didn't need the old apply(plugin = way, but that's the only solution I found. You don't need anything special in your module's plugins {}.

Body:
As titled, this:

plugins {
   if (gradle.gradleVersion < "6.0")
      id("ru.vyarus.quality").version("4.3.0")
}

returns:

Unresolved reference: gradle

gradle is also marked as an error, and hovering the mouse above I get:

'val Build_gradle.gradle: Gradle' can't be called in this context by implicit receiver. Use the explicit one if necessary

Googling around, I tried specifying the receiver:

plugins {
   if (this@Build_gradle.gradle.gradleVersion < "6.0")
      id("ru.vyarus.quality").version("4.3.0")
}

But it fires:

Unresolved reference: getGradle

Is there a way? (other than declaring an outside variable just for that)

Body:
From Limitations of the plugins DSL:

This requires that plugins be specified in a way that Gradle can easily and quickly extract, before executing the rest of the build script. It also requires that the definition of plugins to use be somewhat static.

The plugins {} block does not support arbitrary code. It is constrained, in order to be idempotent (produce the same result every time) and side effect free (safe for Gradle to execute at any time).

In fact, your build script is evaluated against CompiledKotlinPluginsBlock for the plugins block, and CompiledKotlinBuildScript for the rest. So this@Build_gradle doesn't always refer to the same object. You can see this by printing the superclass at different places:

println(this@Build_gradle::class.java.superclass)

And as it turns out CompiledKotlinPluginsBlock doesn't have a getGradle() method.

It's great to know why that happens, but finding a solution wasn't so easy. You can't add a variable outside of plugins {} because it won't be reachable. One way would be to have a static field in your buildSrc folder, but it would be weird needing it only for that.

Here's something I found that works. In your root build.gradle.kts add:

plugins {
    id("ru.vyarus.quality") version "4.3.0" apply false
}

project(":yourModule") {
    if (gradle.gradleVersion < "6.0") {
        apply(plugin = "ru.vyarus.qualit")
    }
}

I wish it didn't need the old apply(plugin = way, but that's the only solution I found. You don't need anything special in your module's plugins {}.


问:
How can I estimate how many Cassandra nodes I need for a given read requests per second load?
I wish to estimate how many cassandra storage nodes I would need to serve a specific number of reads per second.

My node specs are 32 cores, 256GB ram, 10Gbps NIC, 10x 6TB HDDs. Obviously SSDs would be much more preferrable, but these are not available in this instance.

I have around 5x10^11 values of 1kB each = 500TB of values to serve, at a rate of 100,000 read requests per second. The distribution of these requests is completely even, ie, ram capacity caching will have no effect.

If we assume that each HDD can sustain ~100 IOps, then I could expect that I need at least ~ 100 nodes to serve this read load - correct?

I also estimate that I would need at least ~ 20 machines for the total storage with a replication factor of 2, plus overhead.

答:
It's a really broad question - you need to try to test your machines with tools, like, NoSQLBench that was specially built for such tasks.

Typical recommendation is to store ~1Tb of data per Cassandra node (including replication). You need to take into account other factors, like, how long it will take to replace the node in the cluster, or add new one - the speed of streaming is directly proportional to size of data on disk.

HDDs are really not recommended if you want to have low latency answers. I have a client with ~150Tb spread over ~30 machines with HDDs, with a lot of writes although, and read latencies regularly are going above 0.5 second, and higher.  You need to take into account that Cassandra requires random access to data, and head of HDD simply couldn't move so fast to serve requests.


问:
Compare two object arrays and get the difference in Javascript
I have two arrays of objects:

```<code>\\offers
[
{DeskUID: "B11A13", Day: 06 Jun 2020}
{DeskUID: "B11A13", Day: 07 Jun 2020}
{DeskUID: "B12B34", Day: 23 Jun 2020}
]

\\reservations
[
{DeskUID: "B11A13", Day: 06 Jun 2020, Name: "Mike"}
{DeskUID: "B12B34", Day: 23 Jun 2020, Name: "Ali"}
]
</code>```

I would like to have a result where are available offers, that means only the offers without already reserved desks.

```<code>\\result
[
{DeskUID: "B11A13", Day: 07 Jun 2020}
]
</code>```

How to get the difference between two arrays of objects in JavaScript

I already tried solutions on the link above but without success, I just got a result array as sum of all objects from the two arrays.

```<code>            function comparer(otherArray){
                return function(current){
                var reserveDay = new Date (current.Day)
                    return otherArray.filter(function(other){
                        var offerDay = new Date (other.Day)
                        return other.DeskUID == current.DeskUID && offerDay == reserveDay
                    }).length == 0;
                }
            }

            var onlyInA = offers.filter(comparer(reservations));
            var onlyInB = reservations.filter(comparer(offers));

            result = onlyInA.concat(onlyInB);
</code>```

答:
You can simply filter it with some inside it.

var offers = [{ DeskUID: "B11A13", Day: "2020-06-06" }, { DeskUID: "B11A13", Day: "2020-06-07" }, { DeskUID: "B12B34", Day: "2020-06-23" }];
var reservations = [{ DeskUID: "B11A13", Day: "2020-06-06", Name: "Mike" }, { DeskUID: "B12B34", Day: "2020-06-23", Name: "Ali" }];

var result = offers.filter(k=>!reservations.some(d=>d.DeskUID == k.DeskUID && d.Day==k.Day));

console.log(result);```

Body:
I have two arrays of objects:

\\offers
[
{DeskUID: "B11A13", Day: 06 Jun 2020}
{DeskUID: "B11A13", Day: 07 Jun 2020}
{DeskUID: "B12B34", Day: 23 Jun 2020}
]

\\reservations
[
{DeskUID: "B11A13", Day: 06 Jun 2020, Name: "Mike"}
{DeskUID: "B12B34", Day: 23 Jun 2020, Name: "Ali"}
]

I would like to have a result where are available offers, that means only the offers without already reserved desks.

\\result
[
{DeskUID: "B11A13", Day: 07 Jun 2020}
]

How to get the difference between two arrays of objects in JavaScript

I already tried solutions on the link above but without success, I just got a result array as sum of all objects from the two arrays.

            function comparer(otherArray){
                return function(current){
                var reserveDay = new Date (current.Day)
                    return otherArray.filter(function(other){
                        var offerDay = new Date (other.Day)
                        return other.DeskUID == current.DeskUID && offerDay == reserveDay
                    }).length == 0;
                }
            }

            var onlyInA = offers.filter(comparer(reservations));
            var onlyInB = reservations.filter(comparer(offers));

            result = onlyInA.concat(onlyInB);


问:
Assembly move instruction seems to be useless
I'am trying to learn assembly. I disassembled a simple C program and debugged it with gdb. But one thing I've noticed is that values are moved very frequent.

```<code>   0x0000555555555231 <+0>:     push   rbp
   0x0000555555555232 <+1>:     mov    rbp,rsp
   0x0000555555555235 <+4>:     sub    rsp,0x20

   0x0000555555555239 <+8>:     mov    QWORD PTR [rbp-0x18],rdi
   0x000055555555523d <+12>:    mov    QWORD PTR [rbp-0x20],rsi
   0x0000555555555241 <+16>:    mov    rax,QWORD PTR [rbp-0x18]
   0x0000555555555245 <+20>:    mov    rdi,rax
   0x0000555555555248 <+23>:    call   0x5555555551d9 <get_file_size>
</code>```

rdi's value gets moved to the stack at rbp-0x18 (at <+8>), rsi's value to the stack at rbp-0x20 (+12). Then the value at rbp-0x18 gets moved to rax(+16) which will be moved to rdi again(+20). Why is this done? Why not just using rdi or at least moving rbp-0x18 to rdi directly instead via rax (at <+16>)? This could save the instruction at +20

答:
The compilation without any optimisations enabled does not have to much sense if you want to learn some assembler from it.

Here you have an example how the optimizations can change the generated code.

https://godbolt.org/z/YBdLRZ

```<code>char *foo(char *dest, const char *src, size_t len)
{
    char *savedDest = dest;
    size_t index = 0;
    if(len)
    {
        while(--len && (dest[index] = src[index]));
        index++;
        *dest = 0;
    }
    return savedDest;
}
</code>```

No optimizations

```<code>foo:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-24], rdi
        mov     QWORD PTR [rbp-32], rsi
        mov     QWORD PTR [rbp-40], rdx
        mov     rax, QWORD PTR [rbp-24]
        mov     QWORD PTR [rbp-8], rax
        mov     QWORD PTR [rbp-16], 0
        cmp     QWORD PTR [rbp-40], 0
        je      .L2
.L4:
        sub     QWORD PTR [rbp-40], 1
        cmp     QWORD PTR [rbp-40], 0
        je      .L3
        mov     rdx, QWORD PTR [rbp-32]
        mov     rax, QWORD PTR [rbp-16]
        add     rdx, rax
        mov     rcx, QWORD PTR [rbp-24]
        mov     rax, QWORD PTR [rbp-16]
        add     rax, rcx
        movzx   edx, BYTE PTR [rdx]
        mov     BYTE PTR [rax], dl
        movzx   eax, BYTE PTR [rax]
        test    al, al
        jne     .L4
.L3:
        add     QWORD PTR [rbp-16], 1
        mov     rax, QWORD PTR [rbp-24]
        mov     BYTE PTR [rax], 0
.L2:
        mov     rax, QWORD PTR [rbp-8]
        pop     rbp
        ret
</code>```

and optimize of size

```<code>foo:
        mov     rax, rdi
        test    rdx, rdx
        je      .L2
.L4:
        dec     rdx
        je      .L3
        mov     cl, BYTE PTR [rsi]
        mov     BYTE PTR [rax], cl
        test    cl, cl
        jne     .L4
.L3:
        mov     BYTE PTR [rax], 0
.L2:
        ret
</code>```

Body:
I'am trying to learn assembly. I disassembled a simple C program and debugged it with gdb. But one thing I've noticed is that values are moved very frequent.

   0x0000555555555231 <+0>:     push   rbp
   0x0000555555555232 <+1>:     mov    rbp,rsp
   0x0000555555555235 <+4>:     sub    rsp,0x20

   0x0000555555555239 <+8>:     mov    QWORD PTR [rbp-0x18],rdi
   0x000055555555523d <+12>:    mov    QWORD PTR [rbp-0x20],rsi
   0x0000555555555241 <+16>:    mov    rax,QWORD PTR [rbp-0x18]
   0x0000555555555245 <+20>:    mov    rdi,rax
   0x0000555555555248 <+23>:    call   0x5555555551d9 <get_file_size>

rdi's value gets moved to the stack at rbp-0x18 (at <+8>), rsi's value to the stack at rbp-0x20 (+12). Then the value at rbp-0x18 gets moved to rax(+16) which will be moved to rdi again(+20). Why is this done? Why not just using rdi or at least moving rbp-0x18 to rdi directly instead via rax (at <+16>)? This could save the instruction at +20

Body:
The compilation without any optimisations enabled does not have to much sense if you want to learn some assembler from it.

Here you have an example how the optimizations can change the generated code.

https://godbolt.org/z/YBdLRZ

char *foo(char *dest, const char *src, size_t len)
{
    char *savedDest = dest;
    size_t index = 0;
    if(len)
    {
        while(--len && (dest[index] = src[index]));
        index++;
        *dest = 0;
    }
    return savedDest;
}

No optimizations

foo:
        push    rbp
        mov     rbp, rsp
        mov     QWORD PTR [rbp-24], rdi
        mov     QWORD PTR [rbp-32], rsi
        mov     QWORD PTR [rbp-40], rdx
        mov     rax, QWORD PTR [rbp-24]
        mov     QWORD PTR [rbp-8], rax
        mov     QWORD PTR [rbp-16], 0
        cmp     QWORD PTR [rbp-40], 0
        je      .L2
.L4:
        sub     QWORD PTR [rbp-40], 1
        cmp     QWORD PTR [rbp-40], 0
        je      .L3
        mov     rdx, QWORD PTR [rbp-32]
        mov     rax, QWORD PTR [rbp-16]
        add     rdx, rax
        mov     rcx, QWORD PTR [rbp-24]
        mov     rax, QWORD PTR [rbp-16]
        add     rax, rcx
        movzx   edx, BYTE PTR [rdx]
        mov     BYTE PTR [rax], dl
        movzx   eax, BYTE PTR [rax]
        test    al, al
        jne     .L4
.L3:
        add     QWORD PTR [rbp-16], 1
        mov     rax, QWORD PTR [rbp-24]
        mov     BYTE PTR [rax], 0
.L2:
        mov     rax, QWORD PTR [rbp-8]
        pop     rbp
        ret

and optimize of size

foo:
        mov     rax, rdi
        test    rdx, rdx
        je      .L2
.L4:
        dec     rdx
        je      .L3
        mov     cl, BYTE PTR [rsi]
        mov     BYTE PTR [rax], cl
        test    cl, cl
        jne     .L4
.L3:
        mov     BYTE PTR [rax], 0
.L2:
        ret


问:
What is the difference between a normal file download and a PHP-driven download?
Is there a difference between directly downloading a file from a web server, and downloading the same file through a PHP script that uses these headers?  (Assume that all of the variables here contain correct values for the file being downloaded.)

```<code>header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
</code>```

After reading the discussion here, i want to change the question :

With a file on server for user who can download.

What & when do we need to process this task by PHP script?

Same question with direct link of file

答:
If your "normal" download would supply those exact headers, then no.

However, a number of things could cause the server to decide to send different headers:

If gzip is turned on (and browser accepts it)

If the request sent an If-Modified-Since header and the content has not been modified

If the server decides to send a Last-Modified time

If the server has some other sort of cache-control logic

Body:
Is there a difference between directly downloading a file from a web server, and downloading the same file through a PHP script that uses these headers?  (Assume that all of the variables here contain correct values for the file being downloaded.)

header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

After reading the discussion here, i want to change the question :

With a file on server for user who can download.

What & when do we need to process this task by PHP script?

Same question with direct link of file


Title: reducing a nested object in javascript

Body:
I have an object with the structure

"Office": {
    "California" : {
        "Contract1": {
            1: {Price: 1000, Count: 5},
            2: {Price: 2000, Count: 11},
            3: {Price: 3000, Count: 3},
            4: {Price: 2000, Count: 1},...
        },
        "Contract2": {
            1: {Price: 7000, Count: 6},
            2: {Price: 1000, Count: 4},
            3: {Price: 67000, Count: 6},
            4: {Price: 500, Count: 2},...
        },
        "Contract3": {
            1: {Price: 4000, Count: 4},
            2: {Price: 4000, Count: 1},
            3: {Price: 5000, Count: 12},
            4: {Price: 5000, Count: 2},...
        }
    },
    "North Carolina" : {
        "Contract1": {
            1: {Price: 7000, Count: 4},
            2: {Price: 7000, Count: 4},
            3: {Price: 7000, Count: 4},
            4: {Price: 7000, Count: 4},...
        },
        "Contract2": {
            1: {Price: 6000, Count: 4},
            2: {Price: 2000, Count: 10},
            3: {Price: 3000, Count: 3},
            4: {Price: 2000, Count: 3},...
        },
        "Contract3": {
            1: {Price: 4000, Count: 5},
            2: {Price: 2000, Count: 4},
            3: {Price: 4000, Count: 3},
            4: {Price: 2000, Count: 4},...
        },...
}

And I want to reduce it to this:

"Office": {
    "California" : {
        "Contract1": {
            1: {Price: 6000, Count: 19},
            2: {Price: 2000, Count: 1},...
        },
        "Contract2": {
            1: {Price: 75000, Count: 16},
            2: {Price: 500, Count: 2},...
        },
        "Contract3": {
            1: {Price: 13000, Count: 17},
            2: {Price: 5000, Count: 2},...
        }
    },
    "North Carolina" : {
        "Contract1": {
            1: {Price: 21000, Count: 12},
            2: {Price: 7, Count: 4},...
        },
        "Contract2": {
            1: {Price: 11000, Count: 17},
            2: {Price: 2000, Count: 3},...
        },
        "Contract3": {
            1: {Price: 10000, Count: 12},
            2: {Price: 2000, Count: 4},...
        },...
}

The number objects under each contract on the first structure represent the months past. In the second structure I want to sum up the properties of the first 3 number objects can call this 1. Then the second 3 would be 2. These are quarters.

I think I can do this with some sort of combination of map, reduce and filter but these are array functions and I have an object so I’m not sure how to do it. I need to do this for a non ES6 solution.

Any guidance would be really appreciated.

Body:
Based on count it will dynamically populate your required output

  const data = { "Office": {
"California" : {
    "Contract1": {
        1: {Price: 1000, Count: 5}, 2: {Price: 2000, Count: 11},
        3: {Price: 3000, Count: 3}, 4: {Price: 2000, Count: 1},
        5: {Price: 1000, Count: 5}, 6: {Price: 2000, Count: 11},
        7: {Price: 3000, Count: 3}, 8: {Price: 2000, Count: 1},
        9: {Price: 1000, Count: 5}, 10: {Price: 2000, Count: 11},
        11: {Price: 3000, Count: 3}, 12: {Price: 2000, Count: 1},
    },
    "Contract2": {
        1: {Price: 7000, Count: 6}, 2: {Price: 1000, Count: 4},
        3: {Price: 67000, Count: 6}, 4: {Price: 500, Count: 2},
        5: {Price: 7000, Count: 6}, 6: {Price: 1000, Count: 4},
        7: {Price: 67000, Count: 6}, 8: {Price: 500, Count: 2},
        9: {Price: 7000, Count: 6}, 10: {Price: 1000, Count: 4},
        11: {Price: 67000, Count: 6}, 12: {Price: 500, Count: 2},
    },
    "Contract3": {
        1: {Price: 4000, Count: 4}, 2: {Price: 4000, Count: 1},
        3: {Price: 5000, Count: 12}, 4: {Price: 5000, Count: 2},
        5: {Price: 4000, Count: 4}, 6: {Price: 4000, Count: 1},
        7: {Price: 5000, Count: 12}, 8: {Price: 5000, Count: 2},
        9: {Price: 4000, Count: 4}, 10: {Price: 4000, Count: 1},
        11: {Price: 5000, Count: 12}, 12: {Price: 5000, Count: 2},
    }
},
"North Carolina" : {
    "Contract1": {
        1: {Price: 7000, Count: 4}, 2: {Price: 7000, Count: 4},
        3: {Price: 7000, Count: 4}, 4: {Price: 7000, Count: 4},
        5: {Price: 7000, Count: 4}, 6: {Price: 7000, Count: 4},
        7: {Price: 7000, Count: 4}, 8: {Price: 7000, Count: 4},
        9: {Price: 7000, Count: 4}, 10: {Price: 7000, Count: 4},
        11: {Price: 7000, Count: 4}, 12: {Price: 7000, Count: 4},
    },
    "Contract2": {
        1: {Price: 6000, Count: 4}, 2: {Price: 2000, Count: 10},
        3: {Price: 3000, Count: 3}, 4: {Price: 2000, Count: 3},
        5: {Price: 6000, Count: 4}, 6: {Price: 2000, Count: 10},
        7: {Price: 3000, Count: 3}, 8: {Price: 2000, Count: 3},
        9: {Price: 6000, Count: 4}, 10: {Price: 2000, Count: 10},
        11: {Price: 3000, Count: 3}, 12: {Price: 2000, Count: 3},
    },
    "Contract3": {
        1: {Price: 4000, Count: 5}, 2: {Price: 2000, Count: 4},
        3: {Price: 4000, Count: 3}, 4: {Price: 2000, Count: 4},
        5: {Price: 4000, Count: 5}, 6: {Price: 2000, Count: 4},
        7: {Price: 4000, Count: 3}, 8: {Price: 2000, Count: 4},
        9: {Price: 4000, Count: 5}, 10: {Price: 2000, Count: 4},
        11: {Price: 4000, Count: 3}, 12: {Price: 2000, Count: 4},
    },
},
} }

let count = 3;
for(var parent in data['Office']){
  let child1 = data['Office'][parent];
  for(var con in child1){
    child1[con] = Object.keys(child1[con]).reduce((acc,ele,index)=>{
        let key = Math.trunc(index / count);
       return {...acc,...{[key+1]: (key+1 in acc) ? {Price:acc[key+1]['Price']+child1[con][ele]['Price'],Count:acc[key+1]['Count']+child1[con][ele]['Count']} : child1[con][ele]}}
    },{})
  }
}
console.log(data)


问:
How to execute mongodb find query in a loop in nodejs
I am trying to execute mongodb find query in a loop.
I have an object with some properties. The value of each property will be checked in the mongodb to get its
updated value. Once all the property values are updated, i want to perform some other actions.

But before getting the updated object(updatedVehObj), the next line of code (function updatedVehicleData )
is getting executed and its throwing some error,since i dont have the updated values.

Thanks in advance for any help to solve this issue or any better methods for achieving this result.

```<code>const processVehData = async (vehData) => {
  const vehObj = {
    make: 'AUD',
    model: 'A12',
    type: 'S',
  }
  const updatedVehObj = await getDBMapping(vehObj)
  // Do some preocessing with the updated vehicle obj
  const processedDataRes = updatedVehicleData(updatedVehObj)
  return processedDataRe;
}

const getDBMapping = async (vehObj) => {
  let updatedVeh = {}
  MongoClient.connect(connectionStr, mongoOptions, async (err, client) => {
    if (err) {
      console.log('Error in connecting to DB')
    }
    const dbo = client.db('VehicleDataBase')
    for (const key of Object.keys(vehObj)) {
      // Iterating every element in the object
      await dbo
        .collection(key)  // key name will be the collection name in mongodb
        .find({
          code: vehObj[key],
        })
        .toArray()
        .then(result => {
          updatedVeh[key] = result[0] // Framing new object with updated values
        })
        .catch(err => {
          console.log(' Error in getting mapping', err)
        })
    }
    return updatedVeh;
    /*** Expected result
      updatedVeh = {
        "make": "AUDI",
        "model" : "A3 Auto",
        "type" : "Sedan"
      }
    ****/
  })
}

const updatedVehicleData = vehData => {
  // Do something
}

</code>```

答:
Your problem came from the callback of MongoClient.connect(), when performing await getDBMapping(vehObj) you are not waiting for something to be resolved.

Also, you combined await and then on update queries.

A solution could be to use a Promise in getDBMapping function :

const getDBMapping = async (vehObj) => new Promise((resolve, reject) => {
  let updatedVeh = {}
  MongoClient.connect(connectionStr, mongoOptions, async (err, client) => {
    if (err) {
      console.log('Error in connecting to DB')
      return reject(err); // reject is there is an error
    }

    const dbo = client.db('VehicleDataBase')
    for (const key of Object.keys(vehObj)) {
      // use try / catch instead of combined await / then
      try {
        const result = await dbo
          .collection(key)
          .find({
            code: vehObj[key],
          })
          .toArray();

        updatedVeh[key] = result[0];
      } catch (err) {
        console.log('Error in getting mapping', err)
        // reject(err); => you can also reject here, but it could break batch update transaction
      }
    }

    return resolve(updatedVeh);
  })
});
```

Body:
I am trying to execute mongodb find query in a loop.
I have an object with some properties. The value of each property will be checked in the mongodb to get its
updated value. Once all the property values are updated, i want to perform some other actions.

But before getting the updated object(updatedVehObj), the next line of code (function updatedVehicleData )
is getting executed and its throwing some error,since i dont have the updated values.

Thanks in advance for any help to solve this issue or any better methods for achieving this result.

const processVehData = async (vehData) => {
  const vehObj = {
    make: 'AUD',
    model: 'A12',
    type: 'S',
  }
  const updatedVehObj = await getDBMapping(vehObj)
  // Do some preocessing with the updated vehicle obj
  const processedDataRes = updatedVehicleData(updatedVehObj)
  return processedDataRe;
}

const getDBMapping = async (vehObj) => {
  let updatedVeh = {}
  MongoClient.connect(connectionStr, mongoOptions, async (err, client) => {
    if (err) {
      console.log('Error in connecting to DB')
    }
    const dbo = client.db('VehicleDataBase')
    for (const key of Object.keys(vehObj)) {
      // Iterating every element in the object
      await dbo
        .collection(key)  // key name will be the collection name in mongodb
        .find({
          code: vehObj[key],
        })
        .toArray()
        .then(result => {
          updatedVeh[key] = result[0] // Framing new object with updated values
        })
        .catch(err => {
          console.log(' Error in getting mapping', err)
        })
    }
    return updatedVeh;
    /*** Expected result
      updatedVeh = {
        "make": "AUDI",
        "model" : "A3 Auto",
        "type" : "Sedan"
      }
    ****/
  })
}

const updatedVehicleData = vehData => {
  // Do something
}