问:
Getting client side validation to work with Telerik MVC Window
I am using a telerik mvc window extension that is triggered from a custom template link in a telerik mvc grid.  The window is modal and it contains a form for editing data. After successfully implementing client side validation using a standard html page, I have been trying to implement it in the telerik mvc window.  I have not been able to do so successfully.  Is this possible?  Does anybody have a working example of this?

Thanks
Ozzy

答:
You need to load to page in an IFrame. To do this, make sure the url in LoadContentFrom method starts with http or https:

```<code><%= Html.Telerik().Window()
.Name("Window")
.LoadContentFrom("http://www.example.com")
%>
</code>```

if you're using the Url.Action() helper to get the url, include the protocol parameter to get the full url.

E.g
Url.Action("action name","controler name", "http")   <--may also need to include route values or null route value dictionary.

To close to window, you'll need to make a call back to the parent view, try this:

add a bool isValid property to your model

if succesfully validated, reload the view with isValid equals true

onload:

var isValid = '<%: Model.IsValid%>';

if(isValid == 'True')
{
window.parent.$('#MyWindow').data('tWindow').close();
}

Body:
You need to load to page in an IFrame. To do this, make sure the url in LoadContentFrom method starts with http or https:

<%= Html.Telerik().Window()
.Name("Window")
.LoadContentFrom("http://www.example.com")
%>

if you're using the Url.Action() helper to get the url, include the protocol parameter to get the full url.

E.g
Url.Action("action name","controler name", "http")   <--may also need to include route values or null route value dictionary.

To close to window, you'll need to make a call back to the parent view, try this:

add a bool isValid property to your model

if succesfully validated, reload the view with isValid equals true

onload:

var isValid = '<%: Model.IsValid%>';

if(isValid == 'True')
{
window.parent.$('#MyWindow').data('tWindow').close();
}


来源: stackexchange

问:
VBA Copying Excel Range to Different Workbook
I am trying to find a way to copy a range in one workbook, in this case A6:J21,to another workbook. I thought it would be something like the following...

```<code>currentWorksheet = xlWorkBook.Sheets.Item("Command Group")
excelRange = currentWorksheet.Range("A6:J21")
excelDestination = newXlSheet.Range("A6:J21")
excelRange.Copy(excelDestination)
</code>```

But it gives me an error on excelRange.Copy(excelDestination).

The below code runs as expected, so I'm not sure where i'm going wrong here..

```<code>Dim xRng As Excel.Range = CType(currentWorksheet.Cells(7, 7), Excel.Range)
Console.WriteLine(xRng.ToString)
Dim val As Object = xRng.Value()
testString = val.ToString
Console.WriteLine(testString)
newXlSheet.Cells(1, 1) = testString
</code>```

答:
To answer your question "Why is B running, but not A"..

In A:
currentWorksheet = xlWorkBook.Sheets.Item("Command Group")

First, you are missing SET for your object assignment.  Secondly, you are using Workbook.Sheets.Item() which returns a Sheets object. A Sheets object can represent either a chart sheet, or a work sheet, and therefore does not have a .Range() method.

You can verify this by stepping over this code:

```<code>Dim currentWorksheet As Sheets
Set currentWorksheet = ThisWorkbook.Sheets.Item("Command Group")
excelRange = currentWorksheet.Range("A1:A21")
</code>```

It will error, and tell you that the method is not found.

To Fix A: Ensure you get back a Worksheet object by using strong typing.

```<code>Dim currentWorksheet as Worksheet
Set currentWorksheet = ThisWorkbook.Sheets.Item("Command Group")
</code>```

To fix future code and ease the debugging process I highly recommend always declaring Option Explicit at the top of all your modules.

For brevity you can shorten your code to:

```<code>Dim currentWorksheet as Worksheet
Set currentWorksheet = ThisWorkbook.Sheets("Command Group")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find a way to copy a range in one workbook, in this case A6:J21,to another workbook. I thought it would be something like the following...

currentWorksheet = xlWorkBook.Sheets.Item("Command Group")
excelRange = currentWorksheet.Range("A6:J21")
excelDestination = newXlSheet.Range("A6:J21")
excelRange.Copy(excelDestination)

But it gives me an error on excelRange.Copy(excelDestination).

The below code runs as expected, so I'm not sure where i'm going wrong here..

Dim xRng As Excel.Range = CType(currentWorksheet.Cells(7, 7), Excel.Range)
Console.WriteLine(xRng.ToString)
Dim val As Object = xRng.Value()
testString = val.ToString
Console.WriteLine(testString)
newXlSheet.Cells(1, 1) = testString

Body:
To answer your question "Why is B running, but not A"..

In A:
currentWorksheet = xlWorkBook.Sheets.Item("Command Group")

First, you are missing SET for your object assignment.  Secondly, you are using Workbook.Sheets.Item() which returns a Sheets object. A Sheets object can represent either a chart sheet, or a work sheet, and therefore does not have a .Range() method.

You can verify this by stepping over this code:

Dim currentWorksheet As Sheets
Set currentWorksheet = ThisWorkbook.Sheets.Item("Command Group")
excelRange = currentWorksheet.Range("A1:A21")

It will error, and tell you that the method is not found.

To Fix A: Ensure you get back a Worksheet object by using strong typing.

Dim currentWorksheet as Worksheet
Set currentWorksheet = ThisWorkbook.Sheets.Item("Command Group")

To fix future code and ease the debugging process I highly recommend always declaring Option Explicit at the top of all your modules.

For brevity you can shorten your code to:

Dim currentWorksheet as Worksheet
Set currentWorksheet = ThisWorkbook.Sheets("Command Group")


问:
Is It Possible to Make Every Instance of a Word on a Website Non-Breaking?
We have a hyphenated word that we use frequently on our website and we never want it to wrap or break - we always want the two parts of the word on the same line.

Is there a way to make every instance of this word on the site non-breaking or do I have to do it with something like "white-space: nowrap" in a span around every instance of the word?

Ideally, would love to be able to do an update where every instance of the word that exists on the site becomes non-breaking, without having to manually go and update each word.

Thanks!

答:
The fastest way

The fastest way to replace some text globally on a website is to walk through only text nodes inside a DOM tree.

You can achieve that by using document.createTreeWalker and then replacing only text nodes containing the word (or character) you want to change.

var findAndReplaceText = function(el, from, to) {
  if (!el || !from || !to) {
    return;
  }

  var node, nodes = [];
  var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);

  // Find nodes
  while (node = walker.nextNode()) {
    if (from instanceof RegExp) {
      from.test(node.wholeText) && nodes.push(node);
    } else {
      node.wholeText.indexOf(from) !== -1 && nodes.push(node);
    }
  }

  // Change DOM
  while (nodes.length > 0) {
    //nodes[0].replaceWith(
    //  document.createTextNode(nodes[0].wholeText.replace(from, to))
    //);
    nodes[0].textContent = nodes[0].wholeText.replace(from, to)
    nodes.splice(0, 1);
  }
};

findAndReplaceText(document.getElementById('fake-hyphens'), /[\u002d\u2010]/g, '\u2011');
findAndReplaceText(document.documentElement, 'lol', 'non');

// \u2010 - hypen
// \u2011 - non-breakable hyphen
// \u002d - minus```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  float: left;
  line-height: 1em;
  margin-left: 1em;
}

section p {
  width: 200px;
  outline: dashed red 1px;
  padding: 1em;
}</code>```

  Replace to lol-breakable hyphens

one-half mother-in-law eighty-six one-third merry-go-round well-being mass-produced over-the-counter daughter-in-law merry-go-round

  Without replacement for comparison

one-half mother-in-law eighty-six one-third merry-go-round well-being mass-produced over-the-counter daughter-in-law merry-go-round

```

Body:
The fastest way

The fastest way to replace some text globally on a website is to walk through only text nodes inside a DOM tree.

You can achieve that by using document.createTreeWalker and then replacing only text nodes containing the word (or character) you want to change.

var findAndReplaceText = function(el, from, to) {
  if (!el || !from || !to) {
    return;
  }

  var node, nodes = [];
  var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);

  // Find nodes
  while (node = walker.nextNode()) {
    if (from instanceof RegExp) {
      from.test(node.wholeText) && nodes.push(node);
    } else {
      node.wholeText.indexOf(from) !== -1 && nodes.push(node);
    }
  }

  // Change DOM
  while (nodes.length > 0) {
    //nodes[0].replaceWith(
    //  document.createTextNode(nodes[0].wholeText.replace(from, to))
    //);
    nodes[0].textContent = nodes[0].wholeText.replace(from, to)
    nodes.splice(0, 1);
  }
};

findAndReplaceText(document.getElementById('fake-hyphens'), /[\u002d\u2010]/g, '\u2011');
findAndReplaceText(document.documentElement, 'lol', 'non');

// \u2010 - hypen
// \u2011 - non-breakable hyphen
// \u002d - minus

section {
  float: left;
  line-height: 1em;
  margin-left: 1em;
}

section p {
  width: 200px;
  outline: dashed red 1px;
  padding: 1em;
}

<section id="fake-hyphens">
  <header>Replace to lol-breakable hyphens</header>
  <p>one-half mother-in-law eighty-six one-third merry-go-round well-being mass-produced over-the-counter daughter-in-law merry-go-round</p>
</section>

<section>
  <header>Without replacement for comparison</header>
  <p>one-half mother-in-law eighty-six one-third merry-go-round well-being mass-produced over-the-counter daughter-in-law merry-go-round</p>
</section>


问:
piping the output to another command
The diff command works only if it has been provided with 2 files. Is it possible to replace one file with the output of another command? The second command mentioned below does not work.</p>

```<code>$ mysqldump -ushantanu -pPassWord test tbl --skip-extended-insert > to_backup.sql

$ diff  `mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert` to_backup.sql
-bash: /usr/bin/diff: Argument list too long
</code>```

答:
You can pipe one file from stdin</p>

```<code> $ mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert | diff  to_backup.sql -
</code>```

ContentLicense: CC BY-SA 2.5

Title: piping the output to another command

Body:
The diff command works only if it has been provided with 2 files. Is it possible to replace one file with the output of another command? The second command mentioned below does not work.

$ mysqldump -ushantanu -pPassWord test tbl --skip-extended-insert > to_backup.sql

$ diff  `mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert` to_backup.sql
-bash: /usr/bin/diff: Argument list too long

Body:
You can pipe one file from stdin

 $ mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert | diff  to_backup.sql -


问:
How to move an Image on click in React Native
I've recently been learning React Native but haven't really found a way to manipulate the DOM.

I've been trying to make it so that if I click on the TouchableHighlight my Image moves down a couple of px, but I have not managed to get it to move yet and I honestly don't know how to go from here.

My onclick function works since it does return the log every time the button is clicked.

As of now I have this:

```<code>export default class MainBody extends Component {

  onclick = () => {
    console.log('On click works')
  };

  render() {

    return (

      <ScrollView showsHorizontalScrollIndicator={false} style={Style.horList} horizontal={true}>

        <View >

          {/*i need to move this Image down!*/}
          <Image source={require("./img/example.png")}/>
          <View>
            <Text style={Style.peopleInvited}>This is text</Text>
          </View>

          {/*When clicked on this touchable highlight!*/}
          <TouchableHighlight onPress={this.onclick}}>
            <Image source={require('./img/moveImg.png')}/>
          </TouchableHighlight>
        </View>

      </ScrollView>
}
</code>```

If someone could help me get past this that would be greatly appreciated.
Thank you so much for your time!

答:
There are many ways to do this, but perhaps the easiest way would be using states.

```<code>class MainBody extends Component {
    constructor(props) {
        super(props);
        this.state = {
            top: 0 // Initial value
        };
    }
  onclick = () => {
    console.log('On click works')
    this.setState( { top: this.state.top + 5 }) // 5 is value of change.
};

  render() {

    return (

      <ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>

        <View >

          {/*i need to move this Image down!*/}
          <Image style={{top: this.state.top}}source={require("./img/example.png")}/>
          <View>
            <Text>This is text</Text>
          </View>

          {/*When clicked on this touchable highlight!*/}
          <TouchableHighlight onPress={this.onclick}>
            <Image source={require("./img/moveImg.png")}/>
          </TouchableHighlight>
        </View>

      </ScrollView>
  );
  }
}
</code>```

Body:
I've recently been learning React Native but haven't really found a way to manipulate the DOM.

I've been trying to make it so that if I click on the TouchableHighlight my Image moves down a couple of px, but I have not managed to get it to move yet and I honestly don't know how to go from here.

My onclick function works since it does return the log every time the button is clicked.

As of now I have this:

export default class MainBody extends Component {

  onclick = () => {
    console.log('On click works')
  };

  render() {

    return (

      <ScrollView showsHorizontalScrollIndicator={false} style={Style.horList} horizontal={true}>

        <View >

          {/*i need to move this Image down!*/}
          <Image source={require("./img/example.png")}/>
          <View>
            <Text style={Style.peopleInvited}>This is text</Text>
          </View>

          {/*When clicked on this touchable highlight!*/}
          <TouchableHighlight onPress={this.onclick}}>
            <Image source={require('./img/moveImg.png')}/>
          </TouchableHighlight>
        </View>

      </ScrollView>
}

If someone could help me get past this that would be greatly appreciated.
Thank you so much for your time!

Body:
There are many ways to do this, but perhaps the easiest way would be using states.

class MainBody extends Component {
    constructor(props) {
        super(props);
        this.state = {
            top: 0 // Initial value
        };
    }
  onclick = () => {
    console.log('On click works')
    this.setState( { top: this.state.top + 5 }) // 5 is value of change.
};

  render() {

    return (

      <ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>

        <View >

          {/*i need to move this Image down!*/}
          <Image style={{top: this.state.top}}source={require("./img/example.png")}/>
          <View>
            <Text>This is text</Text>
          </View>

          {/*When clicked on this touchable highlight!*/}
          <TouchableHighlight onPress={this.onclick}>
            <Image source={require("./img/moveImg.png")}/>
          </TouchableHighlight>
        </View>

      </ScrollView>
  );
  }
}


问:
Remove row dynamically from table in templates js
I have a page in which rows will be added dynamically using an add button (there is a java script function to add rows to the table on the page), these rows have to be deleted by clicking on a delete image which is a  value in one of the row
 that needs to be removed. I have done something like below, but 'onclick' is not working. The event is not getting triggered. What am I doing wrong here? Thanks.

```<code>function addRow(){
...
...
var deleteRow = "'deleteRowfun(\"rowNumber_"+(rowCount)+"\"); return false;'";

        var someName = "<tr id='rowNumber_" + (rowCount) + "' class = ' " + colorClass + " '><td valign='top' class='value'><label id='contactLastName_" +
            rowCount + "'>" + lastName + "</label></td>
            <td id='deleteContactAction_" + rowCount + "'>" +
            "<input type='image' src='/Projectname/plugins/folder/images/custom/delete-icon.jpg' id='contactDelete_" + rowCount + "'" +
            "title='Delete Contact' name='contactDelete' class='actionsIcon' " +
            "onclick="+ deleteRow + "/></td></tr>";

        $("#contactsTBL tbody").append(someName);
...
...

};

function deleteRowfun(itemId) {
        if (!confirm('Delete?')) {
            return false;
        }
        itemRowId = "#" + itemId
        $(itemRowId).remove();
    }
</code>```

答:
I moved call to deleteRowfun() function into onclickevent:

```<code>function addRow(){
  // calculate last biggest ID
  var rowCount = $("#contactsTBL tbody tr:last").length ?
    parseInt($("#contactsTBL tbody tr:last").attr('id').replace('rowNumber_', '')) + 1 : 0;
  var colorClass = 'color-classs';
  var lastName = `LAST NAME #${rowCount}`;

  var someName = `
    <tr id="rowNumber_${rowCount}" class="${colorClass}">
      <td valign="top" class="value">
        <label id="contactLastName_${rowCount}">${lastName}</label>
      </td>
      <td id="deleteContactAction_${rowCount}">
        <input type="image"
               src="/Projectname/plugins/folder/images/custom/delete-icon.jpg"
               id="contactDelete_${rowCount}"
               title="Delete Contact"
               name="contactDelete"
               class="actionsIcon"
               onclick="deleteRowfun('rowNumber_${rowCount}'); return false;"/>
      </td>
    </tr>`;

    $("#contactsTBL tbody").append(someName);
}
</code>```

plunker: http://plnkr.co/edit/qPGa3wNm3JLf2PKfjVyL?p=preview

Body:
I have a page in which rows will be added dynamically using an add button (there is a java script function to add rows to the table on the page), these rows have to be deleted by clicking on a delete image which is a  value in one of the row
 that needs to be removed. I have done something like below, but 'onclick' is not working. The event is not getting triggered. What am I doing wrong here? Thanks.

function addRow(){
...
...
var deleteRow = "'deleteRowfun(\"rowNumber_"+(rowCount)+"\"); return false;'";

        var someName = "
" + lastName + "
            " +
            "<input type='image' src='/Projectname/plugins/folder/images/custom/delete-icon.jpg' id='contactDelete_" + rowCount + "'" +
            "title='Delete Contact' name='contactDelete' class='actionsIcon' " +
            "onclick="+ deleteRow + "/>
";

        $("#contactsTBL tbody").append(someName);
...
...

};

function deleteRowfun(itemId) {
        if (!confirm('Delete?')) {
            return false;
        }
        itemRowId = "#" + itemId
        $(itemRowId).remove();
    }

Body:
I moved call to deleteRowfun() function into onclickevent:

function addRow(){
  // calculate last biggest ID
  var rowCount = $("#contactsTBL tbody tr:last").length ?
    parseInt($("#contactsTBL tbody tr:last").attr('id').replace('rowNumber_', '')) + 1 : 0;
  var colorClass = 'color-classs';
  var lastName = `LAST NAME #${rowCount}`;

  var someName = `
    <tr id="rowNumber_${rowCount}" class="${colorClass}">
      <td valign="top" class="value">
        <label id="contactLastName_${rowCount}">${lastName}</label>
      </td>
      <td id="deleteContactAction_${rowCount}">
        <input type="image"
               src="/Projectname/plugins/folder/images/custom/delete-icon.jpg"
               id="contactDelete_${rowCount}"
               title="Delete Contact"
               name="contactDelete"
               class="actionsIcon"
               onclick="deleteRowfun('rowNumber_${rowCount}'); return false;"/>
      </td>
    </tr>`;

    $("#contactsTBL tbody").append(someName);
}

plunker: http://plnkr.co/edit/qPGa3wNm3JLf2PKfjVyL?p=preview


问:
How to make the aur package into the archlinux community source?
I have already uploaded my aur package to the aur.archlinux.org (https://aur.archlinux.org/packages/xmake/).

How to make the aur package into the archlinux community source?

I want to run command pacman -S xmake to install my package.

Who can help me?

Thanks!

答:
As a maintainer in AUR, I can answer that the only way is to become a member of the famous trusted users of Arch Linux. Which is kinda hard do integrate if you only have one package (just saw your repository).

To quote the official Arch Linux team:

The minimum requirements to becoming a TU are as follows:

know basic shell scripting

maintain a few packages in AUR with clean, high-quality PKGBUILDs
  basic community involvement (mailing list, forums, IRC)

know Google-Fu

a general idea of the kind of packages you want to maintain (basically, why do you want to become TU?)

Even though you could become a TU by merely fulfilling those minimum requirements, the people judging you during voting might expect more of you. Such as:

involvement in the bug tracker (reporting, research, info)

patches for Arch projects

involvement in a few open-source projects (even if they are your own)

In between your package have a big problem and I marked it as out-of-date because of the following:

According to Arch packaging standard:

Packages should never be installed to /usr/local

You should install all your files under /usr/share/{pkgName}/* according to the standard.


问:
How to retrieve a JPG image using GetManifestResourceStream() method?
I have the following situation:

I have a Solution that is named MySolution, inside this solution there is some projects including a project named PdfReport. Inside this project there is a folder named Shared and inside this folder there is an header.jpg image.

Now I am trying to retrieve this file and I have found this code on the official documentation (http://msdn.microsoft.com/en-us/library/aa287676%28v=vs.71%29.aspx):

```<code>System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
    thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
this.pictureBox1.Image = Image.FromStream(file);
</code>```

On the documentation say that:

Replace "AssemblyName.ImageFile.jpg" with the name of the resource, as
  it is known in the assembly.

I am finding some difficulties to understand what I have to insert in my specific case as input paramether for the GetManifestResourceStream() method.

Can you help me to retrive my file?

Tnx

答:
//first steps
1. you addeed an imager to the project.
2. Right click on the image and change Build Action to Embedded Resource.
Right click on the image and change Build Action to Embedded Resource.

In your code:
uncomment the line below and add a breakpoint. It will return an array with all the resources listed. Simply find your resource, and replace the "assembly.draft.png" with your resource.

```<code>//  var d = thisExe.GetManifestResourceNames();
System.IO.Stream file =
 thisExe.GetManifestResourceStream(@"assembly.draft.png");
while ((read = file.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
</code>```

Body:
I have the following situation:

I have a Solution that is named MySolution, inside this solution there is some projects including a project named PdfReport. Inside this project there is a folder named Shared and inside this folder there is an header.jpg image.

Now I am trying to retrieve this file and I have found this code on the official documentation (http://msdn.microsoft.com/en-us/library/aa287676%28v=vs.71%29.aspx):

System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
    thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
this.pictureBox1.Image = Image.FromStream(file);

On the documentation say that:

Replace "AssemblyName.ImageFile.jpg" with the name of the resource, as
  it is known in the assembly.

I am finding some difficulties to understand what I have to insert in my specific case as input paramether for the GetManifestResourceStream() method.

Can you help me to retrive my file?

Tnx

Body:
//first steps
1. you addeed an imager to the project.
2. Right click on the image and change Build Action to Embedded Resource.
Right click on the image and change Build Action to Embedded Resource.

In your code:
uncomment the line below and add a breakpoint. It will return an array with all the resources listed. Simply find your resource, and replace the "assembly.draft.png" with your resource.

//  var d = thisExe.GetManifestResourceNames();
System.IO.Stream file =
 thisExe.GetManifestResourceStream(@"assembly.draft.png");
while ((read = file.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}


问:
create a dropdown in react to show/hide fetch data based on object class
Currently I am calling the Riot Games api and displaying all the champions. I have added a filter by name section, but i would like to add a dropdown to sort by champion class. On initial page load I want every champion rendered (which it currently does), but then selecting a class from the dropdown only show the champs that have that class. I can show each champions class with
{champion.table.tags}
 and adding the index number or numbers and this is what i want to be able to sort by. If {champion.table.tags[0} or {champion.table.tags[1} = "Fighter" for example. I would like every champion with a tag of "Fighter" to be shown when "Fighter" is selected in the dropdown

I'm pretty new to react and I have built this same feature in Rails without any problem, but I'm struggling with the React way of going about this.

my current code that shows all champs and has a sort function

```<code>import React, { Component } from 'react';
import { Link } from 'react-router';
import _ from 'lodash';

class Champions extends Component {
  constructor(props) {
    super(props);

    this.state = {
      champions: []
    };
  }

  componentWillMount() {
    fetch('http://localhost:3000/champ.json')
    .then(response => response.json())
    .then(champions => {
      this.setState({ champions })
    })
  }

  filter(e){
    this.setState({ filter: e.target.value} )
  }

  render() {
    let champions = this.state.champions;
    console.log('champions: ', champions);

    if(this.state.filter){
      champions = champions.filter( champion =>
      champion.table.name.toLowerCase()
      .includes(this.state.filter.toLowerCase()))
    }

    if(this.state.handleChange){
      tags = champions.handleChange( champion =>
      champion.table.tags
    .includes(this.state.handleChange()))
    }

    return (
      <div>
        <div>
          <input type="text"
                 placeholder="search for a champ"
                 onChange={this.filter.bind(this)}
          />
        </div>

        <div className="Sort">
          <select>
            {champions.map((champion, i) =>
              <option key={i}>{champion.table.tags[0]}
              </option>)}
          </select>
        </div>

      <ul className="champ-list">
        {champions.map(champion => {
          return <li key={champion.table.id} className="col-xs-3">
            <div>
              <Link to={`/${champion.table.id}`} >
              <img src={`http://ddragon.leagueoflegends.com/cdn/7.5.2/img/champion/${champion.table.image.full}`} />
              </Link>
              </div>
              <Link to={`/${champion.table.id}`} >
            <h3>{champion.table.key}</h3>
            <h4>{champion.table.title}</h4>
            <h4>{champion.table.tags}</h4>
            </Link>
          </li>
        })}
      </ul>
      </div>
    );
  }
}

export default Champions;
</code>```

as of right now the dropdown goes through each champion object and populates the  with the first class tag of every champion. I think there are maybe 7 classes total and I can manually create the  if needed, but how can I show All of the champions and then just the ones based on the dropdown selection.

Not sure if this is relevant, but has also given me a bit of a headache in React. The JSON returns an array of 134 objects (champions). Inside each object are several key value pairs as well as more arrays with key value pairs inside of them. The class tags I am trying to sort by are inside of one of these nested arrays.

Any help or even a point in the right direction would be greatly appreciated

答:
figured it out on my own. here's the updated code</p>

```<code>import React, { Component } from 'react';
import { Link } from 'react-router';
import _ from 'lodash';

class Champions extends Component {
  constructor(props) {
    super(props);

    this.state = {
      champions: [],
    };
  }

  componentWillMount() {
    fetch('http://localhost:3000/champ.json')
    .then(response => response.json())
    .then(champions => {
      this.setState({ champions })
      // console.log('setState: ', this.state.champions);
    })
  }

  filter(e){
    this.setState({filter: e.target.value})
  }

  filterChamp(e){
    this.setState({filterChamp: e.target.value})
  }

  render() {
    let champions = this.state.champions;
    // console.log(champions);
    // console.log('props: ', this.props);

    if(this.state.filter){
      champions = champions.filter( champion =>
      champion.table.name.toLowerCase()
      .includes(this.state.filter.toLowerCase()))
    }

    if(this.state.filterChamp){
      champions = champions.filter( champion =>
      champion.table.tags
      .includes(this.state.filterChamp))
    }

    return (
      <div>
        <select onChange={this.filterChamp.bind(this)} value={this.state.filterChamp}>
          <option value="">All Champs</option>
          <option value="Assassin">Assassin</option>
          <option value="Fighter">Fighter</option>
          <option value="Mage">Mage</option>
          <option value="Marksman">Marksman</option>
          <option value="Support">Support</option>
          <option value="Tank">Tank</option>
        </select>

        <input type="text"
               placeholder="search for a champ"
               onChange={this.filter.bind(this)}
        />
      <ul className="champ-list">
        {champions.map(champion => {
          return <li key={champion.table.id} className="col-xs-3">
            <div>
              <Link to={`/champ/${champion.table.name}`} >
              <img src={`http://ddragon.leagueoflegends.com/cdn/7.5.2/img/champion/${champion.table.image.full}`} />
              </Link>
              </div>
              <Link to={`/${champion.table.id}`} >
            <h3>{champion.table.key}</h3>
            <h4>{champion.table.title}</h4>
            </Link>
          </li>
        })}
      </ul>
      </div>
    );
  }
}

export default Champions;
</code>```

Body:
Currently I am calling the Riot Games api and displaying all the champions. I have added a filter by name section, but i would like to add a dropdown to sort by champion class. On initial page load I want every champion rendered (which it currently does), but then selecting a class from the dropdown only show the champs that have that class. I can show each champions class with
{champion.table.tags}
 and adding the index number or numbers and this is what i want to be able to sort by. If {champion.table.tags[0} or {champion.table.tags[1} = "Fighter" for example. I would like every champion with a tag of "Fighter" to be shown when "Fighter" is selected in the dropdown

I'm pretty new to react and I have built this same feature in Rails without any problem, but I'm struggling with the React way of going about this.

my current code that shows all champs and has a sort function

import React, { Component } from 'react';
import { Link } from 'react-router';
import _ from 'lodash';

class Champions extends Component {
  constructor(props) {
    super(props);

    this.state = {
      champions: []
    };
  }

  componentWillMount() {
    fetch('http://localhost:3000/champ.json')
    .then(response => response.json())
    .then(champions => {
      this.setState({ champions })
    })
  }

  filter(e){
    this.setState({ filter: e.target.value} )
  }

  render() {
    let champions = this.state.champions;
    console.log('champions: ', champions);

    if(this.state.filter){
      champions = champions.filter( champion =>
      champion.table.name.toLowerCase()
      .includes(this.state.filter.toLowerCase()))
    }

    if(this.state.handleChange){
      tags = champions.handleChange( champion =>
      champion.table.tags
    .includes(this.state.handleChange()))
    }

    return (

          <input type="text"
                 placeholder="search for a champ"
                 onChange={this.filter.bind(this)}
          />

          <select>
            {champions.map((champion, i) =>
              <option key={i}>{champion.table.tags[0]}
              </option>)}
          </select>

        {champions.map(champion => {
          return

              <Link to={`/${champion.table.id}`} >
              <img src={`http://ddragon.leagueoflegends.com/cdn/7.5.2/img/champion/${champion.table.image.full}`} />
              </Link>

              <Link to={`/${champion.table.id}`} >

{champion.table.key}

{champion.table.title}

{champion.table.tags}

            </Link>

        })}

    );
  }
}

export default Champions;

as of right now the dropdown goes through each champion object and populates the  with the first class tag of every champion. I think there are maybe 7 classes total and I can manually create the  if needed, but how can I show All of the champions and then just the ones based on the dropdown selection.

Not sure if this is relevant, but has also given me a bit of a headache in React. The JSON returns an array of 134 objects (champions). Inside each object are several key value pairs as well as more arrays with key value pairs inside of them. The class tags I am trying to sort by are inside of one of these nested arrays.

Any help or even a point in the right direction would be greatly appreciated

Body:
figured it out on my own. here's the updated code

import React, { Component } from 'react';
import { Link } from 'react-router';
import _ from 'lodash';

class Champions extends Component {
  constructor(props) {
    super(props);

    this.state = {
      champions: [],
    };
  }

  componentWillMount() {
    fetch('http://localhost:3000/champ.json')
    .then(response => response.json())
    .then(champions => {
      this.setState({ champions })
      // console.log('setState: ', this.state.champions);
    })
  }

  filter(e){
    this.setState({filter: e.target.value})
  }

  filterChamp(e){
    this.setState({filterChamp: e.target.value})
  }

  render() {
    let champions = this.state.champions;
    // console.log(champions);
    // console.log('props: ', this.props);

    if(this.state.filter){
      champions = champions.filter( champion =>
      champion.table.name.toLowerCase()
      .includes(this.state.filter.toLowerCase()))
    }

    if(this.state.filterChamp){
      champions = champions.filter( champion =>
      champion.table.tags
      .includes(this.state.filterChamp))
    }

    return (
      <div>
        <select onChange={this.filterChamp.bind(this)} value={this.state.filterChamp}>
          <option value="">All Champs</option>
          <option value="Assassin">Assassin</option>
          <option value="Fighter">Fighter</option>
          <option value="Mage">Mage</option>
          <option value="Marksman">Marksman</option>
          <option value="Support">Support</option>
          <option value="Tank">Tank</option>
        </select>

        <input type="text"
               placeholder="search for a champ"
               onChange={this.filter.bind(this)}
        />
      <ul className="champ-list">
        {champions.map(champion => {
          return <li key={champion.table.id} className="col-xs-3">
            <div>
              <Link to={`/champ/${champion.table.name}`} >
              <img src={`http://ddragon.leagueoflegends.com/cdn/7.5.2/img/champion/${champion.table.image.full}`} />
              </Link>
              </div>
              <Link to={`/${champion.table.id}`} >
            <h3>{champion.table.key}</h3>
            <h4>{champion.table.title}</h4>
            </Link>
          </li>
        })}
      </ul>
      </div>
    );
  }
}

export default Champions;


问:
Aggregarte with condtions of two df
I am looking for solution that allow me to have the mean of some values in data frame by date depending on two criteria in an other data frame

Criteria DF

```<code>  > dput(Criteria)
structure(list(Name = c("ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = c(1992, 1992, 1992, 1992, 1992, 1992, 1992,
 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993,
 1993, 1993), Value = c("FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "FALSE", "TRUE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "TRUE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE",
 "TRUE")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
 -20L), .Names = c("Name", "Date", "Value"))
</code>```

Return DF

```<code>> dput(Return)
structure(list(`Names ` = c("ff", "fd", "fe", "fr", "fz", "fa",
"kl", "ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = structure(c(8065, 8065, 8065, 8065, 8065,
8065, 8065, 8065, 8065, 8065, 8186, 8186, 8186, 8186, 8186, 8186,
8186, 8186, 8186, 8186, 8490, 8490, 8490, 8490, 8490, 8490, 8490,
8431, 8431, 8431), class = "Date"), Value = c(0.2, 0.43, NA,
0.52, -0.002, NA, 0.001, NA, 0.22, 0.32, 0, 0.001, 0.032, 0.9123,
1, 0.32, 0.43, 0.0312, 0.0312, 0.43, 0.53, 0.84, 0.001, -0.0123,
0.43, 0.134, 0.74, 0.0312, 0.9324, 0.06)), row.names = c(NA,
-30L), .Names = c("Names ", "Date", "Value"), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

I tried to calculate the mean Value of Return DF per date , but this mean value should be calculated just for companies have the condition TRUE in Criteria DF in that Year

my solution was

```<code> for (val in Return$Value) {
 if (year(Return$Date)%in% year(Criteria$Date) & Criteria$Value == TRUE)
 result = aggregate(Return$Value, by=list(Return$Date), mean, na.rm= TRUE)
 }
 print result
</code>```

But I failed using the aggregate function .

答:
Consider formatting Return's Date to Year format, then run merge / subset / aggregate. Try also renaming fields to avoid duplicate names requiring suffixes after merging: .1, .x, .y:

```<code>Return$Year <- format(Return$Date, "%Y")

mdf <- subset(merge(Criteria, Return, by.x="Date", by.y="Year"), Value.x==TRUE)

aggdf <- aggregate(Value.y~Date.1, mdf, FUN=mean)

#       Date.1   Value.y
# 1 1992-01-31 0.2412857
# 2 1992-05-31 0.3187700
# 3 1993-01-31 0.3412000
# 4 1993-03-31 0.3803857
</code>```

R fiddle for demonstration

Even consider a dense one-liner:

```<code>aggdf <- aggregate(Value.y~Date.1,
                   subset(merge(Criteria,
                                transform(Return, Year = format(Date, "%Y")),
                          by.x="Date", by.y="Year"), Value.x==TRUE),
                   FUN=mean)
</code>```

Title: Aggregarte with condtions of two df

Body:
I am looking for solution that allow me to have the mean of some values in data frame by date depending on two criteria in an other data frame

Criteria DF

  > dput(Criteria)
structure(list(Name = c("ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = c(1992, 1992, 1992, 1992, 1992, 1992, 1992,
 1992, 1992, 1992, 1993, 1993, 1993, 1993, 1993, 1993, 1993, 1993,
 1993, 1993), Value = c("FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "FALSE", "TRUE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE",
 "TRUE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE",
 "TRUE")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
 -20L), .Names = c("Name", "Date", "Value"))

Return DF

> dput(Return)
structure(list(`Names ` = c("ff", "fd", "fe", "fr", "fz", "fa",
"kl", "ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl",
"ml", "az", "er", "ff", "fd", "fe", "fr", "fz", "fa", "kl", "ml",
"az", "er"), Date = structure(c(8065, 8065, 8065, 8065, 8065,
8065, 8065, 8065, 8065, 8065, 8186, 8186, 8186, 8186, 8186, 8186,
8186, 8186, 8186, 8186, 8490, 8490, 8490, 8490, 8490, 8490, 8490,
8431, 8431, 8431), class = "Date"), Value = c(0.2, 0.43, NA,
0.52, -0.002, NA, 0.001, NA, 0.22, 0.32, 0, 0.001, 0.032, 0.9123,
1, 0.32, 0.43, 0.0312, 0.0312, 0.43, 0.53, 0.84, 0.001, -0.0123,
0.43, 0.134, 0.74, 0.0312, 0.9324, 0.06)), row.names = c(NA,
-30L), .Names = c("Names ", "Date", "Value"), class = c("tbl_df",
"tbl", "data.frame"))

I tried to calculate the mean Value of Return DF per date , but this mean value should be calculated just for companies have the condition TRUE in Criteria DF in that Year

my solution was

 for (val in Return$Value) {
 if (year(Return$Date)%in% year(Criteria$Date) & Criteria$Value == TRUE)
 result = aggregate(Return$Value, by=list(Return$Date), mean, na.rm= TRUE)
 }
 print result

But I failed using the aggregate function .

Body:
Consider formatting Return's Date to Year format, then run merge / subset / aggregate. Try also renaming fields to avoid duplicate names requiring suffixes after merging: .1, .x, .y:

Return$Year <- format(Return$Date, "%Y")

mdf <- subset(merge(Criteria, Return, by.x="Date", by.y="Year"), Value.x==TRUE)

aggdf <- aggregate(Value.y~Date.1, mdf, FUN=mean)

#       Date.1   Value.y
# 1 1992-01-31 0.2412857
# 2 1992-05-31 0.3187700
# 3 1993-01-31 0.3412000
# 4 1993-03-31 0.3803857

R fiddle for demonstration

Even consider a dense one-liner:

aggdf <- aggregate(Value.y~Date.1,
                   subset(merge(Criteria,
                                transform(Return, Year = format(Date, "%Y")),
                          by.x="Date", by.y="Year"), Value.x==TRUE),
                   FUN=mean)


问:
What do people find so appealing about dynamic languages?
It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately.  I've mostly only worked in compiled, static typed languages (C, Java, .Net).  The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP.  Using these technologies has left a bad taste in my mouth when thinking about dynamic languages.  Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime.  And even then, you may not notice an error, as it just creates a new variable, and assigns some default value.  I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.

What I want to know is, what people find so appealing about dynamic languages?  What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages.  It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code?  And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?

答:
I think this kind of argument is a bit stupid: "Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime" yes thats right as a PHP developer I don't see things like mistyped variables until runtime, BUT runtime is step 2 for me, in C++ (Which is the only compiled language I have any experience) it is step 3, after linking, and compiling.

Not to mention that it takes all of a few seconds after I hit save to when my code is ready to run, unlike in compiled languages where it can take literally hours.  I'm sorry if this sounds a bit angry, but I'm kind of tired of people treating me as a second rate programmer because I don't have to compile my code.

OwnerDisplayName: Kibbee

LastEditorDisplayName: kronoz

OwnerDisplayName: Unkwntech


问:
Using <= and >= in XSLT
I would like to use <= and >= when comparing values in <xsl:if test="">. How to do that?

Update:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

<html>
    <body>
        <h1>Average classsize per user and module</h1>
        <table border="1">

            <tr>
                <th>User Email</th>
                <th>Module Code</th>
                <th>Average Value</th>
            </tr>
            <xsl:apply-templates select="//classsize" />
        </table>
    </body>
</html>

</xsl:template>

<xsl:template match="average">
    <xsl:choose>
        <xsl:when test=". < 1">
            <td style="background-color: red;"><xsl:value-of select="." /></td>
        </xsl:when>

        <xsl:when test="1 <= . < 2">
            <td style="background-color: blue;"><xsl:value-of select="." /></td>
        </xsl:when>

        <xsl:when test="2 <= . < 3">
            <td style="background-color: yellow;"><xsl:value-of select="." /></td>
        </xsl:when>

        <xsl:otherwise>
            <td style="background-color: white;"><xsl:value-of select="." /></td>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="//classsize">
    <tr>
        <td><xsl:value-of select="email" /></td>
        <td><xsl:value-of select="modulecode" /></td>
        <xsl:apply-templates select="average" />
    </tr>
</xsl:template>

</xsl:stylesheet>
</code>```

```<code>average < 1 - in red
1 <= average < 2 - in blue
2 <= average < 3 - in yellow
average >= 3 - white
</code>```

答:
You can escape the < and > to < and >, respectively.

See the example for xsl:if on w3schools.

Update:

After seeing you condition, I am not surprised it doesn't work.

Instead of:

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

Try:

```<code>1 <= . and . < 2
</code>```

You can't chain the < and > like that in XSLT.

Title: Using <= and >= in XSLT

Body:
I would like to use <= and >= when comparing values in <xsl:if test="">. How to do that?

Update:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

Average classsize per user and module

                User Email
                Module Code
                Average Value

            <xsl:apply-templates select="//classsize" />

</xsl:template>

<xsl:template match="average">
    <xsl:choose>
        <xsl:when test=". < 1">
            <xsl:value-of select="." />
        </xsl:when>

        <xsl:when test="1 <= . < 2">
            <xsl:value-of select="." />
        </xsl:when>

        <xsl:when test="2 <= . < 3">
            <xsl:value-of select="." />
        </xsl:when>

        <xsl:otherwise>
            <xsl:value-of select="." />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="//classsize">

        <xsl:value-of select="email" />
        <xsl:value-of select="modulecode" />
        <xsl:apply-templates select="average" />

</xsl:template>

</xsl:stylesheet>

average < 1 - in red
1 <= average < 2 - in blue
2 <= average < 3 - in yellow
average >= 3 - white

Body:
You can escape the < and > to &lt; and &gt;, respectively.

See the example for xsl:if on w3schools.

Update:

After seeing you condition, I am not surprised it doesn't work.

Instead of:

1 &lt;= . &lt; 2

Try:

1 &lt;= . and . &lt; 2

You can't chain the < and > like that in XSLT.


问:
jQuery plugin not working inside a .vue component
I'm working in a vue component for my application in Laravel 5.3, I try to integrate the Laravel File Manager in a standalone button, but this not working, nothing happend when I clic on the button for choose an image, this component required a jQuery init setup, like the following line:

```<code>$('.lfm-img').filemanager('image');
</code>```

I checked the component outside the .vue file and its working fine, only inside the .vue file is not working.

This is the vue component

```<code><template>
    <div class="modal fade"
            id="section-{{ section.id }}"
            tabindex="-1"
            role="dialog"
            aria-labelledby="sectionLabel-{{ section.id }}">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button"
                            class="close"
                            data-dismiss="modal"
                            aria-label="Close">
                            <span aria-hidden="true">×</span>
                    </button>

                    <h4 class="modal-title" id="sectionLabel-{{ section.id }}">
                        {{ section.name }}
                    </h4>
                </div>
                <div class="modal-body">
                    <!-- Field List -->
                    <div v-if="editing != true">
                        <ul class="list-group">
                            <li class="list-group-item" v-for="field in fields">
                                <div class="clearfix">
                                    <div class="pull-left">
                                        <span>
                                            {{ field.name }}
                                        </span>
                                    </div>
                                    <div class="pull-right">
                                        <button type="button"
                                                class="btn btn-default"
                                                data-toggle="tooltip"
                                                title="Editar valor"
                                                @click="setField(field)">

                                            <i  class="fa fa-pencil-square fa-lg"
                                                aria-hidden="true"></i>
                                        </button>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <!-- / Field List -->
                    <!-- Save value form -->
                    <div v-else>
                        <form @submit.prevent="updateFieldValue()">
                            <!-- Fields types -->
                            <div v-if="field.fieldtype_id === 1">
                                <div class="form-group vertical-align">
                                    <label class="col-md-2 text-right">
                                        Texto
                                    </label>
                                    <div class="col-md-10">
                                        <input  type="text"
                                                v-model="value"
                                                placeholder="Ingrese el valor"
                                                class="form-control"
                                                required="required">
                                    </div>
                                </div>
                                <p><br></p>
                            </div>
                            <div v-if="field.fieldtype_id === 2">
                                <div class="form-group">
                                    <textarea   v-model="value"
                                                placeholder="Ingrese texto"
                                                class="form-control"
                                                rows="5"
                                                required="required">
                                    </textarea>
                                </div>
                                <p><br></p>
                            </div>
                            <div v-if="field.fieldtype_id === 3">
                                <div class="form-group vertical-align">
                                    <label class="col-md-3 text-right">
                                        Seleccione una imagen
                                    </label>
                                    <div class="col-md-9">
                                        <div class="input-group">
                                            <span class="input-group-btn">
                                                <a  data-input="value"
                                                    data-preview="holder"
                                                    class="btn btn-primary lfm-img">
                                                    <i  class="fa fa-picture-o"
                                                        aria-hidden="true"></i> Seleccionar
                                                </a>
                                            </span>
                                            <input  id="value"
                                                    v-model="value"
                                                    class="form-control"
                                                    type="text"
                                                    name="value"
                                                    required="required">
                                        </div>
                                    </div>
                                </div>
                                <img id="holder" style="margin-top:15px;max-height:100px;">
                                <p><br></p>
                            </div>

                            <!-- Actions -->
                            <div class="clearfix">
                                <div class="pull-right">
                                    <button type="button"
                                            class="btn btn-default"
                                            data-dismiss="modal"
                                            @click="finishEdit()">
                                            Cancelar
                                    </button>
                                    <button type="submit"
                                            class="btn btn-primary">
                                            Guardar
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <!-- / Save value form -->
                </div>
                <div class="modal-footer">
                    <button type="button"
                            class="btn btn-default"
                            @click="finishEdit()"
                            data-dismiss="modal">
                            Cerrar
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['section'],

        data()
        {
            return {
                fields: [],
                field: [],
                value: '',
                loading: true, // start the spin loader
                editing: false // show field list
            }
        },

        ready()
        {
            this.loading = false; // stop the spin loader
            this.getSectionFields();
        },

        methods:
        {
            startEdit()
            {
                this.editing = true;
            },

            finishEdit()
            {
                this.field = [];
                this.value = '';
                this.editing = false;
            },

            setField(field) {
                this.field = field;
                if (this.field.pivot.value !== null) {
                    this.value = this.field.pivot.value;
                }
                this.startEdit();
            },

            getSectionFields()
            {
                var self = this; // store "this." scope
                // GET request
                this.$http.get('/api/getSectionFields/' + this.section.id )
                    .then((response) => {
                    // sucess callback
                    var json = JSON.parse(response.body); // json parse
                    self.fields = json.fields;
                    this.loading = false; // stop the spin loader
                }, function(response) {
                    // error callback
                    console.log(response);
                });
            },

            updateFieldValue()
            {
                this.loading = true // start the spin loader
                var params = {  section : this.section.id,
                                field : this.field.id,
                                value : this.value
                            };
                // POST request
                this.$http.post('/api/update-value', params)
                    .then((response) => {
                    // sucess callback
                    this.getSectionFields();
                    this.finishEdit();
                }, function(response) {
                    // error callback
                    console.log(response);
                    this.getSectionFields();
                });
            }
        }
    }
</script>
</code>```

答:
I solved the problem using Vue.nextTick, running the following code before the file manager be shown to ensure the initialization of the plugins in the latest DOOM update.</p>

```<code>initFilemanager()
{
    this.$nextTick(function() {
        $('.lfm-img').filemanager('image');
    });
},
</code>```

Body:
I'm working in a vue component for my application in Laravel 5.3, I try to integrate the Laravel File Manager in a standalone button, but this not working, nothing happend when I clic on the button for choose an image, this component required a jQuery init setup, like the following line:

$('.lfm-img').filemanager('image');

I checked the component outside the .vue file and its working fine, only inside the .vue file is not working.

This is the vue component

<template>

                    <button type="button"
                            class="close"
                            data-dismiss="modal"
                            aria-label="Close">
                            ×
                    </button>

                        {{ section.name }}

                                            {{ field.name }}

                                        <button type="button"
                                                class="btn btn-default"
                                                data-toggle="tooltip"
                                                title="Editar valor"
                                                @click="setField(field)">

                                        </button>

                        <form @submit.prevent="updateFieldValue()">

                                        Texto

                                        <input  type="text"
                                                v-model="value"
                                                placeholder="Ingrese el valor"
                                                class="form-control"
                                                required="required">

                                    <textarea   v-model="value"
                                                placeholder="Ingrese texto"
                                                class="form-control"
                                                rows="5"
                                                required="required">
                                    </textarea>

                                        Seleccione una imagen

                                                     Seleccionar

                                            <input  id="value"
                                                    v-model="value"
                                                    class="form-control"
                                                    type="text"
                                                    name="value"
                                                    required="required">

                                    <button type="button"
                                            class="btn btn-default"
                                            data-dismiss="modal"
                                            @click="finishEdit()">
                                            Cancelar
                                    </button>
                                    <button type="submit"
                                            class="btn btn-primary">
                                            Guardar
                                    </button>

                        </form>

                    <button type="button"
                            class="btn btn-default"
                            @click="finishEdit()"
                            data-dismiss="modal">
                            Cerrar
                    </button>

</template>

Body:
I solved the problem using Vue.nextTick, running the following code before the file manager be shown to ensure the initialization of the plugins in the latest DOOM update.

initFilemanager()
{
    this.$nextTick(function() {
        $('.lfm-img').filemanager('image');
    });
},


问:
How do you use require() within a map function?
Looking at the docs for CouchDB 1.6.1 here, there is mention that you can use the JS require(path) function. How do you do this? The documentation says path is "A CommonJS module path started from design document root".

My design doc is called _design/data. I have uploaded an attachment to this design doc called test.js, which can be accessed at /_design/data/test.js, and contains the following code:

```<code>exports.stuff = function() {
    this.getMsg = (function() {
        return 'hi';
    })()
}
</code>```

But the following code in my map function:

```<code>function(doc) {
  try {
    var x = require('test.js');
  } catch (e) {
   emit ('error', e)
  }
}
</code>```

results in this error:

```<code>["error", "invalid_require_path", "Object has no property \"test.js\". {\"views\":{\"lib\":null},\"_module_cache\":{}}"]
</code>```

It looks like require is looking for the path as an object in the docparam... but I don't understand why if it is.

Looking at this link, describing this feature in an older version of CouchDB, it says you can:

However, in the upcoming CouchDB 1.1.x views will be able to require modules provided they exist below the 'views' property (eg, 'views/lib/module')

And gives the following code example:

```<code>{
    "_id": "_design/example",
    "lib": {
        // modules here would not be accessible from view functions
    },
    "views": {
        "lib" {
            // this module is accessible from view functions
            "module": "exports.test = 'asdf';"
        },
        "commonjs": {
            "map": function (doc) {
                var val = require('views/lib/module').test;
                emit(doc._id, val);
            }
        }
    }
}
</code>```

But this did not work for me on CouchDB 1.6.1. I get the error:

```<code>{message: "mod.current is null", fileName: "/usr/share/couchdb/server/main.js", lineNumber: 1137, stack: "([object Array],[object Object])@/usr/share/couchdb/server/main.js:1137\n([object Array],[object Object])@/usr/share/couchdb/server/main.js:1143\n([object Array],[object Object],[object Object])@/usr/share/couchdb/server/main.js:1143\n(\"views/lib/module\")@/usr/share/couchdb/server/main.js:1173\n([object Object])@undefined:3\n([object Object])@/usr/share/couchdb/server/main.js:1394\n()@/usr/share/couchdb/server/main.js:1562\n@/usr/share/couchdb/server/main.js:1573\n"
</code>```

答: In your question you didn't provide the function as a string. It's not too easy to spot, but you must stringify functions before storing them in CouchDB (manually or by using .toString()). Caolan has that error in the post that you linked.

Body:
Looking at the docs for CouchDB 1.6.1 here, there is mention that you can use the JS require(path) function. How do you do this? The documentation says path is "A CommonJS module path started from design document root".

My design doc is called _design/data. I have uploaded an attachment to this design doc called test.js, which can be accessed at /_design/data/test.js, and contains the following code:

exports.stuff = function() {
    this.getMsg = (function() {
        return 'hi';
    })()
}

But the following code in my map function:

function(doc) {
  try {
    var x = require('test.js');
  } catch (e) {
   emit ('error', e)
  }
}

results in this error:

["error", "invalid_require_path", "Object has no property \"test.js\". {\"views\":{\"lib\":null},\"_module_cache\":{}}"]

It looks like require is looking for the path as an object in the docparam... but I don't understand why if it is.

Looking at this link, describing this feature in an older version of CouchDB, it says you can:

However, in the upcoming CouchDB 1.1.x views will be able to require modules provided they exist below the 'views' property (eg, 'views/lib/module')

And gives the following code example:

{
    "_id": "_design/example",
    "lib": {
        // modules here would not be accessible from view functions
    },
    "views": {
        "lib" {
            // this module is accessible from view functions
            "module": "exports.test = 'asdf';"
        },
        "commonjs": {
            "map": function (doc) {
                var val = require('views/lib/module').test;
                emit(doc._id, val);
            }
        }
    }
}

But this did not work for me on CouchDB 1.6.1. I get the error:

{message: "mod.current is null", fileName: "/usr/share/couchdb/server/main.js", lineNumber: 1137, stack: "([object Array],[object Object])@/usr/share/couchdb/server/main.js:1137\n([object Array],[object Object])@/usr/share/couchdb/server/main.js:1143\n([object Array],[object Object],[object Object])@/usr/share/couchdb/server/main.js:1143\n(\"views/lib/module\")@/usr/share/couchdb/server/main.js:1173\n([object Object])@undefined:3\n([object Object])@/usr/share/couchdb/server/main.js:1394\n()@/usr/share/couchdb/server/main.js:1562\n@/usr/share/couchdb/server/main.js:1573\n"


问:
importing pyspark in python shell
This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue.  (See http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736)

I have Spark installed properly on my machine and am able to run python programs with the pyspark modules without error when using ./bin/pyspark as my python interpreter.

However, when I attempt to run the regular Python shell, when I try to import pyspark modules I get this error:

```<code>from pyspark import SparkContext
</code>```

and it says

```<code>"No module named pyspark".
</code>```

How can I fix this?  Is there an environment variable I need to set to point Python to the pyspark headers/libraries/etc.?  If my spark installation is /spark/, which pyspark paths do I need to include?  Or can pyspark programs only be run from the pyspark interpreter?

答:
For Linux users, the following is the correct (and non-hard-coded)  way of including the pyspark libaray in PYTHONPATH. Both PATH parts are necessary:

The path to the pyspark Python module itself, and

The path to the zipped library that that pyspark module relies on when imported

Notice below that the zipped library version is dynamically determined, so we do not hard-code it.

```<code>export PYTHONPATH=${SPARK_HOME}/python/:$(echo ${SPARK_HOME}/python/lib/py4j-*-src.zip):${PYTHONPATH}
</code>```

Title: importing pyspark in python shell

Body:
This is a copy of someone else's question on another forum that was never answered, so I thought I'd re-ask it here, as I have the same issue.  (See http://geekple.com/blogs/feeds/Xgzu7/posts/351703064084736)

I have Spark installed properly on my machine and am able to run python programs with the pyspark modules without error when using ./bin/pyspark as my python interpreter.

However, when I attempt to run the regular Python shell, when I try to import pyspark modules I get this error:

from pyspark import SparkContext

and it says

"No module named pyspark".

How can I fix this?  Is there an environment variable I need to set to point Python to the pyspark headers/libraries/etc.?  If my spark installation is /spark/, which pyspark paths do I need to include?  Or can pyspark programs only be run from the pyspark interpreter?

Body:
For Linux users, the following is the correct (and non-hard-coded)  way of including the pyspark libaray in PYTHONPATH. Both PATH parts are necessary:

The path to the pyspark Python module itself, and

The path to the zipped library that that pyspark module relies on when imported

Notice below that the zipped library version is dynamically determined, so we do not hard-code it.

export PYTHONPATH=${SPARK_HOME}/python/:$(echo ${SPARK_HOME}/python/lib/py4j-*-src.zip):${PYTHONPATH}


问:
Why are Nullable<T> considered a value type?
Have you ever tried to use the Convert.ChangeType() method to convert a value to a Nullable<T> type? Awkwardly, it will throw an InvalidCastException saying "Null object cannot be converted to a value type".

Try running this on your immediate window: ?System.Convert.ChangeType(null, typeof(int?))

For some obscure reason, Nullables are considered value types. For example, typeof(int?).IsValueType returns true.

For me, since Nullable<T> accept null, it's a class type, not a value type. Does anyone know why it would implemented differently?

答:
I just saw this question in the "related questions" list at Why Nullable<T> is a struct? and I think my answer there applies here too. The whole point of Nullable<T> is to act like a value type in every regard except for the ability to take a null value.

The null of a null reference can be looked at in two ways. One is that it isn't referencing anything, another is that it has no meaningful value. These things are pretty much two different ways of saying the same thing, but they have different uses.

Nullable<T> gives us the ability to say "this has no meaningful value" and to that extent it can have the same semantics as a null reference, but it is not like a reference in any other way. When null it's nullity is purely that "no meaningful value" null - not "doesn't refer to anything" and when not null it is holding a value, not referring to it.

(Aaronaught argues that this means a Nullable can't really contain null, while I disagree because at the level at which it uses it can have a semantic null, his point is worth considering in that even when "null" a Nullable is different to a reference - really our disagreement is a matter of which level of abstraction we choose to use).


问:
How to get database value not related to the event in Cloud Functions for Firebase?
I have a firebase database and I am currently trying to use cloud functions to perform an operation when a value in my database changes. So far, it successfully triggers code to run when the value in my database changes. However, when the database value changes, I now need to check another value to determine it's status, and then perform an action after that. The problem is that I have ~0 experience with JS and I have no way of debugging my code other than deploying, changing the value in my database, and looking at the console log.

Is there any way to look up another value in the database and read it? How about look up a value and then set a value for it? Here is the code:

exports.determineCompletion =

```<code>functions.database.ref('/Jobs/{pushId}/client_job_complete')
    .onWrite(event => {

        const status = event.data.val();
        const other = functions.database.ref('/Jobs/' + event.params.pushId + '/other_job_complete');
        console.log('Status', status, other);

        if(status == true && **other.getValueSomehow** == true) {
            return **setAnotherValue**;
        }

    });
</code>```

This code partially works, it successfully gets the value associated with client_job_complete and stores it in status. But how do I get the other value?

Additionally, if anyone has any JS or firebase documentation that they think would help me, please share! I have read a bunch on firebase here : https://firebase.google.com/docs/functions/database-events but it only talks about events and is very brief

Thank you for your help!

答:
When writing a database trigger function, the event contains two properties that are references to the location of the data that changed:

```<code>event.data.ref
event.data.adminRef
</code>```

ref is limited to the permissions of the user who triggered the function.  adminRef has full access to the database.

Each of those Reference objects has a root property which gives you a reference to the root of your database.  You can use that reference to build a path to a reference in another part of your database, and read it with the once() method.

You can also use the Firebase admin SDK.

There are lots of code samples that you should probably look at as well.

Body:
I have a firebase database and I am currently trying to use cloud functions to perform an operation when a value in my database changes. So far, it successfully triggers code to run when the value in my database changes. However, when the database value changes, I now need to check another value to determine it's status, and then perform an action after that. The problem is that I have ~0 experience with JS and I have no way of debugging my code other than deploying, changing the value in my database, and looking at the console log.

Is there any way to look up another value in the database and read it? How about look up a value and then set a value for it? Here is the code:

exports.determineCompletion =

functions.database.ref('/Jobs/{pushId}/client_job_complete')
    .onWrite(event => {

        const status = event.data.val();
        const other = functions.database.ref('/Jobs/' + event.params.pushId + '/other_job_complete');
        console.log('Status', status, other);

        if(status == true && **other.getValueSomehow** == true) {
            return **setAnotherValue**;
        }

    });

This code partially works, it successfully gets the value associated with client_job_complete and stores it in status. But how do I get the other value?

Additionally, if anyone has any JS or firebase documentation that they think would help me, please share! I have read a bunch on firebase here : https://firebase.google.com/docs/functions/database-events but it only talks about events and is very brief

Thank you for your help!

Body:
When writing a database trigger function, the event contains two properties that are references to the location of the data that changed:

event.data.ref
event.data.adminRef

ref is limited to the permissions of the user who triggered the function.  adminRef has full access to the database.

Each of those Reference objects has a root property which gives you a reference to the root of your database.  You can use that reference to build a path to a reference in another part of your database, and read it with the once() method.

You can also use the Firebase admin SDK.

There are lots of code samples that you should probably look at as well.


问:
SQL how to filter out a specific row with conflicting where clause
This should be a simple problem but for some reason I can't get it to work. I've got a table like the following:

```<code>|Name|Attribute|
----------------
|Foo |     1   |
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |
|Yum |     1   |
|Yum |     2   |
|Yum |     3   |
</code>```

I want to filter it like the following

```<code>|Name|Attribute|
----------------
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |
</code>```

Note that I've removed all the "Yum" and removed a "Foo" only when Attribute = 1

Problem is that when I do something like this

```<code>SELECT *
FROM table
WHERE name in ('Foo', 'Bar')
AND (name != 'Foo' AND attribute != 1)
</code>```

I get this result

```<code>|Name|Attribute|
----------------
|Bar |     2   |
|Bar |     3   |
</code>```

I would have thought that the brackets group things together?

答:
I think in terms of or:

```<code>where (name = 'Bar') or (name = 'Foo' and attribute <> 1)
</code>```

Body:
This should be a simple problem but for some reason I can't get it to work. I've got a table like the following:

|Name|Attribute|
----------------
|Foo |     1   |
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |
|Yum |     1   |
|Yum |     2   |
|Yum |     3   |

I want to filter it like the following

|Name|Attribute|
----------------
|Foo |     2   |
|Foo |     3   |
|Bar |     1   |
|Bar |     2   |
|Bar |     3   |

Note that I've removed all the "Yum" and removed a "Foo" only when Attribute = 1

Problem is that when I do something like this

SELECT *
FROM table
WHERE name in ('Foo', 'Bar')
AND (name != 'Foo' AND attribute != 1)

I get this result

|Name|Attribute|
----------------
|Bar |     2   |
|Bar |     3   |

I would have thought that the brackets group things together?

Body:
I think in terms of or:

where (name = 'Bar') or (name = 'Foo' and attribute <> 1)


问:
Visualize MPU6050 using openGL
After getting accelerometer/gyroscope from MPU6050, I use this function:

```<code>void AHRSupdate(float gx, float gy, float gz, float ax, float ay, float az,float mx, float my,float mz,double * quad) {
float norm;
float hx, hy, hz, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
double* tempQuat = quad;

// auxiliary variables to reduce number of repeated operations
float q0q0 = q0*q0;
float q0q1 = q0*q1;
float q0q2 = q0*q2;
float q0q3 = q0*q3;
float q1q1 = q1*q1;
float q1q2 = q1*q2;
float q1q3 = q1*q3;
float q2q2 = q2*q2;
float q2q3 = q2*q3;
float q3q3 = q3*q3;

// normalise the measurements
norm = sqrt(ax*ax + ay*ay + az*az);
ax = ax / norm;
ay = ay / norm;
az = az / norm;
norm = sqrt(mx*mx + my*my + mz*mz);
mx = mx / norm;
my = my / norm;
mz = mz / norm;

// compute reference direction of flux
hx = 2*mx*(0.5 - q2q2 - q3q3) + 2*my*(q1q2 - q0q3) + 2*mz*(q1q3 + q0q2);
hy = 2*mx*(q1q2 + q0q3) + 2*my*(0.5 - q1q1 - q3q3) + 2*mz*(q2q3 - q0q1);
hz = 2*mx*(q1q3 - q0q2) + 2*my*(q2q3 + q0q1) + 2*mz*(0.5 - q1q1 - q2q2)
;
bx = sqrt((hx*hx) + (hy*hy));
bz = hz;

// estimated direction of gravity and flux (v and w)
vx = 2*(q1q3 - q0q2);
vy = 2*(q0q1 + q2q3);
vz = q0q0 - q1q1 - q2q2 + q3q3;
wx = 2*bx*(0.5 - q2q2 - q3q3) + 2*bz*(q1q3 - q0q2);
wy = 2*bx*(q1q2 - q0q3) + 2*bz*(q0q1 + q2q3);
wz = 2*bx*(q0q2 + q1q3) + 2*bz*(0.5 - q1q1 - q2q2);

// error is sum of cross product between reference direction of fields and direction measured by sensors
ex = (ay*vz - az*vy) + (my*wz - mz*wy);
ey = (az*vx - ax*vz) + (mz*wx - mx*wz);
ez = (ax*vy - ay*vx) + (mx*wy - my*wx);

// integral error scaled integral gain
exInt = exInt + ex*Ki;
eyInt = eyInt + ey*Ki;
ezInt = ezInt + ez*Ki;

// adjusted gyroscope measurements
gx = gx + Kp*ex + exInt;
gy = gy + Kp*ey + eyInt;
gz = gz + Kp*ez + ezInt;

// integrate quaternion rate and normalise
q0 = q0 + (-q1*gx - q2*gy - q3*gz)*halfT;
q1 = q1 + (q0*gx + q2*gz - q3*gy)*halfT;
q2 = q2 + (q0*gy - q1*gz + q3*gx)*halfT;
q3 = q3 + (q0*gz + q1*gy - q2*gx)*halfT;

// normalise quaternion
norm = sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);
q0 = q0 / norm;
q1 = q1 / norm;
q2 = q2 / norm;
q3 = q3 / norm;

*tempQuat++ = q0;
*tempQuat++ = q1;
*tempQuat++ = q2;
*tempQuat++ = q3;
}
</code>```

To get quaternion value q0 ,q1 , q3. Then I use this function:

```<code>void MPU6050_getYawPitchRoll(double * ypr,double *qu)
{
double gx, gy, gz;
double *tempQ = qu;

double q0,q1,q2,q3;
float sqw = q0*q0;
  float sqx = q1*q1;
  float sqy = q2*q2;
  float sqz = q3*q3;

q0= *tempQ++;
q1= *tempQ++;
q2= *tempQ++;
q3= *tempQ++;

gx = 2 * (q1 * q3 - q0 * q2);
gy = 2 * (q0 * q1 + q2 * q3);
gz = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3;
yaw = atan2(2* (q1 * q2 - q0 * q3), 2 * (q0 * q0 + q1 * q1) - 1) * 180 /   3.1416;  // YAW
pitch = atan(gx / sqrt(gy * gy + gz * gz)) * 180 / 3.1416;  // PITCH
roll = atan(gy / sqrt(gx * gx + gz * gz)) * 180 / 3.1416;   // ROLL

psi = atan2(2 * q1 * q2 - 2 * q0 * q3, 2 * q0*q0 + 2 * q1* q1 - 1)* 180 / 3.1416; // psi
theta = -asin(2 * q1 * q3 + 2 * q0 * q2)* 180 / 3.1416; // theta
phi = atan2(2 * q2 * q3 - 2 * q0 * q1, 2 * q0 * q0 + 2 * q3 * q3 - 1)* 180 / 3.1416; // phi
}
</code>```

To get yaw, pitch, roll, psi, theta and phi.

In PC, I use openGL to draw 3D object. How can I use yaw, pitch, roll, psi, theta and phi to control that 3D object (rotation, translation)? Is that right?

```<code>glRotatef(-Yaw, 0.0f, 1.0f, 0.0f);
glRotatef(-Pitch, 0.0f, 0.0f, 1.0f);
glRotatef(-Roll, 1.0f, 0.0f, 0.0f);
</code>```

答:
you doing it all the old way, why don't you use GLM ?
I did it this way in my project with cinder
I read _quat from MPU and arduino ...

```<code>vec4 axis = toAxisAngle(_quat);
// ...
rotate(axis[0], -axis[1], axis[3], axis[2]); // Note the orders and signs
</code>```

and toAxisAngle :

```<code>/**
 * Converts the quaternion into a float array consisting of: rotation angle
 * in radians, rotation axis x,y,z
 *
 * @return 4-element float array
 */
static const float EPS = 1.1920928955078125E-7f;
vec4  toAxisAngle(const quat& q) {
    vec4 res;
    float sa = (float) sqrt(1.0f - q.w * q.w);
    if (sa < EPS) {
        sa = 1.0f;
    } else {
        sa = 1.0f / sa;
    }
    res[0] = (float) acos(q.w) * 2.0f;
    res[1] = q.x * sa;
    res[2] = q.y * sa;
    res[3] = q.z * sa;
    return res;
}
</code>```

Title: Visualize MPU6050 using openGL

Body:
After getting accelerometer/gyroscope from MPU6050, I use this function:

void AHRSupdate(float gx, float gy, float gz, float ax, float ay, float az,float mx, float my,float mz,double * quad) {
float norm;
float hx, hy, hz, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
double* tempQuat = quad;

// auxiliary variables to reduce number of repeated operations
float q0q0 = q0*q0;
float q0q1 = q0*q1;
float q0q2 = q0*q2;
float q0q3 = q0*q3;
float q1q1 = q1*q1;
float q1q2 = q1*q2;
float q1q3 = q1*q3;
float q2q2 = q2*q2;
float q2q3 = q2*q3;
float q3q3 = q3*q3;

// normalise the measurements
norm = sqrt(ax*ax + ay*ay + az*az);
ax = ax / norm;
ay = ay / norm;
az = az / norm;
norm = sqrt(mx*mx + my*my + mz*mz);
mx = mx / norm;
my = my / norm;
mz = mz / norm;

// compute reference direction of flux
hx = 2*mx*(0.5 - q2q2 - q3q3) + 2*my*(q1q2 - q0q3) + 2*mz*(q1q3 + q0q2);
hy = 2*mx*(q1q2 + q0q3) + 2*my*(0.5 - q1q1 - q3q3) + 2*mz*(q2q3 - q0q1);
hz = 2*mx*(q1q3 - q0q2) + 2*my*(q2q3 + q0q1) + 2*mz*(0.5 - q1q1 - q2q2)
;
bx = sqrt((hx*hx) + (hy*hy));
bz = hz;

// estimated direction of gravity and flux (v and w)
vx = 2*(q1q3 - q0q2);
vy = 2*(q0q1 + q2q3);
vz = q0q0 - q1q1 - q2q2 + q3q3;
wx = 2*bx*(0.5 - q2q2 - q3q3) + 2*bz*(q1q3 - q0q2);
wy = 2*bx*(q1q2 - q0q3) + 2*bz*(q0q1 + q2q3);
wz = 2*bx*(q0q2 + q1q3) + 2*bz*(0.5 - q1q1 - q2q2);

// error is sum of cross product between reference direction of fields and direction measured by sensors
ex = (ay*vz - az*vy) + (my*wz - mz*wy);
ey = (az*vx - ax*vz) + (mz*wx - mx*wz);
ez = (ax*vy - ay*vx) + (mx*wy - my*wx);

// integral error scaled integral gain
exInt = exInt + ex*Ki;
eyInt = eyInt + ey*Ki;
ezInt = ezInt + ez*Ki;

// adjusted gyroscope measurements
gx = gx + Kp*ex + exInt;
gy = gy + Kp*ey + eyInt;
gz = gz + Kp*ez + ezInt;

// integrate quaternion rate and normalise
q0 = q0 + (-q1*gx - q2*gy - q3*gz)*halfT;
q1 = q1 + (q0*gx + q2*gz - q3*gy)*halfT;
q2 = q2 + (q0*gy - q1*gz + q3*gx)*halfT;
q3 = q3 + (q0*gz + q1*gy - q2*gx)*halfT;

// normalise quaternion
norm = sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);
q0 = q0 / norm;
q1 = q1 / norm;
q2 = q2 / norm;
q3 = q3 / norm;

*tempQuat++ = q0;
*tempQuat++ = q1;
*tempQuat++ = q2;
*tempQuat++ = q3;
}

To get quaternion value q0 ,q1 , q3. Then I use this function:

void MPU6050_getYawPitchRoll(double * ypr,double *qu)
{
double gx, gy, gz;
double *tempQ = qu;

double q0,q1,q2,q3;
float sqw = q0*q0;
  float sqx = q1*q1;
  float sqy = q2*q2;
  float sqz = q3*q3;

q0= *tempQ++;
q1= *tempQ++;
q2= *tempQ++;
q3= *tempQ++;

gx = 2 * (q1 * q3 - q0 * q2);
gy = 2 * (q0 * q1 + q2 * q3);
gz = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3;
yaw = atan2(2* (q1 * q2 - q0 * q3), 2 * (q0 * q0 + q1 * q1) - 1) * 180 /   3.1416;  // YAW
pitch = atan(gx / sqrt(gy * gy + gz * gz)) * 180 / 3.1416;  // PITCH
roll = atan(gy / sqrt(gx * gx + gz * gz)) * 180 / 3.1416;   // ROLL

psi = atan2(2 * q1 * q2 - 2 * q0 * q3, 2 * q0*q0 + 2 * q1* q1 - 1)* 180 / 3.1416; // psi
theta = -asin(2 * q1 * q3 + 2 * q0 * q2)* 180 / 3.1416; // theta
phi = atan2(2 * q2 * q3 - 2 * q0 * q1, 2 * q0 * q0 + 2 * q3 * q3 - 1)* 180 / 3.1416; // phi
}

To get yaw, pitch, roll, psi, theta and phi.

In PC, I use openGL to draw 3D object. How can I use yaw, pitch, roll, psi, theta and phi to control that 3D object (rotation, translation)? Is that right?

glRotatef(-Yaw, 0.0f, 1.0f, 0.0f);
glRotatef(-Pitch, 0.0f, 0.0f, 1.0f);
glRotatef(-Roll, 1.0f, 0.0f, 0.0f);

Body:
you doing it all the old way, why don't you use GLM ?
I did it this way in my project with cinder
I read _quat from MPU and arduino ...

vec4 axis = toAxisAngle(_quat);
// ...
rotate(axis[0], -axis[1], axis[3], axis[2]); // Note the orders and signs

and toAxisAngle :

/**
 * Converts the quaternion into a float array consisting of: rotation angle
 * in radians, rotation axis x,y,z
 *
 * @return 4-element float array
 */
static const float EPS = 1.1920928955078125E-7f;
vec4  toAxisAngle(const quat& q) {
    vec4 res;
    float sa = (float) sqrt(1.0f - q.w * q.w);
    if (sa < EPS) {
        sa = 1.0f;
    } else {
        sa = 1.0f / sa;
    }
    res[0] = (float) acos(q.w) * 2.0f;
    res[1] = q.x * sa;
    res[2] = q.y * sa;
    res[3] = q.z * sa;
    return res;
}


问:
Force an error in SPSS Syntax when condition is met
I'm doing a check in my syntax to see if all of the string fields have values. This looks something like this:

```<code>IF(STRING ~= "").
</code>```

Now, instead of filtering or computing a variable, I would like to force an error if there are fields with no values. I'm running a lot of these scripts and I don't want to keep checking the datasets manually. Instead, I just want to receive an error and stop execution.

Is this possible in SPSS Syntax?

答:
First, you can efficiently count the blanks in your string variables with COUNT:

COUNT blanks = A B C(" ").

where you list the string variables to be checked.  So if the sum of blanks is > 0, you want the error to be raised.  First aggregate to a new dataset and activate it:

DATASET DECLARE sum.

AGGREGATE /OUTFILE=sum /count=sum(blanks).

The hard part is getting the job to stop when the blank count is greater than 0.  You can put the job in a syntax file and run it using INSERT with ERROR=STOP, or you can run it as a production job via Utilities or via the -production flag on the command line of an spj (production facility) job.

Here is how to generate an error on a condition.

```<code>DATASET ACTIVATE sum.
begin program.
import spssdata

curs = spssdata.Spssdata()
count = curs.fetchone()
curs.CClose()

if count[0] > 0:
    spss.Submit("blank values exist")
end program.
DATASET CLOSE sum.
</code>```

This code reads the aggregate file and if the blank count is positive issues an invalid command causing an error, which stops the job.

Body:
I'm doing a check in my syntax to see if all of the string fields have values. This looks something like this:

IF(STRING ~= "").

Now, instead of filtering or computing a variable, I would like to force an error if there are fields with no values. I'm running a lot of these scripts and I don't want to keep checking the datasets manually. Instead, I just want to receive an error and stop execution.

Is this possible in SPSS Syntax?

Body:
First, you can efficiently count the blanks in your string variables with COUNT:

COUNT blanks = A B C(" ").

where you list the string variables to be checked.  So if the sum of blanks is > 0, you want the error to be raised.  First aggregate to a new dataset and activate it:

DATASET DECLARE sum.

AGGREGATE /OUTFILE=sum /count=sum(blanks).

The hard part is getting the job to stop when the blank count is greater than 0.  You can put the job in a syntax file and run it using INSERT with ERROR=STOP, or you can run it as a production job via Utilities or via the -production flag on the command line of an spj (production facility) job.

Here is how to generate an error on a condition.

DATASET ACTIVATE sum.
begin program.
import spssdata

curs = spssdata.Spssdata()
count = curs.fetchone()
curs.CClose()

if count[0] > 0:
    spss.Submit("blank values exist")
end program.
DATASET CLOSE sum.

This code reads the aggregate file and if the blank count is positive issues an invalid command causing an error, which stops the job.


问:
ava js test GET returns code 204 POSTMAN GET returns 200
I made some REST API endpoints using koa js 2 and postgres database.

I have a setup/teardown procedure which creates/drops a postgres database catalog (e.g. test_db) before running any tests. (I use npm script 'pretest' hook to do db setup and 'posttest' to do db teardown).

When I run the ava js tests, I have:

2 POST tests (insert 2 rows) - these both PASS

1 GET test (e.g. get /users/1) - FAIL: response code is 204 instead of 200

1 PUT test (e.g. POST /users/:id) - FAIL: response code is 204 instead of 200 .

I can run these tests against my dev config and they all pass

I don't understand how POST can succeed (a row was inserted to table) then the GET for the row that was just inserted returns 204 (no data).

Currently the test database teardown doesn't happen, so I can peek inside test database and verify that the POSTS did succeed, the rows were inserted with the correct ID values (as expected). (e.g. I can see a user with id==1 and a user with id==2) so calling the endpoint /users/1 or /users/2 should succeed when the test is executed.

If I launch my server using the test database, and run POSTMAN against these endpoints and the test database, everything works (e.g. GET /users/1 returns correctly and so does GET /users/2) I get json returned and a code of 200 instead of 204.

I don't understand why my ava tests would be getting code 204 when same call to POSTMAN returns code 200 and valid json response.

Any ideas on what could cause this?

答:
found the solution - I did not seed database with seed data, and because of parallel nature of ava js tests, they were not occurring in sequential order.

For example: I had 2 POSTs occurring, then a GET (from top to bottom)

so there are 2 solutions to this:

seed database with data as part of pre-test setup procedure (DML script)

OR

put a .before the 1st POST test to force POST to appear before GET

test.before('POST user (CREATE)', async t => {

instead of

test('POST user (CREATE)', async t => {

and then

test('GET single user', async t => {  t.plan(3)

const res = await request(makeApp())        .get('/users/1')

then you know your GET :id will succeed (because POST will be forced to occur prior to GET /users/:id (or GET /users/1)

As ava js documentation says:

"Having tests run concurrently forces you to write atomic tests, meaning tests don't depend on global state or the state of other tests, which is a great thing!"

Hopefully this is helpful to a future user!


问:
easiest way to generate base 3 numbers
I am trying to solve a mathematical problem programatically. Having a way to generate base 3 numbers would make it very easy to solve the problem. Do you know of any language that has in-built support for working with numbers of non-trivial base? It would be equally great if you could point me to some tool that can help me generate a sequence of base 3 numbers</p>

答: Numbers don't intrinsically have a base. Representations of numbers do. Typically, you express the concept of "base 3 representation of a number" by using a string consisting of only the '0', '1' and '2' characters (and possibly a decimal point or negative sign or whatever).

Title: easiest way to generate base 3 numbers


问:
How to do change the value in the class with the help of method in C#

I want to call an object from a different class and change its properties.

I want to get into this object and make changes.

But when I type the dot, the properties do not open.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SINIF3 sınıf3 = new SINIF3();

//I want to get into this object and make changes.
//But when I type the dot, the properties do not open.
//For example
//sınıf3.gonder(1).number=2;

            Console.ReadKey();
        }
    }
    class DEGER
    {
        public int number = 1;
    }
    class SINIF3
    {
        public object gonder(int a)
        {
            DEGER objem = new DEGER();
            DEGER objem2 = new DEGER();
            if (a == 1)
                return objem;
            else return objem2;
        }
    }
}
</code>```

答: Change the return type of the gonder method from object to DEGER.  Of course you're not assigning the result of the gonder method to a variable, so the new object which you change the number field in will be thrown away.</p>

Body:
I want to call an object from a different class and change its properties.

I want to get into this object and make changes.

But when I type the dot, the properties do not open.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SINIF3 sınıf3 = new SINIF3();

//I want to get into this object and make changes.
//But when I type the dot, the properties do not open.
//For example
//sınıf3.gonder(1).number=2;

            Console.ReadKey();
        }
    }
    class DEGER
    {
        public int number = 1;
    }
    class SINIF3
    {
        public object gonder(int a)
        {
            DEGER objem = new DEGER();
            DEGER objem2 = new DEGER();
            if (a == 1)
                return objem;
            else return objem2;
        }
    }
}


问:
How can I assign a placeholder datatype to custom classes dictionary in C#?
So I'm noticing that I am using a lot of the same code over and over and over again... So I want to make a universal class where possible, so I don't have the same function redefined in multiple places...

As an example I wanted to try and do this with a SortedDictionary. To do this, I need to be able to assign the data types of the dictionary when I create the custom SortedDictionary.

Is this possible? Something like this:

```<code>using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary
   {
      private SortedDictionary<CustomDataType, CustomDataType> m_dictionary;
   }
}

// Create custom dictionary...
CSortedDictionary<int, List<string>> custom_dictionary
    = new CSortedDictionary<int, List<string>>();
</code>```

答:
Just inherit your class from SortedDictionary with specific generic parameters.

```<code>public class CSortedDictionary : SortedDictionary<int, List<string>>
{
}
</code>```

And use CSortedDictionary - it will have integer keys and values of List<string> type:

```<code>CSortedDictionary custom_dictionary = new CSortedDictionary();
custom_dictionary.Add(42, new List<string>());
custom_dictionary[42].Add("Foo");
</code>```

Body:
So I'm noticing that I am using a lot of the same code over and over and over again... So I want to make a universal class where possible, so I don't have the same function redefined in multiple places...

As an example I wanted to try and do this with a SortedDictionary. To do this, I need to be able to assign the data types of the dictionary when I create the custom SortedDictionary.

Is this possible? Something like this:

using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary
   {
      private SortedDictionary<CustomDataType, CustomDataType> m_dictionary;
   }
}

// Create custom dictionary...
CSortedDictionary<int, List<string>> custom_dictionary
    = new CSortedDictionary<int, List<string>>();

Body:
Just inherit your class from SortedDictionary with specific generic parameters.

public class CSortedDictionary : SortedDictionary<int, List<string>>
{
}

And use CSortedDictionary - it will have integer keys and values of List<string> type:

CSortedDictionary custom_dictionary = new CSortedDictionary();
custom_dictionary.Add(42, new List<string>());
custom_dictionary[42].Add("Foo");


问:
Echo doesn't print what I want on the browser
Simple, I had a html that echo from php (saven in .php) but not even a simpe code as

```<code>    <?php echo"ggg"; ?>
</code>```

works, I tried with xammp and Wamp either chrome and firefox but doesn't work.
What can I do?

edit: already solved, I forgot to run it from localhost, thank you all.

答:
Any of these (or more) could be your answer why it is not working

Is there actually PHP running on your computer? Check it with <?php echo phpinfo(); ?>

Are you accesing the file through your browser doing something like http://localhost/myfile.php

If it is on a remote server, is there PHP installed?
https://stackoverflow.com/a/43129028/2151290

Put your file inside c:/xampp/htdocs for xampp or c:/wamp/www for wamp
// Note that drive name may vary depending where you install c: or d:

Body:
Simple, I had a html that echo from php (saven in .php) but not even a simpe code as

    <?php echo"ggg"; ?>

works, I tried with xammp and Wamp either chrome and firefox but doesn't work.
What can I do?

edit: already solved, I forgot to run it from localhost, thank you all.