问:
How to check if a string contains only digits in Java
In Java for String class there is a method called matches, how to use this method to check if my string is having only digits using regular expression. I tried with below examples, but both of them returned me false as result.

```<code>String regex = "[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
</code>```

```<code>String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
</code>```

答:
According to Oracle's Java Documentation:</p>

```<code>private static final Pattern NUMBER_PATTERN = Pattern.compile(
        "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
        "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
        "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
        "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}
</code>```

Body:
In Java for String class there is a method called matches, how to use this method to check if my string is having only digits using regular expression. I tried with below examples, but both of them returned me false as result.

String regex = "[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));

String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));

Body:
According to Oracle's Java Documentation:

private static final Pattern NUMBER_PATTERN = Pattern.compile(
        "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
        "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
        "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
        "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}


来源: stackexchange

问:
ReactJS How to toggle elements to hide or show
I am very new to React and the ES6 syntax I have a chat widget that i want to toggle to show and hide as i click the header,and I have already implemented an onClick handler, but in terms of the logic I am having trouble finding a similar implementation online. this is my code:</p>

```<code>import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("Hide or unhide chat body")
  }

  render() {
    return (
      <div className={chat.container}>
        <div onClick={this.handleClick.bind(this)}
             className={chat.header}>
          <span className={chat.name}>Idol</span>
        </div>
        <div className={chat.body}>
          This is the Body of the chat
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);
</code>```

答:
It could look like this:

```<code>class ChatWidget extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showChat: true
    };
  }
  handleClick(event) {
    this.setState({
      showChat: !this.state.showChat
    });
  }

  render() {
    return (
      <div className={chat.container}>
        <div onClick={this.handleClick.bind(this)}
             className={chat.header}>
          <span className={chat.name}>Idol</span>
        </div>
        {this.state.showChat &&
         (<div className={chat.body}>
          This is the Body of the chat
         </div>)
        }
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);
</code>```

But there are different approaches for conditional rendering.
See documentation here: https://facebook.github.io/react/docs/conditional-rendering.html

ContentLicense: CC BY-SA 3.0

Body:
I am very new to React and the ES6 syntax I have a chat widget that i want to toggle to show and hide as i click the header,and I have already implemented an onClick handler, but in terms of the logic I am having trouble finding a similar implementation online. this is my code:

import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("Hide or unhide chat body")
  }

  render() {
    return (

          Idol

          This is the Body of the chat

    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);

Body:
It could look like this:

class ChatWidget extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showChat: true
    };
  }
  handleClick(event) {
    this.setState({
      showChat: !this.state.showChat
    });
  }

  render() {
    return (
      <div className={chat.container}>
        <div onClick={this.handleClick.bind(this)}
             className={chat.header}>
          <span className={chat.name}>Idol</span>
        </div>
        {this.state.showChat &&
         (<div className={chat.body}>
          This is the Body of the chat
         </div>)
        }
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);

But there are different approaches for conditional rendering.
See documentation here: https://facebook.github.io/react/docs/conditional-rendering.html


问:
Command Line Copy or Delete
I used robocopy to copy just pdf's from an external hard drive and place them on our server.

source destination *.pdf

It copied over all the folders and subfolders even if there wasn't a .pdf file in the folder. Can someone help me either....

a) Delete empty folders or b) Copy over only folders and subfolders that have .pdf's in them?

Thank you!

答:
Use the following command for copy over only folders and subfolders that have an extension in them in this case ".pdf"

```<code>ROBOCOPY sourcePath destPath *.pdf /MIR /S
</code>```

This will only all files with that extensions and folders that have files with that extension and does not include empty folder.

Title: Command Line Copy or Delete

Body:
Use the following command for copy over only folders and subfolders that have an extension in them in this case ".pdf"

ROBOCOPY sourcePath destPath *.pdf /MIR /S

This will only all files with that extensions and folders that have files with that extension and does not include empty folder.


问:
WCF WebGetAttribute vs WebInvokeAttribute
Is the WebGetAttribute just syntactic sugar for the WebInvokeAttribute with Method = "GET"?
Or is there an underlying difference?</p>

答: Well, there is a difference in handling the request. Generally, use WebGet for GET. See my answer for details.

ContentLicense: CC BY-SA 2.5


问:
Can I execute Two different Classes from same jar file?
I have a project where in one package I have made Server and in Second Package I made Client. It is working fine. I want to create a Jar file. Is it possible to run Client and Server Separately from same jar file?

I have used jar file where there is only one main and when I run jar file, it automatically runs that class. Now here I will be having 2 executable classes. I want to pack them in only one jar and then want to run both from that same jar file. Is it possible? Any Suggestions, links will be of great help.

答:
The short answer is, YES!

The longer answer is that you can specify the class in your command line as well as putting the .jar in the classpath.

Assume two classes

```<code>A.class
B.class
</code>```

jar them into a .jar file

```<code>jar cvf AB.jar A.class B.class
</code>```

run either of them

```<code>java -classpath AB.jar A
java -classpath AB.jar B
</code>```

Body:
The short answer is, YES!

The longer answer is that you can specify the class in your command line as well as putting the .jar in the classpath.

Assume two classes

A.class
B.class

jar them into a .jar file

jar cvf AB.jar A.class B.class

run either of them

java -classpath AB.jar A
java -classpath AB.jar B


问:
Best way to construct a binary tree from a list in python
Assuming each node has self.left, self.right and self.data, whats the best way to construct a binary tree, not a binary search tree (BST), from a list where the numbers are given per level.  Where the first number is level 1, next 2 are level 2, next 4 are level 3, and so on.  For example

```<code>input: [3,5,2,1,4,6,7,8,9,10,11,12,13,14]
</code>```

constructs a tree:

```<code>          3
       /     \
     5         2
    /\         /\
   1  4       6   7
  /\  /\     /\   /\
 8 9 10 11 12 13 14
</code>```

One solution is:

```<code>for node at index i,
left child index = 2i+1
right child index = 2i+2
</code>```

Wondering if there are other possible ways

答:
Here is one way to implement your solution: create a list of tree nodes, each with index position corresponding to the original data list. Then, we can fix up the left- and right links.

```<code>import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

class Tree(object):
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def __repr__(self):
        left = None if self.left is None else self.left.data
        right = None if self.right is None else self.right.data
        return '(D:{}, L:{}, R:{})'.format(self.data, left, right)

def build_tree_breadth_first(sequence):
    # Create a list of trees
    forest = [Tree(x) for x in sequence]

    # Fix up the left- and right links
    count = len(forest)
    for index, tree in enumerate(forest):
        left_index = 2 * index + 1
        if left_index < count:
            tree.left = forest[left_index]

        right_index = 2 * index + 2
        if right_index < count:
            tree.right = forest[right_index]

    for index, tree in enumerate(forest):
        logger.debug('[{}]: {}'.format(index, tree))
    return forest[0]  # root

def main():
    data = [3, 5, 2, 1, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14]
    root = build_tree_breadth_first(data)
    print 'Root is:', root

if __name__ == '__main__':
    main()
</code>```

Output:

```<code>DEBUG:__main__:[0]: (D:3, L:5, R:2)
DEBUG:__main__:[1]: (D:5, L:1, R:4)
DEBUG:__main__:[2]: (D:2, L:6, R:7)
DEBUG:__main__:[3]: (D:1, L:8, R:9)
DEBUG:__main__:[4]: (D:4, L:10, R:11)
DEBUG:__main__:[5]: (D:6, L:12, R:13)
DEBUG:__main__:[6]: (D:7, L:14, R:None)
DEBUG:__main__:[7]: (D:8, L:None, R:None)
DEBUG:__main__:[8]: (D:9, L:None, R:None)
DEBUG:__main__:[9]: (D:10, L:None, R:None)
DEBUG:__main__:[10]: (D:11, L:None, R:None)
DEBUG:__main__:[11]: (D:12, L:None, R:None)
DEBUG:__main__:[12]: (D:13, L:None, R:None)
DEBUG:__main__:[13]: (D:14, L:None, R:None)
Root is: (D:3, L:5, R:2)
</code>```

Body:
Assuming each node has self.left, self.right and self.data, whats the best way to construct a binary tree, not a binary search tree (BST), from a list where the numbers are given per level.  Where the first number is level 1, next 2 are level 2, next 4 are level 3, and so on.  For example

input: [3,5,2,1,4,6,7,8,9,10,11,12,13,14]

constructs a tree:

          3
       /     \
     5         2
    /\         /\
   1  4       6   7
  /\  /\     /\   /\
 8 9 10 11 12 13 14

One solution is:

for node at index i,
left child index = 2i+1
right child index = 2i+2

Wondering if there are other possible ways

Body:
Here is one way to implement your solution: create a list of tree nodes, each with index position corresponding to the original data list. Then, we can fix up the left- and right links.

import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

class Tree(object):
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def __repr__(self):
        left = None if self.left is None else self.left.data
        right = None if self.right is None else self.right.data
        return '(D:{}, L:{}, R:{})'.format(self.data, left, right)

def build_tree_breadth_first(sequence):
    # Create a list of trees
    forest = [Tree(x) for x in sequence]

    # Fix up the left- and right links
    count = len(forest)
    for index, tree in enumerate(forest):
        left_index = 2 * index + 1
        if left_index < count:
            tree.left = forest[left_index]

        right_index = 2 * index + 2
        if right_index < count:
            tree.right = forest[right_index]

    for index, tree in enumerate(forest):
        logger.debug('[{}]: {}'.format(index, tree))
    return forest[0]  # root

def main():
    data = [3, 5, 2, 1, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14]
    root = build_tree_breadth_first(data)
    print 'Root is:', root

if __name__ == '__main__':
    main()

Output:

DEBUG:__main__:[0]: (D:3, L:5, R:2)
DEBUG:__main__:[1]: (D:5, L:1, R:4)
DEBUG:__main__:[2]: (D:2, L:6, R:7)
DEBUG:__main__:[3]: (D:1, L:8, R:9)
DEBUG:__main__:[4]: (D:4, L:10, R:11)
DEBUG:__main__:[5]: (D:6, L:12, R:13)
DEBUG:__main__:[6]: (D:7, L:14, R:None)
DEBUG:__main__:[7]: (D:8, L:None, R:None)
DEBUG:__main__:[8]: (D:9, L:None, R:None)
DEBUG:__main__:[9]: (D:10, L:None, R:None)
DEBUG:__main__:[10]: (D:11, L:None, R:None)
DEBUG:__main__:[11]: (D:12, L:None, R:None)
DEBUG:__main__:[12]: (D:13, L:None, R:None)
DEBUG:__main__:[13]: (D:14, L:None, R:None)
Root is: (D:3, L:5, R:2)


问:
How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)
```<code>DECLARE @day CHAR(2)

SET @day = DATEPART(DAY, GETDATE())

PRINT @day
</code>```

If today was the 9th of December, the above would print "9".

I want to print "09". How do I go about doing this?

答:
Leading 0 day</p>

```<code>SELECT FORMAT(GetDate(), 'dd')
</code>```

Body:
DECLARE @day CHAR(2)

SET @day = DATEPART(DAY, GETDATE())

PRINT @day

If today was the 9th of December, the above would print "9".

I want to print "09". How do I go about doing this?

Body:
Leading 0 day

SELECT FORMAT(GetDate(), 'dd')


问:
Change selection populating undesired results
I have two inputs. I am unsure what I am doing wrong, but I am simply trying to display the div associated with the input selection.

The issue I am having now is that if an input is selected, the console shows that both inputs were selected. Also, the title .pg-selection-title is not showing the correct data.

Why is my change selection now displaying the correct data?

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

 $('.calendar-check').on('change', function () {
  if ($('#cal-2year:checked')) {
    $('#prev-2year').fadeBoolToggle($('#cal-2year:checked').length == 1);
    console.log('A selected');
    $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard:checked')) {
    $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard:checked').length == 1);
    console.log('B selected');
    $('.pg-selection-title').html('B Selected');
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cal-theme-wrap {
  display: none;
}</code>```

<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

    A

    B

```

答:
The problem is that even a jQuery selection that finds no results still returns an object.  So you can't just check for existence-- you have to check the length property to make sure it actually found something.

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

 $('.calendar-check').on('change', function () {
  if ($('#cal-2year:checked').length > 0) {
    $('#prev-2year').fadeBoolToggle($('#cal-2year:checked').length == 1);
    console.log('A selected');
    $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard:checked').length > 0) {
    $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard:checked').length == 1);
    console.log('B selected');
    $('.pg-selection-title').html('B Selected');
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cal-theme-wrap {
  display: none;
}</code>```

<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

    A

    B

```

Body:
I have two inputs. I am unsure what I am doing wrong, but I am simply trying to display the div associated with the input selection.

The issue I am having now is that if an input is selected, the console shows that both inputs were selected. Also, the title .pg-selection-title is not showing the correct data.

Why is my change selection now displaying the correct data?

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

 $('.calendar-check').on('change', function () {
  if ($('#cal-2year:checked')) {
    $('#prev-2year').fadeBoolToggle($('#cal-2year:checked').length == 1);
    console.log('A selected');
    $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard:checked')) {
    $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard:checked').length == 1);
    console.log('B selected');
    $('.pg-selection-title').html('B Selected');
  };
});

.cal-theme-wrap {
  display: none;
}

<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

    A

    B

Body:
The problem is that even a jQuery selection that finds no results still returns an object.  So you can't just check for existence-- you have to check the length property to make sure it actually found something.

jQuery.fn.fadeBoolToggle = function(bool) {
  return bool ? this.fadeIn(400) : this.fadeOut(400);
}

 $('.calendar-check').on('change', function () {
  if ($('#cal-2year:checked').length > 0) {
    $('#prev-2year').fadeBoolToggle($('#cal-2year:checked').length == 1);
    console.log('A selected');
    $('.pg-selection-title').html('A selected');
  };
  if ($('#cal-whiteboard:checked').length > 0) {
    $('#prev-whiteboard').fadeBoolToggle($('#cal-whiteboard:checked').length == 1);
    console.log('B selected');
    $('.pg-selection-title').html('B Selected');
  };
});

.cal-theme-wrap {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="calendar-check" id="cal-2year">
<input type="checkbox" class="calendar-check" id="cal-whiteboard">

<div id="prev-2year" class="cal-theme-wrap">
  <h4 class="pg-selection-title"></h4>
  <p id="calender-preview-choice"></p>
  <div id="calendar-select">
    A
  </div>
</div>
<div id="prev-whiteboard" class="cal-theme-wrap">
  <h4 class="pg-selection-title"></h4>
  <p id="calender-preview-choice"></p>
  <div id="calendar-select">
    B
  </div>
</div>


问:
OxyPlot sum series
I have an Oxyplot chart with two LineSeries and I would like to add a new LineSeries which is sum of the two original LineSeries.

How can I create the Sum LineSeries?

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        var myModel = new PlotModel { Title = "Example 1" };
        myModel.Series.Add(new FunctionSeries(function1, 0, 100, 0.1, "a*1"));
        myModel.Series.Add(new FunctionSeries(function2, 0, 100, 0.1, "b*2"));

        this.plotView1.Model = myModel;
    }

    public double function1(double a)
    {
        double result = 0;
        result = a * 1;
        return result;
    }

    public double function2(double b)
    {
        double result = 0;
        result = b * 2;
        return result;
    }
}
</code>```

答:
Well, you just need to create another function:

```<code>public double function3(double b)
{
   return function1(b) + function2(b);
}
</code>```

and then

```<code>myModel.Series.Add(new FunctionSeries(function3, 0, 100, 0.1, "a+b*2"));
</code>```

Title: OxyPlot sum series

Body:
I have an Oxyplot chart with two LineSeries and I would like to add a new LineSeries which is sum of the two original LineSeries.

How can I create the Sum LineSeries?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        var myModel = new PlotModel { Title = "Example 1" };
        myModel.Series.Add(new FunctionSeries(function1, 0, 100, 0.1, "a*1"));
        myModel.Series.Add(new FunctionSeries(function2, 0, 100, 0.1, "b*2"));

        this.plotView1.Model = myModel;
    }

    public double function1(double a)
    {
        double result = 0;
        result = a * 1;
        return result;
    }

    public double function2(double b)
    {
        double result = 0;
        result = b * 2;
        return result;
    }
}

Body:
Well, you just need to create another function:

public double function3(double b)
{
   return function1(b) + function2(b);
}

and then

myModel.Series.Add(new FunctionSeries(function3, 0, 100, 0.1, "a+b*2"));


问:
Extract values from a dataframe according to identifiers of a list of list
I have a to extract values in a data frame and to assign them to identifiers of a list of list. Example:

Inupt1: BR is my list of lists that looks as follow

```<code>$BR_1
[1] "id5"  "id6"  "id7"  "id8"  "id9"  "id10"

$BR_2
[1] "id13" "id14" "id15" "id16" "id17" "id18" "id19"
</code>```

Input2: DF is my data frame that looks like this:

```<code>Ids      Value
id1      0
id2      0
id3      0
id4      0
id5      1
id6      1
id7      1
id8      1
id9      2
id10     2
id11     0
id12     0
id13     1
id14     2
id15     3
id16     3
id17     3
id18     2
id19     1
id20     0
</code>```

Desired Output:

```<code>BR_1 (1,1,1,1,2,2)  BR_2 (1,2,3,3,3,2,1)
</code>```

Then from these output i need to take only those that do not have the maximum score of 3 (then only BR_1).

Sorry if I am a bit not correct with the terminology. Any idea is very appreciated.

答:
I agree with Sotos' idea using lapply function.

You can create a subset with all values lower than 3:

```<code>newDF = subset(DF, Value <3)
lapply(BR, function(x) newDF[match(x, newDF$Ids),"Value"])
</code>```

Or you can modify your result list:

```<code>raw = lapply(BR, function(x) newDF[match(x, newDF$Ids),"Value"])
result = raw[sapply(raw, max) < 3]
</code>```

Body:
I have a to extract values in a data frame and to assign them to identifiers of a list of list. Example:

Inupt1: BR is my list of lists that looks as follow

$BR_1
[1] "id5"  "id6"  "id7"  "id8"  "id9"  "id10"

$BR_2
[1] "id13" "id14" "id15" "id16" "id17" "id18" "id19"

Input2: DF is my data frame that looks like this:

Ids      Value
id1      0
id2      0
id3      0
id4      0
id5      1
id6      1
id7      1
id8      1
id9      2
id10     2
id11     0
id12     0
id13     1
id14     2
id15     3
id16     3
id17     3
id18     2
id19     1
id20     0

Desired Output:

BR_1 (1,1,1,1,2,2)  BR_2 (1,2,3,3,3,2,1)

Then from these output i need to take only those that do not have the maximum score of 3 (then only BR_1).

Sorry if I am a bit not correct with the terminology. Any idea is very appreciated.

Body:
I agree with Sotos' idea using lapply function.

You can create a subset with all values lower than 3:

newDF = subset(DF, Value <3)
lapply(BR, function(x) newDF[match(x, newDF$Ids),"Value"])

Or you can modify your result list:

raw = lapply(BR, function(x) newDF[match(x, newDF$Ids),"Value"])
result = raw[sapply(raw, max) < 3]


问:
ASP.Net 4.5 - Web Method Does Not Get Called From JQuery
I have set break points in the C# code and the web method is not invoked. I should see four rows returned from the database.

I do not get any errors - the only thing I see in the console is an error on the the length (in the javascript for loop ie i < data.d.length).

Relevant Code

TestApp.aspx.cs

```<code>    namespace WebApplication1
{
    public class User
    {
        public int?   TestID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

    public partial class TestApp : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static User[] Get()
        {
            try
            {
                List<User> details = FetchData("sp_LoadData", null);
                return details.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
</code>```

TestApp.aspx

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestApp.aspx.cs" Inherits="WebApplication1.TestApp" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
    <script src="TestApp.js"></script>
</head>
<body>
    <form id="form1">

                        <table id="example" class="display" cellspacing="1" width="100%" border="1">
                            <thead style="border: solid thin;">
                                <tr>
                                    <th>First name</th>
                                    <th>Last name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Delete</th>
                                </tr>
                            </thead>
                        </table>
</code>```

TestApp.js

```<code>$(document).ready(function () {
    BindGrid();

function BindGrid() {
    var t = $('#example').DataTable();
    t.rows().remove().draw();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestApp.aspx/Get",
        data: "{}",
        dataType: "json",

        success: function (data) {
            for (var i = 0; i < data.d.length; i++) {
                //debugger;
                t.row.add([
                            '<a class="table-edit" onclick="showRecord(' + data.d[i].TestID + ');">' + data.d[i].FirstName + '</a>',
                            data.d[i].LastName,
                            data.d[i].Email,
                            data.d[i].Phone,
                            '<button type="button" onclick="deleteRecord(' + data.d[i].TestID + ');">Delete</button>'
                ]).draw(false);
            }
        },
        error: function (result) {
            debugger;
            alert("Error");
        }
    });
};
</code>```

答:
Use

```<code>[ScriptMethod]
</code>```

Below [WebMethod]

Body:
I have set break points in the C# code and the web method is not invoked. I should see four rows returned from the database.

I do not get any errors - the only thing I see in the console is an error on the the length (in the javascript for loop ie i < data.d.length).

Relevant Code

TestApp.aspx.cs

    namespace WebApplication1
{
    public class User
    {
        public int?   TestID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

    public partial class TestApp : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static User[] Get()
        {
            try
            {
                List<User> details = FetchData("sp_LoadData", null);
                return details.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

TestApp.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestApp.aspx.cs" Inherits="WebApplication1.TestApp" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1">

                                    First name
                                    Last name
                                    Email
                                    Phone
                                    Delete

TestApp.js

$(document).ready(function () {
    BindGrid();

function BindGrid() {
    var t = $('#example').DataTable();
    t.rows().remove().draw();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestApp.aspx/Get",
        data: "{}",
        dataType: "json",

        success: function (data) {
            for (var i = 0; i < data.d.length; i++) {
                //debugger;
                t.row.add([
                            '' + data.d[i].FirstName + '',
                            data.d[i].LastName,
                            data.d[i].Email,
                            data.d[i].Phone,
                            '<button type="button" onclick="deleteRecord(' + data.d[i].TestID + ');">Delete</button>'
                ]).draw(false);
            }
        },
        error: function (result) {
            debugger;
            alert("Error");
        }
    });
};

Body:
Use

[ScriptMethod]

Below [WebMethod]


问:
Simplest SPARQL implementation for educational purposes?
I'd like to learn more about RDF/SPARQL implementation internals, but most of the frameworks are (necessarily) somewhat complicated by real-world performance and implementation consideratins.  I am curious if there is a "reference" implementation that would be suitable as a low-level teaching tool? What is the RDF/SPARQL implementation that is the smallest/cleanest from a code standpoint?</p>

答:
Dave Beckett's Redland is a great way to start.

Features:

Redland is a set of free software C libraries that provide support for the Resource Description Framework (RDF).

```<code>* Modular, object based libraries and APIs for manipulating the RDF graph, triples, URIs and Literals.
* Storage for graphs in memory and persistently with Sleepycat/Berkeley DB, MySQL 3-5, PostgreSQL, AKT Triplestore, SQLite, files or URIs.
* Support for multiple syntaxes for reading and writing RDF as RDF/XML, N-Triples and Turtle Terse RDF Triple Language, RSS and Atom syntaxes via the Raptor RDF Parser Library.
* Querying with SPARQL and RDQL using the Rasqal RDF Query Library.
* Data aggregation and recording provenance support with Redland contexts.
* Language Bindings in Perl, PHP, Python and Ruby via the Redland Bindings package.
* Command line utility programs rdfproc (RDF), rapper (parsing) and roqet (query).
* Portable, fast and with no known memory leaks.
</code>```

Body:
Dave Beckett's Redland is a great way to start.

Features:

Redland is a set of free software C libraries that provide support for the Resource Description Framework (RDF).

* Modular, object based libraries and APIs for manipulating the RDF graph, triples, URIs and Literals.
* Storage for graphs in memory and persistently with Sleepycat/Berkeley DB, MySQL 3-5, PostgreSQL, AKT Triplestore, SQLite, files or URIs.
* Support for multiple syntaxes for reading and writing RDF as RDF/XML, N-Triples and Turtle Terse RDF Triple Language, RSS and Atom syntaxes via the Raptor RDF Parser Library.
* Querying with SPARQL and RDQL using the Rasqal RDF Query Library.
* Data aggregation and recording provenance support with Redland contexts.
* Language Bindings in Perl, PHP, Python and Ruby via the Redland Bindings package.
* Command line utility programs rdfproc (RDF), rapper (parsing) and roqet (query).
* Portable, fast and with no known memory leaks.


问:
php delete sql query not working
```<code><?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
        echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .         $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
        $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";

        //query2
            $sql = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
</code>```

In this php code snippet, query1 is not working whereas query 2 is fine.

I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.

答:
You are not executing your query1 anywhere. Just the following code won't execute your query

```<code>$sql  = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
</code>```

You need another line like the following (as you did for query2)

```<code>if ($conn->query($sql) === TRUE) {

    echo "you liked the song";
}
else {
      echo "Error: " . $sql . "<br>" . $conn->error;
}
</code>```

This executes the query and also checks for errors.

ContentLicense: CC BY-SA 4.0

Title: php delete sql query not working

Body:
<?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
        echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .         $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
        $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";

        //query2
            $sql = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "
" . $conn->error;
            }
        }

In this php code snippet, query1 is not working whereas query 2 is fine.

I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.

Body:
You are not executing your query1 anywhere. Just the following code won't execute your query

$sql  = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;

You need another line like the following (as you did for query2)

if ($conn->query($sql) === TRUE) {

    echo "you liked the song";
}
else {
      echo "Error: " . $sql . "<br>" . $conn->error;
}

This executes the query and also checks for errors.


问:
AVSpeechSynthesizer does not speak after using SFSpeechRecognizer
So I built a simple app that does speech recognition using SFSpeechRecognizer and displays the converted speech to text in a UITextView on the screen. Now I'm trying to make the phone speak that displayed text. It doesn't work for some reason. AVSpeechSynthesizer speak function works only before SFSpeechRecognizer was used. For instance, when the app launches, it has some welcome text displayed in the UITextView, if I tap the speak button, the phone will speak out the welcome text. Then if I do record (for speech recognition), the recognized speech will be displayed in the UITextView. Now I want the phone to speak that text, but unfortunately it doesn't.

here is the code

```<code>import UIKit
import Speech
import AVFoundation

class ViewController: UIViewController, SFSpeechRecognizerDelegate, AVSpeechSynthesizerDelegate {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var microphoneButton: UIButton!

    private let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))!

    private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
    private var recognitionTask: SFSpeechRecognitionTask?
    private let audioEngine = AVAudioEngine()

    override func viewDidLoad() {
        super.viewDidLoad()

        microphoneButton.isEnabled = false

        speechRecognizer.delegate = self

        SFSpeechRecognizer.requestAuthorization { (authStatus) in

            var isButtonEnabled = false

            switch authStatus {
            case .authorized:
                isButtonEnabled = true

            case .denied:
                isButtonEnabled = false
                print("User denied access to speech recognition")

            case .restricted:
                isButtonEnabled = false
                print("Speech recognition restricted on this device")

            case .notDetermined:
                isButtonEnabled = false
                print("Speech recognition not yet authorized")
            }

            OperationQueue.main.addOperation() {
                self.microphoneButton.isEnabled = isButtonEnabled
            }
        }
    }

    @IBAction func speakTapped(_ sender: UIButton) {
        let string = self.textView.text
        let utterance = AVSpeechUtterance(string: string!)
        let synthesizer = AVSpeechSynthesizer()
        synthesizer.delegate = self
        synthesizer.speak(utterance)
    }
    @IBAction func microphoneTapped(_ sender: AnyObject) {
        if audioEngine.isRunning {
            audioEngine.stop()
            recognitionRequest?.endAudio()
            microphoneButton.isEnabled = false
            microphoneButton.setTitle("Start Recording", for: .normal)
        } else {
            startRecording()
            microphoneButton.setTitle("Stop Recording", for: .normal)
        }
    }

    func startRecording() {

        if recognitionTask != nil {  //1
            recognitionTask?.cancel()
            recognitionTask = nil
        }

        let audioSession = AVAudioSession.sharedInstance()  //2
        do {
            try audioSession.setCategory(AVAudioSessionCategoryRecord)
            try audioSession.setMode(AVAudioSessionModeMeasurement)
            try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
        } catch {
            print("audioSession properties weren't set because of an error.")
        }

        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()  //3

        guard let inputNode = audioEngine.inputNode else {
            fatalError("Audio engine has no input node")
        }  //4

        guard let recognitionRequest = recognitionRequest else {
            fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
        } //5

        recognitionRequest.shouldReportPartialResults = true  //6

        recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in  //7

            var isFinal = false  //8

            if result != nil {

                self.textView.text = result?.bestTranscription.formattedString  //9
                isFinal = (result?.isFinal)!
            }

            if error != nil || isFinal {  //10
                self.audioEngine.stop()
                inputNode.removeTap(onBus: 0)

                self.recognitionRequest = nil
                self.recognitionTask = nil

                self.microphoneButton.isEnabled = true
            }
        })

        let recordingFormat = inputNode.outputFormat(forBus: 0)  //11
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
            self.recognitionRequest?.append(buffer)
        }

        audioEngine.prepare()  //12

        do {
            try audioEngine.start()
        } catch {
            print("audioEngine couldn't start because of an error.")
        }

        textView.text = "Say something, I'm listening!"

    }

    func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
        if available {
            microphoneButton.isEnabled = true
        } else {
            microphoneButton.isEnabled = false
        }
    }
}
</code>```

答:
Please use the below code for fixing the issue:

```<code>let audioSession = AVAudioSession.sharedInstance()
            do {

                try audioSession.setCategory(AVAudioSessionCategoryPlayback)
                try audioSession.setMode(AVAudioSessionModeDefault)

            } catch {
                print("audioSession properties weren't set because of an error.")
            }

Here, we have to use  the above code in the following way:

 @IBAction func microphoneTapped(_ sender: AnyObject) {

        if audioEngine.isRunning {
            audioEngine.stop()
            recognitionRequest?.endAudio()
           let audioSession = AVAudioSession.sharedInstance()
            do {

                try audioSession.setCategory(AVAudioSessionCategoryPlayback)
                try audioSession.setMode(AVAudioSessionModeDefault)

            } catch {
                print("audioSession properties weren't set because of an error.")
            }

            microphoneButton.isEnabled = false
            microphoneButton.setTitle("Start Recording", for: .normal)
        } else {
            startRecording()
            microphoneButton.setTitle("Stop Recording", for: .normal)
        }
    }
</code>```

Here, After stopping the audioengine we are setting the audioSession Category to AVAudioSessionCategoryPlayback and audioSession Mode to
AVAudioSessionModeDefault.Then when you call the next text to speech method ,it will work fine.

Body:
So I built a simple app that does speech recognition using SFSpeechRecognizer and displays the converted speech to text in a UITextView on the screen. Now I'm trying to make the phone speak that displayed text. It doesn't work for some reason. AVSpeechSynthesizer speak function works only before SFSpeechRecognizer was used. For instance, when the app launches, it has some welcome text displayed in the UITextView, if I tap the speak button, the phone will speak out the welcome text. Then if I do record (for speech recognition), the recognized speech will be displayed in the UITextView. Now I want the phone to speak that text, but unfortunately it doesn't.

here is the code

import UIKit
import Speech
import AVFoundation

class ViewController: UIViewController, SFSpeechRecognizerDelegate, AVSpeechSynthesizerDelegate {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var microphoneButton: UIButton!

    private let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))!

    private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
    private var recognitionTask: SFSpeechRecognitionTask?
    private let audioEngine = AVAudioEngine()

    override func viewDidLoad() {
        super.viewDidLoad()

        microphoneButton.isEnabled = false

        speechRecognizer.delegate = self

        SFSpeechRecognizer.requestAuthorization { (authStatus) in

            var isButtonEnabled = false

            switch authStatus {
            case .authorized:
                isButtonEnabled = true

            case .denied:
                isButtonEnabled = false
                print("User denied access to speech recognition")

            case .restricted:
                isButtonEnabled = false
                print("Speech recognition restricted on this device")

            case .notDetermined:
                isButtonEnabled = false
                print("Speech recognition not yet authorized")
            }

            OperationQueue.main.addOperation() {
                self.microphoneButton.isEnabled = isButtonEnabled
            }
        }
    }

    @IBAction func speakTapped(_ sender: UIButton) {
        let string = self.textView.text
        let utterance = AVSpeechUtterance(string: string!)
        let synthesizer = AVSpeechSynthesizer()
        synthesizer.delegate = self
        synthesizer.speak(utterance)
    }
    @IBAction func microphoneTapped(_ sender: AnyObject) {
        if audioEngine.isRunning {
            audioEngine.stop()
            recognitionRequest?.endAudio()
            microphoneButton.isEnabled = false
            microphoneButton.setTitle("Start Recording", for: .normal)
        } else {
            startRecording()
            microphoneButton.setTitle("Stop Recording", for: .normal)
        }
    }

    func startRecording() {

        if recognitionTask != nil {  //1
            recognitionTask?.cancel()
            recognitionTask = nil
        }

        let audioSession = AVAudioSession.sharedInstance()  //2
        do {
            try audioSession.setCategory(AVAudioSessionCategoryRecord)
            try audioSession.setMode(AVAudioSessionModeMeasurement)
            try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
        } catch {
            print("audioSession properties weren't set because of an error.")
        }

        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()  //3

        guard let inputNode = audioEngine.inputNode else {
            fatalError("Audio engine has no input node")
        }  //4

        guard let recognitionRequest = recognitionRequest else {
            fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
        } //5

        recognitionRequest.shouldReportPartialResults = true  //6

        recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in  //7

            var isFinal = false  //8

            if result != nil {

                self.textView.text = result?.bestTranscription.formattedString  //9
                isFinal = (result?.isFinal)!
            }

            if error != nil || isFinal {  //10
                self.audioEngine.stop()
                inputNode.removeTap(onBus: 0)

                self.recognitionRequest = nil
                self.recognitionTask = nil

                self.microphoneButton.isEnabled = true
            }
        })

        let recordingFormat = inputNode.outputFormat(forBus: 0)  //11
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
            self.recognitionRequest?.append(buffer)
        }

        audioEngine.prepare()  //12

        do {
            try audioEngine.start()
        } catch {
            print("audioEngine couldn't start because of an error.")
        }

        textView.text = "Say something, I'm listening!"

    }

    func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
        if available {
            microphoneButton.isEnabled = true
        } else {
            microphoneButton.isEnabled = false
        }
    }
}

Body:
Please use the below code for fixing the issue:

let audioSession = AVAudioSession.sharedInstance()
            do {

                try audioSession.setCategory(AVAudioSessionCategoryPlayback)
                try audioSession.setMode(AVAudioSessionModeDefault)

            } catch {
                print("audioSession properties weren't set because of an error.")
            }

Here, we have to use  the above code in the following way:

 @IBAction func microphoneTapped(_ sender: AnyObject) {

        if audioEngine.isRunning {
            audioEngine.stop()
            recognitionRequest?.endAudio()
           let audioSession = AVAudioSession.sharedInstance()
            do {

                try audioSession.setCategory(AVAudioSessionCategoryPlayback)
                try audioSession.setMode(AVAudioSessionModeDefault)

            } catch {
                print("audioSession properties weren't set because of an error.")
            }

            microphoneButton.isEnabled = false
            microphoneButton.setTitle("Start Recording", for: .normal)
        } else {
            startRecording()
            microphoneButton.setTitle("Stop Recording", for: .normal)
        }
    }

Here, After stopping the audioengine we are setting the audioSession Category to AVAudioSessionCategoryPlayback and audioSession Mode to
AVAudioSessionModeDefault.Then when you call the next text to speech method ,it will work fine.


问:
React/JSX support in WebStorm?
I cannot get JSX support in WebStorm. That is, it does not recognise JSX in react component render methods. It just looks like this to me :

Apparently it is possible, and there is some documentation on the web :

https://blog.jetbrains.com/webstorm/2015/10/working-with-reactjs-in-webstorm-coding-assistance/

It states that you should use JSX Harmony which can be found in Preferences | Languages & Frameworks | JavaScript.

But in my version of WebStorm (i.e. the latest 2016.3) there is no such checkbox for JSX Harmony. There is something called JSX Emmet which is already checked by default... but does not help.

答:
I just realised that there is a Javascript language version drop down which you have to change to React JSX. It wasn't clear to me in the documentation, or the 'search' field in the Settings window.

Basically you have to do the following :

And you are done :)

Title: React/JSX support in WebStorm?


问:
Using 'OR' in CakePHP find
I am using CakePHP 3.2 and following find().

```<code>if($filter_data_array['age_younger'] != '')
        {
            $conditions["icases.age <= "] = $filter_data_array['age_younger'];
        }

        if($filter_data_array['age_older'] != '')
        {
            $conditions["icases.age >= "] = $filter_data_array['age_older'];
        }

        if($filter_data_array['go_date_after'] != '')
        {
            $conditions["icases.go_date >= "] = $filter_data_array['go_date_after'];
        }

        if($filter_data_array['go_date_before'] != '')
        {
            $conditions["icases.go_date <= "] = $filter_data_array['go_date_before'];
        }

        if($filter_data_array['client'] != '')
        {
            $conditions["icases.client_id = "] = $filter_data_array['client'];
        }

        if($filter_data_array['case_name'] != '')
        {
            $conditions["icases.name = "] = $filter_data_array['case_name'];
        }

        if($filter_data_array['case_ref'] != '')
        {
            $conditions["icases.case_reference_i_d = "] = $filter_data_array['case_ref'];
        }

        if($filter_data_array['instruction_date'] != '')
        {
            $conditions["icases.date_instruction_received >= "] = $filter_data_array['instruction_date'];
        }

        $cases_data = TableRegistry::get('icases')->find('all')
                ->select(['icases.id', 'icases.state', 'icases.client_id', 'icases.name', 'icases.age', 'icases.case_reference_i_d', 'icases.go_date', 'clients.name'])
                ->innerJoin('icases_users', 'icases_users.icase_id = icases.id')
                ->where($conditions)
                ->innerJoin('clients', 'clients.id = icases.client_id')
                ->order(['clients.name' => 'ASC', 'icases.name' => 'ASC'])
                ->execute()
                ->fetchAll('assoc');
</code>```

Now there is a state column in icases table and I want to filter by

```<code>icases.state='active' OR icases.state='pending' OR icases.state='archive'
</code>```

My question is how do I integrate it into my existing $conditions array?

Thank you in advance.

答:
I think you should use the Advanced Conditions provided by cake. The first example suits your need as far as I understand.

So you should add this before executing the query

```<code>$conditions['OR'] = [['icases.state' => 'active'], ['icases.state' => 'pending'], ['icases.state' => 'archive']];
</code>```

Title: Using 'OR' in CakePHP find

Body:
I am using CakePHP 3.2 and following find().

if($filter_data_array['age_younger'] != '')
        {
            $conditions["icases.age <= "] = $filter_data_array['age_younger'];
        }

        if($filter_data_array['age_older'] != '')
        {
            $conditions["icases.age >= "] = $filter_data_array['age_older'];
        }

        if($filter_data_array['go_date_after'] != '')
        {
            $conditions["icases.go_date >= "] = $filter_data_array['go_date_after'];
        }

        if($filter_data_array['go_date_before'] != '')
        {
            $conditions["icases.go_date <= "] = $filter_data_array['go_date_before'];
        }

        if($filter_data_array['client'] != '')
        {
            $conditions["icases.client_id = "] = $filter_data_array['client'];
        }

        if($filter_data_array['case_name'] != '')
        {
            $conditions["icases.name = "] = $filter_data_array['case_name'];
        }

        if($filter_data_array['case_ref'] != '')
        {
            $conditions["icases.case_reference_i_d = "] = $filter_data_array['case_ref'];
        }

        if($filter_data_array['instruction_date'] != '')
        {
            $conditions["icases.date_instruction_received >= "] = $filter_data_array['instruction_date'];
        }

        $cases_data = TableRegistry::get('icases')->find('all')
                ->select(['icases.id', 'icases.state', 'icases.client_id', 'icases.name', 'icases.age', 'icases.case_reference_i_d', 'icases.go_date', 'clients.name'])
                ->innerJoin('icases_users', 'icases_users.icase_id = icases.id')
                ->where($conditions)
                ->innerJoin('clients', 'clients.id = icases.client_id')
                ->order(['clients.name' => 'ASC', 'icases.name' => 'ASC'])
                ->execute()
                ->fetchAll('assoc');

Now there is a state column in icases table and I want to filter by

icases.state='active' OR icases.state='pending' OR icases.state='archive'

My question is how do I integrate it into my existing $conditions array?

Thank you in advance.

Body:
I think you should use the Advanced Conditions provided by cake. The first example suits your need as far as I understand.

So you should add this before executing the query

$conditions['OR'] = [['icases.state' => 'active'], ['icases.state' => 'pending'], ['icases.state' => 'archive']];


问:
ASP.NET MVC 4 + Ninject MVC 3 = No parameterless constructor defined for this object
UPDATE - Please look at my answer for a link and explanation of the solution to this problem

Before we start, I know this is a very common question and I've been using Ninject for many moons without issues, but now it's come up and I can't figure out a fix. Also, no, none of the results on Google and SO so far have helped me.

So, consider the following bit of code running on a very, very, very simple prototype ASP.NET MVC 4 project from Visual Studio 2012 on Windows Server 2008 R2:

```<code>public class DefaultController : Controller {
    private IGroupPrincipalRepository GroupPrincipalRepository { get; set; }

    [Inject]
    public DefaultController(
        IGroupPrincipalRepository groupPrincipalRepository) {
        this.GroupPrincipalRepository = groupPrincipalRepository;
    }
}
</code>```

And here's the NinjectWebCommon.cs RegisterServices method:

```<code>kernel.Bind(typeof(IGroupPrincipalRepository)).ToConstructor(
    c =>
        new GroupPrincipalRepository(new PrincipalContext(ContextType.Domain, "?", "?", "?", "?"))).InSingletonScope();
</code>```

Now, this is how my other projects that use Ninject (but are ASP.NET MVC 3 on .NET 4) work and as far as I know this is what's needed to make everything work. So, why am I suddenly getting No parameterless constructor defined for this object. exceptions?

UPDATE

Here's the full NinjectWebCommon.cs file:

```<code>[assembly: WebActivator.PreApplicationStartMethod(typeof(App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(App_Start.NinjectWebCommon), "Stop")]

namespace App_Start {
    using System;
    using System.DirectoryServices.AccountManagement;
    using System.Repositories.ActiveDirectory;
    using System.Web;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    using Ninject;
    using Ninject.Web.Common;

    public static class NinjectWebCommon {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        public static void Start() {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        public static void Stop() {
            bootstrapper.ShutDown();
        }

        private static IKernel CreateKernel() {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }

        private static void RegisterServices(
            IKernel kernel) {
            kernel.Bind(typeof(IGroupPrincipalRepository)).ToConstructor(
                c =>
                    new GroupPrincipalRepository(new PrincipalContext(ContextType.Domain, "", "", "", ""))).InSingletonScope();
        }
    }
}
</code>```

UPDATE - Please look at my answer for a link and explanation of the solution to this problem

答:
I fixed mine by Removing Ninject MVC5 and installing Ninject MVC3, from Nuget.

```<code>MVC5 == Ninject.MVC5
MVC4 == Ninject.MVC3
MVC3 == Ninject.MVC3
</code>```

Check the version of the System.Web.MVC in the references to be sure which version of MVC you are currently on.

Body:
UPDATE - Please look at my answer for a link and explanation of the solution to this problem

Before we start, I know this is a very common question and I've been using Ninject for many moons without issues, but now it's come up and I can't figure out a fix. Also, no, none of the results on Google and SO so far have helped me.

So, consider the following bit of code running on a very, very, very simple prototype ASP.NET MVC 4 project from Visual Studio 2012 on Windows Server 2008 R2:

public class DefaultController : Controller {
    private IGroupPrincipalRepository GroupPrincipalRepository { get; set; }

    [Inject]
    public DefaultController(
        IGroupPrincipalRepository groupPrincipalRepository) {
        this.GroupPrincipalRepository = groupPrincipalRepository;
    }
}

And here's the NinjectWebCommon.cs RegisterServices method:

kernel.Bind(typeof(IGroupPrincipalRepository)).ToConstructor(
    c =>
        new GroupPrincipalRepository(new PrincipalContext(ContextType.Domain, "?", "?", "?", "?"))).InSingletonScope();

Now, this is how my other projects that use Ninject (but are ASP.NET MVC 3 on .NET 4) work and as far as I know this is what's needed to make everything work. So, why am I suddenly getting No parameterless constructor defined for this object. exceptions?

UPDATE

Here's the full NinjectWebCommon.cs file:

[assembly: WebActivator.PreApplicationStartMethod(typeof(App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(App_Start.NinjectWebCommon), "Stop")]

namespace App_Start {
    using System;
    using System.DirectoryServices.AccountManagement;
    using System.Repositories.ActiveDirectory;
    using System.Web;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    using Ninject;
    using Ninject.Web.Common;

    public static class NinjectWebCommon {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        public static void Start() {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        public static void Stop() {
            bootstrapper.ShutDown();
        }

        private static IKernel CreateKernel() {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }

        private static void RegisterServices(
            IKernel kernel) {
            kernel.Bind(typeof(IGroupPrincipalRepository)).ToConstructor(
                c =>
                    new GroupPrincipalRepository(new PrincipalContext(ContextType.Domain, "", "", "", ""))).InSingletonScope();
        }
    }
}

UPDATE - Please look at my answer for a link and explanation of the solution to this problem

Body:
I fixed mine by Removing Ninject MVC5 and installing Ninject MVC3, from Nuget.

MVC5 == Ninject.MVC5
MVC4 == Ninject.MVC3
MVC3 == Ninject.MVC3

Check the version of the System.Web.MVC in the references to be sure which version of MVC you are currently on.


问:
Environment variable empty on echo
I added an environment variable to /etc/environment like this:

```<code>PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
ENVIRONMENT_TYPE="test"
</code>```

But it show empty when i try to "echo $ENVIRONMENT_TYPE", echoing out the PATH variables displays correctly. Why is my new variable not showing?

答:
after adding the values just execute:</p>

```<code>source /etc/environment
</code>```

Title: Environment variable empty on echo

Body:
I added an environment variable to /etc/environment like this:

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
ENVIRONMENT_TYPE="test"

But it show empty when i try to "echo $ENVIRONMENT_TYPE", echoing out the PATH variables displays correctly. Why is my new variable not showing?

Body:
after adding the values just execute:

source /etc/environment


问:
MongoDB Aggregation: Priorization of matches?
I have problems understanding how to sort my items with priorization.

I found that this can be achieved with aggregate. Assume this is my Collection:

```<code>{
'title': 'Applepie'
"categories" : [
        "Cake",
        "Healthy",
    ],
},
{
'title': 'Chocolatecake'
"categories" : [
        "Cake",
        "Healthy",
    ],
},
{
'title': 'Some other Cake without apple in the title but in category'
"categories" : [
        "Cake",
        "Apple",
    ],
}
</code>```

I want to achieve following output if my regex is apple:

```<code>{
    'title': 'Applepie'
    "categories" : [
            "Cake",
            "Healthy",
        ],
},
{
    'title': 'Some other Cake without apple in the title but in category'
    "categories" : [
            "Cake",
            "Apple",
        ],
    }
</code>```

This is what I have so far which basically only finds matches until now:

```<code>var regex = new RegExp('abc', 'i');

db.getCollection('items').aggregate([
    { $match: {
        $or: [
             { title: { $regex: regex }},
             { categories: { $regex: regex }}
        ]
        }
    },
    {
    /* sort that those with the matching title come first and then those with matching category */
    }
])
</code>```

答:
You may be able to achieve that effect to some degree with the $project operator that lets you add new fields on the fly that you could then use to sort by, but this would not be very straightforward. See:

https://docs.mongodb.com/manual/reference/operator/aggregation/project/

Mongo doesn't support sorting that would do all that for you.

In practice what is usually done in cases like this is getting the data for both fields matching and sorting/filtering in your own code, or to get two requests - one for the first field matching and one for the second field matching and merging them together. This is not as wasteful as it seems, the performance impact can often be not measurable but you have to test it yourself for your own code, data and usage.

Body:
I have problems understanding how to sort my items with priorization.

I found that this can be achieved with aggregate. Assume this is my Collection:

{
'title': 'Applepie'
"categories" : [
        "Cake",
        "Healthy",
    ],
},
{
'title': 'Chocolatecake'
"categories" : [
        "Cake",
        "Healthy",
    ],
},
{
'title': 'Some other Cake without apple in the title but in category'
"categories" : [
        "Cake",
        "Apple",
    ],
}

I want to achieve following output if my regex is apple:

{
    'title': 'Applepie'
    "categories" : [
            "Cake",
            "Healthy",
        ],
},
{
    'title': 'Some other Cake without apple in the title but in category'
    "categories" : [
            "Cake",
            "Apple",
        ],
    }

This is what I have so far which basically only finds matches until now:

var regex = new RegExp('abc', 'i');

db.getCollection('items').aggregate([
    { $match: {
        $or: [
             { title: { $regex: regex }},
             { categories: { $regex: regex }}
        ]
        }
    },
    {
    /* sort that those with the matching title come first and then those with matching category */
    }
])


问:
How to close browser popup in robot framework?
After login in Chrome browser, I am getting a save password popup from the browser. I want to handle that popup and want to close that using Robot Framework
Browse popup window
Thanks</p>

答:
I do not think this is real to be honest (as it's property of the browser.) Are you having issues with that? The only thing you can dismiss is javascript alert and probably the best way to handle this is:

```<code>${alert} =    Get Alert Message    dismiss=${dismiss}
</code>```

I have this in my test teardown with Run Keyword and Ignore Error, it makes me able to fetch optional js alert content and debug (also dismisses it do the rest of the suite can be executed.)

Body:
I do not think this is real to be honest (as it's property of the browser.) Are you having issues with that? The only thing you can dismiss is javascript alert and probably the best way to handle this is:

${alert} =    Get Alert Message    dismiss=${dismiss}

I have this in my test teardown with Run Keyword and Ignore Error, it makes me able to fetch optional js alert content and debug (also dismisses it do the rest of the suite can be executed.)


问:
Breaking a grid into 50 square subunits in R using x y coordinates
I have data with X-Y coordinates on a rectangular grid

```<code>dX <- runif(1000,0, 500)
dY <- runif( 500,0, 500)
d <- data.frame(dX, dY)
</code>```

I want to assign 50 'plot numbers' to this data, such that anything between 0-100 dX and 0-100 dY is plot 1. anything between 100-200 dX and 1000-200 dY is plot 2. Etc. I can imagine writing 50 lines of code to do this, but I would really prefer to write 1!

答:
```<code>#DATA
set.seed(42)
dX <- runif(1000,0, 500)
dY <- runif( 500,0, 500)
d <- data.frame(dX, dY)

x_grid = seq(0, 500, 500/5)[-1]
y_grid = seq(0, 500, 500/5)[-1]
grids = expand.grid(x_grid, y_grid)
dX2 = ceiling(d$dX/100)*100
dY2 = ceiling(d$dY/100)*100
d$group = match(paste(dX2,dY2,sep = "-"), paste(grids$Var1,grids$Var2,sep="-"))
plot(d$dX, d$dY, type = "p", col = d$group, pch = 19)
</code>```

Body:
I have data with X-Y coordinates on a rectangular grid

dX <- runif(1000,0, 500)
dY <- runif( 500,0, 500)
d <- data.frame(dX, dY)

I want to assign 50 'plot numbers' to this data, such that anything between 0-100 dX and 0-100 dY is plot 1. anything between 100-200 dX and 1000-200 dY is plot 2. Etc. I can imagine writing 50 lines of code to do this, but I would really prefer to write 1!


问:
Python - Why ndarray passed by value changes outside function?
I have the following function:

```<code>def a_function(foo):
    bar = foo
    print("bar1: ", bar, id(foo))
    bar[0] = foo[2]
    print("bar2: ", bar, id(foo))
</code>```

Call with list as parameter:

```<code>foo = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print("foo1: ", foo, id(foo))
a_function(foo[:])
print("foo2: ", foo, id(foo))
</code>```

Output:

```<code>foo1:  [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901565768
bar1:  [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901566472
bar2:  [2, 1, 2, 3, 4, 5, 6, 7, 8] 140118901566472
foo2:  [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901565768
</code>```

Call with ndarray as parameter:

```<code>foo = np.arange(0,9)
print("foo1: ", foo, id(foo))
a_function(foo[:])
print("foo2: ", foo, id(foo))
</code>```

Output:

```<code>foo1:  [0 1 2 3 4 5 6 7 8] 139814139381760
bar1:  [0 1 2 3 4 5 6 7 8] 139814115258000
bar2:  [2 1 2 3 4 5 6 7 8] 139814115258000
foo2:  [2 1 2 3 4 5 6 7 8] 139814139381760
</code>```

I passed it as a copy foo[:] even copied again inside the function and also it has it's own id. However foo2 changed it's value outside the scope of the function when it's a ndarray. How is this possible?

答:
In Python,

```<code>bar = foo
</code>```

does not make a copy.  bar and foo reference the same array object.

This action makes a copy of a list, but just a view of an array:

```<code>foo[:]
</code>```

You need to use foo.copy() if you want to isolate changes in bar from foo.

I'd suggest reviewing some of the basic numpy documentation, especially the stuff about views and copies.

Body:
I have the following function:

def a_function(foo):
    bar = foo
    print("bar1: ", bar, id(foo))
    bar[0] = foo[2]
    print("bar2: ", bar, id(foo))

Call with list as parameter:

foo = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print("foo1: ", foo, id(foo))
a_function(foo[:])
print("foo2: ", foo, id(foo))

Output:

foo1:  [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901565768
bar1:  [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901566472
bar2:  [2, 1, 2, 3, 4, 5, 6, 7, 8] 140118901566472
foo2:  [0, 1, 2, 3, 4, 5, 6, 7, 8] 140118901565768

Call with ndarray as parameter:

foo = np.arange(0,9)
print("foo1: ", foo, id(foo))
a_function(foo[:])
print("foo2: ", foo, id(foo))

Output:

foo1:  [0 1 2 3 4 5 6 7 8] 139814139381760
bar1:  [0 1 2 3 4 5 6 7 8] 139814115258000
bar2:  [2 1 2 3 4 5 6 7 8] 139814115258000
foo2:  [2 1 2 3 4 5 6 7 8] 139814139381760

I passed it as a copy foo[:] even copied again inside the function and also it has it's own id. However foo2 changed it's value outside the scope of the function when it's a ndarray. How is this possible?

Body:
In Python,

bar = foo

does not make a copy.  bar and foo reference the same array object.

This action makes a copy of a list, but just a view of an array:

foo[:]

You need to use foo.copy() if you want to isolate changes in bar from foo.

I'd suggest reviewing some of the basic numpy documentation, especially the stuff about views and copies.


问:
Scrolling fixed section
Exploring web, I found this amazing effect on this site http://www.guglieri.com/
(the scrolling effect)
I want to build a script that recreates the same effect but I don't understand the logical behavior.

Basically, I started to calculate the body height setting the position property of each section to "absolute" and summing the height of the body to the height of each section.

Now, the idea is to save into an array the offset of each one and, when scrolltop is major or equals to this offset... I start to move section to top through the translateY property and I stop moving when it is equals to the height of the viewport. But now I'm stuck!!

I googled for an already existing plugin but I didn't found anything. So please help me to found a solution ;)

Concept here:

var
  body = $('body')
  section = $('section');
section.each(function(i,el){
  $(el).css({
    'z-index' : section.length - i
  })
  body.height(body.height()+$(el).height());
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
}
section {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  font-family: sans-serif;
}
section.a {
  background-color:indianred
}
section.b {
  background-color:royalblue
}
section.c {
  background-color:deepskyblue
}
section.d {
  background-color:tomato;
}

section div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
  font-size: 6em;
  color: #FFF;
}</code>```

a

b

c

d

```

答:
You can try pagePiling.js, but the difference is this one uses auto scrolling.

A similar effect can be achieved by using the fullPage.js parallax extension with the options offset:100 autoScrolling:false.

Title: Scrolling fixed section

Body:
Exploring web, I found this amazing effect on this site http://www.guglieri.com/
(the scrolling effect)
I want to build a script that recreates the same effect but I don't understand the logical behavior.

Basically, I started to calculate the body height setting the position property of each section to "absolute" and summing the height of the body to the height of each section.

Now, the idea is to save into an array the offset of each one and, when scrolltop is major or equals to this offset... I start to move section to top through the translateY property and I stop moving when it is equals to the height of the viewport. But now I'm stuck!!

I googled for an already existing plugin but I didn't found anything. So please help me to found a solution ;)

Concept here:

var
  body = $('body')
  section = $('section');
section.each(function(i,el){
  $(el).css({
    'z-index' : section.length - i
  })
  body.height(body.height()+$(el).height());
});

body {
  margin: 0;
}
section {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  font-family: sans-serif;
}
section.a {
  background-color:indianred
}
section.b {
  background-color:royalblue
}
section.c {
  background-color:deepskyblue
}
section.d {
  background-color:tomato;
}

section div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
  font-size: 6em;
  color: #FFF;
}

a

b

c

d


问:
nifi executescript flowfile creation issue in Python
I am scraping a page (e.g., facebook page ) using python script and want to pass on each post to be written to a file (something like gettwitter process). ExecuteScript is first processor in my nifi data flow. I managed to create a flow file using session.create() and no issues in that.

However, I am confused about how to put the data I read from facebook into outputstreamCallback. Most of the examples I have seen have used java overriding but I have to use Python and must admit I am little new to that.

I have found so many examples on reading the flow file but nothing much on. Below is something in Java which I want to do in Python.

```<code>FlowFile flowFile = session.create();
flowFile = session.write(flowFile, new OutputStreamCallback() {
    @Override
    public void process(final OutputStream out) throws IOException {
        out.write(tweet.getBytes(StandardCharsets.UTF_8));
</code>```

If there is any other way, please guide. Thanks.

After adopting the changes suggested by @James I wrote a snippet which is given below but not flow file transferred. No compilation error though.

```<code>import urllib2
import json
import datetime
import csv
import time
import sys
import traceback
from org.apache.nifi.processor.io import OutputStreamCallback
from org.python.core.util import StringUtil

class WriteContentCallback(OutputStreamCallback):
    def __init__(self, content):
        self.content_text = content

    def process(self, outputStream):
        try:
            outputStream.write(StringUtil.toBytes(self.content_text))
        except:
            traceback.print_exc(file=sys.stdout)
            raise

#app_id = "<FILL IN>"
#app_secret = "<FILL IN>" # DO NOT SHARE WITH ANYONE!
page_id = "dsssssss"
#page_id = raw_input("Please Paste Public Page Name:")

#access_token = app_id + "|" + app_secret

access_token = "sdfsdfsf%sdfsdf"

#access_token = raw_input("Please Paste Your Access Token:")

def scrapeFacebookPageFeedStatus(page_id, access_token):
        flowFile = session.create()
        flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data"))
        flowFile = session.write()
        session.transfer(flowFile, REL_SUCCESS)

        has_next_page = False
        num_processed = 0   # keep a count on how many we've processed
        scrape_starttime = datetime.datetime.now()

        while has_next_page:
            print "Scraping %s Facebook Page: %s\n" % (page_id, scrape_starttime)
            has_next_page = False

        print "\nDone!\n%s Statuses Processed in %s" % \
                (num_processed, datetime.datetime.now() - scrape_starttime)

if __name__ == '__main__':
    scrapeFacebookPageFeedStatus(page_id, access_token)
    flowFile = session.create()
    flowFile = session.write(flowFile, WriteContentCallback("and your data"))
    session.transfer(flowFile, REL_SUCCESS)
</code>```

Below is the output from nifi-app.log

```<code>> [root@ambari logs]# tail -100 nifi-app.log 2017-04-03 14:08:07,989
> INFO [StandardProcessScheduler Thread-6]
> o.a.n.c.s.TimerDrivenSchedulingAgent Scheduled
> ExecuteScript[id=a62f4b97-8fd7-15cd-95b9-505e1b960805] to run with 1
> threads 2017-04-03 14:08:08,938 INFO [Flow Service Tasks Thread-2]
> o.a.nifi.controller.StandardFlowService Saved flow controller
> org.apache.nifi.controller.FlowController@44ec5960 // Another save
> pending = false 2017-04-03 14:08:13,789 INFO [StandardProcessScheduler
> Thread-3] o.a.n.c.s.TimerDrivenSchedulingAgent Scheduled
> PutFile[id=a62f4b8e-8fd7-15cd-7517-56593deabf55] to run with 1 threads
> 2017-04-03 14:08:14,296 INFO [Flow Service Tasks Thread-2]
> o.a.nifi.controller.StandardFlowService Saved flow controller
> org.apache.nifi.controller.FlowController@44ec5960 // Another save
> pending = false
</code>```

答:
Here is a simple implementation of a NiFi OutputStreamCallback in Python ExecuteScript:</p>

```<code>import sys
import traceback
from org.apache.nifi.processor.io import OutputStreamCallback
from org.python.core.util import StringUtil

class WriteContentCallback(OutputStreamCallback):
    def __init__(self, content):
        self.content_text = content

    def process(self, outputStream):
        try:
            outputStream.write(StringUtil.toBytes(self.content_text))
        except:
            traceback.print_exc(file=sys.stdout)
            raise

# Create new FlowFile with content
flowFile = session.create()
flowFile = session.write(flowFile, WriteContentCallback("This is the flowfile content"))
session.transfer(flowFile, REL_SUCCESS)
</code>```

Body:
I am scraping a page (e.g., facebook page ) using python script and want to pass on each post to be written to a file (something like gettwitter process). ExecuteScript is first processor in my nifi data flow. I managed to create a flow file using session.create() and no issues in that.

However, I am confused about how to put the data I read from facebook into outputstreamCallback. Most of the examples I have seen have used java overriding but I have to use Python and must admit I am little new to that.

I have found so many examples on reading the flow file but nothing much on. Below is something in Java which I want to do in Python.

FlowFile flowFile = session.create();
flowFile = session.write(flowFile, new OutputStreamCallback() {
    @Override
    public void process(final OutputStream out) throws IOException {
        out.write(tweet.getBytes(StandardCharsets.UTF_8));

If there is any other way, please guide. Thanks.

After adopting the changes suggested by @James I wrote a snippet which is given below but not flow file transferred. No compilation error though.

import urllib2
import json
import datetime
import csv
import time
import sys
import traceback
from org.apache.nifi.processor.io import OutputStreamCallback
from org.python.core.util import StringUtil

class WriteContentCallback(OutputStreamCallback):
    def __init__(self, content):
        self.content_text = content

    def process(self, outputStream):
        try:
            outputStream.write(StringUtil.toBytes(self.content_text))
        except:
            traceback.print_exc(file=sys.stdout)
            raise

#app_id = "<FILL IN>"
#app_secret = "<FILL IN>" # DO NOT SHARE WITH ANYONE!
page_id = "dsssssss"
#page_id = raw_input("Please Paste Public Page Name:")

#access_token = app_id + "|" + app_secret

access_token = "sdfsdfsf%sdfsdf"

#access_token = raw_input("Please Paste Your Access Token:")

def scrapeFacebookPageFeedStatus(page_id, access_token):
        flowFile = session.create()
        flowFile = session.write(flowFile, WriteContentCallback("Hello there this is my data"))
        flowFile = session.write()
        session.transfer(flowFile, REL_SUCCESS)

        has_next_page = False
        num_processed = 0   # keep a count on how many we've processed
        scrape_starttime = datetime.datetime.now()

        while has_next_page:
            print "Scraping %s Facebook Page: %s\n" % (page_id, scrape_starttime)
            has_next_page = False

        print "\nDone!\n%s Statuses Processed in %s" % \
                (num_processed, datetime.datetime.now() - scrape_starttime)

if __name__ == '__main__':
    scrapeFacebookPageFeedStatus(page_id, access_token)
    flowFile = session.create()
    flowFile = session.write(flowFile, WriteContentCallback("and your data"))
    session.transfer(flowFile, REL_SUCCESS)

Below is the output from nifi-app.log

> [root@ambari logs]# tail -100 nifi-app.log 2017-04-03 14:08:07,989
> INFO [StandardProcessScheduler Thread-6]
> o.a.n.c.s.TimerDrivenSchedulingAgent Scheduled
> ExecuteScript[id=a62f4b97-8fd7-15cd-95b9-505e1b960805] to run with 1
> threads 2017-04-03 14:08:08,938 INFO [Flow Service Tasks Thread-2]
> o.a.nifi.controller.StandardFlowService Saved flow controller
> org.apache.nifi.controller.FlowController@44ec5960 // Another save
> pending = false 2017-04-03 14:08:13,789 INFO [StandardProcessScheduler
> Thread-3] o.a.n.c.s.TimerDrivenSchedulingAgent Scheduled
> PutFile[id=a62f4b8e-8fd7-15cd-7517-56593deabf55] to run with 1 threads
> 2017-04-03 14:08:14,296 INFO [Flow Service Tasks Thread-2]
> o.a.nifi.controller.StandardFlowService Saved flow controller
> org.apache.nifi.controller.FlowController@44ec5960 // Another save
> pending = false

Body:
Here is a simple implementation of a NiFi OutputStreamCallback in Python ExecuteScript:

import sys
import traceback
from org.apache.nifi.processor.io import OutputStreamCallback
from org.python.core.util import StringUtil

class WriteContentCallback(OutputStreamCallback):
    def __init__(self, content):
        self.content_text = content

    def process(self, outputStream):
        try:
            outputStream.write(StringUtil.toBytes(self.content_text))
        except:
            traceback.print_exc(file=sys.stdout)
            raise

# Create new FlowFile with content
flowFile = session.create()
flowFile = session.write(flowFile, WriteContentCallback("This is the flowfile content"))
session.transfer(flowFile, REL_SUCCESS)


问:
Realloc int array's new spaces in memory to 0
I have an int array that needs to grow when it sees a higher int value than it already has, is there any way to call realloc() and set all the new spaces in memory that are being created? Or do I need to loop through all the new spaces in memory and set them to 0 one by one? Code below for clarity.</p>

```<code>int main(){
    int i;
    int currentSize = 10;
    int *checkList = malloc(sizeof(int) * currentSize);
    while((i = readInt(fp))){
        if(i > currentSize){
             currentSize = i + 1;
             checklist = realloc(checkList, sizeof(int) * (i + 1));
             //Need to loop through checklist and declare empty mem to 0?
        }
        if(!checkList[i]) checkList[i]++;
    }

    //should have an array where seen values index in checklist == 1
}
</code>```

答:
Instead of looping, you can use memset to set all values in a particular memory range to a intended value.

You code can be modified like below to use memset

```<code>int main(){
    int i;
    int currentSize = 10;
    int *checkList = malloc(sizeof(int) * currentSize);
    while((i = readInt(fp))){
        if(i >= currentSize){
             checklist = realloc(checkList, sizeof(int) * (i + 1));
             //Need to loop through checklist and declare empty mem to 0?
             memset(checklist+currentSize, 0, (sizeof(int) * ((i+1) - currentSize)));
             currentSize = i + 1;
        }
        if(!checkList[i]) checkList[i]++;
    }

    //should have an array where seen values index in checklist == 1
}
</code>```

Body:
I have an int array that needs to grow when it sees a higher int value than it already has, is there any way to call realloc() and set all the new spaces in memory that are being created? Or do I need to loop through all the new spaces in memory and set them to 0 one by one? Code below for clarity.

int main(){
    int i;
    int currentSize = 10;
    int *checkList = malloc(sizeof(int) * currentSize);
    while((i = readInt(fp))){
        if(i > currentSize){
             currentSize = i + 1;
             checklist = realloc(checkList, sizeof(int) * (i + 1));
             //Need to loop through checklist and declare empty mem to 0?
        }
        if(!checkList[i]) checkList[i]++;
    }

    //should have an array where seen values index in checklist == 1
}

Body:
Instead of looping, you can use memset to set all values in a particular memory range to a intended value.

You code can be modified like below to use memset

int main(){
    int i;
    int currentSize = 10;
    int *checkList = malloc(sizeof(int) * currentSize);
    while((i = readInt(fp))){
        if(i >= currentSize){
             checklist = realloc(checkList, sizeof(int) * (i + 1));
             //Need to loop through checklist and declare empty mem to 0?
             memset(checklist+currentSize, 0, (sizeof(int) * ((i+1) - currentSize)));
             currentSize = i + 1;
        }
        if(!checkList[i]) checkList[i]++;
    }

    //should have an array where seen values index in checklist == 1
}


问:
Need to create replays of actor movements and actions for game
Here are some basics about the game:

```<code>- RTS (Real-time strategy)
- Every object on the game screen is an "actor".
- Every actor has an (x,y) position, HP, and type.
- Works in rounds. Every round, every actor takes one action (move, shoot, build, etc.)
</code>```

What is the most efficient way to store up to 5000 rounds with the position and relevant information of every actor stored with each round. I would like to be able to scrub back and forth across rounds and be able to call up the relevant information on an actor for that round (i.e. an actors health on a specific round).

I know how I would do this by just writing information to a .txt file and then reading from it (this is how I made preset maps), but for a 5000 round match, the .txt file would be immense. Is there any easier way that people tackle this problem in game development? I've seen it done in RTS games quite often.

Edit - All commands are given at the beginning of the game before the game even starts. For example, the player can command something akin to "if you are a fighter - every round - find the nearest enemy and move towards it if you can't shoot it, or shoot it if you are in range. Otherwise, move south." So, there are no commands inputted after the first round begins. Rather, each actor implements the same logic every round.

答:
Use mappers for your attribute names, for instanced write h=100 instead of playerHealth=100
Only save changes, a static unmovable object, like a stone, does not need 5000 entries.
Use LF instead of CRLF.

Veeery simplified Sample (where r is round, p is player, a is action, Bh is Build house):
r=0[p=0,x=100,y=100,h=100,a=Bh(101,102),p=1,x=105,y=105,h=99,a=Bh(106,106)]
~77 characters for two players each round = 385'000 bytes.

Or:
0p0x100y100h100aBh101,102,p1x105y105h99aBh106,106
Stores the same information, needs fancy code, but only 51 bytes = 255'000 bytes for 5000 rounds, that's 0.2 Megabytes. Let's say you save 10 times more data times 100 players, it's still only 200 Megabytes. If you zip it after the round, it will be reduced to about 10 MB's, I guess.

Also try to save the data with a charset that only uses only 1 byte per character, if you want to have a textfile instead of binary data.

Body:
Here are some basics about the game:

- RTS (Real-time strategy)
- Every object on the game screen is an "actor".
- Every actor has an (x,y) position, HP, and type.
- Works in rounds. Every round, every actor takes one action (move, shoot, build, etc.)

What is the most efficient way to store up to 5000 rounds with the position and relevant information of every actor stored with each round. I would like to be able to scrub back and forth across rounds and be able to call up the relevant information on an actor for that round (i.e. an actors health on a specific round).

I know how I would do this by just writing information to a .txt file and then reading from it (this is how I made preset maps), but for a 5000 round match, the .txt file would be immense. Is there any easier way that people tackle this problem in game development? I've seen it done in RTS games quite often.

Edit - All commands are given at the beginning of the game before the game even starts. For example, the player can command something akin to "if you are a fighter - every round - find the nearest enemy and move towards it if you can't shoot it, or shoot it if you are in range. Otherwise, move south." So, there are no commands inputted after the first round begins. Rather, each actor implements the same logic every round.


问:
Audio being played from microphone is choppy and sounds like air blowing into the microphone
I'm recording audio using the following:

```<code>    localInput?.installTap(onBus: 0, bufferSize: 4096, format: localInputFormat) {
        (buffer, time) -> Void in

        let audioBuffer = self.audioBufferToBytes(audioBuffer: buffer)
        let output = self.outputStream!.write(audioBuffer, maxLength: Int(buffer.frameLength))

        if output > 0 {
            print("\(#file) > \(#function) > \(output) bytes written from queue \(self.currentQueueName())")
        }
        else if output == -1 {
            let error = self.outputStream!.streamError
            print("\(#file) > \(#function) > Error writing to stream: \(error?.localizedDescription)")
        }
    }
</code>```

Where my localInputFormat is the following:

```<code>self.localInput = self.localAudioEngine.inputNode
self.localAudioEngine.attach(self.localAudioPlayer)
self.localInputFormat = self.localInput?.inputFormat(forBus: 0)
self.localAudioEngine.connect(self.localAudioPlayer, to: self.localAudioEngine.mainMixerNode, format: self.localInputFormat)
</code>```

The function audioBufferToBytes is as follows:

```<code>func audioBufferToBytes(audioBuffer: AVAudioPCMBuffer) -> [UInt8] {
    let srcLeft = audioBuffer.floatChannelData![0]
    let bytesPerFrame = audioBuffer.format.streamDescription.pointee.mBytesPerFrame
    let numBytes = Int(bytesPerFrame * audioBuffer.frameLength)

    // initialize bytes by 0
    var audioByteArray = [UInt8](repeating: 0, count: numBytes)

    srcLeft.withMemoryRebound(to: UInt8.self, capacity: numBytes) { srcByteData in
        audioByteArray.withUnsafeMutableBufferPointer {
            $0.baseAddress!.initialize(from: srcByteData, count: numBytes)
        }
    }

    return audioByteArray
}
</code>```

On the other device, when I receive the data I have to convert it back. So as it's received it runs through the following:

```<code>func bytesToAudioBuffer(_ buf: [UInt8]) -> AVAudioPCMBuffer {

    let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 1, interleaved: true)
    let frameLength = UInt32(buf.count) / fmt.streamDescription.pointee.mBytesPerFrame

    let audioBuffer = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: frameLength)
    audioBuffer.frameLength = frameLength

    let dstLeft = audioBuffer.floatChannelData![0]

    buf.withUnsafeBufferPointer {
        let src = UnsafeRawPointer($0.baseAddress!).bindMemory(to: Float.self, capacity: Int(frameLength))
        dstLeft.initialize(from: src, count: Int(frameLength))
    }

    return audioBuffer
}
</code>```

And lastly, we play this audio data:

```<code>                self.audioPlayerQueue.async {
                    self.peerAudioPlayer.scheduleBuffer(audioBuffer)

                    if (!self.peerAudioPlayer.isPlaying && self.localAudioEngine.isRunning) {
                        self.peerAudioPlayer.play()
                    }
                }
</code>```

However, on either speaker I just hear what sounds like someone tapping the microphone every half-second(ish). Not them actually talking or anything. I imagine this is due to my conversion from an audio buffer to bytes and back, but I'm not sure. Does anyone see any issues with the above?

Thanks.

答: If anyone is interested in the solution, basically the issue was that the audio on the recording device was 17640 bytes but to stream it, it breaks it up into smaller pieces, and on the receiving device I had to read the first 17640 bytes and THEN play the audio. Not play every small bit of data that was received. </p>

Body:
I'm recording audio using the following:

    localInput?.installTap(onBus: 0, bufferSize: 4096, format: localInputFormat) {
        (buffer, time) -> Void in

        let audioBuffer = self.audioBufferToBytes(audioBuffer: buffer)
        let output = self.outputStream!.write(audioBuffer, maxLength: Int(buffer.frameLength))

        if output > 0 {
            print("\(#file) > \(#function) > \(output) bytes written from queue \(self.currentQueueName())")
        }
        else if output == -1 {
            let error = self.outputStream!.streamError
            print("\(#file) > \(#function) > Error writing to stream: \(error?.localizedDescription)")
        }
    }

Where my localInputFormat is the following:

self.localInput = self.localAudioEngine.inputNode
self.localAudioEngine.attach(self.localAudioPlayer)
self.localInputFormat = self.localInput?.inputFormat(forBus: 0)
self.localAudioEngine.connect(self.localAudioPlayer, to: self.localAudioEngine.mainMixerNode, format: self.localInputFormat)

The function audioBufferToBytes is as follows:

func audioBufferToBytes(audioBuffer: AVAudioPCMBuffer) -> [UInt8] {
    let srcLeft = audioBuffer.floatChannelData![0]
    let bytesPerFrame = audioBuffer.format.streamDescription.pointee.mBytesPerFrame
    let numBytes = Int(bytesPerFrame * audioBuffer.frameLength)

    // initialize bytes by 0
    var audioByteArray = [UInt8](repeating: 0, count: numBytes)

    srcLeft.withMemoryRebound(to: UInt8.self, capacity: numBytes) { srcByteData in
        audioByteArray.withUnsafeMutableBufferPointer {
            $0.baseAddress!.initialize(from: srcByteData, count: numBytes)
        }
    }

    return audioByteArray
}

On the other device, when I receive the data I have to convert it back. So as it's received it runs through the following:

func bytesToAudioBuffer(_ buf: [UInt8]) -> AVAudioPCMBuffer {

    let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 1, interleaved: true)
    let frameLength = UInt32(buf.count) / fmt.streamDescription.pointee.mBytesPerFrame

    let audioBuffer = AVAudioPCMBuffer(pcmFormat: fmt, frameCapacity: frameLength)
    audioBuffer.frameLength = frameLength

    let dstLeft = audioBuffer.floatChannelData![0]

    buf.withUnsafeBufferPointer {
        let src = UnsafeRawPointer($0.baseAddress!).bindMemory(to: Float.self, capacity: Int(frameLength))
        dstLeft.initialize(from: src, count: Int(frameLength))
    }

    return audioBuffer
}

And lastly, we play this audio data:

                self.audioPlayerQueue.async {
                    self.peerAudioPlayer.scheduleBuffer(audioBuffer)

                    if (!self.peerAudioPlayer.isPlaying && self.localAudioEngine.isRunning) {
                        self.peerAudioPlayer.play()
                    }
                }

However, on either speaker I just hear what sounds like someone tapping the microphone every half-second(ish). Not them actually talking or anything. I imagine this is due to my conversion from an audio buffer to bytes and back, but I'm not sure. Does anyone see any issues with the above?

Thanks.


问:
Flow interfaces versus object type aliases
What is the difference between these Flow type definitions?

interface Vehicle {
  start(): void,
  stop(): void
}
```

<pre class="lang-js prettyprint-override"><code>type Vehicle = {
  start(): void,
  stop(): void
};
</code>```

As far as I can tell, they can be used in the same way.

答:
interfaces and types are similar, and the difference is mostly historical I believe. The recent changes to implement property variance also brought the behavior of type more in line with the behavior of interface. I believe the goal is to eventually make them identical and possibly even remove interface.

There may still be subtle difference but for most uses I don't think you will notice a difference.

One major difference is that if you want to use implements (e.g. class Foo implements Bar {...}) then Bar must be an interface -- not a type. However it's worth noting that marking a class as implementing an interface is not mandatory. Flow implements structural subtyping so if you have a class instance you can pass it to something that expects a compatible type even without explicitly indicating that the class implements a particular interface.

Body:
What is the difference between these Flow type definitions?

interface Vehicle {
  start(): void,
  stop(): void
}

type Vehicle = {
  start(): void,
  stop(): void
};

As far as I can tell, they can be used in the same way.


问:
User Interface inspiration for iPhone Apps
Does anyone have any suggestions for a site that potentially has some inspirational user interfaces for building my own iPhone Apps. It's straight forward to continually build out applications with the conventional UIKit widgets, but it does not set you apart from the competition. Some resources on how to build attractive interfaces is highly desired for inspiration. This is for someone with minimal Photoshop/Illustrator skills, but doesn't mind using sites such as iStockPhoto and working with custom views.</p>

答:
I hate to burst your bubble, but great design is not something you will get from finding a "site" to look at.  Major universities have graduate design programs, that's the kind of place where some people learn to be great designers.  Multiple courses and textbooks on design and all the related areas (art, architecture, psychology, biomechanics, etc., etc.)  I've seen too many engineers, without at least some of this training, routinely suggest some really bad UI design ideas.  Don't be another one of them.

Treat learning great design as something far bigger than finding a site (or learning another programming language, etc.), more like a multi-year endeavor, and you might have a chance.

Or find and team up with someone who's already an experienced designer.