问:
How to correctly use php header(Location: )
I have read several answers and questions, however, I still cannot seem to get my header() to work.  This is just a simple contact form, and This is my last step to send guests to a thankyou page.  What am I missing.

```<code>  <?php

    $fname = $lname = $cname = $email = $budget = $services = "";

    $error_counter = 0;

    $error_report = "";

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

      if (empty($_POST['fname'])) {
        $fname_error = 'Please provide your first name.';
        $error_counter++;
      } else {
        $fname = test_input($_POST['fname']);

        if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
          $fnameErr = "Only letters and white space allowed";
          $error_counter++;
        }
      }
      if (empty($_POST['lname'])) {
        $lname_error = 'Please provide your last name.';
        $error_counter++;
      } else {
        $lname = test_input($_POST['lname']);

        if (!preg_match("/[a-zA-Z \.]/",$lname)) {
          $lnameErr = "Only letters and white space allowed";
          $error_counter++;
        }
      }
      if (empty($_POST['cname'])) {
        $cname = '';
      } else {
        $cname = test_input($_POST['cname']);

        if (!preg_match("/^[a-zA-Z0-9 \.]*$/",$cname)) {
          $cnameErr = "Only letters and white space allowed";
          $error_counter++;
        }
      }
      if (empty($_POST['phone'])) {
        $phone = '';
      } else {
        $phone = test_input($_POST['phone']);

        if (!preg_match("/^[()\-0-9 \.]*$/",$phone)) {
          $phoneErr = "Please use only the following: ( ) - . 0-9.";
          $error_counter++;
        }
      }
      if (empty($_POST['email'])) {
        $email_error = 'Please provide an email so that I can get back in touch with you.';
        $error_counter++;
      }  else {
        $email = test_input($_POST['email']);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { //validate email
          $emailErr = "Invalid email format";
          $error_counter++;
        }
      }
      if (empty($_POST['budget'])) {
        $budget_error = 'Please provide an estimated budget.';
        $error_counter++;
      } else {
        $budget = test_input($_POST['budget']);
      }
      if (empty($_POST['textarea'])) {
        $textarea = '';
      } else {
        $textarea = test_input($_POST['textarea']);
      }

      if (isset($_POST['new-website'])) {
        $services = $services."New Website<br>";
      }
      if (isset($_POST['website-redesign'])) {
        $services = $services."Website Re-design<br>";
      }
      if (isset($_POST['mobile-website'])) {
        $services = $services."Mobile Website<br>";
      }
      if (isset($_POST['online-resume'])) {
        $services = $services."Online Resume<br>";
      }
      if (isset($_POST['non-profit-website'])) {
        $services = $services."Non-profit Website<br>";
      }
      if (isset($_POST['seo'])) {
        $services = $services."SEO<br>";
      }
      if (isset($_POST['google-adwords'])) {
        $services = $services."Google AdWords<br>";
      }
      if (isset($_POST['graphics-design'])) {
        $services = $services."Graphics Design<br>";
      }
      if (isset($_POST['other'])) {
        $services = $services."Other<br>";
      }

      $fname = test_input($_POST['fname']);
      $lname = test_input($_POST['lname']);
      $cname = test_input($_POST['cname']);
      $phone = test_input($_POST['phone']);
      $email = test_input($_POST['email']);
      $budget = test_input($_POST['budget']);
      $textarea = test_input($_POST['textarea']);

      if ($error_counter == 0) {

        $to = "dpeaches96@gmail.com";
        $subject = "Website Contact Peachwebdev";

        $name_final = "Name: ".$fname." ".$lname."<br><br>";
        $company_final = "Company: ".$cname."<br><br>";
        $phone_final = "Phone Number: ".$phone."<br><br>";
        $email_final = "Email: ".$email."<br><br>";
        $budget_final = "Est. Budget: ".$budget."<br><br>";
        $services_final = "Services: <br>".$services."<br><br>";
        $textarea_final = "Comments:  ".$textarea."<br><br>";
        $message =  $name_final.$company_final.$phone_final.$email_final.$budget_final.$services_final.$textarea_final;

        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= 'From: '.$email;

        mail($to,$subject,$message,$headers);

        header("Location: http://www.peachwebdev.com/pages/thankyou.html");
        exit;

      } else {
        echo '<script type="text/javascript"> alert(\'There were errors in your form. Please try again.\'); </script>';
        $error_report = "<div class='alert alert-danger'>There were errors in your form, please correct and submit again.</div>";
      }

    }

    function test_input($data) {
      $data = htmlspecialchars($data);
      $data = trim($data);
      $data = stripslashes($data);
      return $data;
    }

     ?>
</code>```

And I am aware that my code can probably made better, so if there are suggestions on simplifying or condensing, I would gladly appreciate it!

答:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
Refer the documentation.

One way to test is replace the call to header() in your code with a simple echo with some custom string (say 'XYZXYZ'). Then look at the raw output and check if there are any characters before this string.

Body:
I have read several answers and questions, however, I still cannot seem to get my header() to work.  This is just a simple contact form, and This is my last step to send guests to a thankyou page.  What am I missing.

  <?php

    $fname = $lname = $cname = $email = $budget = $services = "";

    $error_counter = 0;

    $error_report = "";

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

      if (empty($_POST['fname'])) {
        $fname_error = 'Please provide your first name.';
        $error_counter++;
      } else {
        $fname = test_input($_POST['fname']);

        if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
          $fnameErr = "Only letters and white space allowed";
          $error_counter++;
        }
      }
      if (empty($_POST['lname'])) {
        $lname_error = 'Please provide your last name.';
        $error_counter++;
      } else {
        $lname = test_input($_POST['lname']);

        if (!preg_match("/[a-zA-Z \.]/",$lname)) {
          $lnameErr = "Only letters and white space allowed";
          $error_counter++;
        }
      }
      if (empty($_POST['cname'])) {
        $cname = '';
      } else {
        $cname = test_input($_POST['cname']);

        if (!preg_match("/^[a-zA-Z0-9 \.]*$/",$cname)) {
          $cnameErr = "Only letters and white space allowed";
          $error_counter++;
        }
      }
      if (empty($_POST['phone'])) {
        $phone = '';
      } else {
        $phone = test_input($_POST['phone']);

        if (!preg_match("/^[()\-0-9 \.]*$/",$phone)) {
          $phoneErr = "Please use only the following: ( ) - . 0-9.";
          $error_counter++;
        }
      }
      if (empty($_POST['email'])) {
        $email_error = 'Please provide an email so that I can get back in touch with you.';
        $error_counter++;
      }  else {
        $email = test_input($_POST['email']);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { //validate email
          $emailErr = "Invalid email format";
          $error_counter++;
        }
      }
      if (empty($_POST['budget'])) {
        $budget_error = 'Please provide an estimated budget.';
        $error_counter++;
      } else {
        $budget = test_input($_POST['budget']);
      }
      if (empty($_POST['textarea'])) {
        $textarea = '';
      } else {
        $textarea = test_input($_POST['textarea']);
      }

      if (isset($_POST['new-website'])) {
        $services = $services."New Website
";
      }
      if (isset($_POST['website-redesign'])) {
        $services = $services."Website Re-design
";
      }
      if (isset($_POST['mobile-website'])) {
        $services = $services."Mobile Website
";
      }
      if (isset($_POST['online-resume'])) {
        $services = $services."Online Resume
";
      }
      if (isset($_POST['non-profit-website'])) {
        $services = $services."Non-profit Website
";
      }
      if (isset($_POST['seo'])) {
        $services = $services."SEO
";
      }
      if (isset($_POST['google-adwords'])) {
        $services = $services."Google AdWords
";
      }
      if (isset($_POST['graphics-design'])) {
        $services = $services."Graphics Design
";
      }
      if (isset($_POST['other'])) {
        $services = $services."Other
";
      }

      $fname = test_input($_POST['fname']);
      $lname = test_input($_POST['lname']);
      $cname = test_input($_POST['cname']);
      $phone = test_input($_POST['phone']);
      $email = test_input($_POST['email']);
      $budget = test_input($_POST['budget']);
      $textarea = test_input($_POST['textarea']);

      if ($error_counter == 0) {

        $to = "dpeaches96@gmail.com";
        $subject = "Website Contact Peachwebdev";

        $name_final = "Name: ".$fname." ".$lname."

";
        $company_final = "Company: ".$cname."

";
        $phone_final = "Phone Number: ".$phone."

";
        $email_final = "Email: ".$email."

";
        $budget_final = "Est. Budget: ".$budget."

";
        $services_final = "Services:
".$services."

";
        $textarea_final = "Comments:  ".$textarea."

";
        $message =  $name_final.$company_final.$phone_final.$email_final.$budget_final.$services_final.$textarea_final;

        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= 'From: '.$email;

        mail($to,$subject,$message,$headers);

        header("Location: http://www.peachwebdev.com/pages/thankyou.html");
        exit;

      } else {
        echo '';
        $error_report = "
There were errors in your form, please correct and submit again.
";
      }

    }

    function test_input($data) {
      $data = htmlspecialchars($data);
      $data = trim($data);
      $data = stripslashes($data);
      return $data;
    }

     ?>

And I am aware that my code can probably made better, so if there are suggestions on simplifying or condensing, I would gladly appreciate it!


来源: stackexchange

问:
ReactJS: Uncaught TypeError: this.props. is not a function
I have two react-components. Parent component has a function handleOnChangeTaskCategory which is used like props in child component.
Parent component:

export default class TodoList extends React.Component{
    constructor(props) {
        this.handleOnChangeTaskCategory = this.handleOnChangeTaskCategory.bind(this);
    }

    handleOnChangeTaskCategory(taskList) {//
    }

    render() {
        return (

{
                    this.state.toDoList.map(taskList => {
                        return <TaskGroup onEditTaskCategory={this.handleOnEditTaskCategory} />
                    })
                }

        );
    }
}```
</div>
</div>
</p>
<p>And children component:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export default class TaskGroup extends React.Component {
    constructor(props) {
        this.handleOnAddTask = this.handleOnAddTask.bind(this);
    }
    handleOnAddTask() {
        this.props.onEditTaskCategory(update(this.props.listOfTasks, {
            tasks: {
                $push: newTask
            }
        }));
    }

    render() {
        return (
                    Add task
        );
    }
}</code>```

But when I click "Add task", I have an error

Uncaught TypeError: this.props.onEditTaskCategory is not a function
at TaskGroup.handleOnAddTask

答:
class method -> handleOnChangeTaskCategory
method passed to component property -> handleOnEditTaskCategory

you have typo there

ContentLicense: CC BY-SA 4.0

Body:
I have two react-components. Parent component has a function handleOnChangeTaskCategory which is used like props in child component.
Parent component:

export default class TodoList extends React.Component{
    constructor(props) {
        this.handleOnChangeTaskCategory = this.handleOnChangeTaskCategory.bind(this);
    }

    handleOnChangeTaskCategory(taskList) {//
    }

    render() {
        return (

{
                    this.state.toDoList.map(taskList => {
                        return <TaskGroup onEditTaskCategory={this.handleOnEditTaskCategory} />
                    })
                }

        );
    }
}

And children component:

export default class TaskGroup extends React.Component {
    constructor(props) {
        this.handleOnAddTask = this.handleOnAddTask.bind(this);
    }
    handleOnAddTask() {
        this.props.onEditTaskCategory(update(this.props.listOfTasks, {
            tasks: {
                $push: newTask
            }
        }));
    }

    render() {
        return (
                    Add task
        );
    }
}

But when I click "Add task", I have an error

Uncaught TypeError: this.props.onEditTaskCategory is not a function
at TaskGroup.handleOnAddTask

ContentLicense: CC BY-SA 3.0


问:
How to import .graphql files with webpack
Trying to import this file:

```<code>subscription onNewNotification {
    notification {
        id
        content
        seen
    }
}
</code>```

I get this error when running babel-node to compile the whole thing: SyntaxError: .../graphql/NotificationSubscription.graphql: Unexpected token, expected ;

This is how my webpack loaders look like:

```<code>module: {
        loaders: [
            {
                test: /\.js?$/,
                include: [
                    path.join(__dirname, 'client'),
                    path.join(__dirname, 'server/shared'),
                ],
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['react-hmre'],
                },
            },
            {
                test: /\.json?$/,
                loader: 'json-loader',
            },
            {
                test: /\.scss$/,
                loaders: ['style-loader', 'css-loader', 'sass-loader'],
            },
            { test: /\.css$/, loader: 'style-loader!css-loader' },

            { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=image/svg+xml' },
            {
                test: /\.(graphql|gql)$/,
                exclude: /node_modules/,
                loader: 'graphql-tag/loader',
            },
        ],

    },
</code>```

No idea why this is happening, I'm following the Apollo docs and I don't see anything about this on google: http://dev.apollodata.com/react/webpack.html

答:
Well, I am having the same problem too. After talk with on guy on apollo slack channel we start to debug and discover what is the problem. We discover that the problem was the 'babel-register' that in some kind of way trying to compile the .graphql files even with the rule to ignore. So there are two paths you can go:

Easier to do:
Instead of creating a graphql file you can just create a js file to save your queries and create them using the gql function on react-apollo package and export it as a variable.

More sofisticated:
If you use webpack you can create a configuration that will compile all your server code in one bundle and run the bundle using node (no babel-node or babel-register) like it is in GitHunt-React example (https://github.com/apollographql/GitHunt-React). It's not so simple like the first one but it's more elegant.

Body:
Trying to import this file:

subscription onNewNotification {
    notification {
        id
        content
        seen
    }
}

I get this error when running babel-node to compile the whole thing: SyntaxError: .../graphql/NotificationSubscription.graphql: Unexpected token, expected ;

This is how my webpack loaders look like:

module: {
        loaders: [
            {
                test: /\.js?$/,
                include: [
                    path.join(__dirname, 'client'),
                    path.join(__dirname, 'server/shared'),
                ],
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['react-hmre'],
                },
            },
            {
                test: /\.json?$/,
                loader: 'json-loader',
            },
            {
                test: /\.scss$/,
                loaders: ['style-loader', 'css-loader', 'sass-loader'],
            },
            { test: /\.css$/, loader: 'style-loader!css-loader' },

            { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?mimetype=image/svg+xml' },
            {
                test: /\.(graphql|gql)$/,
                exclude: /node_modules/,
                loader: 'graphql-tag/loader',
            },
        ],

    },

No idea why this is happening, I'm following the Apollo docs and I don't see anything about this on google: http://dev.apollodata.com/react/webpack.html


问:
Get DataFlavor[] from a custom DataFlavor
I want created a program that copies images from a folder into the clipboard, but the images become black.

After doing some research, I found this: Clipboard copy from outlook always has black background set when retrieved as image from Java clipboard object
There he says using image\x-emf fixes the problem. But I can't figure out how to get the TransferData from " new DataFlavor("image/x-emf") "

```<code>package Package1;

import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.ImageIcon;

/** Transferable image */
public class imageSelection implements Transferable {
    private Image image;

    /** Creates a transferable object that is an image.
     *  <p>imageSelection(Image)
     * */
    public imageSelection(Image image) {
        this.image = image;
    }

    public DataFlavor[] getTransferDataFlavors() {
        //DataFlavor[] BlackBackgroundImage = new DataFlavor[] { DataFlavor.imageFlavor }; // <--- Gives me a black background instead of transparent

        DataFlavor[] transferData = null;
        try {
            transferData =  new DataFlavor("image/x-emf"); // <---- How to get TransferData from this
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            error.displayError(e.getStackTrace(), "Error creating DataFlavor (mime type: image/x-emf)");
        }
        return transferData;
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return DataFlavor.imageFlavor.equals(flavor);
    }

    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (!DataFlavor.imageFlavor.equals(flavor)) {
            throw new UnsupportedFlavorException(flavor);
        }
        return image;
    }
}
</code>```

Method call (where emojiLocation is the path to the image):

```<code>imageSelection imgSel = new imageSelection(new ImageIcon(emojiLocation).getImage());
</code>```

Thanks in advance!

答:
Solution:
    return new DataFlavor[] { transferData }
Sorry for missing something so obvious.
This didn't lead me to other problems tho and didn't allow me to achieve a transparent image, so I made a new question in hope to solve this: Set clipboard to transparent image</p>

Body:
I want created a program that copies images from a folder into the clipboard, but the images become black.

After doing some research, I found this: Clipboard copy from outlook always has black background set when retrieved as image from Java clipboard object
There he says using image\x-emf fixes the problem. But I can't figure out how to get the TransferData from " new DataFlavor("image/x-emf") "

package Package1;

import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.ImageIcon;

/** Transferable image */
public class imageSelection implements Transferable {
    private Image image;

    /** Creates a transferable object that is an image.
     *
imageSelection(Image)
     * */
    public imageSelection(Image image) {
        this.image = image;
    }

    public DataFlavor[] getTransferDataFlavors() {
        //DataFlavor[] BlackBackgroundImage = new DataFlavor[] { DataFlavor.imageFlavor }; // <--- Gives me a black background instead of transparent

        DataFlavor[] transferData = null;
        try {
            transferData =  new DataFlavor("image/x-emf"); // <---- How to get TransferData from this
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            error.displayError(e.getStackTrace(), "Error creating DataFlavor (mime type: image/x-emf)");
        }
        return transferData;
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return DataFlavor.imageFlavor.equals(flavor);
    }

    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (!DataFlavor.imageFlavor.equals(flavor)) {
            throw new UnsupportedFlavorException(flavor);
        }
        return image;
    }
}

Method call (where emojiLocation is the path to the image):

imageSelection imgSel = new imageSelection(new ImageIcon(emojiLocation).getImage());

Thanks in advance!


问:
Using a single constructor union type
In Elm, I sometimes find myself defining a record type by using a union type with only a single constructor. I then use a case-statement with only a single case to unpack the record fields:

```<code>type Model =
    Model { stack: List Int }

update msg model =
    case model of
        Model { stack } ->
            ...
</code>```

Is there a shorter way to unpack this? The single-case case looks kind of silly. It causes unnecessary indentation and verbosity.

Also: I'm using type instead of type alias to be more explicit when dealing with the central data structures in a program (which tend to have few fields and be used in only a few places in the program, so the extra  verbosity is not that much of a problem). Would it be better style to just give up on this approach and use a type alias for records whenever possible?

答:
You can pattern match in the function signature itself:

update msg (Model model) =
    model.stack ...
```

<p>or, if you want to use <code>stack</code> directly:</p>

<pre class="lang-elm prettyprint-override"><code>update msg (Model { stack }) =
    ...
</code>```

As for whether you should do this type of thing? I've used it in the past when explicitly trying to hide implementation details from a model. You just have to be willing to deal with the extra verbosity that it inevitably introduces. It really is up to you to decide whether it is necessary. I would probably lean towards avoiding it unless there's an explicit need.

Title: Using a single constructor union type

Body:
In Elm, I sometimes find myself defining a record type by using a union type with only a single constructor. I then use a case-statement with only a single case to unpack the record fields:

type Model =
    Model { stack: List Int }

update msg model =
    case model of
        Model { stack } ->
            ...

Is there a shorter way to unpack this? The single-case case looks kind of silly. It causes unnecessary indentation and verbosity.

Also: I'm using type instead of type alias to be more explicit when dealing with the central data structures in a program (which tend to have few fields and be used in only a few places in the program, so the extra  verbosity is not that much of a problem). Would it be better style to just give up on this approach and use a type alias for records whenever possible?

Body:
You can pattern match in the function signature itself:

update msg (Model model) =
    model.stack ...

or, if you want to use stack directly:

update msg (Model { stack }) =
    ...

As for whether you should do this type of thing? I've used it in the past when explicitly trying to hide implementation details from a model. You just have to be willing to deal with the extra verbosity that it inevitably introduces. It really is up to you to decide whether it is necessary. I would probably lean towards avoiding it unless there's an explicit need.


问:
SyntaxError when extending Number object
I am trying to extend the Number object with this code:

Number.prototype.isNumber = function(i){
  if(arguments.length === 1){
    return !isNaN(parseFloat(i)) && isFinite(i);
  } else {
    return !isNaN(parseFloat(this)) && isFinite(this);
  }
}

try {
  var x = 8.isNumber();
} catch(err) {
  console.log(err);
}```
</div>
</div>
</p>

<p>I get <code>SyntaxError: identifier starts immediately after numeric literal</code></p>

<p>also when I try the following:</p>

```Number.isNumber(8)
```

I get Number.isNumber is not a function!!

答:
I couldn't help it but provide an additional answer although you already accepted one.

The first thing you need to know, is that there is a fundamental difference between the Number object, and the Number prototype (see here).

As it stands, you are extending the Number prototype, not the object itself! Your isNumber implementation actually has the same effect like the following:

```<code>Number.prototype.isNumber = function(){return isFinite(this)}
</code>```

Why? Because in order to execute this prototype method, the parser first needs to know the type of the literal you are invoking the function on. That's why you either need to turn your number literal into an expression by wrapping it in parentheses: (8).isNumber() or by using an even weirder notation 8..isNumber() (the first . is the decimal point, the second the property accessor). At this point, the javascript engine already evaluated it as a Number and thus can execute the isNumber() method.

On the other hand, although at first glimpse your code looks like it could handle the following case correctly (since you are doing a parseFloat): "8".isNumber() will always throw an exception, because here we have a string literal, and the String prototype does not have the according method. This means, you will never be able to detect numbers that are actually string literals in the first place.

What you instead should do, is directly extend the Number object so you can actually do a proper check without having to deal with errors:

```<code>Number.isFiniteNumber = function(i){
    return !Number.isNaN(i) && Number.isFinite(i);
}

Number.isFiniteNumber(8);        // returns true
Number.isFiniteNumber("3.141");  // returns true
Number.isFiniteNumber(".2e-34"); // returns true
Number.isFiniteNumber(Infinity); // returns false

// just for informational purposes
typeof Infinity === "number" // is true
</code>```

Bonus material:

Extending native objects is potentially dangerous.

Number.isNaN() probably does not what you think it does.

Body:
I am trying to extend the Number object with this code:

Number.prototype.isNumber = function(i){
  if(arguments.length === 1){
    return !isNaN(parseFloat(i)) && isFinite(i);
  } else {
    return !isNaN(parseFloat(this)) && isFinite(this);
  }
}

try {
  var x = 8.isNumber();
} catch(err) {
  console.log(err);
}

I get SyntaxError: identifier starts immediately after numeric literal

also when I try the following:

Number.isNumber(8)

I get Number.isNumber is not a function!!

Body:
I couldn't help it but provide an additional answer although you already accepted one.

The first thing you need to know, is that there is a fundamental difference between the Number object, and the Number prototype (see here).

As it stands, you are extending the Number prototype, not the object itself! Your isNumber implementation actually has the same effect like the following:

Number.prototype.isNumber = function(){return isFinite(this)}

Why? Because in order to execute this prototype method, the parser first needs to know the type of the literal you are invoking the function on. That's why you either need to turn your number literal into an expression by wrapping it in parentheses: (8).isNumber() or by using an even weirder notation 8..isNumber() (the first . is the decimal point, the second the property accessor). At this point, the javascript engine already evaluated it as a Number and thus can execute the isNumber() method.

On the other hand, although at first glimpse your code looks like it could handle the following case correctly (since you are doing a parseFloat): "8".isNumber() will always throw an exception, because here we have a string literal, and the String prototype does not have the according method. This means, you will never be able to detect numbers that are actually string literals in the first place.

What you instead should do, is directly extend the Number object so you can actually do a proper check without having to deal with errors:

Number.isFiniteNumber = function(i){
    return !Number.isNaN(i) && Number.isFinite(i);
}

Number.isFiniteNumber(8);        // returns true
Number.isFiniteNumber("3.141");  // returns true
Number.isFiniteNumber(".2e-34"); // returns true
Number.isFiniteNumber(Infinity); // returns false

// just for informational purposes
typeof Infinity === "number" // is true

Bonus material:

Extending native objects is potentially dangerous.

Number.isNaN() probably does not what you think it does.


问:
Knockout adding options to select list
I am struggling figuring out how to correctly add more options to a select list dynamically.

This code works, but it wipes out everything existing in the array because it is setting the value of the array instead of pushing:

```<code>// add seller to dropdown list
var opts = [];
opts.push({Text: studentName, Value: result.sellerID});
console.log("opts: " + JSON.stringify(opts));
if (sellerOptionModel.sellers.indexOf(opts) < 0) {
  sellerOptionModel.sellers(opts);
}
</code>```

And this code does not work, it just adds a blank item to the dropdown select list:

```<code>// add seller to dropdown list
var opts = [];
opts.push({Text: studentName, Value: result.sellerID});
console.log("opts: " + JSON.stringify(opts));
if (sellerOptionModel.sellers.indexOf(opts) < 0) {
  sellerOptionModel.sellers.push(opts);
}
</code>```

ViewModel:

```<code>var SellerOptionModel = function() {
  var self = this;
  self.sellers = ko.observableArray([]);
  self.sellerID = ko.observable();
}
</code>```

Full JS function with the above KO code in in the success part:

```<code>$("#nextForm").on('click', function(e) {
  e.preventDefault();
  var room = $("#roomSelect").val();
  var invalidItems = invalidItemsArr.join(",");
  $("#invalidItems").val(invalidItems);
  if(verify == "True") {
    var seller = $('#sellerSelect').val();
  }
  if(room == "") {
    e.preventDefault();
    slideDownMsg("Please select a room first.");
    slideUpMsg(4000);
  } else {
    var firstName = capitalizeFirstLetter($.trim($("#firstName").val()));
    var lastName = capitalizeFirstLetter($.trim($("#lastName").val()));
    if(verify != "True" && (firstName == "" || lastName == "")) {
      e.preventDefault();
      slideDownMsg("Please fill in the student's first and last name.");
      slideUpMsg(3500);
    } else if(seller == "") {
      e.preventDefault();
      slideDownMsg("Please select a seller from the dropdown.");
      slideUpMsg(3500);
    } else { // all good we can save the student
      $.ajax({
        url: '@Url.Action("SaveStudent", "Tally")',
        type: 'POST',
        data: $("#tallyForm").serialize(),
        success: function (result) {
          if(result.success == true) {
            var studentName = firstName + " " + lastName;
            slideDownMsg("Tally entry saved for " + studentName + ".");
            slideUpMsg(4000);
            var room = $("#roomSelect").val();
            $("#tallyForm")[0].reset();
            $("#roomSelect").val(room);
            tallyViewModel.items([]);
            tallyViewModel.addLine();
            if(room != "") {
              getImage(room);
            }
            tallyViewModel.runningQty(0);
            tallyViewModel.runningTotal(0);

            // add seller to dropdown list
            var opts = [];
            opts.push({Text: studentName, Value: result.sellerID});
            console.log("opts: " + JSON.stringify(opts));
            if (sellerOptionModel.sellers.indexOf(opts) < 0) {
              sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID})
            }
            sellerOptionModel.sellers.sort();
          } else {
            slideDownMsg("Failed saving tally entry for " + firstName + " " + lastName + ".");
            slideUpMsg(4000);
          }
        },
        error: function (request, status, error) {
          e.preventDefault();
          displayError("Error", request.responseText);
        }
      });
    }
  }
});
</code>```

答:
Dynamically adding items to a select list in knockout should be as easy as adding the item to the observable array that the select list is bound to. The trick is not replacing the contents of the existing array.

Instead of creating a new array, and setting the observable array to it, you should directly push the item into the original observable array.

```<code>sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID});
</code>```

The problem of only adding an item if it doesn't already exist boils down to how you define whether an item is the same item. Normally an "object" is only equivalent if it's the exact same object reference, and a similar object with the same internal values does not count. For example:

```<code>var a = { id: 3 };
var b = { id: 3 };
console.log(a == b); //returns false;
</code>```

What you really want to use to compare your option objects is probably the Value property that you've given them. indexOf isn't going to help you there so you'll need to loop through the items manually and check each one's Value property against the new item's value.

```<code>var match = false;
for (var i = 0; i < sellerOptionModel.sellers().length; i++) {
    if(sellerOptionModel.sellers()[i].Value == result.sellerID){
        match = true;
        break;
    }
}
if (!match) {
    console.log("new id added");
    sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID});
    sellerOptionModel.sellers.sort();
}else{
    console.log("id already exists")
}
</code>```

Working example: https://jsfiddle.net/jlspake/8c3tvn9u/

Title: Knockout adding options to select list

Body:
I am struggling figuring out how to correctly add more options to a select list dynamically.

This code works, but it wipes out everything existing in the array because it is setting the value of the array instead of pushing:

// add seller to dropdown list
var opts = [];
opts.push({Text: studentName, Value: result.sellerID});
console.log("opts: " + JSON.stringify(opts));
if (sellerOptionModel.sellers.indexOf(opts) < 0) {
  sellerOptionModel.sellers(opts);
}

And this code does not work, it just adds a blank item to the dropdown select list:

// add seller to dropdown list
var opts = [];
opts.push({Text: studentName, Value: result.sellerID});
console.log("opts: " + JSON.stringify(opts));
if (sellerOptionModel.sellers.indexOf(opts) < 0) {
  sellerOptionModel.sellers.push(opts);
}

ViewModel:

var SellerOptionModel = function() {
  var self = this;
  self.sellers = ko.observableArray([]);
  self.sellerID = ko.observable();
}

Full JS function with the above KO code in in the success part:

$("#nextForm").on('click', function(e) {
  e.preventDefault();
  var room = $("#roomSelect").val();
  var invalidItems = invalidItemsArr.join(",");
  $("#invalidItems").val(invalidItems);
  if(verify == "True") {
    var seller = $('#sellerSelect').val();
  }
  if(room == "") {
    e.preventDefault();
    slideDownMsg("Please select a room first.");
    slideUpMsg(4000);
  } else {
    var firstName = capitalizeFirstLetter($.trim($("#firstName").val()));
    var lastName = capitalizeFirstLetter($.trim($("#lastName").val()));
    if(verify != "True" && (firstName == "" || lastName == "")) {
      e.preventDefault();
      slideDownMsg("Please fill in the student's first and last name.");
      slideUpMsg(3500);
    } else if(seller == "") {
      e.preventDefault();
      slideDownMsg("Please select a seller from the dropdown.");
      slideUpMsg(3500);
    } else { // all good we can save the student
      $.ajax({
        url: '@Url.Action("SaveStudent", "Tally")',
        type: 'POST',
        data: $("#tallyForm").serialize(),
        success: function (result) {
          if(result.success == true) {
            var studentName = firstName + " " + lastName;
            slideDownMsg("Tally entry saved for " + studentName + ".");
            slideUpMsg(4000);
            var room = $("#roomSelect").val();
            $("#tallyForm")[0].reset();
            $("#roomSelect").val(room);
            tallyViewModel.items([]);
            tallyViewModel.addLine();
            if(room != "") {
              getImage(room);
            }
            tallyViewModel.runningQty(0);
            tallyViewModel.runningTotal(0);

            // add seller to dropdown list
            var opts = [];
            opts.push({Text: studentName, Value: result.sellerID});
            console.log("opts: " + JSON.stringify(opts));
            if (sellerOptionModel.sellers.indexOf(opts) < 0) {
              sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID})
            }
            sellerOptionModel.sellers.sort();
          } else {
            slideDownMsg("Failed saving tally entry for " + firstName + " " + lastName + ".");
            slideUpMsg(4000);
          }
        },
        error: function (request, status, error) {
          e.preventDefault();
          displayError("Error", request.responseText);
        }
      });
    }
  }
});

Body:
Dynamically adding items to a select list in knockout should be as easy as adding the item to the observable array that the select list is bound to. The trick is not replacing the contents of the existing array.

Instead of creating a new array, and setting the observable array to it, you should directly push the item into the original observable array.

sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID});

The problem of only adding an item if it doesn't already exist boils down to how you define whether an item is the same item. Normally an "object" is only equivalent if it's the exact same object reference, and a similar object with the same internal values does not count. For example:

var a = { id: 3 };
var b = { id: 3 };
console.log(a == b); //returns false;

What you really want to use to compare your option objects is probably the Value property that you've given them. indexOf isn't going to help you there so you'll need to loop through the items manually and check each one's Value property against the new item's value.

var match = false;
for (var i = 0; i < sellerOptionModel.sellers().length; i++) {
    if(sellerOptionModel.sellers()[i].Value == result.sellerID){
        match = true;
        break;
    }
}
if (!match) {
    console.log("new id added");
    sellerOptionModel.sellers.push({Text: studentName, Value: result.sellerID});
    sellerOptionModel.sellers.sort();
}else{
    console.log("id already exists")
}

Working example: https://jsfiddle.net/jlspake/8c3tvn9u/


问:
Access VBA Public Function - Variable for Control and Field?
I want to set up a public function like the following:

(A)

```<code>Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkControl = -1
ElseIf chkField = "N" Then
    chkControl = 0
Else: chkControl = 0
End If
End Function
</code>```

(B)

```<code>Public Function CheckYNFlipper(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkField = "N"
    chkControl = 0
ElseIf chkField = "N" Then
    chkField = "Y"
    chkControl = -1
Else: chkField = "Y"
    chkControl = -1
End If
End Function
</code>```

The reason for this is, that I have a form, which has an underlying SQL table.  I have no control over the data, but I must represent it, for the ability to maintain it.  I have 10 fields, in the underlying table, which have a Y or N as their values.  The data types are actually nvarchar(10).  At the same time, I have to show these fields as checkbox controls, on the form, for ease of use.

The above code, is an attempt I am making to A - set the checkbox control to align with the current value in the table--> -1 = Y and 0 = N, and to B - update the table value, and switch the check box to checked or unchecked, from what it was, to the opposite, based on the onclick event of that control.

I want to make chkField and chkControl variables to the public function, that would be the table-field, and the form-control.  I can't seem to get the right syntax, and was hoping someone might have clarification on how to do this.

for the form load and current, I tried this:

```<code>CheckYNField Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA
</code>```

for the on click, I tried this:

```<code>CheckYNFlipper Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA
</code>```

I've tried some other methods, but doesn't seem to be working.  I'm doing something wrong, but I can't tell what.  Appreciate any tips!

Edit/Update:
I tried Kostas K.'s solution, abandoning the idea of making a public functions with parameters for the fields and controls.  I put the following, on load and on current:

```<code>With Me
    If .txtfieldboundtablefieldA.Value = "Y" Then
        .unboundchkA.Value = True
    ElseIf .txtfieldboundtablefieldA.Value = "N" Then
        .unboundchkA.Value = False
    Else: .unboundchkA.Value = False
    End If
End With
</code>```

This is on a continuous form, so that it can show like a giant grid.  There are the identifying bound field controls, and then a series of these checkboxes, to display the Y/N true/false status of each of these particular fields.  I can't bound the checkboxes to the fields, because it changes the field value in the table to -1 or 0, and we need it to stay Y or N.  I added a bound text field, to hold the table/field value for each row (hence the call to a text box control in the above revised code).  The checkbox is unbound, and is there to display the field value, and allow the user to check and uncheck, so I can use on-click code to change the table field value between Y and N.

The above code is not seeming to show the correct checkbox value for each bound text field, based on each row.  It shows based on the row that currently has focus.  If I click on a row, where the table field is Y, all rows checkboxes on the form show true.  If I move to a row, where the table field is N, all checkboxes for all rows change to false.  I am struggling to just initially get 1 checkbox to show accurately, on every row of the continuous form, based on every record in the table.  This is a small table, like 30 records.  I really didn't think it would be so difficult to present this the way we need to.

Any ideas, how I could better do this?

答:
chkControl is a Control, so you need to access a property of that control.  Try changing your code to:

```<code>Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkControl.Value = -1
ElseIf chkField = "N" Then
    chkControl.Value = 0
Else: chkControl.Value = 0
End If
End Function
</code>```

and then the same idea in your other function.

Body:
I want to set up a public function like the following:

(A)

Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkControl = -1
ElseIf chkField = "N" Then
    chkControl = 0
Else: chkControl = 0
End If
End Function

(B)

Public Function CheckYNFlipper(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkField = "N"
    chkControl = 0
ElseIf chkField = "N" Then
    chkField = "Y"
    chkControl = -1
Else: chkField = "Y"
    chkControl = -1
End If
End Function

The reason for this is, that I have a form, which has an underlying SQL table.  I have no control over the data, but I must represent it, for the ability to maintain it.  I have 10 fields, in the underlying table, which have a Y or N as their values.  The data types are actually nvarchar(10).  At the same time, I have to show these fields as checkbox controls, on the form, for ease of use.

The above code, is an attempt I am making to A - set the checkbox control to align with the current value in the table--> -1 = Y and 0 = N, and to B - update the table value, and switch the check box to checked or unchecked, from what it was, to the opposite, based on the onclick event of that control.

I want to make chkField and chkControl variables to the public function, that would be the table-field, and the form-control.  I can't seem to get the right syntax, and was hoping someone might have clarification on how to do this.

for the form load and current, I tried this:

CheckYNField Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA

for the on click, I tried this:

CheckYNFlipper Forms("frmFormNameA").Controls(chkCheckNameA), tblTableName.FieldA

I've tried some other methods, but doesn't seem to be working.  I'm doing something wrong, but I can't tell what.  Appreciate any tips!

Edit/Update:
I tried Kostas K.'s solution, abandoning the idea of making a public functions with parameters for the fields and controls.  I put the following, on load and on current:

With Me
    If .txtfieldboundtablefieldA.Value = "Y" Then
        .unboundchkA.Value = True
    ElseIf .txtfieldboundtablefieldA.Value = "N" Then
        .unboundchkA.Value = False
    Else: .unboundchkA.Value = False
    End If
End With

This is on a continuous form, so that it can show like a giant grid.  There are the identifying bound field controls, and then a series of these checkboxes, to display the Y/N true/false status of each of these particular fields.  I can't bound the checkboxes to the fields, because it changes the field value in the table to -1 or 0, and we need it to stay Y or N.  I added a bound text field, to hold the table/field value for each row (hence the call to a text box control in the above revised code).  The checkbox is unbound, and is there to display the field value, and allow the user to check and uncheck, so I can use on-click code to change the table field value between Y and N.

The above code is not seeming to show the correct checkbox value for each bound text field, based on each row.  It shows based on the row that currently has focus.  If I click on a row, where the table field is Y, all rows checkboxes on the form show true.  If I move to a row, where the table field is N, all checkboxes for all rows change to false.  I am struggling to just initially get 1 checkbox to show accurately, on every row of the continuous form, based on every record in the table.  This is a small table, like 30 records.  I really didn't think it would be so difficult to present this the way we need to.

Any ideas, how I could better do this?

Body:
chkControl is a Control, so you need to access a property of that control.  Try changing your code to:

Public Function CheckYNField(chkControl As Control, chkField As String)
If chkField = "Y" Then
    chkControl.Value = -1
ElseIf chkField = "N" Then
    chkControl.Value = 0
Else: chkControl.Value = 0
End If
End Function

and then the same idea in your other function.


问:
Is it possible to set an initial value when initializing CBCharacteristic?
Admittedly, I have a hard time with the wording of the Apple Docs so I might be missing something.  However, it doesn't seem to be the case.

Here's the question.

Given:

```<code>let charSomeUUID = CBUUID(string: "12345678-1234-12234-1234-123456789qwe")
someCharacteristic    = CBMutableCharacteristic(type: charSomeUUID, properties: [CBCharacteristicProperties.read, CBCharacteristicProperties.notify], value: nil, permissions: CBAttributePermissions.readable)
</code>```

How would one provide an initial value for the value field?

I see how to do it in didReceiveRead.  But I'd like to set an initial value.

I've tried putting a string into a data object and putting it in the value spot and that doesn't seem to work.  And the swift 3 equivalent of the (Objective C) example in the Apple docs doesn't seem to work (anymore?).

Thanks for the help.

答:
Apologies.

I actually had another piece of code that was wrong that ended up being the real problem.

For future reverence here is code to show that what I originally thought would not work does, in fact, work.

```<code>let stringValue : String = "something"
    let dataValue = stringValue.data(using: String.Encoding.utf8)

    // Device Info
    someCharacteristic    = CBMutableCharacteristic(type: someUUID, properties: CBCharacteristicProperties.read, value: dataValue, permissions: CBAttributePermissions.readable)
</code>```

NOTE: When adding a value by this method your characteristic needs to be read only.  Still some things to read up on there.

Failing to use read only results in the following error:

```<code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Characteristics with cached values must be read-only'
</code>```

Sulthan, thank you for your attention.  Sorry for the mix up.

Body:
Admittedly, I have a hard time with the wording of the Apple Docs so I might be missing something.  However, it doesn't seem to be the case.

Here's the question.

Given:

let charSomeUUID = CBUUID(string: "12345678-1234-12234-1234-123456789qwe")
someCharacteristic    = CBMutableCharacteristic(type: charSomeUUID, properties: [CBCharacteristicProperties.read, CBCharacteristicProperties.notify], value: nil, permissions: CBAttributePermissions.readable)

How would one provide an initial value for the value field?

I see how to do it in didReceiveRead.  But I'd like to set an initial value.

I've tried putting a string into a data object and putting it in the value spot and that doesn't seem to work.  And the swift 3 equivalent of the (Objective C) example in the Apple docs doesn't seem to work (anymore?).

Thanks for the help.

Body:
Apologies.

I actually had another piece of code that was wrong that ended up being the real problem.

For future reverence here is code to show that what I originally thought would not work does, in fact, work.

let stringValue : String = "something"
    let dataValue = stringValue.data(using: String.Encoding.utf8)

    // Device Info
    someCharacteristic    = CBMutableCharacteristic(type: someUUID, properties: CBCharacteristicProperties.read, value: dataValue, permissions: CBAttributePermissions.readable)

NOTE: When adding a value by this method your characteristic needs to be read only.  Still some things to read up on there.

Failing to use read only results in the following error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Characteristics with cached values must be read-only'

Sulthan, thank you for your attention.  Sorry for the mix up.


问:
Get specific values from XML with ID values
I have next XML file:

```<code><root>
    <location id='IBM'>
        <property name='locale' value='en-EN' />
        <property name='path' value='c:\program files\IBM' />
        <property name='option' value='licence' />
        <package kind='offering' name='IBM tools'>
            <property name='cic.name' value='IBM Studio'/>
            <property name='cic.version' value='13.4'/>
        </package>
    </location>
    <location id='Microsoft'>
        <property name='locale' value='en-EN' />
        <property name='path' value='c:\program files\MS' />
        <property name='option' value='licence' />
        <package kind='offering' name='Microsoft'>
            <property name='cic.name' value='Windows XP'/>
            <property name='cic.version' value='10.3.2'/>
        </package>
    </location>
</root>
</code>```

How I can get this values from cic.name and cic.version inside that XML structure:

IBM Studio
  13.4
Windows Xp
  10.3.2

I have tried this

```<code>XElement roots = XElement.Load(@"C:\test.xml");

foreach (var i in roots.Descendants("location"))
{
   Console.WriteLine(i.Attribute("id").Value);
}
</code>```

But I get only:
IBM
Microsoft

Thank you!

答:
Try something like this</p>

```<code>foreach (var Locations in roots.Descendants("location"))
{
    foreach (var item in Locations.Descendants("package"))
    {
        Console.WriteLine(item.Attribute("id").Value);
    }

}
</code>```

Body:
I have next XML file:

<root>
    <location id='IBM'>
        <property name='locale' value='en-EN' />
        <property name='path' value='c:\program files\IBM' />
        <property name='option' value='licence' />
        <package kind='offering' name='IBM tools'>
            <property name='cic.name' value='IBM Studio'/>
            <property name='cic.version' value='13.4'/>
        </package>
    </location>
    <location id='Microsoft'>
        <property name='locale' value='en-EN' />
        <property name='path' value='c:\program files\MS' />
        <property name='option' value='licence' />
        <package kind='offering' name='Microsoft'>
            <property name='cic.name' value='Windows XP'/>
            <property name='cic.version' value='10.3.2'/>
        </package>
    </location>
</root>

How I can get this values from cic.name and cic.version inside that XML structure:

IBM Studio
  13.4
Windows Xp
  10.3.2

I have tried this

XElement roots = XElement.Load(@"C:\test.xml");

foreach (var i in roots.Descendants("location"))
{
   Console.WriteLine(i.Attribute("id").Value);
}

But I get only:
IBM
Microsoft

Thank you!

Body:
Try something like this

foreach (var Locations in roots.Descendants("location"))
{
    foreach (var item in Locations.Descendants("package"))
    {
        Console.WriteLine(item.Attribute("id").Value);
    }

}


问:
C/C++: uint8_t bitfields behave incorrectly and inconsistently
I have the following code:

```<code>struct Foo {
  uint16_t a:5;
  uint16_t b:5;
  uint16_t c:5;
};
uint16_t bits = 0xdae;
const Foo& foo = *reinterpret_cast<const Foo*>(&bits);

printf("%x %x %x\n", foo.a, foo.b, foo.c);
</code>```

The output is what I expect when I work it out on paper:

e d 3

If I use uint32_t instead of uint16_t bitfields, I get the same result.

But when I use uint8_t bitfields instead of uint16_t, I get an inconsistent result that is either:

e d 6

or

e d 16

Neither is correct. Why does using uint8_t for bitfields cause this strange behavior?

答:
The memory layout of bit-fields is implementation defined. Confer, for example, this online draft c++ standard:

9.6 Bit-fields

(1) ... Allocation of bit-fields within a class object is
  implementation-defined. Alignment of bit-fields is
  implementation-defined.

Thus, as you do not introduce explicit padding by bit-fields of length 0, you have no control on how the compiler will lay out your struct in memory. Actually, I think that you yield undefined behaviour, as you are converting one pointer to another one with probably different alignment requirements, and accessing padding bits (as it would happen with the assignment of a reinterpreted cast) is undefined behaviour, too.

Note that you can control padding of bit fields in a standardised way:

(2) A declaration for a bit-field that omits the identifier declares an
  unnamed bit-field. Unnamed bit-fields are not members and cannot be
  initialized. [Note: An unnamed bit-field is useful for padding to
  conform to externally-imposed layouts. — end note ] As a special case,
  an unnamed bit-field with a width of zero specifies alignment of the
  next bit-field at an allocation unit boundary. Only when declaring an
  unnamed bit-field may the value of the constant-expression be equal to
  zero.

See the following code that makes use of this feature; Note that it yields a different result as I found no way of how to control padding such that I could get consecutive 5-bit-piecies. So I adapted the example to something that works on the level of byte borders:

```<code>struct Foo {
    uint8_t a:5;
    uint8_t :0;
    uint8_t b:5;
    uint8_t :0;
    uint8_t c:5;
};

union DifferentView {
    uint32_t bits;
    struct Foo foo;
};

int main()
{
    union DifferentView myView;

    myView.bits = 0x0d0a0e;
    printf("%x %x %x\n", myView.foo.a, myView.foo.b, myView.foo.c);
    // Output: e a d

    return 0;
}
</code>```

Body:
I have the following code:

struct Foo {
  uint16_t a:5;
  uint16_t b:5;
  uint16_t c:5;
};
uint16_t bits = 0xdae;
const Foo& foo = *reinterpret_cast<const Foo*>(&bits);

printf("%x %x %x\n", foo.a, foo.b, foo.c);

The output is what I expect when I work it out on paper:

e d 3

If I use uint32_t instead of uint16_t bitfields, I get the same result.

But when I use uint8_t bitfields instead of uint16_t, I get an inconsistent result that is either:

e d 6

or

e d 16

Neither is correct. Why does using uint8_t for bitfields cause this strange behavior?

Body:
The memory layout of bit-fields is implementation defined. Confer, for example, this online draft c++ standard:

9.6 Bit-fields

(1) ... Allocation of bit-fields within a class object is
  implementation-defined. Alignment of bit-fields is
  implementation-defined.

Thus, as you do not introduce explicit padding by bit-fields of length 0, you have no control on how the compiler will lay out your struct in memory. Actually, I think that you yield undefined behaviour, as you are converting one pointer to another one with probably different alignment requirements, and accessing padding bits (as it would happen with the assignment of a reinterpreted cast) is undefined behaviour, too.

Note that you can control padding of bit fields in a standardised way:

(2) A declaration for a bit-field that omits the identifier declares an
  unnamed bit-field. Unnamed bit-fields are not members and cannot be
  initialized. [Note: An unnamed bit-field is useful for padding to
  conform to externally-imposed layouts. — end note ] As a special case,
  an unnamed bit-field with a width of zero specifies alignment of the
  next bit-field at an allocation unit boundary. Only when declaring an
  unnamed bit-field may the value of the constant-expression be equal to
  zero.

See the following code that makes use of this feature; Note that it yields a different result as I found no way of how to control padding such that I could get consecutive 5-bit-piecies. So I adapted the example to something that works on the level of byte borders:

struct Foo {
    uint8_t a:5;
    uint8_t :0;
    uint8_t b:5;
    uint8_t :0;
    uint8_t c:5;
};

union DifferentView {
    uint32_t bits;
    struct Foo foo;
};

int main()
{
    union DifferentView myView;

    myView.bits = 0x0d0a0e;
    printf("%x %x %x\n", myView.foo.a, myView.foo.b, myView.foo.c);
    // Output: e a d

    return 0;
}


问:
A Module in Angular (2+) should be an App by itself created with angular-cli?
I want to separate the login/register workflow into an isolated module. So far I created the module (ng g module login-module) and I want to add the Facebook and Google SDKs to it.

The thing is, the main module (AppModule) is the responsible for the dependencies (package.json) and I would like to isolate the dependencies for the login/register workflow too.

That means that my LoginModule should be an Angular App by itself (created with ng new login-module)?

答: No, modules are a way of puting together elements, "functional units", that relate to each other. They are by no means an individual application, although good encapsulation could allow you to transform a module into an independent application. You could read a lot more about it here</p>


问:
Need WeakMap (a, b) -> c
I have a memoized fn, where the fn is memoized by two input references:

```<code>let NewRefCursor = memoized(
    (deref, swap) => refToHash(deref) + refToHash(swap), // memoizer identity fn
    (deref, swap) => new RefCursor(deref, swap)); // the function we are memoizing
</code>```

The behavior I need is NewRefCursor(a, b) === NewRefCursor(a, b). When a or b gets garbage collected, the cursor should also be garbage collected.

refToHash is another memoized function that uses ES6 WeakMap so that references seen are still allowed to GC.

NewRefCursor is much trickier to memoize because it uses two parameters to determine cache hit, thus isn't compatible with WeakMap, thus will prevent any reference seen from ever being GC'ed. I am open to any manner of trickery, attaching private fields to input objects, probabilistic data structures. This leak needs to be solved. The only solution I have so far is to add a parameter to memoize that bounds the cache size, and tune that parameter on a per-app basis. gross.

答:
See memoize in https://github.com/Dans-labs/dariah/blob/master/client/src/js/lib/utils.js
It solves the problem in a generic way by building a WeakMap index of all arguments that are objects. The WeakMap index assigns unique integers to objects, which can then be put together with the other arguments by stringify.</p>

Title: Need WeakMap (a, b) -> c

Body:
I have a memoized fn, where the fn is memoized by two input references:

let NewRefCursor = memoized(
    (deref, swap) => refToHash(deref) + refToHash(swap), // memoizer identity fn
    (deref, swap) => new RefCursor(deref, swap)); // the function we are memoizing

The behavior I need is NewRefCursor(a, b) === NewRefCursor(a, b). When a or b gets garbage collected, the cursor should also be garbage collected.

refToHash is another memoized function that uses ES6 WeakMap so that references seen are still allowed to GC.

NewRefCursor is much trickier to memoize because it uses two parameters to determine cache hit, thus isn't compatible with WeakMap, thus will prevent any reference seen from ever being GC'ed. I am open to any manner of trickery, attaching private fields to input objects, probabilistic data structures. This leak needs to be solved. The only solution I have so far is to add a parameter to memoize that bounds the cache size, and tune that parameter on a per-app basis. gross.


问:
Custom hardware causing Linux boot to hang after initrd on PC
We've created some custom hardware that uses PCIe 2.0. This hardware works with an HP DL360 G7 server with CentOS Linux 5.4. So on the HP server Linux is able to cold-boot just fine, recognize the card, and interface with our driver. However, when we try plugging the card into a regular Dell T3500 PC Linux is unable to boot. It hangs after initrd with no crash, debug, or error messages. So my question is, what tools or settings are available to help debug this problem? We want to know why the boot process can't get past initrd.</p>

答: Boot from a live CD such as Knoppix and use the utilities available to you there to diagnose the problem (dmesg, dconf, lspci, etc).  It could very well be that there are conflicts between your driver and hardware that's on the Dell.</p>

ContentLicense: CC BY-SA 2.5


问:
Eclipse copies heavy resources all the time
I have some heavy resource files in my project which I need to package in the jar.

I use eclipse as my IDE and it's been very slow since every change I make results in eclipse rebuilding the project, which copies the resources to target folder.

I've tried executing the resources plugin on prepare-package phase but it seems to be executed anyway.

What can I do with it?

答:
I'd suggest using a Maven profile.
So you can:

Move all your resources inside a profile (i.e. by default, you have no resources; but when you activate your profile, they become available).

Activate the mentioned profile only when you package the jar; in all other situations (i.e. when Eclipse builds) it is disabled.


问:
Recover data from columns DC2Type:array
Have a column with this format "DC2Type:array" in symphony try to read data as array but receive a Null.

my function is:

```<code>public function getData()
{
    return $this->data;
}
</code>```

need some particular way or is another inconvenient different.  Thank you.

答:
check your data is set or not: example code</p>

```<code>public $data ;

public function getData()
{
    return $this->data;
}

public function setData($data)
{
    return $this->data = $data;
}
</code>```

Title: Recover data from columns DC2Type:array

Body:
Have a column with this format "DC2Type:array" in symphony try to read data as array but receive a Null.

my function is:

public function getData()
{
    return $this->data;
}

need some particular way or is another inconvenient different.  Thank you.

Body:
check your data is set or not: example code

public $data ;

public function getData()
{
    return $this->data;
}

public function setData($data)
{
    return $this->data = $data;
}


问:
how to specify normalizr schema for nested object
Input:

```<code>provider: {
                id: 1,
                name: 'abc',
                npi: 1234,
                credentials: [{
                      id: 1,
                      description: 'abc'
                 }],
                specialties: [{
                      id: 1,
                      description: 'abc'
                 }],
                 supervisingPhysician: {
                          id: 2,
                          name: 'xyz',
                          npi: 56789,
                          credentials: [{
                                id: 1,
                                description: 'abc'
                           }],
                        }
           }
</code>```

Schema

```<code>import { schema } from 'normalizr';
import _ from 'lodash';

let specialtySchema = new schema.Entity('specialties');

export const providerSchema = new schema.Entity('provider', {
    specialties: [specialtySchema], primarySpecialty: specialtySchema
});
</code>```

expected Output: (something like)

```<code>entities: { providers: { "1" : {..., supervisingPhysician: 2, specialties: 1},
                         "2" : {..., specialties: 1}
                       },
            specialties: {"1" : {...specialty object}
          }
</code>```

in my example both my root provider object and nested supervisingPhysician object are same type (a provider) of object.

How can I define the schema such that I can normalize both root and supervisingPhysician together.

Thanks for looking at this.

答:
This can be achieved pretty easily by naming the entity key of the supervisingPhysician-entity 'providers'.

```<code>// define normal schema credentials and specialties
const credentialSchema = new schema.Entity('credentials');
const specialtySchema = new schema.Entity('specialties');

// define the supervisingPhysician schema with 'providers' as key
// normalizr will now put all supervisingPhysicians directly into the providers object
const supervisingPhysicianSchema = new schema.Entity('providers', {
  credentials: [credentialSchema]
});

// define 'root'-provider schema
const providerSchema = new schema.Entity('providers', {
  credentials: [credentialSchema],
  specialties: [specialtySchema],
  supervisingPhysician: supervisingPhysicianSchema
});

// the whole data schema
const dataSchema = { provider: providerSchema };

// ready to normalize
normalize(input, dataSchema);
</code>```

This will give you the following result:

```<code>{
    entities: {
        credentials: {
            1: {
                id: 1,
                description: "abc"
            }
        },
        specialties: {
            1: {
                id: 1,
                description: "abc"
            }
        },
        providers: {
            1: {
                id: 1,
                name: "abc",
                npi: 1234,
                credentials: [ 1 ],
                specialties: [ 1 ],
                supervisingPhysician: 2
            },
            2: {
                id: 2,
                name: "xyz",
                npi: 56789,
                credentials: [ 1 ]
            }
        }
    },
    result: {
        provider: 1
    }
}
</code>```

For clarification and reference, this is how I declared input:

```<code>const input = {
  provider: {
    id: 1,
    name: "abc",
    npi: 1234,
    credentials: [{ id: 1, description: "abc" }],
    specialties: [{ id: 1, description: "abc" }],
    supervisingPhysician: {
      id: 2,
      name: "xyz",
      npi: 56789,
      credentials: [{ id: 1, description: "abc" }]
    }
  }
};
</code>```

Body:
Input:

provider: {
                id: 1,
                name: 'abc',
                npi: 1234,
                credentials: [{
                      id: 1,
                      description: 'abc'
                 }],
                specialties: [{
                      id: 1,
                      description: 'abc'
                 }],
                 supervisingPhysician: {
                          id: 2,
                          name: 'xyz',
                          npi: 56789,
                          credentials: [{
                                id: 1,
                                description: 'abc'
                           }],
                        }
           }

Schema

import { schema } from 'normalizr';
import _ from 'lodash';

let specialtySchema = new schema.Entity('specialties');

export const providerSchema = new schema.Entity('provider', {
    specialties: [specialtySchema], primarySpecialty: specialtySchema
});

expected Output: (something like)

entities: { providers: { "1" : {..., supervisingPhysician: 2, specialties: 1},
                         "2" : {..., specialties: 1}
                       },
            specialties: {"1" : {...specialty object}
          }

in my example both my root provider object and nested supervisingPhysician object are same type (a provider) of object.

How can I define the schema such that I can normalize both root and supervisingPhysician together.

Thanks for looking at this.

Body:
This can be achieved pretty easily by naming the entity key of the supervisingPhysician-entity 'providers'.

// define normal schema credentials and specialties
const credentialSchema = new schema.Entity('credentials');
const specialtySchema = new schema.Entity('specialties');

// define the supervisingPhysician schema with 'providers' as key
// normalizr will now put all supervisingPhysicians directly into the providers object
const supervisingPhysicianSchema = new schema.Entity('providers', {
  credentials: [credentialSchema]
});

// define 'root'-provider schema
const providerSchema = new schema.Entity('providers', {
  credentials: [credentialSchema],
  specialties: [specialtySchema],
  supervisingPhysician: supervisingPhysicianSchema
});

// the whole data schema
const dataSchema = { provider: providerSchema };

// ready to normalize
normalize(input, dataSchema);

This will give you the following result:

{
    entities: {
        credentials: {
            1: {
                id: 1,
                description: "abc"
            }
        },
        specialties: {
            1: {
                id: 1,
                description: "abc"
            }
        },
        providers: {
            1: {
                id: 1,
                name: "abc",
                npi: 1234,
                credentials: [ 1 ],
                specialties: [ 1 ],
                supervisingPhysician: 2
            },
            2: {
                id: 2,
                name: "xyz",
                npi: 56789,
                credentials: [ 1 ]
            }
        }
    },
    result: {
        provider: 1
    }
}

For clarification and reference, this is how I declared input:

const input = {
  provider: {
    id: 1,
    name: "abc",
    npi: 1234,
    credentials: [{ id: 1, description: "abc" }],
    specialties: [{ id: 1, description: "abc" }],
    supervisingPhysician: {
      id: 2,
      name: "xyz",
      npi: 56789,
      credentials: [{ id: 1, description: "abc" }]
    }
  }
};


问:
Second list view not expanding in linear layout fragemnt
My linear layout having two list views, when i add items in second list view, its not expanding. its getting scrolled automatically,

i have used match_parent in my linear layout, even though the second list view (getting scrolled instead of expanding) or the linear layout is not expanding.

Can anyone please help me to expand the list view or the linear layout.

problem in linear layout or the second list view?

but the first list view expanding properly.

fragment_one.xml

```<code>        <LinearLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_weight="1"
                android:descendantFocusability="blocksDescendants"
                android:padding="10dip" >

                <ListView
                    android:id="@+id/list_nation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#B29090"
                    android:nestedScrollingEnabled="true">
                </ListView>

                <ListView
                    android:id="@+id/list_regional"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#4A9C67"
                    android:focusable="false"
                    android:nestedScrollingEnabled="true">
                </ListView>

            </LinearLayout>
</code>```

答:
When you add multiple scrolls in a single screen it always shows problems. Because they conflict with each other.
There are two solution for your problem.

If you want to keep your each listview to take half screen then add "weightsum = 100" in your main linear layout and set weight of both listviews to "50".

If you want your first list to scroll till end and at the end of first you want the second one to start scrolling, then calculate the height of your lists on run time and assign the calculated height to your listviews. Check this: Android: How to measure total height of ListView

Body:
My linear layout having two list views, when i add items in second list view, its not expanding. its getting scrolled automatically,

i have used match_parent in my linear layout, even though the second list view (getting scrolled instead of expanding) or the linear layout is not expanding.

Can anyone please help me to expand the list view or the linear layout.

problem in linear layout or the second list view?

but the first list view expanding properly.

fragment_one.xml

        <LinearLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:layout_weight="1"
                android:descendantFocusability="blocksDescendants"
                android:padding="10dip" >

                <ListView
                    android:id="@+id/list_nation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#B29090"
                    android:nestedScrollingEnabled="true">
                </ListView>

                <ListView
                    android:id="@+id/list_regional"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#4A9C67"
                    android:focusable="false"
                    android:nestedScrollingEnabled="true">
                </ListView>

            </LinearLayout>


问:
problem to listview android
i've got a listView with some data that i inflated to get some nice background color. The problem is that i want to get some awesome separators and i'm unable to setDividerHeight() depending on the row's data, because it seems that i can't inflate two views on the same getView() method, here's some code:

```<code>public View getView(int position, View convertView, ViewGroup parent){
    String myText = getItem(position).toString();
    String firstLetter = Character.toString(myText.charAt(0));
    if(convertView == null){
        convertView = this.inflater.inflate(R.layout.lettersrows, null);

    }
    TextView tv = (TextView)convertView.findViewById(R.id.label);
    tv.setText(this.list.get(position));
    tv.setTextSize(25);
    convertView.setBackgroundColor((position & 1) == 1 ? Color.WHITE : Color.LTGRAY);

    /**This is what i want to do*/
    if(!firstLetter.equals("A")){
        convertView = this.inflater.inflate(R.layout.letters, null);
        ListView lv = (ListView)convertView.findViewById(R.id.letters_listview);
        lv.setDividerHeight(3);
    }
    return convertView;
}
</code>```

The error i'm getting is a NullPointerException at: tv.setText(this.list.get(position));
I guess that dues to that the convertView is now a ListView that's why it doesn't find where to set the text. How could i fix this problem.

Best regards.

答:
You can use your custom Adapter to inflate as many different types of layout as you want.

For this, you just need to change your getViewTypeCount method to return the type of different views you want (2 in your example, regular item and separator) and adapt your getView() method to chose the correct view type to display.

Everything is explained in this great tutorial

Note: In the tutorial, they do that by implementing a getItemViewType() method. This can be useful in some cases.

Title: problem to listview android

Body:
i've got a listView with some data that i inflated to get some nice background color. The problem is that i want to get some awesome separators and i'm unable to setDividerHeight() depending on the row's data, because it seems that i can't inflate two views on the same getView() method, here's some code:

public View getView(int position, View convertView, ViewGroup parent){
    String myText = getItem(position).toString();
    String firstLetter = Character.toString(myText.charAt(0));
    if(convertView == null){
        convertView = this.inflater.inflate(R.layout.lettersrows, null);

    }
    TextView tv = (TextView)convertView.findViewById(R.id.label);
    tv.setText(this.list.get(position));
    tv.setTextSize(25);
    convertView.setBackgroundColor((position & 1) == 1 ? Color.WHITE : Color.LTGRAY);

    /**This is what i want to do*/
    if(!firstLetter.equals("A")){
        convertView = this.inflater.inflate(R.layout.letters, null);
        ListView lv = (ListView)convertView.findViewById(R.id.letters_listview);
        lv.setDividerHeight(3);
    }
    return convertView;
}

The error i'm getting is a NullPointerException at: tv.setText(this.list.get(position));
I guess that dues to that the convertView is now a ListView that's why it doesn't find where to set the text. How could i fix this problem.

Best regards.


问:
Post data to Google Spreadsheet via AppsScript (private deployment)
I am trying to post data using HTML forms or AJAX over to AppsScript attached to a Google Spreadsheet. I got the app to the state that it works with app deployed to "anyone, even anonymous".

But my goal is to create JS script or PHP which will use service account to authenticate and post data to this Spreadsheet.

I can't find any helpful documenation or example.

Here is my code: [HTML]

<!DOCTYPE html>

<form method="post" action="https://script.google.com/a/macros/domainname/s/AKfycbzVVBWfeffKo7OHdhAtjjgri0ouJ5qIkSjQTpsIISw8/exec">
  First name:

  <input type="text" name="firstname" value="test1">

  Last name:

  <input type="text" name="lastname" value="test2">

  <input type="submit" value="Submit">
</form>

```
</div>
</div>
</p>

<p>[Apps Script]</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>function doPost(e) {

  try {
    var doc     = SpreadsheetApp.getActiveSpreadsheet();
    var sheet   = doc.getSheetByName("Sheet1");

    sheet.getRange(1,1).setValue(JSON.stringify(e.parameters));

  }
  catch(error) {
    Logger.log(e);
  }
  finally {
    return;
  }

}</code>```

I already created the service account and have the JSON file with clientID, Secrets etc. I imagine I need to append the POST with this data somehow but I am not sure how to achieve that so Google Apps will authenticate it.

The reason for this is that the company who wants this app cannot enable sharing documents to everyone who have the link for security reasons.

I need to publish with settings show below:

If I set to "Anyone within domain" I get

So I want to execute my Form somehow so it executes as a user within that domain.

Can someone help with some documentation URLs or some tutorial, etc?

Best Regards
Matt

答:
There is no reason to use service accounts in this case, even with your restriction.

Publish the app to run as you, then all spreadsheet calls will use your credentials not the user that uses your webapp.

Also, its not possible to use 2-legged oauth with service accounts in apps script, it only supports 3-legged oauth.

Body:
I am trying to post data using HTML forms or AJAX over to AppsScript attached to a Google Spreadsheet. I got the app to the state that it works with app deployed to "anyone, even anonymous".

But my goal is to create JS script or PHP which will use service account to authenticate and post data to this Spreadsheet.

I can't find any helpful documenation or example.

Here is my code: [HTML]

<!DOCTYPE html>

<form method="post" action="https://script.google.com/a/macros/domainname/s/AKfycbzVVBWfeffKo7OHdhAtjjgri0ouJ5qIkSjQTpsIISw8/exec">
  First name:

  <input type="text" name="firstname" value="test1">

  Last name:

  <input type="text" name="lastname" value="test2">

  <input type="submit" value="Submit">
</form>

[Apps Script]

function doPost(e) {

  try {
    var doc     = SpreadsheetApp.getActiveSpreadsheet();
    var sheet   = doc.getSheetByName("Sheet1");

    sheet.getRange(1,1).setValue(JSON.stringify(e.parameters));

  }
  catch(error) {
    Logger.log(e);
  }
  finally {
    return;
  }

}

I already created the service account and have the JSON file with clientID, Secrets etc. I imagine I need to append the POST with this data somehow but I am not sure how to achieve that so Google Apps will authenticate it.

The reason for this is that the company who wants this app cannot enable sharing documents to everyone who have the link for security reasons.

I need to publish with settings show below:

If I set to "Anyone within domain" I get

So I want to execute my Form somehow so it executes as a user within that domain.

Can someone help with some documentation URLs or some tutorial, etc?

Best Regards
Matt


问:
React Redux Proper way of iterating over data on init
I have a form in React where users can see data (returned via async on load) and edit it inline. If I navigate to the form from another page via a link, the form works as expected as the data is loaded before the main render function, however, if I refresh the page with the form on it, the data isn't populated properly despite it coming through in props.

So:
Initial render with loading div -> Data comes back -> Props set -> Render fires -> State is set

Since the inputs on the form have initial values set from this.state, they're blank on the second render. However, if I navigate here from another page, everything works as you would expect. It seems like I'm missing something regarding React/Redux.

Here's the bottom presentation component:

```<code>class ContactInfoForm extends React.Component {
    constructor (props, context) {
        super(props, context);

        this.state = Object.assign({}, props.contactInfo);

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

    render () {
        const {
            contactInfo
        } = this.props;

        console.log(this.state); // {} - first render {} - second render
        console.log(this.props); // {} - first render {stuff} - second render

        return (
            <form>
                <div className="col-xs-12">
                    <TextInputGroup
                        name="email"
                        value={this.state.email}
                        onChange={this.handleChange}
                        floatedLabel="Email/Username"
                        placeholder="Email/Username"
                        className="AccountPreferences__field"
                        labelClass="AccountPreferences__label"
                    />
                </div>
            </form>
        );
    }
}
</code>```

I understand that setState is asynchronous so this makes sense, but I'm wondering what is the best way to initialize a form in React/Redux.

答:
You need to use the componentWillReceiveProps lifecycle method it will get called whenever any change happens to props values so at that time you need to update the state value.

Use this:

```<code>componentWillReceiveProps(newProps){
    this.setState(newProps.contactInfo);
}
</code>```

componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component
  receives new props. If you need to update the state in response to
  prop changes (for example, to reset it), you may compare this.props
  and nextProps and perform state transitions using this.setState() in
  this method.

Body:
I have a form in React where users can see data (returned via async on load) and edit it inline. If I navigate to the form from another page via a link, the form works as expected as the data is loaded before the main render function, however, if I refresh the page with the form on it, the data isn't populated properly despite it coming through in props.

So:
Initial render with loading div -> Data comes back -> Props set -> Render fires -> State is set

Since the inputs on the form have initial values set from this.state, they're blank on the second render. However, if I navigate here from another page, everything works as you would expect. It seems like I'm missing something regarding React/Redux.

Here's the bottom presentation component:

class ContactInfoForm extends React.Component {
    constructor (props, context) {
        super(props, context);

        this.state = Object.assign({}, props.contactInfo);

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

    render () {
        const {
            contactInfo
        } = this.props;

        console.log(this.state); // {} - first render {} - second render
        console.log(this.props); // {} - first render {stuff} - second render

        return (
            <form>

                    <TextInputGroup
                        name="email"
                        value={this.state.email}
                        onChange={this.handleChange}
                        floatedLabel="Email/Username"
                        placeholder="Email/Username"
                        className="AccountPreferences__field"
                        labelClass="AccountPreferences__label"
                    />

            </form>
        );
    }
}

I understand that setState is asynchronous so this makes sense, but I'm wondering what is the best way to initialize a form in React/Redux.

Body:
You need to use the componentWillReceiveProps lifecycle method it will get called whenever any change happens to props values so at that time you need to update the state value.

Use this:

componentWillReceiveProps(newProps){
    this.setState(newProps.contactInfo);
}

componentWillReceiveProps:

componentWillReceiveProps() is invoked before a mounted component
  receives new props. If you need to update the state in response to
  prop changes (for example, to reset it), you may compare this.props
  and nextProps and perform state transitions using this.setState() in
  this method.


问:
Chef - Housing large tarball files
I am currently getting into chef configuration management and trying to find the best way to house large tarball files to be pulled by nodes. For example, if I have a recipe that involves pushing a tarball to a node then extracting it, I am unsure of where to house these.

I was thinking keep them in git so I can grab them with a wget but the limit there is only 100mb. Would I house them all on my server then sftp them to the nodes?  Is there a common practice in Chef in doing this?

答: You can use pretty much anything to do that. If nodes only need to download from there, then simplest will be some nginx or apache site. You will need a place to store the files, e.g. /var/www/mytars and nginx or apache running on that machine with a site configured. Then any node can download with remote_file resource.

Title: Chef - Housing large tarball files


问:
H2 Database (embedded) connection timeout
I get the following exception when connecting to the database:

```<code>org.h2.jdbc.JdbcSQLException: Connection is broken: "connect timed out" [90067-142]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
    at org.h2.message.DbException.get(DbException.java:156)
    at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:326)
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:248)
    at org.h2.engine.SessionRemote.createSession(SessionRemote.java:214)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:111)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:95)
    at org.h2.Driver.connect(Driver.java:73)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
................
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:525)
    at org.h2.util.NetUtils.createSocket(NetUtils.java:109)
    at org.h2.util.NetUtils.createSocket(NetUtils.java:91)
    at org.h2.engine.SessionRemote.initTransfer(SessionRemote.java:92)
    at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:322)
    ... 38 more
</code>```

The connection string looks as follows:

```<code>jdbc:h2:C:\Users\Michael\.myadd\db;AUTO_SERVER=TRUE;CIPHER=AES
</code>```

What can be the reason for such exception?

Thanks!

答:
I guess you read the docs about the automatic mixed mode? It's hard to say what the problem is, because for me it works. Could you post the content of the file C:\Users\Michael.myadd\db.lock.db ? For me it is (after connecting):

```<code>#FileLock
#Tue Dec 14 22:29:22 CET 2010
id=12ce6c9a16a912077e514cc6fff231e91b09d2dbe43
method=file
server=192.168.0.126\:52068
</code>```

That means the database is open, and the client that opened it started a server on this IP address and port.

Body:
I get the following exception when connecting to the database:

org.h2.jdbc.JdbcSQLException: Connection is broken: "connect timed out" [90067-142]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
    at org.h2.message.DbException.get(DbException.java:156)
    at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:326)
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:248)
    at org.h2.engine.SessionRemote.createSession(SessionRemote.java:214)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:111)
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:95)
    at org.h2.Driver.connect(Driver.java:73)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
................
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:525)
    at org.h2.util.NetUtils.createSocket(NetUtils.java:109)
    at org.h2.util.NetUtils.createSocket(NetUtils.java:91)
    at org.h2.engine.SessionRemote.initTransfer(SessionRemote.java:92)
    at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:322)
    ... 38 more

The connection string looks as follows:

jdbc:h2:C:\Users\Michael\.myadd\db;AUTO_SERVER=TRUE;CIPHER=AES

What can be the reason for such exception?

Thanks!

Body:
I guess you read the docs about the automatic mixed mode? It's hard to say what the problem is, because for me it works. Could you post the content of the file C:\Users\Michael.myadd\db.lock.db ? For me it is (after connecting):

#FileLock
#Tue Dec 14 22:29:22 CET 2010
id=12ce6c9a16a912077e514cc6fff231e91b09d2dbe43
method=file
server=192.168.0.126\:52068

That means the database is open, and the client that opened it started a server on this IP address and port.


问:
Can't save new-alias even if i made ps1 file
i've used command:

```<code>Get-Variable profile | Format-List
</code>```

i did it for check where is my powershell profile folder.
After i did it it showed me this path:

```<code>C:\Users\Dom\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
</code>```

I opened this path and file named Microsoft.PowerShellISE_profile.ps1 where i've saved my alias with command: New-Alias rc Restart-Computer but this alias doesn't work.. Powershell act like this file never existed.. Any suggestions?

答:
This script will look for $Search through the 4 profiles for the current host and print the finds with 4 lines of context:

```<code>## Search-PSProfiles.ps1
$ProfileNames = $PROFILE | Get-Member -MemberType noteproperty | select -Expandproperty Name
$Search = 'Restart'
ForEach ($Prof in $ProfileNames){
  $ThisProfile = $Profile."$Prof"
  if (Test-Path $ThisProfile){
  "{0,25} search for $Search in $ThisProfile " -f "`$Profile.$Prof"
    Get-Content $ThisProfile|Select-String -AllMatches $Search -Context 0,4
  } else {
  "{0,25} doesn't exist ({1})" -f "`$Profile.$Prof",$ThisProfile
  }
}
</code>```

Sample output started from a PoSh console:

```<code>$Profile.AllUsersAllHosts doesn't exist (C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1)
$Profile.AllUsersCurrentHost doesn't exist (C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1)
$Profile.CurrentUserAllHosts search for restart in C:\Users\UserName\Documents\WindowsPowerShell\profile.ps1

> New-Alias rc Restart-Computer
$Profile.CurrentUserCurrentHost search for restart in C:\Users\UserName\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
</code>```

Body:
i've used command:

Get-Variable profile | Format-List

i did it for check where is my powershell profile folder.
After i did it it showed me this path:

C:\Users\Dom\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

I opened this path and file named Microsoft.PowerShellISE_profile.ps1 where i've saved my alias with command: New-Alias rc Restart-Computer but this alias doesn't work.. Powershell act like this file never existed.. Any suggestions?

Body:
This script will look for $Search through the 4 profiles for the current host and print the finds with 4 lines of context:

## Search-PSProfiles.ps1
$ProfileNames = $PROFILE | Get-Member -MemberType noteproperty | select -Expandproperty Name
$Search = 'Restart'
ForEach ($Prof in $ProfileNames){
  $ThisProfile = $Profile."$Prof"
  if (Test-Path $ThisProfile){
  "{0,25} search for $Search in $ThisProfile " -f "`$Profile.$Prof"
    Get-Content $ThisProfile|Select-String -AllMatches $Search -Context 0,4
  } else {
  "{0,25} doesn't exist ({1})" -f "`$Profile.$Prof",$ThisProfile
  }
}

Sample output started from a PoSh console:

$Profile.AllUsersAllHosts doesn't exist (C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1)
$Profile.AllUsersCurrentHost doesn't exist (C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1)
$Profile.CurrentUserAllHosts search for restart in C:\Users\UserName\Documents\WindowsPowerShell\profile.ps1

> New-Alias rc Restart-Computer
$Profile.CurrentUserCurrentHost search for restart in C:\Users\UserName\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1


问:
Is there any way to force a git add ignoring line ending problems?
I have a giant directory which I need to import into git, and I am suffering the hell of line ending management.

Initially I need to just put everything inside the repo, having no time to deal with line endings. To get that, I added a .gitattributes file with * -text, but that doesn't solve the problem because there are lots of subdirectories containing modules with their own .gitattributes files and text=auto.

Is there any way to get all the files inside the repo with no more struggle?

答:
The gitattributes documentation states:

When deciding what attributes are assigned to a path, Git consults:

$GIT_DIR/info/attributes file (which has the highest precedence),

.gitattributes file in the same directory as the path in question, and its parent directories up to the toplevel of the work tree (the further the directory that contains .gitattributes is from the path in question, the lower its precedence).

Finally global and system-wide files are considered (they have the lowest precedence).

If you wish to affect only a single repository (i.e., to assign attributes to files that are particular to one user’s workflow for that repository), then attributes should be placed in the $GIT_DIR/info/attributes file.

So try and set your * -text directive in $GIT_DIR/info/attributes, at least for your initial add and commit.