问:
Delegates and protocols with VC not connected
I have a parent view controller i.e. HomeViewController which has a navigation bar button via which a user can trigger an alert and enter a string. This string needs to be passed to the child view controller.

Here is the relevant code in the parent view controller:

```<code>protocol NewSectionDelegate {
    func sendSectionName(name : String)
}

class HomeViewController: UIViewController {
var sectionNameDelegate : NewSectionDelegate?

func addCardAsChild() { // add the child VC to the parent VC
if cardViewController == nil {
                cardViewController = CardViewController()
                addViewController(newViewController: cardViewController!)
            } else {
                addViewController(newViewController: cardViewController!)
            }
}

func triggerAlert() {
let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
                alertController.addTextField(configurationHandler:
                    {(_ textField: UITextField) -> Void in //txtview customization
                    })

                let addAction = UIAlertAction(title: "Add", style: .default) { _ in
                    guard let sectionName = alertController.textFields?.first?.text else { return }
                    self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
                }

                alertController.addAction(addAction)
                self.present(alertController, animated: true, completion: nil)
}
</code>```

And here is the child view controller:

```<code>class CardViewController: UIViewController,  NewSectionDelegate {

override func viewDidLoad() {
        super.viewDidLoad()
        let homeViewController = HomeViewController()
        homeViewController.sectionNameDelegate = self
     }

    func sendSectionName(name: String) {
print("received name:\(name)") // This line of code is never called
}
</code>```

The data is not getting passed and I have no idea why.

答:
Is this what you are looking for?</p>

```<code>protocol NewSectionDelegate {
    func sendSectionName(name : String)
}

class HomeViewController: UIViewController {
    var sectionNameDelegate : NewSectionDelegate?
    var cardViewController = CardViewController()

    func addCardAsChild() { // add the child VC to the parent VC
        self.addChild(self.cardViewController)
    }

    func triggerAlert() {
        let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
        alertController.addTextField(configurationHandler:
            {(_ textField: UITextField) -> Void in //txtview customization
        })

        let addAction = UIAlertAction(title: "Add", style: .default) { _ in
            guard let sectionName = alertController.textFields?.first?.text else { return }
            self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
        }

        alertController.addAction(addAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

class CardViewController: UIViewController,  NewSectionDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let homeViewController = self.parent as? HomeViewController else { return }
        homeViewController.sectionNameDelegate = self
    }

    func sendSectionName(name: String) {
        print("received name:\(name)") // This line of code is never called
    }
}
</code>```

Body:
I have a parent view controller i.e. HomeViewController which has a navigation bar button via which a user can trigger an alert and enter a string. This string needs to be passed to the child view controller.

Here is the relevant code in the parent view controller:

protocol NewSectionDelegate {
    func sendSectionName(name : String)
}

class HomeViewController: UIViewController {
var sectionNameDelegate : NewSectionDelegate?

func addCardAsChild() { // add the child VC to the parent VC
if cardViewController == nil {
                cardViewController = CardViewController()
                addViewController(newViewController: cardViewController!)
            } else {
                addViewController(newViewController: cardViewController!)
            }
}

func triggerAlert() {
let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
                alertController.addTextField(configurationHandler:
                    {(_ textField: UITextField) -> Void in //txtview customization
                    })

                let addAction = UIAlertAction(title: "Add", style: .default) { _ in
                    guard let sectionName = alertController.textFields?.first?.text else { return }
                    self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
                }

                alertController.addAction(addAction)
                self.present(alertController, animated: true, completion: nil)
}

And here is the child view controller:

class CardViewController: UIViewController,  NewSectionDelegate {

override func viewDidLoad() {
        super.viewDidLoad()
        let homeViewController = HomeViewController()
        homeViewController.sectionNameDelegate = self
     }

    func sendSectionName(name: String) {
print("received name:\(name)") // This line of code is never called
}

The data is not getting passed and I have no idea why.

Body:
Is this what you are looking for?

protocol NewSectionDelegate {
    func sendSectionName(name : String)
}

class HomeViewController: UIViewController {
    var sectionNameDelegate : NewSectionDelegate?
    var cardViewController = CardViewController()

    func addCardAsChild() { // add the child VC to the parent VC
        self.addChild(self.cardViewController)
    }

    func triggerAlert() {
        let alertController = UIAlertController(title: "New section", message: "Name the section with a words or a sentence", preferredStyle: .alert)
        alertController.addTextField(configurationHandler:
            {(_ textField: UITextField) -> Void in //txtview customization
        })

        let addAction = UIAlertAction(title: "Add", style: .default) { _ in
            guard let sectionName = alertController.textFields?.first?.text else { return }
            self.sectionNameDelegate?.sendSectionName(name: sectionName) // Sending string; verified that the string is not nil
        }

        alertController.addAction(addAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

class CardViewController: UIViewController,  NewSectionDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let homeViewController = self.parent as? HomeViewController else { return }
        homeViewController.sectionNameDelegate = self
    }

    func sendSectionName(name: String) {
        print("received name:\(name)") // This line of code is never called
    }
}


来源: stackexchange

问:
Email date parser when right click on browser
[EDIT] I rewrote the question to mention specifically the context menu. Thanks for the remark.

I'm looking to create a date parser for email, so that in case of text selection and right click, there will be an option in the context menu to identify the selected text (say 7/6/2011 10:30 meeting with John) and add to my calendar (I'm using Google's calendar).

I was thinking of developing such a thing in Javascript, is there a way to hook up to the right-click context menu of the browser without the use of extensions?
Or it's better to create desktop application that hooks up to the "copy" event?
Is there a library for date parsing on Javascript or others?

Thanks in advance.

答:
As you're probably aware, all browsers use the right mouse button to pop up a context menu.

Most browsers allow you to disable this feature via Javascript, but a few do not -- notably Opera. In older versions of Opera it was simply not possible to use right click in Javascript. In newer versions it is possible, but the feature still had to be switched on by the user in their browser configuration. Only in very recent versions has this feature defaulted to being switched on.

Therefore, if any of your users are running Opera, you will likely have problems with any functionality you imlement for the right-click.

There's quite a detailed write up of this issue here: http://unixpapa.com/js/mouse.html

To answer the final part of your question: You asked if there's a decent date parser library for Javascript. Obviously you know about JS's built-in Date object, but that can only get you so far. For more advanced parsing, I recommend checking out this library: http://www.datejs.com/

ContentLicense: CC BY-SA 3.0


问:
Multi-task learning with mutually exclusive tasks?

I wish to perform multi-task learning by performing segmentation and classification using shared layers as shown in the figure. However, the output 1 will be a segmentation mask that works with a different loss function like Dice loss and output 2 works with softmax activations to deliver class probabilities. Also, the data are mutually exclusive, the segmentation task comes from natural image domain, and classification from medical image domain. Is Keras or Pytorch have a defined way or examples demonstrating such multi-task learning tasks?

答:
I suppose you want to alternate between the two tasks while training.

I will also assume you are going to mix the two tasks within the same batch.

You can make a custom Dataset that returns

class MixedDataset(Dataset):
  # ...
  def __getitem__(self, index):
    # ... get data according to index
    return img, seg, seg_flag, class, class_flag
```

<p>for medical images the <code>seg</code> is going to be a dummy mask and the <code>seg_flag</code> is going to be zero, while the <code>class</code> is going to be the target class and <code>class_flag</code> is 1.<br>
On the other hand, for natural images <code>seg</code> is going to be the desired segmentation mask and <code>seg_flag</code> is 1, while <code>class</code> is going to be a dummy and <code>class_flag</code> is zero.</p>

<p>Now you can run your training code:</p>

<pre class="lang-py prettyprint-override"><code>for i, (img, seg, seg_flag, class, class_flag) in train_loader:
  opt.zero_grad()
  pred_mask, pred_class = model(img)  # predict both
  loss_seg = seg_flag * dice_loss_fuction(pred_mask, seg)
  loss_class = class_flag * cross_entropy_loss_function(pred_class, class)
  (loss_seg + loss_class).backward()
  opt.step()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I suppose you want to alternate between the two tasks while training.

I will also assume you are going to mix the two tasks within the same batch.

You can make a custom Dataset that returns

class MixedDataset(Dataset):
  # ...
  def __getitem__(self, index):
    # ... get data according to index
    return img, seg, seg_flag, class, class_flag

for medical images the seg is going to be a dummy mask and the seg_flag is going to be zero, while the class is going to be the target class and class_flag is 1.

On the other hand, for natural images seg is going to be the desired segmentation mask and seg_flag is 1, while class is going to be a dummy and class_flag is zero.

Now you can run your training code:

for i, (img, seg, seg_flag, class, class_flag) in train_loader:
  opt.zero_grad()
  pred_mask, pred_class = model(img)  # predict both
  loss_seg = seg_flag * dice_loss_fuction(pred_mask, seg)
  loss_class = class_flag * cross_entropy_loss_function(pred_class, class)
  (loss_seg + loss_class).backward()
  opt.step()


问:
How to color one of a 100 boxes with a button in a modal using javascript
Just to make it easier Im explaining what I wish to do in a simplified example.

I have 100 boxes on my site using simple html/css. (styling not shown)

I have written a bit of JS to open a modal that opens when clicking on one of the 100 boxes carrying the same class: class="boxes":

The modal has an Id of "modal":

```<code>var modal = document.getElementById("modal");
var boxes = document.getElementsByClassName("box");
var boxesLength = boxes.length;
</code>```

When any box is clicked the modal appears:

```<code>    for (var i = 0; i < boxesLength; i++) {
    boxes[i].onclick = function () {
    modal.style.display = "block";
    };
    }
</code>```

Now I wish to color the box  that was clicked using a button in the modal that was opened. The code that doesn't work but is my closest guess looks like this:

```<code>//get the coloring button in the modal which has Id of "green".

var coloring = document.getElementById("green");

coloring.onclick = function () {
boxes[i].style.backgroundColor = "#90EE90";
//closing the modal after clicking which works
modal.style.display = "none";
};
</code>```

Writing "boxes[0]" will color the first box, but that is of course not what I wish. I wish to color the box that was clicked.

Thank you for any input. Good day!

on request ive added som simple html

```<code>    //The modal
    <div id="modal">
            <button id="green">Completed</button>
    </div>

    //just some boxes
    <div class="boxes"></div>
    <div class="boxes"></div>
    <div class="boxes"></div>
    <div class="boxes"></div>
    .... 96 more boxes
</code>```

答:
In accordance to how I understood your issue.You want the background color to show on the box that was clicked for it to show the modal.
Here is my solution.

//to pass it as a global variable between functions
var randomv = {}
 var modal = document.getElementById("modal");
 var close = document.querySelector('.close')

//get all box
var x = document.getElementById("innerBox").querySelectorAll(".box");
  //for each box execute the following
  x.forEach(box => {
    //on clicking each box, execute a function
    box.addEventListener("click", function () {
      //this references the parent element which in this case is the box
      randomv.parent = this
      //display the modal on clicking the box
      modal.style.display = "block";
    })
  });

//hide the modal on clicking the x
close.addEventListener("click", function(){
 modal.style.display = "none"
});

  function changeColor() {
  //first ensure the background color is normal for each box
    x.forEach(box => {
      box.style.backgroundColor = "white";
    });
  //reserve the parent element to a variable
    var parent_div = randomv.parent
   //change the parent's bg color
    parent_div.style.backgroundColor = "green";
  }
</script>```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #modal {
      display: none;
    }

    #innerBox {
      width: 100vw;
      display: flex;

    }
    .box{
      flex-grow: 1;

    }
    .close,.box{
     cursor: pointer;
    }</code>```

model content

 x

      <button onclick="changeColor()">green</button>

box1

box2

box3

box4

```

Body:
Just to make it easier Im explaining what I wish to do in a simplified example.

I have 100 boxes on my site using simple html/css. (styling not shown)

I have written a bit of JS to open a modal that opens when clicking on one of the 100 boxes carrying the same class: class="boxes":

The modal has an Id of "modal":

var modal = document.getElementById("modal");
var boxes = document.getElementsByClassName("box");
var boxesLength = boxes.length;

When any box is clicked the modal appears:

    for (var i = 0; i < boxesLength; i++) {
    boxes[i].onclick = function () {
    modal.style.display = "block";
    };
    }

Now I wish to color the box  that was clicked using a button in the modal that was opened. The code that doesn't work but is my closest guess looks like this:

//get the coloring button in the modal which has Id of "green".

var coloring = document.getElementById("green");

coloring.onclick = function () {
boxes[i].style.backgroundColor = "#90EE90";
//closing the modal after clicking which works
modal.style.display = "none";
};

Writing "boxes[0]" will color the first box, but that is of course not what I wish. I wish to color the box that was clicked.

Thank you for any input. Good day!

on request ive added som simple html

    //The modal

            <button id="green">Completed</button>

    //just some boxes

    .... 96 more boxes

Body:
In accordance to how I understood your issue.You want the background color to show on the box that was clicked for it to show the modal.
Here is my solution.

//to pass it as a global variable between functions
var randomv = {}
 var modal = document.getElementById("modal");
 var close = document.querySelector('.close')

//get all box
var x = document.getElementById("innerBox").querySelectorAll(".box");
  //for each box execute the following
  x.forEach(box => {
    //on clicking each box, execute a function
    box.addEventListener("click", function () {
      //this references the parent element which in this case is the box
      randomv.parent = this
      //display the modal on clicking the box
      modal.style.display = "block";
    })
  });

//hide the modal on clicking the x
close.addEventListener("click", function(){
 modal.style.display = "none"
});

  function changeColor() {
  //first ensure the background color is normal for each box
    x.forEach(box => {
      box.style.backgroundColor = "white";
    });
  //reserve the parent element to a variable
    var parent_div = randomv.parent
   //change the parent's bg color
    parent_div.style.backgroundColor = "green";
  }
</script>

  #modal {
      display: none;
    }

    #innerBox {
      width: 100vw;
      display: flex;

    }
    .box{
      flex-grow: 1;

    }
    .close,.box{
     cursor: pointer;
    }

  <div class="container">

    <div id="modal">model content
      <div class="close"> x </div>
      <button onclick="changeColor()">green</button>
    </div>
    <div id="innerBox">
      <div class="box 1">box1</div>
      <div class="box 2">box2</div>
      <div class="box 3">box3</div>
      <div class="box 4">box4</div>
    </div>
  </div>


问:
GET http://localhost:3000/bundle.js net::ERR_ABORTED 404 (Not Found)
There are already other similar questions, but the issue is still haunting me in spite of those answers - I am using webpack and babel on a project, but the browser's console is always showing an error 404 while trying to find bundle.js.

This is my package.json:

```<code>{
  "name": "node-str",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./bin/server.js"
  },
  "keywords": [],
  "author": "Pedro_Coelho",
  "license": "ISC",
  "dependencies": {
    "babel-register": "^6.26.0",
    "body-parser": "^1.18.3",
    "create-react-class": "^15.6.3",
    "debug": "^3.1.0",
    "ejs": "^2.6.1",
    "express": "^4.16.3",
    "guid": "0.0.12",
    "http": "0.0.0",
    "md5": "^2.2.1",
    "mongoose": "^5.2.4",
    "react": "^16.6.1",
    "react-dom": "^16.6.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "nodemon": "^1.18.3",
    "webpack-cli": "^3.1.2"
  }
}
</code>```

This is my webpack.config.js:

```<code>module.exports = {
    entry: 'src/client.js',
    output: {
      filename:'bundle.js',
        //path: './public',
        path:__dirname + 'dist',
        publicPath: "./public"
    },
    module: {
        loaders: [
            {
              test: /\.jsx?$/,
              loader: 'babel-loader',

              exclude: /node_modules/,
              query: {
                cacheDirectory: true,
                presets: ['react', 'es2015']
              }
            }
          ]
    },
    //devtool: 'source-map',
    resolve: {
        extensions: ['', '.js', '.jsx']
      },
      devServer: { historyApiFallback: true }, // to serve your index.html in place of 404 responses
};
</code>```

and this is my about.js file, where bundle.js is being referenced in a script:

```<code>var React = require('react');
var createReactClass = require('create-react-class');

module.exports = createReactClass({
    _handleClick: function () {
        alert("Hello!");
    },
    render: function () {
        return (
            <html>
                <head>
                    <title>About - React Page</title>
                    <link rel='stylesheet' type="text/css" href='/style.css' />
                </head>
                <body>
                    <div>
                        <h1>Hello World!</h1>
                        <p>Isn't server-side rendering remarkable?</p>
                        <button onClick={this._handleClick}>Click Me</button>
                    </div>
                    <script type="text/javascript" src='/bundle.js' />
                </body>
            </html>
        );
    }
});
</code>```

Project's structure:

>>structure<<

Any clue why is this happening?

答:
Use

```<code>output: {
  ...
  publicPath: '/',
},
</code>```

in your webpack config.

Body:
There are already other similar questions, but the issue is still haunting me in spite of those answers - I am using webpack and babel on a project, but the browser's console is always showing an error 404 while trying to find bundle.js.

This is my package.json:

{
  "name": "node-str",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./bin/server.js"
  },
  "keywords": [],
  "author": "Pedro_Coelho",
  "license": "ISC",
  "dependencies": {
    "babel-register": "^6.26.0",
    "body-parser": "^1.18.3",
    "create-react-class": "^15.6.3",
    "debug": "^3.1.0",
    "ejs": "^2.6.1",
    "express": "^4.16.3",
    "guid": "0.0.12",
    "http": "0.0.0",
    "md5": "^2.2.1",
    "mongoose": "^5.2.4",
    "react": "^16.6.1",
    "react-dom": "^16.6.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "nodemon": "^1.18.3",
    "webpack-cli": "^3.1.2"
  }
}

This is my webpack.config.js:

module.exports = {
    entry: 'src/client.js',
    output: {
      filename:'bundle.js',
        //path: './public',
        path:__dirname + 'dist',
        publicPath: "./public"
    },
    module: {
        loaders: [
            {
              test: /\.jsx?$/,
              loader: 'babel-loader',

              exclude: /node_modules/,
              query: {
                cacheDirectory: true,
                presets: ['react', 'es2015']
              }
            }
          ]
    },
    //devtool: 'source-map',
    resolve: {
        extensions: ['', '.js', '.jsx']
      },
      devServer: { historyApiFallback: true }, // to serve your index.html in place of 404 responses
};

and this is my about.js file, where bundle.js is being referenced in a script:

var React = require('react');
var createReactClass = require('create-react-class');

module.exports = createReactClass({
    _handleClick: function () {
        alert("Hello!");
    },
    render: function () {
        return (

                    <title>About - React Page</title>
                    <link rel='stylesheet' type="text/css" href='/style.css' />

Hello World!

Isn't server-side rendering remarkable?

                        <button onClick={this._handleClick}>Click Me</button>

Body:
Use

output: {
  ...
  publicPath: '/',
},

in your webpack config.


问:
Regex to capture between two characters that matches a word inbetween
I am trying to find out the best way possible for extracting all the text in between two characters (ignoring line breaks) that matches a word in between the two characters specified.

In the below example, i want to find by the zip 22222 and extract/group its block from { till } that is {
   "zip":"22222",
   "total":2
}

Example :

```<code>{
   "zip":"11111",
   "total":1
},
{
   "zip":"22222",
   "total":2
},
{
   "zip":"33333",
   "total":3
}
</code>```

Want to extract/capture/group the block {...} for zip 22222 as below :

```<code>{
   "zip":"22222",
   "total":2
}
</code>```

I tried the below, but this is capturing the blocks for all zip codes

```<code>(?s)(?<={)(.*?)(?=})
</code>```

https://regex101.com/r/0wTDyj/1

Body:
I am trying to find out the best way possible for extracting all the text in between two characters (ignoring line breaks) that matches a word in between the two characters specified.

In the below example, i want to find by the zip 22222 and extract/group its block from { till } that is {
   "zip":"22222",
   "total":2
}

Example :

{
   "zip":"11111",
   "total":1
},
{
   "zip":"22222",
   "total":2
},
{
   "zip":"33333",
   "total":3
}

Want to extract/capture/group the block {...} for zip 22222 as below :

{
   "zip":"22222",
   "total":2
}

I tried the below, but this is capturing the blocks for all zip codes

(?s)(?<={)(.*?)(?=})

https://regex101.com/r/0wTDyj/1

Body:
Below regex worked for me :

(?s)(?={)(?:(?:(?!"zip").)?"zip"\s:\s*"22222".*?)(?<=})


问:
Google Docs Time-driven file permission change
I have a Google Doc that I want to change the user permissions for, based on the time of day. To be precise, I need it to be restricted from 9am - 12pm and 1pm to 6pm. At all other times I want anyone with the link to be able to comment on it.

Up until now I have been manually doing this every day, but I want it to be automatic. Is this possible?

答:
You can create a script using Apps Script, and use time-driven triggers to run functions from the script at specific times or time intervals.

You can change a file's sharing permissions, commenters, editors, etc. with the class File from the Drive service to modify the Doc's commenters.


问:
,what is the use and benefit of Serialize() function in php
I know its Generates a storable representation of a value and  used to access the objects across the php files but what if i dont use this function while storing the objects.</p>

答:
When you want to store or send data in a "safe" format, preserving PHP type and structure.

For example, you have an UTF-8 string with Japanese text. Or a multidimensional array. You can save it to a text file or insert into a database.

```<code>$array = array( 'key' => 'value', 'other_key' => 'other_value');
file_put_contents( 'array.txt', serialize( $array ) );
</code>```

When you want to use the stored data, you may use the "unserialize" function:

```<code>$contents = file_get_contents( 'array.txt' );
$array = unserialize( $contents );
</code>```

You can serialize values of any PHP type, including objects, but except the "resource" type (database connections, file handlers, etc.)

When you unserialize an object, you must ensure to have loaded its class previously.

More at the PHP manual: http://php.net/serialize

Body:
When you want to store or send data in a "safe" format, preserving PHP type and structure.

For example, you have an UTF-8 string with Japanese text. Or a multidimensional array. You can save it to a text file or insert into a database.

$array = array( 'key' => 'value', 'other_key' => 'other_value');
file_put_contents( 'array.txt', serialize( $array ) );

When you want to use the stored data, you may use the "unserialize" function:

$contents = file_get_contents( 'array.txt' );
$array = unserialize( $contents );

You can serialize values of any PHP type, including objects, but except the "resource" type (database connections, file handlers, etc.)

When you unserialize an object, you must ensure to have loaded its class previously.

More at the PHP manual: http://php.net/serialize


问:
How does this pointer-based strcat work in C?
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

```<code>char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}
</code>```

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

答:
The crucial thing to understand in this code is the way C handles strings (an array of characters terminated by '\0'). The first thing to do is ditch the analogy to a string as a word, and think of it in a value-by-value basis.

The dest argument of the function represents the pointer to the first character of the destination string. To add more characters after the dest string, we need to get to its '\0' terminator, because that's where the second string will land. That's the purpose of this loop:

while (*dest)
      dest++;
```
<p>(<code>(*dest)</code> condition is equivalent to <code>(*dest != '\0')</code>, because <code>'\0'</code> has a numerical value of <code>0</code>, which is equivalent to <code>false</code>)</p>
<p>After we've gotten to the position where the second string needs to begin, we start copying it character by character:</p>
<pre class="lang-c prettyprint-override"><code>while (*dest++ = *src++)
      ;
</code>```

Note that (*dest++ = *src++) has a single '=' character, meaning it is an assignment, not a comparison. The value being tested inside the parentheses is the thing getting assigned, i.e. *src. So, it will continue as long as (*src != '\0'), which happens to be where the second string ends. Also note that the '\0' character IS ALSO COPIED in these assignments, which is an absolute must, because without it the resulting string wouldn't be terminated (so, technically speaking it wouldn't even be a valid string).

Great, now that we've copied the string where it needs to be, we need to return the pointer to the first character. Ah, but we've moved the pointer in the first loop! That's where rdest comes in, saving the initial position before the loops so that we can return it at the end.

Body:
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

Body:
The crucial thing to understand in this code is the way C handles strings (an array of characters terminated by '\0'). The first thing to do is ditch the analogy to a string as a word, and think of it in a value-by-value basis.

The dest argument of the function represents the pointer to the first character of the destination string. To add more characters after the dest string, we need to get to its '\0' terminator, because that's where the second string will land. That's the purpose of this loop:

while (*dest)
      dest++;

((*dest) condition is equivalent to (*dest != '\0'), because '\0' has a numerical value of 0, which is equivalent to false)

After we've gotten to the position where the second string needs to begin, we start copying it character by character:

while (*dest++ = *src++)
      ;

Note that (*dest++ = *src++) has a single '=' character, meaning it is an assignment, not a comparison. The value being tested inside the parentheses is the thing getting assigned, i.e. *src. So, it will continue as long as (*src != '\0'), which happens to be where the second string ends. Also note that the '\0' character IS ALSO COPIED in these assignments, which is an absolute must, because without it the resulting string wouldn't be terminated (so, technically speaking it wouldn't even be a valid string).

Great, now that we've copied the string where it needs to be, we need to return the pointer to the first character. Ah, but we've moved the pointer in the first loop! That's where rdest comes in, saving the initial position before the loops so that we can return it at the end.


问:
Full Calendar in React TypeError: Cannot read property 'calendar' of undefined
I am getting an error when trying to store information about selected time in state. Any help is appreciated, thank you for your time! Please let me know if you guys are needing anymore specific information.

Following is my code snippet from my component:

```<code>  const Calendar = (props) => {

  const [startTime, setStartTime] = React.useState('');

  const handleSelect = (selectedInfo) => {
    //alert(selectedInfo.startStr);
    setStartTime(selectedInfo.startStr);
  }

  return (
    <FullCalendar
      defaultView="timeGridWeek"
      weekends={false}
      allDaySlot={false}
      plugins={[ timeGridPlugin, dayGridPlugin, interactionPlugin ]}
      minTime="08:00:00"
      selectable={true}
      selectMirror={true}
      selectOverlap={false}
      select={handleSelect}
      header={{
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay'
      }}
      events={[
        { title: 'event 1', start: '2020-03-16 10:00:00', end: '2020-03-16 12:00:00' },
        { title: 'event 2', start: '2020-03-19' }
      ]}
    />
  );
}
</code>```

答: Upgrading fullcalendar and fullcalendar-react to version 4.4.1 resolved this issue for me. It appears It was a bug.

Body:
I am getting an error when trying to store information about selected time in state. Any help is appreciated, thank you for your time! Please let me know if you guys are needing anymore specific information.

Following is my code snippet from my component:

  const Calendar = (props) => {

  const [startTime, setStartTime] = React.useState('');

  const handleSelect = (selectedInfo) => {
    //alert(selectedInfo.startStr);
    setStartTime(selectedInfo.startStr);
  }

  return (
    <FullCalendar
      defaultView="timeGridWeek"
      weekends={false}
      allDaySlot={false}
      plugins={[ timeGridPlugin, dayGridPlugin, interactionPlugin ]}
      minTime="08:00:00"
      selectable={true}
      selectMirror={true}
      selectOverlap={false}
      select={handleSelect}
      header={{
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay'
      }}
      events={[
        { title: 'event 1', start: '2020-03-16 10:00:00', end: '2020-03-16 12:00:00' },
        { title: 'event 2', start: '2020-03-19' }
      ]}
    />
  );
}


问:
Using dictionary in flask
i trying to use a dict in my flask app to generate a pair Name - One Time Password for new users.
(Yes, i know what using a database is prefered and better, but now i need only dict)

```<code>account = session['user_id']
token = secrets.token_hex(16)
users = ({account: {'Login': account, 'Secret': token}})
Name = users[account]['Login']
Key = users[account]['Secret']
print(users[account])
</code>```

Pairs name key will be pushed to next webpage.

If i understand correctly, every time user reloading page or another user attempts to get a key a dict will be re-created?

答: Yes it will create a new one each time and you can prevent it by checking the value of the dictionary.</p>

Title: Using dictionary in flask

Body:
i trying to use a dict in my flask app to generate a pair Name - One Time Password for new users.
(Yes, i know what using a database is prefered and better, but now i need only dict)

account = session['user_id']
token = secrets.token_hex(16)
users = ({account: {'Login': account, 'Secret': token}})
Name = users[account]['Login']
Key = users[account]['Secret']
print(users[account])

Pairs name key will be pushed to next webpage.

If i understand correctly, every time user reloading page or another user attempts to get a key a dict will be re-created?


问:
Can't get defaultRedirect to work
In my web.config, I have:

```<code><system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>
</code>```

In Views/Shared/Error.cshtml, I have:

```<code>@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<h2>
    Sorry, an error occurred while processing your request.
</h2>
</code>```

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.

答:
One solution is create ErrorController

```<code>public class ErrorController : Controller
{
    //
    // GET: /Error/

    public ActionResult Error()
    {
        return View();
    }

    public ActionResult Error404()
    {
        return View("Error");
    }

}
</code>```

Change Web.config

Title: Can't get defaultRedirect to work

Body:
In my web.config, I have:

<system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>

In Views/Shared/Error.cshtml, I have:

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}

    Sorry, an error occurred while processing your request.

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.

Body:
One solution is create ErrorController

public class ErrorController : Controller
{
    //
    // GET: /Error/

    public ActionResult Error()
    {
        return View();
    }

    public ActionResult Error404()
    {
        return View("Error");
    }

}

Change Web.config


问:
Problem in using scipy.spatial.cKDTree or queryBallPoint with random 2d points using nearest neighbors between two datasets
I have P_0 points spread randomly in a 2d box. Then I divide them in two groups S and I. If some points of S come too close to I, they are deleted from the S group and added to the I group. The problem I am facing is that sometimes they are not correctly deleted from S, but they are properly added to I. Hence, the total number of points keeps erroneously growing.
Here is the code:

```<code>from scipy.spatial import cKDTree
import numpy as np
import matplotlib.pyplot as plt
P_0 = 100 # initial susceptible population
# dimensions of box
Lx = 5.0
Ly = 5.0
# generate P_0 random points inside box
X = np.random.uniform(0, Lx, P_0)
Y = np.random.uniform(0, Ly, P_0)
pts = np.column_stack((X, Y)) # array of 2d points
S = np.arange(10, P_0) # indices of the susceptible
I = np.arange(10) # indices of the infected
# Divide points into infected and susceptible groups
r_I = pts[I]
r_S = pts[S]
tree = cKDTree(r_S)
# idx represents the indices to points in r_S which are closer than r to
# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

plt.figure('S group')
plt.plot (pts[S, 0], pts[S, 1], 'bo') # plot the updated r_S points

plt.figure('I group')
plt.plot (pts[I, 0], pts[I, 1], 'ro') # plot the updated r_I points
print len(S), len(I), len(S)+len(I), len(idx)
plt.show()
</code>```

So, I don't know why not all points in r_S closer than r, sometimes aren't deleted from S.
One might have to run the code a few times for the error to appear, or just increase P_0 to 1000 for example or increase the value of r. it might be a problem with idx and the way I am using numpy delete.

答:
As I just commented, I just had to eliminate the duplicates in idx.
I added the line

```<code>idx = np.unique(idx)
</code>```

just below idx = idx.astype(int)

Body:
I have P_0 points spread randomly in a 2d box. Then I divide them in two groups S and I. If some points of S come too close to I, they are deleted from the S group and added to the I group. The problem I am facing is that sometimes they are not correctly deleted from S, but they are properly added to I. Hence, the total number of points keeps erroneously growing.
Here is the code:

from scipy.spatial import cKDTree
import numpy as np
import matplotlib.pyplot as plt
P_0 = 100 # initial susceptible population
# dimensions of box
Lx = 5.0
Ly = 5.0
# generate P_0 random points inside box
X = np.random.uniform(0, Lx, P_0)
Y = np.random.uniform(0, Ly, P_0)
pts = np.column_stack((X, Y)) # array of 2d points
S = np.arange(10, P_0) # indices of the susceptible
I = np.arange(10) # indices of the infected
# Divide points into infected and susceptible groups
r_I = pts[I]
r_S = pts[S]
tree = cKDTree(r_S)
# idx represents the indices to points in r_S which are closer than r to
# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

plt.figure('S group')
plt.plot (pts[S, 0], pts[S, 1], 'bo') # plot the updated r_S points

plt.figure('I group')
plt.plot (pts[I, 0], pts[I, 1], 'ro') # plot the updated r_I points
print len(S), len(I), len(S)+len(I), len(idx)
plt.show()

So, I don't know why not all points in r_S closer than r, sometimes aren't deleted from S.
One might have to run the code a few times for the error to appear, or just increase P_0 to 1000 for example or increase the value of r. it might be a problem with idx and the way I am using numpy delete.

Body:
As I just commented, I just had to eliminate the duplicates in idx.
I added the line

idx = np.unique(idx)

just below idx = idx.astype(int)


问:
Inheritance with lombok annotation get errors
In my project, lombok is used to avoid writing getters and setters for a class.
I have two classes Child extends Parent:

```<code>@Value
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Parent {
    @Nonnull
    @JsonProperty("personId")
    private final String personId;

    @JsonProperty("personTag")
    private final String personTag;
    ...
}
</code>```

And

```<code>@Value
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Child extends Parent {
    @Nonnull
    @JsonProperty("childId")
    private final String childId;
    ...
}
</code>```

But this doesn't seems work as no default constructor available in Parent. I'm not familiar with the lombok annotation. Is there any good way to extend the Base class and use the lombok annotation at the same time?

答:
TL;DR: add @NonFinal annotation to your superclass

Details: @Value annotation makes the class final, so you cannot inherit from it. Experimental @NonFinal annotation should prevent this.

```<code>import lombok.Value;
import lombok.experimental.NonFinal;

@Value
@NonFinal
public class Parent {
</code>```

REF: https://projectlombok.org/features/Value

NOTE: For performance reasons (if it matters) final (value) objects can be (theoretically) super fast. The optimizer can allocate them in the stack memory, or reuse the same stack block in cycles, so no GC overheads.

(This is similar to how .NET structure value objects are usually allocated by .NET framework)

By adding @NonFinal such an optimization opportunity disappears.

Body:
In my project, lombok is used to avoid writing getters and setters for a class.
I have two classes Child extends Parent:

@Value
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Parent {
    @Nonnull
    @JsonProperty("personId")
    private final String personId;

    @JsonProperty("personTag")
    private final String personTag;
    ...
}

And

@Value
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Child extends Parent {
    @Nonnull
    @JsonProperty("childId")
    private final String childId;
    ...
}

But this doesn't seems work as no default constructor available in Parent. I'm not familiar with the lombok annotation. Is there any good way to extend the Base class and use the lombok annotation at the same time?

Body:
TL;DR: add @NonFinal annotation to your superclass

Details: @Value annotation makes the class final, so you cannot inherit from it. Experimental @NonFinal annotation should prevent this.

import lombok.Value;
import lombok.experimental.NonFinal;

@Value
@NonFinal
public class Parent {

REF: https://projectlombok.org/features/Value

NOTE: For performance reasons (if it matters) final (value) objects can be (theoretically) super fast. The optimizer can allocate them in the stack memory, or reuse the same stack block in cycles, so no GC overheads.

(This is similar to how .NET structure value objects are usually allocated by .NET framework)

By adding @NonFinal such an optimization opportunity disappears.


问:
How to associate and filter two related arrays?
I have two arrays and I want to link together when processing them.

```<code>$dat = array(
    "2020-02-01",
    "2020-02-05",
    "2020-02-10",
    "2020-02-12",
    "2020-02-15"
);
$word = array(
    "Attend To,Explore,Unaided,dull,bad"
);

//User input
$start = "2020-01-01";
$end = "2020-02-07";
</code>```

I want the input to affect the second array too, so when the first array gets its result from first 2, then the second array too should have it from the first 2.

```<code>//Filter out dates between start and end date
$result = array_filter($dat, function($data_item) use($start, $end) {
    return $data_item >= $start && $data_item <= $end;
});
</code>```

and the result is

```<code>Array
(
    [0] => 2020-02-01
    [1] => 2020-02-05
)
</code>```

I want it to be able to link $dat and $word so that the result for word too will be

```<code>Array
(
    [0] => Attend To
    [1] => Explore
)
</code>```

答:
The original keys will be maintained after array_filter, so get the entries for keys that are the same by computing the intersection.  It appears that $word is a one element array with a string, so just explode it:

```<code>$word_result = array_intersect_key(explode(',', $word[0]), $result);
</code>```

See a Demo.

If one of the arrays has unique values, you can combine the array and just operate on that.

```<code>$comb = array_combine(explode(',', $word[0]), $dat);

$result = array_filter($comb, function($data_item) use($start,$end) {
    return $data_item >= $start && $data_item <= $end;
});
</code>```

This yields:

```<code>Array
(
    [Attend To] => 2020-02-01
    [Explore] => 2020-02-05
)
</code>```

You can use the array as is or use array_keys to get the keys as the $word array.

If it's not guaranteed to be $word[0] then you can use reset($word) or current($word).

Body:
I have two arrays and I want to link together when processing them.

$dat = array(
    "2020-02-01",
    "2020-02-05",
    "2020-02-10",
    "2020-02-12",
    "2020-02-15"
);
$word = array(
    "Attend To,Explore,Unaided,dull,bad"
);

//User input
$start = "2020-01-01";
$end = "2020-02-07";

I want the input to affect the second array too, so when the first array gets its result from first 2, then the second array too should have it from the first 2.

//Filter out dates between start and end date
$result = array_filter($dat, function($data_item) use($start, $end) {
    return $data_item >= $start && $data_item <= $end;
});

and the result is

Array
(
    [0] => 2020-02-01
    [1] => 2020-02-05
)

I want it to be able to link $dat and $word so that the result for word too will be

Array
(
    [0] => Attend To
    [1] => Explore
)

Body:
The original keys will be maintained after array_filter, so get the entries for keys that are the same by computing the intersection.  It appears that $word is a one element array with a string, so just explode it:

$word_result = array_intersect_key(explode(',', $word[0]), $result);

See a Demo.

If one of the arrays has unique values, you can combine the array and just operate on that.

$comb = array_combine(explode(',', $word[0]), $dat);

$result = array_filter($comb, function($data_item) use($start,$end) {
    return $data_item >= $start && $data_item <= $end;
});

This yields:

Array
(
    [Attend To] => 2020-02-01
    [Explore] => 2020-02-05
)

You can use the array as is or use array_keys to get the keys as the $word array.

If it's not guaranteed to be $word[0] then you can use reset($word) or current($word).


问:
How to check for duplicate email address in spartacus storefront?
How can you check that an email address already exists in spartacus? The reference class for this type of query would be UserService. But it does not contain this kind of method or anything simillar.

答:
In the past, we had this functionality built in. But because of security reasons our backend is not sending us any feedback about email/password/account being incorrect/existing/etc anymore. So even if you'd do anything on the frontend, the backend will not help with that.

Here's one of the PRs, where we had to change the register flow - before, it was logging you in automatically once registered successfully, but if your email was already used, it wasn't logging you in - boom, security issue (possibility to check if a given email is used on this specific site)

So, unless you customize your backend (not sure if even possible), you cannot really check if email already exists in Spartacus.


问:
User is not permitted to create v$ or x$ in one of my oracle database
In my Oracle 19c, the oracle user I have created is not allowed to create v$ or x$ views. Is it restricted from the 12c version?</p>

答:
It is allowed(But with lowercase v$), You just need to create it with name wrapped in the double quotes:

See issue:

```<code>SQL> create or replace view v$tejash
  2  as select * from dual;
create or replace view v$tejash
                       *
ERROR at line 1:
ORA-00999: invalid view name
</code>```

same issue if I use the upper case V$

```<code>SQL> create or replace view "V$TEJASH"
  2  as select * from dual;
create or replace view "V$TEJASH"
                       *
ERROR at line 1:
ORA-00999: invalid view name

SQL>
</code>```

Use lowercase v$ and it is resolved.

```<code>SQL> create or replace view "v$tejash"
  2  as select * from dual;

View created.

SQL>
</code>```

Although, It is not recommended to use such names.

Body:
It is allowed(But with lowercase v$), You just need to create it with name wrapped in the double quotes:

See issue:

SQL> create or replace view v$tejash
  2  as select * from dual;
create or replace view v$tejash
                       *
ERROR at line 1:
ORA-00999: invalid view name

same issue if I use the upper case V$

SQL> create or replace view "V$TEJASH"
  2  as select * from dual;
create or replace view "V$TEJASH"
                       *
ERROR at line 1:
ORA-00999: invalid view name

SQL>

Use lowercase v$ and it is resolved.

SQL> create or replace view "v$tejash"
  2  as select * from dual;

View created.

SQL>

Although, It is not recommended to use such names.


问:
Create custom merge strategy
I've heard it mentioned that you can create your own strategies for detecting merge conflicts. This question, for instance, suggests that it's possible. I'd like to give this a try, but I can't find any further information at all.

I understand that I need to create some executable and have it in the path - no problem - but what will be passed to this executable, and what should it output

答:
A merge strategy is one selected by git merge -s.  You're correct that you would just have to put an executable program into your $PATH (or Git's git-core directory, which the git front end adds to $PATH).

The problem is that writing a merge strategy is not trivial (in fact it's very hard in general) and the arguments that Git passes are undocumented.  You will have to figure them out from the Git source, and be aware that they might change in a future version of Git.  Some of them are secreted in environment variables—in particular, the legends you can attach to the commits involved in the merge are in environment variables that contain the hash ID of the commits in question.

(I have not written a merge strategy myself and don't have any particular advice, other than: use GIT_TRACE=1 git merge -s <strategy> to invoke your strategy to see what the argv elements are.  The hidden environment variables used to be exposed in the git stash script but git stash has been rewritten in C.)

Your merge strategy's job is to update Git's index to hold the merge result, then exit with a zero status (success); or, don't, and exit with a nonzero status—normally 1—to indicate failure.  If you wish to be user-friendly it's advisable to update the work-tree based on any successful merge result, too.  There may be a special exit status for "merge not even attempted" (vs "merge failed, I leave a mess for human to finish merge with") but that too is not documented.

The built in set of merge strategies is:

git-merge-recursive: git merge -s recursive invokes this one; it's the usual one most people are most familiar with.

git-merge-resolve: git merge -s resolve invokes this.  It's actually the same program as git merge-recursive, it just does something different when there is more than one merge base commit.

git-merge-octopus: While git merge -s octopus invokes this one, so does any git merge that lacks a -s option, but mentions more than one other-commit to merge.

git-merge-ours: git merge -s ours invokes this.

git-merge-subtree: git merge -s subtree invokes this.  Like git-merge-resolve, is just a variant of git-merge-recursive.

If you don't pass a -s argument, Git will use -s recursive unless you named two or more commit arguments.

As you can see from the list above, there are really only three strategies built in to Git: octopus, ours, and "everything else". The octopus strategy does not handle merge conflicts (at all), and -s ours completely ignores all other input commits, which makes its code relatively simple, so most of the hard work is in the single remaining merge strategy.

Title: Create custom merge strategy


问:
how to intstall mcpack in minecraft programatically android
i'm trying to send (install) my mcpack file using this code but is is not working, minecraft support this type of extenstion to install mods (.mcpack, .mcaddon, .mcworld, .mctemplate, .modpkg how we can define mimetypes for these extensions)

please go through this image i need exactly like this https://imgur.com/14rIBvN

```<code> try {
    //File path = new File(getFilesDir(), "dl");
    File file = new File(path);
    PackageManager manager = this.getPackageManager();
    // Get URI and MIME type of file
    Intent share = new Intent(Intent.ACTION_SEND);
    //share.setType("image/jpeg");
    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
    share.setPackage("com.mojang.minecraftpe");//package name of the app
    startActivity(Intent.createChooser(share, "Select Minecraft to install"));
} catch (Exception e) {
    Log.i(TAG, "App not found.. "+e.getMessage());
}
</code>```

答: Open with minecraft and it will open and it will day download started and if it works it will say, If it does not work it will say, Minecraft onlu supports .mcpack, .mcworld, .mctemplate on pocket edition</p>

Body:
i'm trying to send (install) my mcpack file using this code but is is not working, minecraft support this type of extenstion to install mods (.mcpack, .mcaddon, .mcworld, .mctemplate, .modpkg how we can define mimetypes for these extensions)

please go through this image i need exactly like this https://imgur.com/14rIBvN

 try {
    //File path = new File(getFilesDir(), "dl");
    File file = new File(path);
    PackageManager manager = this.getPackageManager();
    // Get URI and MIME type of file
    Intent share = new Intent(Intent.ACTION_SEND);
    //share.setType("image/jpeg");
    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
    share.setPackage("com.mojang.minecraftpe");//package name of the app
    startActivity(Intent.createChooser(share, "Select Minecraft to install"));
} catch (Exception e) {
    Log.i(TAG, "App not found.. "+e.getMessage());
}


问:
Log4j2 log4j-core
I have added spring-boot-starter-log4j2 dependency in pom.xml which is of version 2.2.5. I am trying to change the version of org.apache.logging.log4j.log4j-core from 2.12.1 to 2.13.3
However, in doing so I am getting runtime exception. I went through other solutions which suggest that maybe log4j jar is included twice. I am unable to solve the error by excluding that also. This runtime exception occurs only when org.apache.logging.log4j.log4j-core version is changed. Changing version of other api included under spring-boot-starter-log4j2 does not cause any exception.
What am I missing?
Pom.xml
...

```<code>  <!-- Add Log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>
</code>```

...
Dependency Tree
Dependency Tree
Runtime Exception
...

```<code>Exception in thread "main" java.lang.NoSuchMethodError: org.apache.logging.log4j.util.PropertiesUtil.getStringProperty([Ljava/lang/String;Ljava/lang/String;Lorg/apache/logging/log4j/util/Supplier;)Ljava/lang/String;
at org.apache.logging.log4j.core.util.BasicAuthorizationProvider.<init>(BasicAuthorizationProvider.java:45)
at org.apache.logging.log4j.core.config.ConfigurationFactory.authorizationProvider(ConfigurationFactory.java:216)
at org.apache.logging.log4j.core.config.ConfigurationFactory.getInstance(ConfigurationFactory.java:189)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:687)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:708)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:263)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:243)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45)
at org.apache.logging.log4j.LogManager.getContext(LogManager.java:174)
at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:648)
at com.vzw.jitrjis.StartUp.<clinit>(StartUp.java:22)
</code>```

...

答:
You have two version of log4j jars in the classpath. This is causing the classpath conflicts. Log4j might be included in the classpath with transitive dependencies.
If you want to identify the multiple jars, try viewing the dependency tree.
If you are using maven , it is as simple as running this command.</p>

```<code>mvn dependency:tree
</code>```

Title: Log4j2 log4j-core

Body:
I have added spring-boot-starter-log4j2 dependency in pom.xml which is of version 2.2.5. I am trying to change the version of org.apache.logging.log4j.log4j-core from 2.12.1 to 2.13.3
However, in doing so I am getting runtime exception. I went through other solutions which suggest that maybe log4j jar is included twice. I am unable to solve the error by excluding that also. This runtime exception occurs only when org.apache.logging.log4j.log4j-core version is changed. Changing version of other api included under spring-boot-starter-log4j2 does not cause any exception.
What am I missing?
Pom.xml
...

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.3</version>
</dependency>

...
Dependency Tree
Dependency Tree
Runtime Exception
...

Exception in thread "main" java.lang.NoSuchMethodError: org.apache.logging.log4j.util.PropertiesUtil.getStringProperty([Ljava/lang/String;Ljava/lang/String;Lorg/apache/logging/log4j/util/Supplier;)Ljava/lang/String;
at org.apache.logging.log4j.core.util.BasicAuthorizationProvider.<init>(BasicAuthorizationProvider.java:45)
at org.apache.logging.log4j.core.config.ConfigurationFactory.authorizationProvider(ConfigurationFactory.java:216)
at org.apache.logging.log4j.core.config.ConfigurationFactory.getInstance(ConfigurationFactory.java:189)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:687)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:708)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:263)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:243)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:45)
at org.apache.logging.log4j.LogManager.getContext(LogManager.java:174)
at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:648)
at com.vzw.jitrjis.StartUp.<clinit>(StartUp.java:22)

...

Body:
You have two version of log4j jars in the classpath. This is causing the classpath conflicts. Log4j might be included in the classpath with transitive dependencies.
If you want to identify the multiple jars, try viewing the dependency tree.
If you are using maven , it is as simple as running this command.

mvn dependency:tree


问:
How to fix type inference for a component variable in a jest Mount test built with reactjs?
My scenario is a react project built in typescript, and specifically regarding a unit test involving mount from Enzyme. I'm working on aligning the project with the tsconfig parameter "noImplicitAny": true, I'm wondering how to fix the let component issue described under.

```<code>let wrapper

beforeEach(() => {
  wrapper = mount(<Component/>)
})

it('shows the rendered component', () => {
  expect(wrapper.find('.class-component')).toHaveLength(1)
})
</code>```

and error is:

```<code>Variable 'wrapper' implicitly has type 'any' in some locations where its type cannot be determined.ts (7034)
</code>```

How to create the inference of type Component to variable component?

答:
The return type of mount(<Component/>) is ReactWrapper. you can just explicitly set the type for wrapper when declaring.

```<code>import { ReactWrapper } from 'enzyme';

let wrapper: ReactWrapper;

beforeEach(() => {
  wrapper = mount(<Component/>) // ts will no longer infer the type for wrapper as any
})

</code>```

Similarly ShallowWrapper can be used as the type for the wrapper when using shallow rendering. Keep in mind both ReactWrapper and ShallowWrapper are generic, so you can also provide additional type information for the component as type arguments.

Body:
My scenario is a react project built in typescript, and specifically regarding a unit test involving mount from Enzyme. I'm working on aligning the project with the tsconfig parameter "noImplicitAny": true, I'm wondering how to fix the let component issue described under.

let wrapper

beforeEach(() => {
  wrapper = mount(<Component/>)
})

it('shows the rendered component', () => {
  expect(wrapper.find('.class-component')).toHaveLength(1)
})

and error is:

Variable 'wrapper' implicitly has type 'any' in some locations where its type cannot be determined.ts (7034)

How to create the inference of type Component to variable component?

Body:
The return type of mount(<Component/>) is ReactWrapper. you can just explicitly set the type for wrapper when declaring.

import { ReactWrapper } from 'enzyme';

let wrapper: ReactWrapper;

beforeEach(() => {
  wrapper = mount(<Component/>) // ts will no longer infer the type for wrapper as any
})

Similarly ShallowWrapper can be used as the type for the wrapper when using shallow rendering. Keep in mind both ReactWrapper and ShallowWrapper are generic, so you can also provide additional type information for the component as type arguments.


问:
ElasticSearch Sorting using NEST 7
I'm using ElarsticSearch 7.7 & NEST 7.7 and I'm trying to use the sort function. But I'm getting an error,

I'm getting an error saying,
"Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory." caused by: "Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted

this is my code below

```<code>public SearchResult Search(string searchQuery, int storeId, int pageNumber = 1, int pageSize = 10, IList<SearchFilter> requestFilter = null, decimal? priceFrom = null, decimal? priceTo = null, string sortBy = null)
    {
        var queryContainer = new QueryContainer();
        var multiMatch = new QueryStringQuery
        {
            Fields = Infer.Field<ElasticIndexGroupProduct>(p => p.Name)
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.CategoryName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.VendorName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.CategoryName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ManufacturerName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ShortDescription))),
            Boost = 1.1,
            Name = "named_query",
            Query = searchQuery,
            DefaultOperator = Operator.Or,
            Analyzer = "standard",
            QuoteAnalyzer = "keyword",
            AllowLeadingWildcard = true,
            MaximumDeterminizedStates = 2,
            Escape = true,
            FuzzyPrefixLength = 2,
            FuzzyMaxExpansions = 3,
            FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
            Rewrite = MultiTermQueryRewrite.ConstantScore,
            Fuzziness = Fuzziness.Auto,
            TieBreaker = 1,
            AnalyzeWildcard = true,
            MinimumShouldMatch = 2,
            QuoteFieldSuffix = "'",
            Lenient = true,
            AutoGenerateSynonymsPhraseQuery = false
        };
        queryContainer &= multiMatch;

        //sorting
        var sorts = new List<ISort>();
        switch (sortBy)
        {
            case "z-a":
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Descending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x=>x.Name)), Order = SortOrder.Descending });
                break;
            default:
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Ascending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)), Order = SortOrder.Ascending });
                break;
        }

       var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
        {
            Profile = true,
            Query = queryContainer,
            From = (pageNumber - 1) * pageSize,
            Size = pageSize,
            Version = true,
            Sort = sorts
        };

        var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
        return GenerateSearchResult(searchQuery, searchResponse);
    }
</code>```

this is the error

答: If you want to be able to perform full text search on Name as well as sort and aggregate on it, then you probably want to index it as a multi_field with both text and keyword data type.

Title: ElasticSearch Sorting using NEST 7

Body:
I'm using ElarsticSearch 7.7 & NEST 7.7 and I'm trying to use the sort function. But I'm getting an error,

I'm getting an error saying,
"Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory." caused by: "Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted

this is my code below

public SearchResult Search(string searchQuery, int storeId, int pageNumber = 1, int pageSize = 10, IList<SearchFilter> requestFilter = null, decimal? priceFrom = null, decimal? priceTo = null, string sortBy = null)
    {
        var queryContainer = new QueryContainer();
        var multiMatch = new QueryStringQuery
        {
            Fields = Infer.Field<ElasticIndexGroupProduct>(p => p.Name)
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.CategoryName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.VendorName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.CategoryName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ManufacturerName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ShortDescription))),
            Boost = 1.1,
            Name = "named_query",
            Query = searchQuery,
            DefaultOperator = Operator.Or,
            Analyzer = "standard",
            QuoteAnalyzer = "keyword",
            AllowLeadingWildcard = true,
            MaximumDeterminizedStates = 2,
            Escape = true,
            FuzzyPrefixLength = 2,
            FuzzyMaxExpansions = 3,
            FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
            Rewrite = MultiTermQueryRewrite.ConstantScore,
            Fuzziness = Fuzziness.Auto,
            TieBreaker = 1,
            AnalyzeWildcard = true,
            MinimumShouldMatch = 2,
            QuoteFieldSuffix = "'",
            Lenient = true,
            AutoGenerateSynonymsPhraseQuery = false
        };
        queryContainer &= multiMatch;

        //sorting
        var sorts = new List<ISort>();
        switch (sortBy)
        {
            case "z-a":
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Descending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x=>x.Name)), Order = SortOrder.Descending });
                break;
            default:
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Ascending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)), Order = SortOrder.Ascending });
                break;
        }

       var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
        {
            Profile = true,
            Query = queryContainer,
            From = (pageNumber - 1) * pageSize,
            Size = pageSize,
            Version = true,
            Sort = sorts
        };

        var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
        return GenerateSearchResult(searchQuery, searchResponse);
    }

this is the error


问:
How do I speed up a SQL UPDATE that also contains a JOIN on 25 million rows
the query i'd like to speed up (or replace with another process):

```<code>UPDATE en_pages, keywords
SET en_pages.keyword = keywords.keyword
WHERE en_pages.keyword_id = keywords.id
</code>```

table en_pages has the proper structure but only has non-unique page_ids and keyword_ids in it.  i'm trying to add the actual keywords(strings) to this table where they match keyword_ids.  there are 25 million rows in table en_pages that need updating.

i'm adding the keywords so that this one table can be queried in real time and return keywords (the join is obviously too slow for "real time").

we apply this query (and some others) to sub units of our larger dataset.  we do this frequently to create custom interfaces for specific sub units of our data for different user groups (sorry if that's confusing).

this all works fine if you give it an hour to run, but i'm trying to speed it up.

is there a better way to do this that would be faster using php and/or mysql?

答:
Maybe I'm wrong or missunderstood the question but...

Couldn't you use TRIGGERS ?

Like... when a new INSERT is detected on "en_pages", doing a UPDATE after on that same row?

(I don't know how frequent INSERTS are in that table)

This is just an idea.

How often does "en_pages.keyword" and "en_pages.keyword_id" changes after being inserted ?!?!?

Body:
the query i'd like to speed up (or replace with another process):

UPDATE en_pages, keywords
SET en_pages.keyword = keywords.keyword
WHERE en_pages.keyword_id = keywords.id

table en_pages has the proper structure but only has non-unique page_ids and keyword_ids in it.  i'm trying to add the actual keywords(strings) to this table where they match keyword_ids.  there are 25 million rows in table en_pages that need updating.

i'm adding the keywords so that this one table can be queried in real time and return keywords (the join is obviously too slow for "real time").

we apply this query (and some others) to sub units of our larger dataset.  we do this frequently to create custom interfaces for specific sub units of our data for different user groups (sorry if that's confusing).

this all works fine if you give it an hour to run, but i'm trying to speed it up.

is there a better way to do this that would be faster using php and/or mysql?


问:
How to use Getstream Rest API to get response in Postman?
I am trying to implement Stream chat Rest APIs ( by following this link : https://getstream.io/chat/docs_rest ) provided by GetStream. So, I put the baseUrl and expected headers in following ways :

```<code>Request Url     : https://chat-us-east-1.stream-io-api.com/channeltypes
</code>```

These are the values which I put in Headers section of Postman :

```<code>Authorization   : <Getstream token (generating from setUser function) from backend>
Stream-Auth-Type: jwt
api_key         : <Getstream API key>
</code>```

But I am getting this response on hitting API on Postman:

{
      "code": 17,
      "message": "ListChannelTypes failed with error: \"Channel types can be described only with server-side auth\"",
      "StatusCode": 403,
      "duration": "0.00ms"
  }

I am unable to find out what I am missing or doing wrong in using the Rest API of Getstream. Please suggest and help in fixing this issue.

答:
As described in error message:

Channel types can be described only with server-side auth

It's only possible with server side authentication.

When you use Authorization: <Getstream token (generating from setUser function) from backend>, this is for client-side.

You need to use your secret in the token to enable server-side and to gueary in this endpoint.

Body:
I am trying to implement Stream chat Rest APIs ( by following this link : https://getstream.io/chat/docs_rest ) provided by GetStream. So, I put the baseUrl and expected headers in following ways :

Request Url     : https://chat-us-east-1.stream-io-api.com/channeltypes

These are the values which I put in Headers section of Postman :

Authorization   : <Getstream token (generating from setUser function) from backend>
Stream-Auth-Type: jwt
api_key         : <Getstream API key>

But I am getting this response on hitting API on Postman:

{
      "code": 17,
      "message": "ListChannelTypes failed with error: \"Channel types can be described only with server-side auth\"",
      "StatusCode": 403,
      "duration": "0.00ms"
  }

I am unable to find out what I am missing or doing wrong in using the Rest API of Getstream. Please suggest and help in fixing this issue.


问:
Using Java Stream API, finding highest value of variable, with the stream of the changes made to the variable

Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

```<code>enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}
</code>```

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

```<code>// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0
</code>```

Bob's highest balance is 1700.

答:
What you need is to find the maximum value of a cumulative sum. In pseudo-code, this would be something like:

```<code>transactions = [1200, 500, -700, 300, -800, -500]
csum = cumulativeSum(transactions) // should be [1200,1700,1000,1300,500,0]
max(csum) // should be 1700
</code>```

The imperative way:

The traditional for-loop is well suited for such cases. It should be fairly easy to write and is probably the most efficient alternative both in time and space. It does not require multiple iterations and it does not require extra lists.

int max = 0;
int csum = 0;
for (Transaction t: transactions) {
    int amount = (t.getAction() == TransactionAction.WITHDRAW ? -1 : 1) * t.getAmount();
    csum += amount;
    if (csum > max) max = csum;
}
```

<p><strong>Diving into functional:</strong></p>

<p>Streams are a functional programming concept and, as such, they are free of side-effects and well suited for stateless operations. Keeping the cumulative state is considered a side-effect, and then we would have to talk about Monads to bring those side-effects under control and... we don't want to go that way.</p>

<p>Java, not being a functional language (although allowing for functional style), cares less about purity. You could simply have a control variable outside the stream to keep track of that external state within the current <code>map</code> or <code>reduce</code> operations. But that would also be giving up everything Streams are meant for.</p>

<p>So let's see how Java's experienced fellows do in this matter. In pure Haskell, the cumulative sum can be achieved with a Scan Left operation:</p>

<pre class="lang-hs prettyprint-override"><code>λ> scanl1 (+) [1200, 500, -700, 300, -800, -500]
[1200,1700,1000,1300,500,0]
</code>```

Finding the maximum of this would be as simple as:

λ> maximum ( scanl1 (+) [1200, 500, -700, 300, -800, -500] )
1700
```

<p><strong>A Java Streams solution:</strong></p>

<p>Java does not have such an idiomatic way of expressing a scan left, but you may achieve a similar result with <code>collect</code>.</p>

```transactions.stream()
    .map(t -> (t.getAction() == TransactionAction.WITHDRAW ? -1 : 1) * t.getAmount())
    .collect(ArrayList<Integer>::new, (csum, amount) ->
        csum.add(csum.size() > 0 ? csum.get(csum.size() - 1) + amount : amount),
        ArrayList::addAll)
    .stream()
    .max(Integer::compareTo);
// returns Optional[1700]
```

<p><strong>EDIT:</strong> As correctly pointed out in the comments, this accumulator function is not associative and problems would appear if trying to use <code>parallelStream</code> instead of <code>stream</code>. </p>

<p>This can be further simplified. For example, if you enrich your TransactionAction enum with a multiplier (-1 for <code>WITHDRAW</code> and 1 for <code>DEPOSIT</code>), then <code>map</code> could be replaced with:</p>

<pre class="lang-java prettyprint-override"><code>.map(t -> t.getAction().getMultiplier() * t.getAmount())
</code>```

EDIT: Yet another approach: Parallel Prefix Sum

Since Java 8, arrays offer a parallelPrefix operation that could be used like:

Integer[] amounts = transactions.stream()
    .map(t -> (t.getAction() == TransactionAction.WITHDRAW ? -1 : 1) * t.getAmount())
    .toArray(Integer[]::new);

Arrays.parallelPrefix(amounts, Integer::sum);

Arrays.stream(amounts).max(Integer::compareTo);
// returns Optional[1700]
```

As Streams collect, it also requires an associative function, Integer::sum satisfies that property. The downside is that it requires an array and can't be used with lists. Although the parallelPrefix is very efficient, setting up the array to work with it could not pay off.

Wrapping up:

Again, it's possible to achieve this with Java Streams although it won't be as efficient as a traditional loop both in time and space. But you benefit from the compositionality of streams. As always, it's a trade-off.

Body:
Context/Scenario

Let's say we have an immutable object called Transaction, where transaction.getAction() would return a TransactionAction enum which can be DEPOSIT or WITHDRAW, and transaction.getAmount() would return an Integer which specify the amount of money being deposit or withdrawn.

enum TransactionAction {
    WITHDRAW,
    DEPOSIT
}

public class Transaction {

    private final TransactionAction action;
    private final int amount;

    public Transaction(TransactionAction action, int amount) {
        this.action = action;
        this.amount = amount;
    }

    public TransactionAction getAction() {
        return action;
    }

    public int getAmount() {
        return amount;
    }

}

Question

We now have a Stream<Transaction> which is a stream filled with Transaction that can either be DEPOSIT or WITHDRAW. We can imagine this Stream<Transaction> as a history of transactions of one particular bank account.

What I am trying to achieve is to get the highest balance the account has ever achieved in most efficient manner (thus using Stream API).

Example

Bob transaction history is:

// balance start at 0
[DEPOSIT]   1200        // balance: 1200
[DEPOSIT]   500         // balance: 1700
[WITHDRAW]  700         // balance: 1000
[DEPOSIT]   300         // balance: 1300
[WITHDRAW]  800         // balance: 500
[WITHDRAW]  500         // balance: 0

Bob's highest balance is 1700.

Body:
What you need is to find the maximum value of a cumulative sum. In pseudo-code, this would be something like:

transactions = [1200, 500, -700, 300, -800, -500]
csum = cumulativeSum(transactions) // should be [1200,1700,1000,1300,500,0]
max(csum) // should be 1700

The imperative way:

The traditional for-loop is well suited for such cases. It should be fairly easy to write and is probably the most efficient alternative both in time and space. It does not require multiple iterations and it does not require extra lists.

int max = 0;
int csum = 0;
for (Transaction t: transactions) {
    int amount = (t.getAction() == TransactionAction.WITHDRAW ? -1 : 1) * t.getAmount();
    csum += amount;
    if (csum > max) max = csum;
}

Diving into functional:

Streams are a functional programming concept and, as such, they are free of side-effects and well suited for stateless operations. Keeping the cumulative state is considered a side-effect, and then we would have to talk about Monads to bring those side-effects under control and... we don't want to go that way.

Java, not being a functional language (although allowing for functional style), cares less about purity. You could simply have a control variable outside the stream to keep track of that external state within the current map or reduce operations. But that would also be giving up everything Streams are meant for.

So let's see how Java's experienced fellows do in this matter. In pure Haskell, the cumulative sum can be achieved with a Scan Left operation:

λ> scanl1 (+) [1200, 500, -700, 300, -800, -500]
[1200,1700,1000,1300,500,0]

Finding the maximum of this would be as simple as:

λ> maximum ( scanl1 (+) [1200, 500, -700, 300, -800, -500] )
1700

A Java Streams solution:

Java does not have such an idiomatic way of expressing a scan left, but you may achieve a similar result with collect.

transactions.stream()
    .map(t -> (t.getAction() == TransactionAction.WITHDRAW ? -1 : 1) * t.getAmount())
    .collect(ArrayList<Integer>::new, (csum, amount) ->
        csum.add(csum.size() > 0 ? csum.get(csum.size() - 1) + amount : amount),
        ArrayList::addAll)
    .stream()
    .max(Integer::compareTo);
// returns Optional[1700]

EDIT: As correctly pointed out in the comments, this accumulator function is not associative and problems would appear if trying to use parallelStream instead of stream.

This can be further simplified. For example, if you enrich your TransactionAction enum with a multiplier (-1 for WITHDRAW and 1 for DEPOSIT), then map could be replaced with:

.map(t -> t.getAction().getMultiplier() * t.getAmount())

EDIT: Yet another approach: Parallel Prefix Sum

Since Java 8, arrays offer a parallelPrefix operation that could be used like:

Integer[] amounts = transactions.stream()
    .map(t -> (t.getAction() == TransactionAction.WITHDRAW ? -1 : 1) * t.getAmount())
    .toArray(Integer[]::new);

Arrays.parallelPrefix(amounts, Integer::sum);

Arrays.stream(amounts).max(Integer::compareTo);
// returns Optional[1700]

As Streams collect, it also requires an associative function, Integer::sum satisfies that property. The downside is that it requires an array and can't be used with lists. Although the parallelPrefix is very efficient, setting up the array to work with it could not pay off.

Wrapping up:

Again, it's possible to achieve this with Java Streams although it won't be as efficient as a traditional loop both in time and space. But you benefit from the compositionality of streams. As always, it's a trade-off.


问:
Whats the point of DOCTYPE?
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks </p>

<p>UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01? </p>

答:
The biggest thing is having a doctype or not. If you don't, the browser will work in a "quirks" mode rather than standards mode and many things will be slightly different. If you have one — any — that typically activates more standards-compliant behavior in the browser.

See this article for the details of what doctypes do on various different browsers and what modes — quirks, standards, almost-standards, etc. — different browsers have. Quoting a relevant section:

Modes for text/html Content

The choice
  of the mode for text/html content
  depends on doctype sniffing (discussed
  later in this document). In IE8 and
  IE9, the mode also depends on other
  factors. However, by default even in
  IE8 and IE9, the mode depends on the
  doctype for non-intranet sites that
  are not on a blacklist supplied by
  Microsoft.

It cannot be stressed
  enough that the exact behavior of the
  modes varies from browser to browser
  even though discussion in this
  document has been unified.

Quirks Mode

In the Quirks mode the
  browsers violate contemporary Web
  format specifications in order to
  avoid “breaking” pages authored
  according to practices that were
  prevalent in the late 1990s. Different
  browsers implement different quirks.
  In Internet Explorer 6, 7, 8 and 9,
  the Quirks mode is effectively frozen
  IE 5.5. In other browsers, the Quirks
  mode is a handful of deviations from
  the Almost Standards mode.

If you are authoring new pages now,
  you are supposed to comply with the
  relevant specifications (CSS 2.1 in
  particular) and use the Standards
  mode.

Standards Mode

In the Standards mode
  the browsers try to give conforming
  documents the specification-wise
  correct treatment to the extent
  implemented in a particular browser.

Since different browsers are at
  different stages of compliance, the
  Standards mode isn’t a single target,
  either.

HTML 5 calls this mode the “no quirks
  mode”.

Almost Standards Mode

Firefox, Safari,
  Chrome, Opera (since 7.5), IE8 and IE9
  also have a mode known as “the Almost
  Standards mode”, which implements the
  vertical sizing of table cells
  traditionally and not rigorously
  according to the CSS2 specification.
  Mac IE 5, Windows IE 6 and 7, Opera
  prior to 7.5 and Konqueror do not need
  an Almost Standards mode, because they
  don’t implement the vertical sizing of
  table cells rigorously according to
  the CSS2 specification in their
  respective Standards modes anyway. In
  fact, their Standards modes are closer
  to the Almost Standards mode than to
  the Standards mode of newer browsers.

HTML 5 calls this mode the “limited
  quirks mode”.

IE7 Mode

IE8 and IE9 have a mode that
  is mostly a frozen copy of the mode
  that was the Standards mode in IE7.
  Other browsers do not have a mode like
  this, and this mode is not specified
  by HTML5.

IE8 Standards Mode

IE9 has a mode that
  is mostly a frozen copy of the mode
  that was the Standards mode in IE8.
  Other browsers do not have a mode like
  this, and this mode is not specified
  by HTML5.

IE8 Almost Standards Mode

IE9 has a
  mode that is mostly a frozen copy of
  the mode that was the Almost Standards
  mode in IE8. Other browsers do not
  have a mode like this, and this mode
  is not specified by HTML5.

...but see the article for a full discussion.

Title: Whats the point of DOCTYPE?

Body:
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks

UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01?