问:
Creating a maze solving algorithm in Java
I've been assigned with the task of creating a maze solver in Java. Here's the assignment:

```<code>Write an application that finds a path through a maze.
The maze should be read from a file.  A sample maze is shown below.

O O O O O X O
X X O X O O X
O X O O X X X
X X X O O X O
X X X X O O X
O O O O O O O
X X O X X X O
</code>```

The character 'X' represents a wall or a blocked position and the character 'O'     represents an
open position.  You may assume that the entrance to the maze is always in the lower right hand
corner, and the exit is always in the upper left hand corner.  Your program should send its
output to a file.  If a path is found the output file should contain the path.  If a path is
not found a message should be sent to the file.  Please note that a maze may have more than
one solution path, but in this exercise you are only being asked to locate one solution, not
all solutions.

Your program should use a stack to record the path that it is exploring and backtrack when it
reaches a blocked position.

Be sure to write a complete algorithm before writing your code.  Feel free to create any additional
classes that will help you complete the assignment.

```<code>Here's my Algorithm:
1)Initialize array list to hold maze
2)Read text file holding maze in format
    o x x x x o
    o o x o x x
    o o o o o x
    x x x x o o
3)Create variables to hold numbers of columns and rows
3)While text file has next line
    A. Read next line
    B. Tokenize line
    C. Create a temporary ArrayList
    D. While there are tokens
        i. Get token
        ii. create a Point
        iii. add point to temp ArrayList
        iv. increment maximum number of columns
    E. Add temp to maze arraylist, increment max rows
    F. initialize a hold of points as max rows - 1
    G. Create a start point with x values as maximum number of rows - 1, and y values as maximum number of columns - 1
    H. Create stack of points and push starting location
    I. While finished searching is not done
        i. Look at top of stack and check for finish
        ii. check neighbors
        iii. is there an open neighbor?
            - if yes, update flags and push
            - if no, pop from stack
    J. Print solution
4. Done is true
</code>```

Anyway, what I have set up is a Points class that has set/get methods for traveling in all cardinal directions which will return booleans as shown:

```<code>public class Points<E>
{
private int xCoord;
private int yCoord;
private char val;
private boolean N;
private boolean S;
private boolean E;
private boolean W;

public Points()
{
    xCoord =0;
    yCoord =0;
    val =' ';
    N = true;
    S = true;
    E = true;
    W = true;

}

public Points (int X, int Y)
{
        xCoord = X;
        yCoord = Y;

}

public void setX(int x)
{
    xCoord = x;
}
public void setY(int y)
{
    yCoordinate = y;
}

public void setNorth(boolean n)
{
    N = n;
}
public void setSouth(boolean s)
{
    S= s;
}
public void setEast(boolean e)
{
    E = e;
}

public void setWest(boolean w)
{
    W = w;
}

public int getX()
{
    return xCoord;

}

public int getY()
{
    return yCoord;
}
public char getVal()
{
    return val;
}

public boolean getNorth()
{
    return N;
}
public boolean getSouth()
{
    return S;
}

public boolean getEast()
{
    return E;
}
public boolean getWest()
{
    return W;
}

public String toString1()
{
    String result = "(" + xCoord + ", " +yCoord + ")";
    return result;
}
</code>```

}

I'm just having problems getting the actual solving down in the main. Here's what I have:

```<code>import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;

public class MazeSolve1
{
  public static void main(String[] args)
  {
//Create arrayList of Points
ArrayList<ArrayList<Points>> MAZE = new ArrayList<ArrayList<Points>>();
Scanner in = new Scanner(System.in);

//Read File in
System.out.print("Enter the file name: ");
String fileName = in.nextLine();
fileName = fileName.trim();
FileReader reader = new FileReader(fileName+".txt");
Scanner in2 = new Scanner(reader);

//Write file out
FileWriter writer = new FileWriter("Numbers.out");
PrintWriter out = new PrintWriter(writer);
boolean done = false;
int maxCol = 0;
int maxRow = 0;

while(!done) {

    //creating array lists
    while (in2.hasNextLine()) {
        //Read next line
        String nextLine = in2.nextLine();
        //Tokenize Line
        StringTokenizer st = new StringTokenizer(nextLine, " ");
        //Create temp ArrayList
        ArrayList<ArrayList<Points>> temp = new ArrayList<ArrayList<Points>>();

        //While there are more tokens
        while (st.hasNextToken()) {
            String token = st.nextToken();
            Points pt = new Points();
            temp.add(pt);
            maxCol++
        }
        MAZE.add(temp);
        maxRow++;
    }

    //create hold arraylist for max rows of maze -1
    //create variables for start x and y coordinates
    ArrayList<ArrayList<Points>> hold = new ArrayList<ArrayList<Points>>();
    hold = MAZE.get(maxRow - 1);
    int startColumn = hold.get(maxCol - 1);
    int startRow = hold.get(maxRow - 1);
    Point start = new Point();
    start.setX(startColumn);
    start.setY(startRow);

    //initialize stack, and push the start position
    MyStack<Points> st = new ArrayStack<Points>();
    st.push(start.toString1());
    //south and east of start are edges of array
    start.setSouth(false);
    start.setEast(false);

    //while your position is not equal to point (0,0) [finish]
    while (st.peek() != "(0, 0)") {

        //getting the next coordinate to the North
        int nextY = start.getY() - 1;
        int nextX = start.getX();

        //if character to the North is an O it's open and the North flag is true
        if (hold.get(nextY) = 'O' && start.getNorth() == true) {
            //set flags and push coordinate
            start.setNorth(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the East
        nextX = start.getX() + 1;
        //if character to the East is a O and the East flag is true
        if (hold.get(nextX) = 'O' && start.getEast() == true) {
            //set flags and push coordinate
            start.setEast(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the South
        nextY = start.getY() + 1;
        //if character to the South is a O and the West flag is true
        if (hold.get(nextY) = 'O' && start.getSouth() == true) {
            //set flags and push coordinate
            start.setSouth(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop() }

        //keep looping until the top of the stack reads (0, 0)
    }

done = true;
}

//Print the results
System.out.println("---Path taken---");
for (int i = 0; i< st.size(); i++) {
    System.out.println(st.pop);
    i++
}
</code>```

Aside from any syntax errors, could you guys offer me some help? Thanks a lot.

答:
I tried to implement this using DFS algorithm utilizing some Java OOP concepts.

See complete solution on my github repository

```<code>private boolean solveDfs() {
    Block block = stack.peekFirst();
    if (block == null) {
        // stack empty and not reached the finish yet; no solution
        return false;
    } else if (block.equals(maze.getEnd())) {
        // reached finish, exit the program
        return true;
    } else {
        Block next = maze.getNextAisle(block);
        // System.out.println("next:" + next);
        if (next == null) {
            // Dead end, chose alternate path
            Block discard = stack.pop();
            discard.setInPath(false);
            // System.out.println("Popped:" + discard);
        } else {
            // Traverse next block
            next.setVisited(true);
            next.setInPath(true);
            stack.push(next);
        }
    }
    return solveDfs();
</code>```

}

Body:
I've been assigned with the task of creating a maze solver in Java. Here's the assignment:

Write an application that finds a path through a maze.
The maze should be read from a file.  A sample maze is shown below.

O O O O O X O
X X O X O O X
O X O O X X X
X X X O O X O
X X X X O O X
O O O O O O O
X X O X X X O

The character 'X' represents a wall or a blocked position and the character 'O'     represents an
open position.  You may assume that the entrance to the maze is always in the lower right hand
corner, and the exit is always in the upper left hand corner.  Your program should send its
output to a file.  If a path is found the output file should contain the path.  If a path is
not found a message should be sent to the file.  Please note that a maze may have more than
one solution path, but in this exercise you are only being asked to locate one solution, not
all solutions.

Your program should use a stack to record the path that it is exploring and backtrack when it
reaches a blocked position.

Be sure to write a complete algorithm before writing your code.  Feel free to create any additional
classes that will help you complete the assignment.

Here's my Algorithm:
1)Initialize array list to hold maze
2)Read text file holding maze in format
    o x x x x o
    o o x o x x
    o o o o o x
    x x x x o o
3)Create variables to hold numbers of columns and rows
3)While text file has next line
    A. Read next line
    B. Tokenize line
    C. Create a temporary ArrayList
    D. While there are tokens
        i. Get token
        ii. create a Point
        iii. add point to temp ArrayList
        iv. increment maximum number of columns
    E. Add temp to maze arraylist, increment max rows
    F. initialize a hold of points as max rows - 1
    G. Create a start point with x values as maximum number of rows - 1, and y values as maximum number of columns - 1
    H. Create stack of points and push starting location
    I. While finished searching is not done
        i. Look at top of stack and check for finish
        ii. check neighbors
        iii. is there an open neighbor?
            - if yes, update flags and push
            - if no, pop from stack
    J. Print solution
4. Done is true

Anyway, what I have set up is a Points class that has set/get methods for traveling in all cardinal directions which will return booleans as shown:

public class Points<E>
{
private int xCoord;
private int yCoord;
private char val;
private boolean N;
private boolean S;
private boolean E;
private boolean W;

public Points()
{
    xCoord =0;
    yCoord =0;
    val =' ';
    N = true;
    S = true;
    E = true;
    W = true;

}

public Points (int X, int Y)
{
        xCoord = X;
        yCoord = Y;

}

public void setX(int x)
{
    xCoord = x;
}
public void setY(int y)
{
    yCoordinate = y;
}

public void setNorth(boolean n)
{
    N = n;
}
public void setSouth(boolean s)
{
    S= s;
}
public void setEast(boolean e)
{
    E = e;
}

public void setWest(boolean w)
{
    W = w;
}

public int getX()
{
    return xCoord;

}

public int getY()
{
    return yCoord;
}
public char getVal()
{
    return val;
}

public boolean getNorth()
{
    return N;
}
public boolean getSouth()
{
    return S;
}

public boolean getEast()
{
    return E;
}
public boolean getWest()
{
    return W;
}

public String toString1()
{
    String result = "(" + xCoord + ", " +yCoord + ")";
    return result;
}

}

I'm just having problems getting the actual solving down in the main. Here's what I have:

import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;

public class MazeSolve1
{
  public static void main(String[] args)
  {
//Create arrayList of Points
ArrayList<ArrayList<Points>> MAZE = new ArrayList<ArrayList<Points>>();
Scanner in = new Scanner(System.in);

//Read File in
System.out.print("Enter the file name: ");
String fileName = in.nextLine();
fileName = fileName.trim();
FileReader reader = new FileReader(fileName+".txt");
Scanner in2 = new Scanner(reader);

//Write file out
FileWriter writer = new FileWriter("Numbers.out");
PrintWriter out = new PrintWriter(writer);
boolean done = false;
int maxCol = 0;
int maxRow = 0;

while(!done) {

    //creating array lists
    while (in2.hasNextLine()) {
        //Read next line
        String nextLine = in2.nextLine();
        //Tokenize Line
        StringTokenizer st = new StringTokenizer(nextLine, " ");
        //Create temp ArrayList
        ArrayList<ArrayList<Points>> temp = new ArrayList<ArrayList<Points>>();

        //While there are more tokens
        while (st.hasNextToken()) {
            String token = st.nextToken();
            Points pt = new Points();
            temp.add(pt);
            maxCol++
        }
        MAZE.add(temp);
        maxRow++;
    }

    //create hold arraylist for max rows of maze -1
    //create variables for start x and y coordinates
    ArrayList<ArrayList<Points>> hold = new ArrayList<ArrayList<Points>>();
    hold = MAZE.get(maxRow - 1);
    int startColumn = hold.get(maxCol - 1);
    int startRow = hold.get(maxRow - 1);
    Point start = new Point();
    start.setX(startColumn);
    start.setY(startRow);

    //initialize stack, and push the start position
    MyStack<Points> st = new ArrayStack<Points>();
    st.push(start.toString1());
    //south and east of start are edges of array
    start.setSouth(false);
    start.setEast(false);

    //while your position is not equal to point (0,0) [finish]
    while (st.peek() != "(0, 0)") {

        //getting the next coordinate to the North
        int nextY = start.getY() - 1;
        int nextX = start.getX();

        //if character to the North is an O it's open and the North flag is true
        if (hold.get(nextY) = 'O' && start.getNorth() == true) {
            //set flags and push coordinate
            start.setNorth(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the East
        nextX = start.getX() + 1;
        //if character to the East is a O and the East flag is true
        if (hold.get(nextX) = 'O' && start.getEast() == true) {
            //set flags and push coordinate
            start.setEast(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop(); }

        //look at coordinate to the South
        nextY = start.getY() + 1;
        //if character to the South is a O and the West flag is true
        if (hold.get(nextY) = 'O' && start.getSouth() == true) {
            //set flags and push coordinate
            start.setSouth(false);
            st.push(start.toString1());
        }
        //else pop from stack
        else { st.pop() }

        //keep looping until the top of the stack reads (0, 0)
    }

done = true;
}

//Print the results
System.out.println("---Path taken---");
for (int i = 0; i< st.size(); i++) {
    System.out.println(st.pop);
    i++
}

Aside from any syntax errors, could you guys offer me some help? Thanks a lot.

Body:
I tried to implement this using DFS algorithm utilizing some Java OOP concepts.

See complete solution on my github repository

private boolean solveDfs() {
    Block block = stack.peekFirst();
    if (block == null) {
        // stack empty and not reached the finish yet; no solution
        return false;
    } else if (block.equals(maze.getEnd())) {
        // reached finish, exit the program
        return true;
    } else {
        Block next = maze.getNextAisle(block);
        // System.out.println("next:" + next);
        if (next == null) {
            // Dead end, chose alternate path
            Block discard = stack.pop();
            discard.setInPath(false);
            // System.out.println("Popped:" + discard);
        } else {
            // Traverse next block
            next.setVisited(true);
            next.setInPath(true);
            stack.push(next);
        }
    }
    return solveDfs();

}


来源: stackexchange

问:
invalid comparison between distintc pointer types: 'type*' and 'type&(*)()'
I cannot understand why the compiler is complaining about a bad comparison attempt.

The offending comparison is this:

```<code>method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble) {
        ...
    }
...
}
</code>```

And here are the type declarations of the compared items:

```<code>const fltSemantics &getSemantics() const;
static const fltSemantics &IEEEdouble();
</code>```

The error indicated by the compiler looks like this:

comparison between distinct pointer types 'const llvm::fltSemantics*' and 'const llvm::fltSemantics& (*)()' lacks a cast [-fpermissive]

Can anybody help me understand this? I am a beginner but to me it looks both terms in the comparison are of type const fltsemantics &&.

PS: I am compiling with gcc and C++11 compliance.

答:
&APFloat::IEEEdouble evaluates to a pointer to a function while &V.getSemantics() evaluates to a pointer to a const llvm::fltSemantics*. That's why you can't compare them.

You can use:

```<code>if (&V.getSemantics() == &APFloat::IEEEdouble()) {
</code>```

to get past the compiler. However, that does not seem right. You probably want to compare the values returned by the functions, not the pointers to those values. In that case, you need to use:

```<code>if (V.getSemantics() == APFloat::IEEEdouble()) {
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I cannot understand why the compiler is complaining about a bad comparison attempt.

The offending comparison is this:

method(const APFloat& V) {
...
    if (&V.getSemantics() == &APFloat::IEEEdouble) {
        ...
    }
...
}

And here are the type declarations of the compared items:

const fltSemantics &getSemantics() const;
static const fltSemantics &IEEEdouble();

The error indicated by the compiler looks like this:

comparison between distinct pointer types 'const llvm::fltSemantics*' and 'const llvm::fltSemantics& (*)()' lacks a cast [-fpermissive]

Can anybody help me understand this? I am a beginner but to me it looks both terms in the comparison are of type const fltsemantics &&.

PS: I am compiling with gcc and C++11 compliance.

Body:
&APFloat::IEEEdouble evaluates to a pointer to a function while &V.getSemantics() evaluates to a pointer to a const llvm::fltSemantics*. That's why you can't compare them.

You can use:

if (&V.getSemantics() == &APFloat::IEEEdouble()) {

to get past the compiler. However, that does not seem right. You probably want to compare the values returned by the functions, not the pointers to those values. In that case, you need to use:

if (V.getSemantics() == APFloat::IEEEdouble()) {


问:
Async post with VueJS and Axios
I have the methods and created properties in VueJS

```<code>created() {
  axios.get('/wp-json/wp/v2/users/' + portal.user.id + '?context=edit', {headers: {'X-WP-Nonce': portal.nonce}})
  .then(response => {
    this.user = response.data;
  })
  .catch(e => {
    this.errors.push(e);
  });

  axios.get('/wp-json/wp/v2/categories')
  .then(response => {
    this.terms = response.data;
  })
  .catch(e => {
    this.errors.push(e);
  });
},

methods: {
  createPost: function() {

    let title = this.new_post_title;
    let content = this.new_post_content;
    let tags = this.new_post_tags;
    let status = this.status;

    let data = {
      'title': title,
      'content': content,
      'status': status,
    };

    axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}})
    .then(response => {
      console.log(response);
    })
    .catch(e => {
      this.errors.push(e);
      console.log(this.errors);
    });

    this.new_post_title = '';
    this.new_post_content = '';
    this.new_post_tags = '';
  }
},
</code>```

Everything is working with the request, the data is being posted to WordPress and when i do a page refresh, I get the new post at the top of the page like it should be.

But how do I go about getting the page to load the new post asynchronously after the request is completed?

答:
If your post gets created successfully, that means if you make a get request to the posts endpoint, you would get that newly created post. As you would with a page refresh. So my point is to just directly insert the new post into the page, on the client side, after a successful post request. No get request necessary.

I don't know the structure of your component hierarchy, or whether you're using Vuex. But from the component that created the post, you would $emit an event that contains the new post data.

```<code>createPost: function() {

    let title = this.new_post_title;
    let content = this.new_post_content;
    let tags = this.new_post_tags;
    let status = this.status;

    let data = {
      'title': title,
      'content': content,
      'status': status,
    };

    axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}})
    .then(response => {
      console.log(response);
      this.$emit('new-post',data)
    })
    .catch(e => {
      this.errors.push(e);
      console.log(this.errors);
    });

    this.new_post_title = '';
    this.new_post_content = '';
    this.new_post_tags = '';
  }
</code>```

The parent of this component would catch the event, containing the data. Continue emitting events or passing props until you reach the component that displays the list. Once you're in the list component, push the new post into the posts array, and it'll show up on the page.

Title: Async post with VueJS and Axios

Body:
I have the methods and created properties in VueJS

created() {
  axios.get('/wp-json/wp/v2/users/' + portal.user.id + '?context=edit', {headers: {'X-WP-Nonce': portal.nonce}})
  .then(response => {
    this.user = response.data;
  })
  .catch(e => {
    this.errors.push(e);
  });

  axios.get('/wp-json/wp/v2/categories')
  .then(response => {
    this.terms = response.data;
  })
  .catch(e => {
    this.errors.push(e);
  });
},

methods: {
  createPost: function() {

    let title = this.new_post_title;
    let content = this.new_post_content;
    let tags = this.new_post_tags;
    let status = this.status;

    let data = {
      'title': title,
      'content': content,
      'status': status,
    };

    axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}})
    .then(response => {
      console.log(response);
    })
    .catch(e => {
      this.errors.push(e);
      console.log(this.errors);
    });

    this.new_post_title = '';
    this.new_post_content = '';
    this.new_post_tags = '';
  }
},

Everything is working with the request, the data is being posted to WordPress and when i do a page refresh, I get the new post at the top of the page like it should be.

But how do I go about getting the page to load the new post asynchronously after the request is completed?

Body:
If your post gets created successfully, that means if you make a get request to the posts endpoint, you would get that newly created post. As you would with a page refresh. So my point is to just directly insert the new post into the page, on the client side, after a successful post request. No get request necessary.

I don't know the structure of your component hierarchy, or whether you're using Vuex. But from the component that created the post, you would $emit an event that contains the new post data.

createPost: function() {

    let title = this.new_post_title;
    let content = this.new_post_content;
    let tags = this.new_post_tags;
    let status = this.status;

    let data = {
      'title': title,
      'content': content,
      'status': status,
    };

    axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}})
    .then(response => {
      console.log(response);
      this.$emit('new-post',data)
    })
    .catch(e => {
      this.errors.push(e);
      console.log(this.errors);
    });

    this.new_post_title = '';
    this.new_post_content = '';
    this.new_post_tags = '';
  }

The parent of this component would catch the event, containing the data. Continue emitting events or passing props until you reach the component that displays the list. Once you're in the list component, push the new post into the posts array, and it'll show up on the page.


问:
Find way for gathering data and replace with values from another table
I am looking for an Oracle SQL query to find a specific pattern and replace them with values from another table.

Scenario:

Table 1:

```<code>No      column1
-----------------------------------------
12345  user:12345;group:56789;group:6785;...
</code>```

Note: field 1 may be has one or more pattern

Table2 :

```<code>Id     name       type
----------------------
12345  admin      user
56789  testgroup  group
</code>```

Result must be the same

```<code>No        column1
-----------------------------------
12345     user: admin;group:testgroup
</code>```

答:
Logic:

First split the concatenated string to individual rows using connect
by clause and regex.

Join the newly created table(split_tab) with Table2(tab2).

Use listagg function to concatenate data in the columns.

Query:

```<code>WITH tab1 AS
     ( SELECT '12345' NO
             ,'user:12345;group:56789;group:6785;' column1
        FROM DUAL )
    ,tab2 AS
     ( SELECT 12345 id
             ,'admin' name
             ,'user' TYPE
        FROM DUAL
      UNION
      SELECT 56789 id
            ,'testgroup' name
            ,'group' TYPE
        FROM DUAL )
SELECT no
      ,listagg(category||':'||name,';') WITHIN GROUP (ORDER BY tab2.id) column1
  FROM ( SELECT    NO
                  ,REGEXP_SUBSTR( column1, '(\d+)', 1, LEVEL ) id
                  ,REGEXP_SUBSTR( column1, '([a-z]+)', 1, LEVEL ) CATEGORY
              FROM tab1
        CONNECT BY LEVEL <= regexp_count( column1, '\d+' ) ) split_tab
      ,tab2
 WHERE split_tab.id = tab2.id
 GROUP BY no
</code>```

Output:

```<code>No     Column1
12345  user:admin;group:testgroup
</code>```

Body:
I am looking for an Oracle SQL query to find a specific pattern and replace them with values from another table.

Scenario:

Table 1:

No      column1
-----------------------------------------
12345  user:12345;group:56789;group:6785;...

Note: field 1 may be has one or more pattern

Table2 :

Id     name       type
----------------------
12345  admin      user
56789  testgroup  group

Result must be the same

No        column1
-----------------------------------
12345     user: admin;group:testgroup

Body:
Logic:

First split the concatenated string to individual rows using connect
by clause and regex.

Join the newly created table(split_tab) with Table2(tab2).

Use listagg function to concatenate data in the columns.

Query:

WITH tab1 AS
     ( SELECT '12345' NO
             ,'user:12345;group:56789;group:6785;' column1
        FROM DUAL )
    ,tab2 AS
     ( SELECT 12345 id
             ,'admin' name
             ,'user' TYPE
        FROM DUAL
      UNION
      SELECT 56789 id
            ,'testgroup' name
            ,'group' TYPE
        FROM DUAL )
SELECT no
      ,listagg(category||':'||name,';') WITHIN GROUP (ORDER BY tab2.id) column1
  FROM ( SELECT    NO
                  ,REGEXP_SUBSTR( column1, '(\d+)', 1, LEVEL ) id
                  ,REGEXP_SUBSTR( column1, '([a-z]+)', 1, LEVEL ) CATEGORY
              FROM tab1
        CONNECT BY LEVEL <= regexp_count( column1, '\d+' ) ) split_tab
      ,tab2
 WHERE split_tab.id = tab2.id
 GROUP BY no

Output:

No     Column1
12345  user:admin;group:testgroup


问:
Combobox inside another combobox
Need help writing a code - I've developed a userform.

I need one combo box to show the main section of a letter:
"based on our determination HE/SHE is entitled to a refund"
"based on our determination HE/SHE is not entitled to a refund"

but I also need a combo box to select gender:
"HE"
"SHE"

so far I have:

```<code>Private Sub Userform_Initialize()
With ComboBoxDecision
.AddItem "based on our determination HE/SHE is entitled to a refund"
.AddItem "based on our determination HE/SHE is not entitled to a refund"
End With
With ComboBoxGender
.AddItem "HE"
.AddItem "SHE"
End With
lbl_exit:
Exit sub
End Sub

Private Sub CommandButtonOk_Click()
Application.ScreenUpdating = False
With ActiveDocument
    .Bookmarks("Decision").Range.Text = ComboBoxDecision.Value
    End With
Application.ScreenUpdating = True
Unload Me
End Sub
</code>```

Is there a way to do:

```<code>.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is entitled to a refund"
.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is not entitled to a refund"
</code>```

Happy to supply any more information.

答:
You can store multiple choices in different columns of the same combo box. Depending upon the choice of gender you then hide one or the other of the columns. In code that would look as follows.</p>

```<code>Option Explicit
Option Base 0

Private Sub UserForm_Initialize()

    Dim Arr(1, 1) As String

    ' Column, item:
    Arr(1, 0) = "Based on our determination she is not entitled to a refund"
    Arr(0, 0) = Replace(Arr(1, 0), "not", "")
    Arr(1, 1) = Replace(Arr(1, 0), "she", "he")
    Arr(0, 1) = Replace(Arr(1, 1), "not", "")
    With CbxDecision
        .List = Arr
        .ColumnCount = 2
        .ListIndex = 0
    End With

    With CbxGender
        .List = Split("He She")
        .ListIndex = 0
    End With
End Sub

Private Sub CbxGender_Change()
    ' set the list width for 1st and 2nd column
    ' one of them must always be 0 (= hidden)
    CbxDecision.ColumnWidths = Split("0pt;90pt|90pt;0pt", "|")(CbxGender.ListIndex)
End Sub
</code>```

Title: Combobox inside another combobox

Body:
Need help writing a code - I've developed a userform.

I need one combo box to show the main section of a letter:
"based on our determination HE/SHE is entitled to a refund"
"based on our determination HE/SHE is not entitled to a refund"

but I also need a combo box to select gender:
"HE"
"SHE"

so far I have:

Private Sub Userform_Initialize()
With ComboBoxDecision
.AddItem "based on our determination HE/SHE is entitled to a refund"
.AddItem "based on our determination HE/SHE is not entitled to a refund"
End With
With ComboBoxGender
.AddItem "HE"
.AddItem "SHE"
End With
lbl_exit:
Exit sub
End Sub

Private Sub CommandButtonOk_Click()
Application.ScreenUpdating = False
With ActiveDocument
    .Bookmarks("Decision").Range.Text = ComboBoxDecision.Value
    End With
Application.ScreenUpdating = True
Unload Me
End Sub

Is there a way to do:

.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is entitled to a refund"
.AddItem "based on our determination "Whatever option was selected in ComboBoxGender" is not entitled to a refund"

Happy to supply any more information.

Body:
You can store multiple choices in different columns of the same combo box. Depending upon the choice of gender you then hide one or the other of the columns. In code that would look as follows.

Option Explicit
Option Base 0

Private Sub UserForm_Initialize()

    Dim Arr(1, 1) As String

    ' Column, item:
    Arr(1, 0) = "Based on our determination she is not entitled to a refund"
    Arr(0, 0) = Replace(Arr(1, 0), "not", "")
    Arr(1, 1) = Replace(Arr(1, 0), "she", "he")
    Arr(0, 1) = Replace(Arr(1, 1), "not", "")
    With CbxDecision
        .List = Arr
        .ColumnCount = 2
        .ListIndex = 0
    End With

    With CbxGender
        .List = Split("He She")
        .ListIndex = 0
    End With
End Sub

Private Sub CbxGender_Change()
    ' set the list width for 1st and 2nd column
    ' one of them must always be 0 (= hidden)
    CbxDecision.ColumnWidths = Split("0pt;90pt|90pt;0pt", "|")(CbxGender.ListIndex)
End Sub


问:
prevent Excel sheet opening on OLEDBCommand query
I am working with c# in WPF.  Pulling data into datatables.  Everything was working OK until I changed to using the actual worksheet name as pulled from the sheet via a foreach (worksheet in workbook) loop.

Now that I have the actual worksheet name and include it in my OLEDbCommand, the worksheet open on the screen.

I would like to prevent/stop the Excel file from opening on the screen as it is not needed nor desired.

Below is the connection string and the beginning of the try/catch that has the commands and query.

```<code>string con_string = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fullFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'";
try
{
    OleDbConnection con = new OleDbConnection(con_string);
    con.Open();
    //OleDbCommand ocon = new OleDbCommand("SELECT * FROM [" + myMonth + " " + year + "$]", con);
    OleDbCommand ocon = new OleDbCommand("SELECT * FROM [" + myWorkSheet + "$]", con);
    OleDbDataAdapter sda = new OleDbDataAdapter(ocon);
    sda.Fill(data);
    dGrid.DataContext = data;
}
</code>```

If I revert back to the commented out line using the myMonth and year variables (created in a SelectionChanged method from a Calendar object), the spreadsheet does not open.

The following is the code that access and creates the list of actual worksheets I use to populate a comboBox dropdown.

```<code>Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open(fullFilePath);
String[] excelSheets = new String[excelBook.Worksheets.Count];
int i = 0;
foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets)
{
    excelSheets[i] = wSheet.Name;
    cmbBox2.Items.Add(excelSheets[i]);
    i++;
}
</code>```

答:
Add these two lines-

```<code>xlApp.DisplayAlerts = false;
xlApp.Visible = false;
</code>```

below this line-

```<code>Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
</code>```

Body:
I am working with c# in WPF.  Pulling data into datatables.  Everything was working OK until I changed to using the actual worksheet name as pulled from the sheet via a foreach (worksheet in workbook) loop.

Now that I have the actual worksheet name and include it in my OLEDbCommand, the worksheet open on the screen.

I would like to prevent/stop the Excel file from opening on the screen as it is not needed nor desired.

Below is the connection string and the beginning of the try/catch that has the commands and query.

string con_string = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fullFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'";
try
{
    OleDbConnection con = new OleDbConnection(con_string);
    con.Open();
    //OleDbCommand ocon = new OleDbCommand("SELECT * FROM [" + myMonth + " " + year + "$]", con);
    OleDbCommand ocon = new OleDbCommand("SELECT * FROM [" + myWorkSheet + "$]", con);
    OleDbDataAdapter sda = new OleDbDataAdapter(ocon);
    sda.Fill(data);
    dGrid.DataContext = data;
}

If I revert back to the commented out line using the myMonth and year variables (created in a SelectionChanged method from a Calendar object), the spreadsheet does not open.

The following is the code that access and creates the list of actual worksheets I use to populate a comboBox dropdown.

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelBook = xlApp.Workbooks.Open(fullFilePath);
String[] excelSheets = new String[excelBook.Worksheets.Count];
int i = 0;
foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in excelBook.Worksheets)
{
    excelSheets[i] = wSheet.Name;
    cmbBox2.Items.Add(excelSheets[i]);
    i++;
}

Body:
Add these two lines-

xlApp.DisplayAlerts = false;
xlApp.Visible = false;

below this line-

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();


问:
Asserting that a parent component exists in angular unit test
I have a top level component AppComponent and in it's template property it renders the <child> element on the page. (<child> is another Angular component).

Do I need to tell the unit test to ignore the <child> element or declare it in some way for the test?

I'm not actually trying to test <child> in this test file, I will create a separate unit test file to validate it's functionality.

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent, ChildComponent],
  imports: [BrowserModule]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: '<child></child>'
})
export class AppComponent { }
</code>```

child.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})
export class ChildComponent { }
</code>```

app.component.spec.ts

```<code>import { async, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

describe('App', (() => {
  beforeEach(async() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] }).compileComponents();
  }));
  it('should work', () => {
    let fixture = TestBed.createComponent(AppComponent);
    // assert app.component exists
  });
});
</code>```

When I run the unit test, I'm getting this error:

```<code>Error: This test module uses the component ChildComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. in /tmp/karma-typescript-bundle-3142O76A6m7KjQOD.js (line 3929)
</code>```

答:
You need to add the ChildComponent to your module:

```<code>  beforeEach(() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] });
  });
</code>```

Body:
I have a top level component AppComponent and in it's template property it renders the <child> element on the page. (<child> is another Angular component).

Do I need to tell the unit test to ignore the <child> element or declare it in some way for the test?

I'm not actually trying to test <child> in this test file, I will create a separate unit test file to validate it's functionality.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent, ChildComponent],
  imports: [BrowserModule]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: '<child></child>'
})
export class AppComponent { }

child.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})
export class ChildComponent { }

app.component.spec.ts

import { async, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ChildComponent } from './child.component';

describe('App', (() => {
  beforeEach(async() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] }).compileComponents();
  }));
  it('should work', () => {
    let fixture = TestBed.createComponent(AppComponent);
    // assert app.component exists
  });
});

When I run the unit test, I'm getting this error:

Error: This test module uses the component ChildComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. in /tmp/karma-typescript-bundle-3142O76A6m7KjQOD.js (line 3929)

Body:
You need to add the ChildComponent to your module:

  beforeEach(() => {
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] });
  });


问:
Split responsive menu into two coloumns
This is the website I'm working on http://www.jokerleb.com/ and I'm using this https://responsive.menu, the free version. it will appear on devices 400px and smaller.

How to split its columns into 2 like so?

Don't know how to edit the CSS to make it look right, if it's possible in the first place.

答:
Adds these lines to your code :

```<code>@media screen and (max-width: 400px){
    #responsive-menu-container{
        width:100%;
    }

    #responsive-menu {
        display: flex;
        flex-wrap: wrap;
    }

    #responsive-menu li{
        width:50%;
    }
}
</code>```

It works for me.

OwnerDisplayName: Lynob

Title: Split responsive menu into two coloumns

Body:
Adds these lines to your code :

@media screen and (max-width: 400px){
    #responsive-menu-container{
        width:100%;
    }

    #responsive-menu {
        display: flex;
        flex-wrap: wrap;
    }

    #responsive-menu li{
        width:50%;
    }
}

It works for me.


问:
Regular expression file extensions
What is the regular expression for all files which end on

```<code>"*.med"
</code>```

but not

```<code>"*.result.med"
</code>```

?

I tried

```<code>((?!.result.med).med$)
</code>```

without success. I does give all .med files including .result.med files.

答:
You need a lookbehind instead of a lookahead here :

^.*(?<!\.result)\.med$

Your lookahead does not work because for a file *.result.med, when the regex engine positionned just before the last dot, it checks if there is .result.med (there isn't, because what follows is .med) then matches .med$

You can also do this with a lookahead, but you need to do it this way :

^(?!.*\.result.med$).*\.med$

Title: Regular expression file extensions

Body:
What is the regular expression for all files which end on

"*.med"

but not

"*.result.med"

?

I tried

((?!.result.med).med$)

without success. I does give all .med files including .result.med files.


问:
Overlapping times issue with 'findmeetingtimes' call in Microsoft Graph API
When attempting to complete a findmeetingtimes call with the Microsoft Graph API (as seen here: https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/user_findmeetingtimes), I am experiencing an issue where asynchronously looping and completing the call is returning a 500 error only when two meetings are scheduled in the exact same time slot (i.e. two meetings are scheduled at exactly 4:30PM - 5:00PM. The exact error message in the error object that is returned is:

"Invalid value for arg:Overlaps are not supported within TimeSlots,
  value:{"start":2017-05-10T20:00:00Z,"min":30} ↵Parameter name:
  Overlaps are not supported within TimeSlots"

Does anyone have any suggestions for a fix/work around for this?

Thanks

答: This was a bug in our API. We've deployed a fix that should clear this up.</p>


问:
Unable to display single custom post type in wordpress
i am showing the projects added customly on to my home page by simple queering them. using these lines of code

```<code>$args = array( 'post_type' => 'recent-projects', 'posts_per_page' => 10 ,'order' => 'ASC');
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo get_post_permalink( $post->ID, $leavename, $sample );
    endwhile;
</code>```

when i click on the permalink of the custom posts then it is showing me the index page. while i have archive.php too.
here is the code from functions.php.

```<code>register_post_type( 'recent-projects',
// CPT Options
    array(
        'labels' => array(
            'name' => __( 'Recent Projects' ),
            'singular_name' => __( 'Recent Project' )
        ),
        'taxonomies' => array('recordings', 'category', 'whatever'),  //add this....
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'recent-projects'),
        'supports' => array(
        'title',
        'editor',
        'excerpt',
        'trackbacks',
        'custom-fields',
        'comments',
        'revisions',
        'thumbnail',
        'author',
        'page-attributes',)

    )
);
</code>```

and this is the code in file named archive-recent-projects.php

```<code><?php get_header(); ?>
<div class="content-area">
    <div class="container main_content_wrap">
      <div class="page_wrapper">

        <section id="site-main" class="site-main content-part" >
            <div class="blog-post">
                <h1 class="classic-title"><span>Recent Projects</span></h1>
                <br>
                <br>
                <ul>
                <?php
                    $args = array( 'post_type' => 'recent-projects','order' => 'ASC');
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();?>
                       <li>
                        <small><?php the_time('F jS, Y'); ?></small><br>
                        <strong>-</strong>  <?php the_title(); ?><br> <a href="<?php the_permalink(); ?>">Read</a><br><br>
                    </li>

                <?php endwhile; // end of the loop. ?>
            </ul>
            </div>
        </section>
        </div><!--end .page_wrapper-->
    </div>
</div>
<?php get_footer(); ?>
</code>```

答: Use get_the_ID() instead of $post->ID for get_post_permalink. $post->ID will get the ID of the current page, which in your case is the homepage.

Body:
i am showing the projects added customly on to my home page by simple queering them. using these lines of code

$args = array( 'post_type' => 'recent-projects', 'posts_per_page' => 10 ,'order' => 'ASC');
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo get_post_permalink( $post->ID, $leavename, $sample );
    endwhile;

when i click on the permalink of the custom posts then it is showing me the index page. while i have archive.php too.
here is the code from functions.php.

register_post_type( 'recent-projects',
// CPT Options
    array(
        'labels' => array(
            'name' => __( 'Recent Projects' ),
            'singular_name' => __( 'Recent Project' )
        ),
        'taxonomies' => array('recordings', 'category', 'whatever'),  //add this....
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'recent-projects'),
        'supports' => array(
        'title',
        'editor',
        'excerpt',
        'trackbacks',
        'custom-fields',
        'comments',
        'revisions',
        'thumbnail',
        'author',
        'page-attributes',)

    )
);

and this is the code in file named archive-recent-projects.php

<?php get_header(); ?>

Recent Projects

                <?php
                    $args = array( 'post_type' => 'recent-projects','order' => 'ASC');
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();?>

                        <?php the_time('F jS, Y'); ?>

                        -  <?php the_title(); ?>
 <a href="<?php the_permalink(); ?>">Read

                <?php endwhile; // end of the loop. ?>

<?php get_footer(); ?>


问:
Can I make this script even faster?
I wrote a simple script for an internship, which trawls through a provided directory and deletes any file older than a specified number of days.  I've spent all my free time today attempting to tighten it up. Here's what I've got so far:

```<code>function delOld($dir, $numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    get-childItem $dir -Recurse -file |
    where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan} |
    remove-Item -whatif
}
</code>```

Here is an example of a call of the function:

```<code>delOld -dir "C:\Users\me\Desktop\psproject" -numDays 5
</code>```

Sorry for the difficulty of reading, I found that condensing the operations into one line was more efficient than reassigning them to legible variables each iteration. The remove-item is whatif'd at the moment for testing purposes. I'm aware that at this point, I probably cannot speed it up much, however, I am running it on over a TB of files, so every operation counts.

Thanks in advance for any advice you have to offer!

答:
This will delete everything in parallel processing.

```<code>workflow delOld([string]$dir, [int]$numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    $Files = get-childItem $dir -Recurse -file | where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan}
    foreach -parallel ($file in $files){
        Remove-Item $File
    }

}

delOld -dir "C:\Users\AndrewD\Downloads" -numDays 8
</code>```

Now if its alot of folders try this

Title: Can I make this script even faster?

Body:
I wrote a simple script for an internship, which trawls through a provided directory and deletes any file older than a specified number of days.  I've spent all my free time today attempting to tighten it up. Here's what I've got so far:

function delOld($dir, $numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    get-childItem $dir -Recurse -file |
    where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan} |
    remove-Item -whatif
}

Here is an example of a call of the function:

delOld -dir "C:\Users\me\Desktop\psproject" -numDays 5

Sorry for the difficulty of reading, I found that condensing the operations into one line was more efficient than reassigning them to legible variables each iteration. The remove-item is whatif'd at the moment for testing purposes. I'm aware that at this point, I probably cannot speed it up much, however, I am running it on over a TB of files, so every operation counts.

Thanks in advance for any advice you have to offer!

Body:
This will delete everything in parallel processing.

workflow delOld([string]$dir, [int]$numDays){
    $timespan = new-timespan -days $numDays
    $curTime = get-date
    $Files = get-childItem $dir -Recurse -file | where-object {(($curTime)-($_.LastWriteTime)) -gt $timespan}
    foreach -parallel ($file in $files){
        Remove-Item $File
    }

}

delOld -dir "C:\Users\AndrewD\Downloads" -numDays 8

Now if its alot of folders try this


问:
How do you implement the UIAccessibility protocol?
The "Accessibility Programming Guide For iOS" states:

Another way is to implement the isAccessibilityElement method of the UIAccessibility protocol in the implementation of your custom subclass. The following code snippet shows how to do this:

But when I am doing so, as in the following code:

```<code>class UITextLayerLabel : UIView, UIAccessibility {
</code>```

XCode returns me this error:

```<code> [...] Use of undeclared type 'UIAccessibility'
</code>```

What I am missing? A specific import? Is the protocol still available with iOS 10/XCode8?

答:
As pointed out here, UIAccessibility is an informal protocol. For the difference between an informal protocol and a formal one, see here.

Basically, there is no type called UIAccessibility. Actually, UIView is already conforming to UIAccessibility. To make your custom view accessible, just override the properties and methods starting with accessibility.

So when do you need to implement UIAccessibility? As stated here,

You can use  UIAccessibilityElement  to provide information about an
  icon or text image is not automatically accessible because it does not
  inherit from UIView (or  UIControl ). A view that contains such
  nonview items creates an instance of  UIAccessibilityElement  to
  represent each item that needs to be accessible.

Body:
The "Accessibility Programming Guide For iOS" states:

Another way is to implement the isAccessibilityElement method of the UIAccessibility protocol in the implementation of your custom subclass. The following code snippet shows how to do this:

But when I am doing so, as in the following code:

class UITextLayerLabel : UIView, UIAccessibility {

XCode returns me this error:

 [...] Use of undeclared type 'UIAccessibility'

What I am missing? A specific import? Is the protocol still available with iOS 10/XCode8?


问:
Which layer do repository interfaces belong when using DI?
I recently joined a large team/project that uses the repository pattern and dependency injection throughout the solution. I noticed that the repository interfaces were located in a Data layer project, requiring the Business layer project to depend directly on it. It is my understanding that when using DI you would want to reverse this dependency to decouple the business logic from data access (Data references interfaces from the Business layer). When I suggested this to the team, there was a mixed reaction. They didn't see the benefit and argued against it ("everyone knows not to directly reference the concrete types", "we'll never need to swap out our data access technology", etc.).

Is it good practice to keep repository interfaces in the same project as the implementation (Data layer)? If the Business layer only references the repository interfaces from Data layer, are there any drawbacks to this setup?

答: It belongs to data access layer in an application.</p>


问:
Echo Option from 1 single column
Hello guys I have this table :

```<code>ID| NUM_Slides |P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12
3 | 2          |1  | 1  | 0  | 0  | 0  | 0  | 0  | 0  | 0  | 0   | 0   | 0
</code>```

I want to select the values only from P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11 and P12 and insert them into a <option> tag

I got this so far but dont work

```<code><?php
$query = "SELECT P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12 FROM slider_settings_img where slider_settings_img.ID = $ID";
$result1 =$connect->query($query);
$resultado = $result1->fetch_all();
?>

<select name ="selectedValue" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<option value=""<?php echo $row1[1];?>"><?php echo $row1[1];?>"</option>
<?php endwhile;?>
</select>
</code>```

because my query only return 1 array I want the Options to be display 1,1,0,0,0,0,0,0,0,0,0

can some 1 help me

答:
There are several problems.

$resultado = $result1->fetch_all(); You can't fetch any more rows in your while loop if you've already fetched them all.

while($row1 = mysqli_fetch_array($result1)):; Your query selects one row. You don't need to use a while loop at all.

That while loop is set up to iteratively fetch rows from a query result, but you need to fetch one row and iterate over its columns.

Couple of important typos.

```<code><?php
$query = "SELECT P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12
          FROM slider_settings_img where slider_settings_img.ID = $ID";
$result1 = $connect->query($query);
$row = mysqli_fetch_assoc($result1);    // fetch one row
?>
<select name ="selectedValue" id="selected" >
<!-- iterate over each column of the row -->
<?php foreach ($row as $col): ?>
    <option value="<?php echo $col ?>"><?php echo $col ?></option>
<?php endforeach ?>
</select>
</code>```

Title: Echo Option from 1 single column

Body:
Hello guys I have this table :

ID| NUM_Slides |P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 | P11 | P12
3 | 2          |1  | 1  | 0  | 0  | 0  | 0  | 0  | 0  | 0  | 0   | 0   | 0

I want to select the values only from P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11 and P12 and insert them into a <option> tag

I got this so far but dont work

<?php
$query = "SELECT P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12 FROM slider_settings_img where slider_settings_img.ID = $ID";
$result1 =$connect->query($query);
$resultado = $result1->fetch_all();
?>

<select name ="selectedValue" id="selected" >
<?php while($row1 = mysqli_fetch_array($result1)):;?>
<option value=""<?php echo $row1[1];?>"><?php echo $row1[1];?>"</option>
<?php endwhile;?>
</select>

because my query only return 1 array I want the Options to be display 1,1,0,0,0,0,0,0,0,0,0

can some 1 help me

Body:
There are several problems.

$resultado = $result1->fetch_all(); You can't fetch any more rows in your while loop if you've already fetched them all.

while($row1 = mysqli_fetch_array($result1)):; Your query selects one row. You don't need to use a while loop at all.

That while loop is set up to iteratively fetch rows from a query result, but you need to fetch one row and iterate over its columns.

Couple of important typos.

<?php
$query = "SELECT P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,P11,P12
          FROM slider_settings_img where slider_settings_img.ID = $ID";
$result1 = $connect->query($query);
$row = mysqli_fetch_assoc($result1);    // fetch one row
?>
<select name ="selectedValue" id="selected" >
<!-- iterate over each column of the row -->
<?php foreach ($row as $col): ?>
    <option value="<?php echo $col ?>"><?php echo $col ?></option>
<?php endforeach ?>
</select>


Title: convert an rdd of dictionary to df

Body:
How can i make an pipelined rdd of dict into a dataframe in pyspark

[{'ACARS 20170507/20170506085012209001.rcv': 'QU SOUTA8X\r\n.BJSXCXA 060849\r\nM12\r\nFI CX731/AN B-LAN\r\nDT BJS HKG 060849 M63A\r\n-  OFF,V01,CX 731 20170506 1,VHHH,OMDB,0833,0849,----,  600', 'ACARS 20170507/20170502020906017001.rcv': 'QU SOUTA8X\r\n.BJSXCXA 020209\r\nM12\r\nFI KA876/AN B-LAB\r\nDT BJS HKG 020209 M11A\r\n-  OFF,V01,KA 876 20170502 1,VHHH,ZSPD,0149,0208,----,  294', 'ACARS 20170507/20170505050124358002.rcv': 'QU SOUTA8X\r\n.BKKXCXA 050501\r\nCFD\r\nFI CX690/AN B-LAJ\r\nDT BKK XSP 050501 C10A\r\n-  .1/WRN/DBN17D/WN1705050500  261707002SMOKE LAVATORY DET FAULT'}]

Body:
Start:

>>> a = [{'ACARS 20170507/20170506085012209001.rcv': 'QU SOUTA8X\r\n.BJSXCXA 060849\r\nM12\r\nFI CX731/AN B-LAN\r\nDT BJS HKG 060849 M63A\r\n-  OFF,V01,CX 731 20170506 1,VHHH,OMDB,0833,0849,----,  600', 'ACARS 20170507/20170502020906017001.rcv': 'QU SOUTA8X\r\n.BJSXCXA 020209\r\nM12\r\nFI KA876/AN B-LAB\r\nDT BJS HKG 020209 M11A\r\n-  OFF,V01,KA 876 20170502 1,VHHH,ZSPD,0149,0208,----,  294', 'ACARS 20170507/20170505050124358002.rcv': 'QU SOUTA8X\r\n.BKKXCXA 050501\r\nCFD\r\nFI CX690/AN B-LAJ\r\nDT BKK XSP 050501 C10A\r\n-  .1/WRN/DBN17D/WN1705050500  261707002SMOKE LAVATORY DET FAULT'}]
>>> rdd = sc.parallelize(a)

Get a rdd with the keys:

>>> rdd_k = rdd.flatMap(lambda x: x.keys())
>>> rdd_k.take(3)
['ACARS 20170507/20170506085012209001.rcv', 'ACARS 20170507/20170505050124358002.rcv', 'ACARS 20170507/20170502020906017001.rcv']

Get a rdd with the values:

>>> rdd_v = rdd.flatMap(lambda x: x.values())
>>> rdd_v.take(3)
['QU SOUTA8X\r\n.BJSXCXA 060849\r\nM12\r\nFI CX731/AN B-LAN\r\nDT BJS HKG 060849 M63A\r\n-  OFF,V01,CX 731 20170506 1,VHHH,OMDB,0833,0849,----,  600', 'QU SOUTA8X\r\n.BKKXCXA 050501\r\nCFD\r\nFI CX690/AN B-LAJ\r\nDT BKK XSP 050501 C10A\r\n-  .1/WRN/DBN17D/WN1705050500  261707002SMOKE LAVATORY DET FAULT', 'QU SOUTA8X\r\n.BJSXCXA 020209\r\nM12\r\nFI KA876/AN B-LAB\r\nDT BJS HKG 020209 M11A\r\n-  OFF,V01,KA 876 20170502 1,VHHH,ZSPD,0149,0208,----,  294']

Zip the two rdds, you will have a rdd of tuples, every tuple is a pair (key,value) of your starting dictionary:

>>> newRdd = rdd_k.zip(rdd_v)
>>> newRdd.first()
('ACARS 20170507/20170506085012209001.rcv', 'QU SOUTA8X\r\n.BJSXCXA 060849\r\nM12\r\nFI CX731/AN B-LAN\r\nDT BJS HKG 060849 M63A\r\n-  OFF,V01,CX 731 20170506 1,VHHH,OMDB,0833,0849,----,  600')

Convert to dataframe:

>>> df = newRdd.toDF()
>>> df.show()
+--------------------+--------------------+
|                  _1|                  _2|
+--------------------+--------------------+
|ACARS 20170507/20...|QU SOUTA8X
.BJSX...|
|ACARS 20170507/20...|QU SOUTA8X
.BKKX...|
|ACARS 20170507/20...|QU SOUTA8X
.BJSX...|
+--------------------+--------------------+


问:
Optimize an algorithm which is executed a lot of times
I have a couple of for loops and the innermost one will be executed a lot of times. This innermost loop contains some heavy calculations using numpy, so all of this is taking a lot of time. So I am trying to optimize the innermost loop.

The most inner-loop contains the following logic:

I have two numpy-arrays (much larger in real life):

```<code>left = np.asarray([0.4, 0.2, 0.2, 0.7, 0.6, 0.2, 0.3])
right= np.asarray([0.2, 0.7, 0.3, 0.2, 0.1, 0.9, 0.7])
</code>```

These are compared to a threshold to see if I should go left or right. If left[x] > 0.55 and right[x] < 0.45 I want to go left.
If left[x] < 0.55 and right[x] > 0.45 I want to go right.
I have solved this by creating two boolean arrays, one for left and one for right, according to:

```<code>leftListBool = ((left > 0.55)*1 + (right < 0.45)*1 - 1) > 0
rightListBool = ((right > 0.55)*1 + (left < 0.45)*1 - 1) > 0
</code>```

Which for the above example gives me:

```<code>leftListBool = [False False False  True  True False False]
rightListBool = [False  True False False False  True  True]
</code>```

But I am not allowed to go left if I went left the last time (and same for right). Therefore I loop these list according to:

```<code>wentLeft = False
wentRight = False
a = 0
for idx, v in enumerate(leftListBool):
    if leftListBool[idx] and not wentRight:
        a += DoAThing(idx)
        wentLeft = False
        wentRight = True
    elif rightListBool[idx] and not wentLeft:
        a += DoAnotherThing(idx)
        wentLeft = True
        wentRight = False
</code>```

Where DoAThing() and DoAnotherThing() simply fetches a value from a numpy-array.

This is as far as I have come in terms of optimization (it was much worse before). Note that I need to do DoAThing() and DoAnotherThing() in the correct orders, since they depend on the previous value.

What have I tried?

My first idea was to create a unified list of leftListbool and rightListBool, which would look like (left = 1 and right = -1):

```<code>unified = [0 1 0 -1 -1 1 1]
</code>```

But I am stuck to do this in a more optimal way than:

```<code>buyListBool.astype(int)-sellListBool.astype(int)
</code>```

But even if I achieve this, I need to only include the first value, if for example I have two 1 following each other, which would result in:

```<code>unified = [0 1 0 -1 0 1 0]
</code>```

In which case I could reduce the for-loop to:

```<code>for i in unified:
    if i == 1:
        a += DoAThing(a)
    elif i == -1:
        a += DoAnotherThing(a)
</code>```

But even this for-loop can mayby be optimized using some numpy-magic which I haven't figured out yet.

Complete runable code:

```<code>start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,3)
        left = res[:,0]
        right = res[:,1]
        valList = res[:,2]

        #These two statements can probably be optimized
        leftListBool = ((left > topLimit)*1 + (right < bottomLimit)*1 - 1) > 0
        rightListBool = ((right > topLimit)*1 + (left < bottomLimit)*1 - 1) > 0

        wentLeft = False
        wentRight = False
        a=0
        #Hopefully this loop can be optimized
        for idx, v in enumerate(leftListBool):
            if leftListBool[idx] and not wentRight:
                a += valList[idx]
                wentLeft = False
                wentRight = True
            elif rightListBool[idx] and not wentLeft:
                a += valList[idx]
                wentLeft = True
                wentRight = False

end = time.time()
print(end - start)
</code>```

答:
Based on the updated questions I'll present a way to vectorize the code:

```<code>import time

start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,3)
        left = res[:,0]
        right = res[:,1]
        valList = res[:,2]

        # Arrays containing where to go left and when to go right
        leftListBool = ((left > topLimit) & (right < bottomLimit))
        rightListBool = ((right > topLimit) & (left < bottomLimit))

        # Exclude all points that are neither right or left
        common = leftListBool | rightListBool
        valList = valList[common]
        leftListBool = leftListBool[common]
        rightListBool = rightListBool[common]

        # Remove the values where you would go right or left multiple times in a row
        leftListBool[1:] &= leftListBool[1:] ^ leftListBool[:-1]
        rightListBool[1:] &= rightListBool[1:] ^ rightListBool[:-1]
        valList = valList[leftListBool | rightListBool]

        # Just use np.sum to calculate the sum of the remaining items
        a = np.sum(valList)

end = time.time()
print(end - start)
</code>```

The inner loop is completly vectorized and the approach is (on my computer) 3 times faster than your original code. Let me know if I need to add more explanation about some parts. The ^ (xor operator) is just a more performant way of np.diff that works only for boolean arrays.

ContentLicense: CC BY-SA 4.0

Body:
I have a couple of for loops and the innermost one will be executed a lot of times. This innermost loop contains some heavy calculations using numpy, so all of this is taking a lot of time. So I am trying to optimize the innermost loop.

The most inner-loop contains the following logic:

I have two numpy-arrays (much larger in real life):

left = np.asarray([0.4, 0.2, 0.2, 0.7, 0.6, 0.2, 0.3])
right= np.asarray([0.2, 0.7, 0.3, 0.2, 0.1, 0.9, 0.7])

These are compared to a threshold to see if I should go left or right. If left[x] > 0.55 and right[x] < 0.45 I want to go left.
If left[x] < 0.55 and right[x] > 0.45 I want to go right.
I have solved this by creating two boolean arrays, one for left and one for right, according to:

leftListBool = ((left > 0.55)*1 + (right < 0.45)*1 - 1) > 0
rightListBool = ((right > 0.55)*1 + (left < 0.45)*1 - 1) > 0

Which for the above example gives me:

leftListBool = [False False False  True  True False False]
rightListBool = [False  True False False False  True  True]

But I am not allowed to go left if I went left the last time (and same for right). Therefore I loop these list according to:

wentLeft = False
wentRight = False
a = 0
for idx, v in enumerate(leftListBool):
    if leftListBool[idx] and not wentRight:
        a += DoAThing(idx)
        wentLeft = False
        wentRight = True
    elif rightListBool[idx] and not wentLeft:
        a += DoAnotherThing(idx)
        wentLeft = True
        wentRight = False

Where DoAThing() and DoAnotherThing() simply fetches a value from a numpy-array.

This is as far as I have come in terms of optimization (it was much worse before). Note that I need to do DoAThing() and DoAnotherThing() in the correct orders, since they depend on the previous value.

What have I tried?

My first idea was to create a unified list of leftListbool and rightListBool, which would look like (left = 1 and right = -1):

unified = [0 1 0 -1 -1 1 1]

But I am stuck to do this in a more optimal way than:

buyListBool.astype(int)-sellListBool.astype(int)

But even if I achieve this, I need to only include the first value, if for example I have two 1 following each other, which would result in:

unified = [0 1 0 -1 0 1 0]

In which case I could reduce the for-loop to:

for i in unified:
    if i == 1:
        a += DoAThing(a)
    elif i == -1:
        a += DoAnotherThing(a)

But even this for-loop can mayby be optimized using some numpy-magic which I haven't figured out yet.

Complete runable code:

start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,3)
        left = res[:,0]
        right = res[:,1]
        valList = res[:,2]

        #These two statements can probably be optimized
        leftListBool = ((left > topLimit)*1 + (right < bottomLimit)*1 - 1) > 0
        rightListBool = ((right > topLimit)*1 + (left < bottomLimit)*1 - 1) > 0

        wentLeft = False
        wentRight = False
        a=0
        #Hopefully this loop can be optimized
        for idx, v in enumerate(leftListBool):
            if leftListBool[idx] and not wentRight:
                a += valList[idx]
                wentLeft = False
                wentRight = True
            elif rightListBool[idx] and not wentLeft:
                a += valList[idx]
                wentLeft = True
                wentRight = False

end = time.time()
print(end - start)

Body:
Based on the updated questions I'll present a way to vectorize the code:

import time

start = time.time()

topLimit = 0.55
bottomLimit = 0.45

for outI in range(200):
    for midI in range(200):
        topLimit = 0.55
        bottomLimit = 0.45
        res = np.random.rand(200,3)
        left = res[:,0]
        right = res[:,1]
        valList = res[:,2]

        # Arrays containing where to go left and when to go right
        leftListBool = ((left > topLimit) & (right < bottomLimit))
        rightListBool = ((right > topLimit) & (left < bottomLimit))

        # Exclude all points that are neither right or left
        common = leftListBool | rightListBool
        valList = valList[common]
        leftListBool = leftListBool[common]
        rightListBool = rightListBool[common]

        # Remove the values where you would go right or left multiple times in a row
        leftListBool[1:] &= leftListBool[1:] ^ leftListBool[:-1]
        rightListBool[1:] &= rightListBool[1:] ^ rightListBool[:-1]
        valList = valList[leftListBool | rightListBool]

        # Just use np.sum to calculate the sum of the remaining items
        a = np.sum(valList)

end = time.time()
print(end - start)

The inner loop is completly vectorized and the approach is (on my computer) 3 times faster than your original code. Let me know if I need to add more explanation about some parts. The ^ (xor operator) is just a more performant way of np.diff that works only for boolean arrays.


问:
Missing A Detail About Boost (.lib files)
Where do I find the lib files for linking my program when using some Boost libraries?
Decided to try its threading functionality but I am getting

Error 6   fatal error LNK1104: cannot
  open file
  'libboost_thread-vc90-mt-gd-1_42.lib' InterviewPractice

after I include

Error 6   fatal error LNK1104: cannot
  open file
  'libboost_thread-vc90-mt-gd-1_42.lib' InterviewPractice

I can't find where to get the .lib files for proper linking on the boost website?
Any tips? :)

答: I hit the same link error using boost version 1.44 and the pre-built installer.  I unzipped "libboost_data_time_vc100-mt-gd-144.zip" which contains only the missing .lib and this seems to have solved the problem.</p>

ContentLicense: CC BY-SA 2.5


问:
Need advice on whether PIVOT is the correct tool in SQL Server
My data looks like this:

```<code>| ACCNT | AMOUNT | TYPE | YEAR |
|-------|--------|------|------|
|  458  | 168.80 | A    | 2014 |
|  458  | 282.77 | A    | 2015 |
|  458  | 64.70  | B    | 2015 |
|  458  | 91.25  | A    | 2016 |
|  458  | 398.00 | B    | 2016 |
|  458  | 104.45 | C    | 2016 |
|  927  | 445.00 | B    | 2014 |
|  927  | 25.00  | A    | 2015 |
|  927  | 10.00  | NULL | 2015 |
|  927  | 132.00 | A    | 2016 |
|  927  | 381.40 | B    | 2016 |
|  927  | 210.00 | C    | 2016 |
...
</code>```

An Accnt might not have a value for each Year, and the Type will occasionally be NULL.
I want to have just one row per Accnt, and combine the Amount & Type columns under a Year heading, i.e. to get it looking like this:

```<code>| ACCNT |   2014    |       2015         |           2016             |
|-------|-----------|--------------------|----------------------------|
|  458  | 168.80,A  | 282.77,A;64.70,B   | 91.25,A;398.00,B;104.45,C  |
|  927  | 445.00,B  | 25.00,A;10.00,NULL | 132.00,A;381.40,B;210.00,C |
...
</code>```

I can pivot on the [Year]...

```<code>SELECT * FROM
 (SELECT [Accnt], [Amount], [Type], [Year] FROM data_table)
 AS Source
PIVOT
(
 MAX([Amount]) FOR [Year] IN ([2014],[2015],[2016])
) AS PVT
</code>```

...but still end up with multiple rows per Accnt.

The following gets closer to the format I'm looking for...

```<code>SELECT Accnt, [1] AS '2014', [2] AS '2015', [3] AS '2016'
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Accnt ORDER BY [Year] Asc) AS AccountID,
Accnt, CONVERT(nvarchar,Amount) + ',' + [Type]  AS Amount_And_Type
FROM  data_table) PIVOT (MAX(Amount_And_Type)
FOR AccountID IN ([1], [2], [3])) AS data_pvt
</code>```

...but it's just giving me the first three rows for each Accnt:

```<code>| ACCNT |   2014    |   2015   |  2016   |
|-------|-----------|----------|---------|
|  458  | 168.80,A  | 282.77,A | 67.40,B |
|  927  | 445.00,B  | 25.00,A  | NULL    |
</code>```

Is what I'm trying to do even possible with a Pivot?

Body:
My data looks like this:

| ACCNT | AMOUNT | TYPE | YEAR |
|-------|--------|------|------|
|  458  | 168.80 | A    | 2014 |
|  458  | 282.77 | A    | 2015 |
|  458  | 64.70  | B    | 2015 |
|  458  | 91.25  | A    | 2016 |
|  458  | 398.00 | B    | 2016 |
|  458  | 104.45 | C    | 2016 |
|  927  | 445.00 | B    | 2014 |
|  927  | 25.00  | A    | 2015 |
|  927  | 10.00  | NULL | 2015 |
|  927  | 132.00 | A    | 2016 |
|  927  | 381.40 | B    | 2016 |
|  927  | 210.00 | C    | 2016 |
...

An Accnt might not have a value for each Year, and the Type will occasionally be NULL.
I want to have just one row per Accnt, and combine the Amount & Type columns under a Year heading, i.e. to get it looking like this:

| ACCNT |   2014    |       2015         |           2016             |
|-------|-----------|--------------------|----------------------------|
|  458  | 168.80,A  | 282.77,A;64.70,B   | 91.25,A;398.00,B;104.45,C  |
|  927  | 445.00,B  | 25.00,A;10.00,NULL | 132.00,A;381.40,B;210.00,C |
...

I can pivot on the [Year]...

SELECT * FROM
 (SELECT [Accnt], [Amount], [Type], [Year] FROM data_table)
 AS Source
PIVOT
(
 MAX([Amount]) FOR [Year] IN ([2014],[2015],[2016])
) AS PVT

...but still end up with multiple rows per Accnt.

The following gets closer to the format I'm looking for...

SELECT Accnt, [1] AS '2014', [2] AS '2015', [3] AS '2016'
FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Accnt ORDER BY [Year] Asc) AS AccountID,
Accnt, CONVERT(nvarchar,Amount) + ',' + [Type]  AS Amount_And_Type
FROM  data_table) PIVOT (MAX(Amount_And_Type)
FOR AccountID IN ([1], [2], [3])) AS data_pvt

...but it's just giving me the first three rows for each Accnt:

| ACCNT |   2014    |   2015   |  2016   |
|-------|-----------|----------|---------|
|  458  | 168.80,A  | 282.77,A | 67.40,B |
|  927  | 445.00,B  | 25.00,A  | NULL    |

Is what I'm trying to do even possible with a Pivot?

Body:
You can query as below:

;with cte as (
    select Accnt, iif([2014] is null,null, concat([2014],',',[Type])) as [2014a]
        ,iif([2015] is null,null, concat([2015],',',[Type])) as [2015a]
        ,iif([2016] is null,null, concat([2016],',',[Type])) as [2016a]
     from youracct
    pivot(max(amount) for [year] in ([2014],[2015],[2016])) p
)
select c.Accnt, [2014]= stuff(( Select ';'+[2014a] from cte where Accnt = c.Accnt for xml path('')),1,1,'')
,[2015]=stuff(( Select ';'+[2015a] from cte where Accnt = c.Accnt for xml path('')),1,1,'')
,[2016]=stuff(( Select ';'+[2016a] from cte where Accnt = c.Accnt for xml path('')),1,1,'')
from cte c
group by c.Accnt

But dynamic sql for this approach is bit complex but we can do..

Output as below:

+-------+---------+-----------------+------------------------+
| Accnt |  2014   |      2015       |          2016          |
+-------+---------+-----------------+------------------------+
|   458 | 168.8,A | 282.77,A;64.7,B | 91.25,A;398,B;104.45,C |
|   927 | 445,B   | 10,;25,A        | 132,A;381.4,B;210,C    |
+-------+---------+-----------------+------------------------+


问:
build dynamic array for charts.js
i'm having trouble with building an array in js to pass into a charts.js obj. I have the following array;

```<code>{"Questions":{"name":"Hello World"},"Options":{"inner":{"No":"723","Yes":"6","Maybe":"0"}}}
</code>```

Which is passed through to the function below as 'response'. I want to cycle through each item in the 'inner' array and build an array of objects to pass into my chart.js.

```<code>function drawChart(response){
    var array = JSON.parse(response)
    var options = array['Options']['inner'];

    for(var option in options){
      var datasetValue = [];

      datasetValue.push = {
          value: parseInt(options[option]),
          color: "#F7464A",
          highlight: "#FF5A5E",
          label: option
      }
    }
    console.log(datasetValue);
    var mydata = {
        datasetValue
    }

    var pieData = [
        {
            value: 300,
            color: "#F7464A",
            highlight: "#FF5A5E",
            label: "Red"
        },
        {
            value: 50,
            color: "#46BFBD",
            highlight: "#5AD3D1",
            label: "Green"
        },
        {
            value: 100,
            color: "#FDB45C",
            highlight: "#FFC870",
            label: "Yellow"
        },
        {
            value: 40,
            color: "#949FB1",
            highlight: "#A8B3C5",
            label: "Grey"
        },
        {
            value: 120,
            color: "#4D5360",
            highlight: "#616774",
            label: "Dark Grey"
        }
    ];
    var ctxOptions = {
        responsive: true,
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
        showTooltips: false,
    };
    var pie_ctx = document.getElementById("donut").getContext("2d");
    var chart = new Chart(pie_ctx).Doughnut(mydata, ctxOptions);
  }
</code>```

You can see above i have two arrays, my dynamic array i'm trying to build 'datasetValue' and 'pieData'. pieData is a sample, and if i pass this array into my new chart, the array works fine, but my datasetValue only seems to contain the last item, rather that all the objects as pieData does. Heres an output from my console.log(datasetValue);

```<code>[push: Object]
push
:
Object
color
:
"#F7464A"
highlight
:
"#FF5A5E"
label
:
"Maybe"
value
:
0
</code>```

What i'm i doing wring in rebuilding my array to match the pieData array format?

答:
I think datasetValue.push = { is overriding the Array.push function for datasetValue.  Try datasetValue.push( { to append.

Also, it's likely that only the very last value will be added to datasetValue since you're resetting it on every iteration:

```<code>for(var option in options){
      var datasetValue = [];
</code>```

Title: build dynamic array for charts.js

Body:
i'm having trouble with building an array in js to pass into a charts.js obj. I have the following array;

{"Questions":{"name":"Hello World"},"Options":{"inner":{"No":"723","Yes":"6","Maybe":"0"}}}

Which is passed through to the function below as 'response'. I want to cycle through each item in the 'inner' array and build an array of objects to pass into my chart.js.

function drawChart(response){
    var array = JSON.parse(response)
    var options = array['Options']['inner'];

    for(var option in options){
      var datasetValue = [];

      datasetValue.push = {
          value: parseInt(options[option]),
          color: "#F7464A",
          highlight: "#FF5A5E",
          label: option
      }
    }
    console.log(datasetValue);
    var mydata = {
        datasetValue
    }

    var pieData = [
        {
            value: 300,
            color: "#F7464A",
            highlight: "#FF5A5E",
            label: "Red"
        },
        {
            value: 50,
            color: "#46BFBD",
            highlight: "#5AD3D1",
            label: "Green"
        },
        {
            value: 100,
            color: "#FDB45C",
            highlight: "#FFC870",
            label: "Yellow"
        },
        {
            value: 40,
            color: "#949FB1",
            highlight: "#A8B3C5",
            label: "Grey"
        },
        {
            value: 120,
            color: "#4D5360",
            highlight: "#616774",
            label: "Dark Grey"
        }
    ];
    var ctxOptions = {
        responsive: true,
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%>
<span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%>
<%}%>
",
        showTooltips: false,
    };
    var pie_ctx = document.getElementById("donut").getContext("2d");
    var chart = new Chart(pie_ctx).Doughnut(mydata, ctxOptions);
  }

You can see above i have two arrays, my dynamic array i'm trying to build 'datasetValue' and 'pieData'. pieData is a sample, and if i pass this array into my new chart, the array works fine, but my datasetValue only seems to contain the last item, rather that all the objects as pieData does. Heres an output from my console.log(datasetValue);

[push: Object]
push
:
Object
color
:
"#F7464A"
highlight
:
"#FF5A5E"
label
:
"Maybe"
value
:
0

What i'm i doing wring in rebuilding my array to match the pieData array format?

Body:
I think datasetValue.push = { is overriding the Array.push function for datasetValue.  Try datasetValue.push( { to append.

Also, it's likely that only the very last value will be added to datasetValue since you're resetting it on every iteration:

for(var option in options){
      var datasetValue = [];


问:
How to correctly render a ar-SA date and time string
So, I've got a DateTime value, and I need to render it out using the ar-SA culture (using the Gregorian Calendar).

The format I'd like to use is dd-MMM-yyyy HH:mm.

I'm using this currently to format it -

```<code>dateTimeValue.ToString("dd-MMM-yyyy HH:mm", culture)
</code>```

In en-GB, I'd see -

06-Jun-2017 16:49

In ar-SA, when I use the same method, I see -

06-يونيو-2017 16:49

Now, from what I can work out, I think it's the RTL string that's causing the problem, since it's always on the right-hand side.

How do I render out this date correctly in RTL?

答:
```<code>var dt = DateTime.Parse("31/1/2016 12:00 AM", CultureInfo.GetCultureInfo("ar-SA"));
// Throws FormatException
</code>```

And you can't parse this string with ar-SA culture because this culture uses ص as a AMDesignator since it uses UmAlQuraCalendar rather than a GregorianCalendar.

You can use InvariantCulture (which uses AM as a AMDesignator and uses GregorianCalendar) instead with DateTime.ParseExact method with specify it's format exactly.

```<code>string s = "31/1/2016 12:00 AM";
DateTime dt = DateTime.ParseExact(s, "dd/M/yyyy hh:mm tt",CultureInfo.InvariantCulture);
</code>```

Reference here. Someone had the same problem as you more or less and this seemed to have solved the error. Hope this helps.

To render it go have a look here and here. They seemed to have a similar issue with the rendering that may be able to resolve your issue.

Body:
So, I've got a DateTime value, and I need to render it out using the ar-SA culture (using the Gregorian Calendar).

The format I'd like to use is dd-MMM-yyyy HH:mm.

I'm using this currently to format it -

dateTimeValue.ToString("dd-MMM-yyyy HH:mm", culture)

In en-GB, I'd see -

06-Jun-2017 16:49

In ar-SA, when I use the same method, I see -

06-يونيو-2017 16:49

Now, from what I can work out, I think it's the RTL string that's causing the problem, since it's always on the right-hand side.

How do I render out this date correctly in RTL?

Body:
var dt = DateTime.Parse("31/1/2016 12:00 AM", CultureInfo.GetCultureInfo("ar-SA"));
// Throws FormatException

And you can't parse this string with ar-SA culture because this culture uses ص as a AMDesignator since it uses UmAlQuraCalendar rather than a GregorianCalendar.

You can use InvariantCulture (which uses AM as a AMDesignator and uses GregorianCalendar) instead with DateTime.ParseExact method with specify it's format exactly.

string s = "31/1/2016 12:00 AM";
DateTime dt = DateTime.ParseExact(s, "dd/M/yyyy hh:mm tt",CultureInfo.InvariantCulture);

Reference here. Someone had the same problem as you more or less and this seemed to have solved the error. Hope this helps.

To render it go have a look here and here. They seemed to have a similar issue with the rendering that may be able to resolve your issue.


问:
Can I get access from code behind (of a ResourceDictionary) to a named control?
Is it possible to get access from a code behind (of a ResourceDictionary) to a named control?

E.g. for me it is necessary to create lots of folder picking dialogs. A dialog may contain several rows for each folder that has to be chosen.
Each row consists of: Label (Name), TextBox (Chosen Path) and a Button (opens FileBrowserDialog).

So now I want to access the TextBox when the FileBrowserDialog is finished. But I can not access the "SelectedFolderTextBox" from CodeBehind.

Is there a better way to achieve what I want to do?

XAML

```<code><ResourceDictionary ...>
    ...

    <StackPanel x:Key="FolderSearchPanel"
                x:Shared="False">
        <Label Content="Foldername"/>
        <TextBox x:Name="SelectedFolderTextBox"
                 Text="C:\Folder\Path\"/>
        <Button Content="..."
                Click="Button_Click"/>
    </StackPanel>
</ResourceDictionary>
</code>```

CodeBehind

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    // Initialize and show
    var dialog = new System.Windows.Forms.FolderBrowserDialog();
    System.Windows.Forms.DialogResult result = dialog.ShowDialog();

    // Process result
    if (result == System.Windows.Forms.DialogResult.OK)
    {
        string selectedPath = dialog.SelectedPath;

        SelectedFolderTextBox.Text = selectedPath;  // THIS DOES NOT WORK
                                                    // since I don't have access to it
                                                    // but describes best, what I want to do
    }
}
</code>```

答:
when you have a repeated group of controls and a bit of associated functionality it makes sense to create a reusable control:

Add UserControl via project "Add Item" dialog and use this xaml and code:

```<code><UserControl x:Class="WpfDemos.FolderPicker"
             x:Name="folderPicker"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="75" d:DesignWidth="300">
    <StackPanel>
        <Label Content="{Binding Path=Title, ElementName=folderPicker}"/>
        <TextBox x:Name="SelectedFolderTextBox"
                 Text="{Binding Path=FullPath, ElementName=folderPicker,
                                UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="..." Click="PickClick"/>
    </StackPanel>
</UserControl>
</code>```

```<code>public partial class FolderPicker : UserControl
{
    public FolderPicker()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TitleProperty = DependencyProperty.Register(
        "Title", typeof (string), typeof (FolderPicker), new PropertyMetadata("Folder"));

    public string Title
    {
        get { return (string) GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty FullPathProperty = DependencyProperty.Register(
        "FullPath", typeof (string), typeof (FolderPicker), new FrameworkPropertyMetadata(@"C:\", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public string FullPath
    {
        get { return (string) GetValue(FullPathProperty); }
        set { SetValue(FullPathProperty, value); }
    }

    private void PickClick(object sender, RoutedEventArgs e)
    {
        using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
        {
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                FullPath = dialog.SelectedPath;
        }
    }
}
</code>```

TextBox is accessible from code-behind. Dependency properties Title and FullPath allows to customize control for different usages and create bindings with a view model (something you can't do with controls group declared as resource). Example

view model:

```<code>public class MyViewModel
{
    public string Src { get; set; }
    public string Target { get; set; }
}
</code>```

view:

```<code>public MyWindow()
{
    InitializeComponent();
    this.DataContext = new MyViewModel { Src = "C:", Target = "D:" }
}
</code>```

```<code><StackPanel>
    <wpfDemos:FolderPicker Title="Source"      FullPath="{Binding Path=Src}"   />
    <wpfDemos:FolderPicker Title="Destination" FullPath="{Binding Path=Target}"/>
</StackPanel>
</code>```

Body:
Is it possible to get access from a code behind (of a ResourceDictionary) to a named control?

E.g. for me it is necessary to create lots of folder picking dialogs. A dialog may contain several rows for each folder that has to be chosen.
Each row consists of: Label (Name), TextBox (Chosen Path) and a Button (opens FileBrowserDialog).

So now I want to access the TextBox when the FileBrowserDialog is finished. But I can not access the "SelectedFolderTextBox" from CodeBehind.

Is there a better way to achieve what I want to do?

XAML

<ResourceDictionary ...>
    ...

    <StackPanel x:Key="FolderSearchPanel"
                x:Shared="False">

        <TextBox x:Name="SelectedFolderTextBox"
                 Text="C:\Folder\Path\"/>
        <Button Content="..."
                Click="Button_Click"/>
    </StackPanel>
</ResourceDictionary>

CodeBehind

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Initialize and show
    var dialog = new System.Windows.Forms.FolderBrowserDialog();
    System.Windows.Forms.DialogResult result = dialog.ShowDialog();

    // Process result
    if (result == System.Windows.Forms.DialogResult.OK)
    {
        string selectedPath = dialog.SelectedPath;

        SelectedFolderTextBox.Text = selectedPath;  // THIS DOES NOT WORK
                                                    // since I don't have access to it
                                                    // but describes best, what I want to do
    }
}

Body:
when you have a repeated group of controls and a bit of associated functionality it makes sense to create a reusable control:

Add UserControl via project "Add Item" dialog and use this xaml and code:

<UserControl x:Class="WpfDemos.FolderPicker"
             x:Name="folderPicker"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="75" d:DesignWidth="300">
    <StackPanel>
        <Label Content="{Binding Path=Title, ElementName=folderPicker}"/>
        <TextBox x:Name="SelectedFolderTextBox"
                 Text="{Binding Path=FullPath, ElementName=folderPicker,
                                UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="..." Click="PickClick"/>
    </StackPanel>
</UserControl>

public partial class FolderPicker : UserControl
{
    public FolderPicker()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty TitleProperty = DependencyProperty.Register(
        "Title", typeof (string), typeof (FolderPicker), new PropertyMetadata("Folder"));

    public string Title
    {
        get { return (string) GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty FullPathProperty = DependencyProperty.Register(
        "FullPath", typeof (string), typeof (FolderPicker), new FrameworkPropertyMetadata(@"C:\", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public string FullPath
    {
        get { return (string) GetValue(FullPathProperty); }
        set { SetValue(FullPathProperty, value); }
    }

    private void PickClick(object sender, RoutedEventArgs e)
    {
        using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
        {
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                FullPath = dialog.SelectedPath;
        }
    }
}

TextBox is accessible from code-behind. Dependency properties Title and FullPath allows to customize control for different usages and create bindings with a view model (something you can't do with controls group declared as resource). Example

view model:

public class MyViewModel
{
    public string Src { get; set; }
    public string Target { get; set; }
}

view:

public MyWindow()
{
    InitializeComponent();
    this.DataContext = new MyViewModel { Src = "C:", Target = "D:" }
}

<StackPanel>
    <wpfDemos:FolderPicker Title="Source"      FullPath="{Binding Path=Src}"   />
    <wpfDemos:FolderPicker Title="Destination" FullPath="{Binding Path=Target}"/>
</StackPanel>


问:
Read array of objects and output values by given conditions in JavaScript
Here is the problem:

Client wants to buy 2 same name PCs both color white or black with the total price less than 1600. Write a JavaScript program that would read given array var pcs and would find him the best offers.

var pcs = [
 { "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
 { "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
 { "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
 { "model":"dell", "price":697, "color":{"black":1,"white":2} },
 { "model":"acer", "price":620, "color":{"black":4,"white":2} },
 { "model":"apple", "price":2560, "color":{"white":3,"black":1} },
 { "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
    PC,
    Collors,
    offer = "Offers: " + "\n";

for (var i = 0; i < pcs.length; i++) {
    PC = pcs[i];
    Collors = Object.keys(PC.color);

    if ((((PC.price) * 2) <= 1600) && (PC.color.black >= 2 || PC.color.white >= 2)) {

        for ( var j = 0; j < Collors.length; j++) {

            if ((PC.color.black >= 2) && (PC.color.white >= 2)) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[0] + " and " + Collors[1] + "\n";
            }

            else if (((PC.color.black >= 2) && (Collors[j] === "black"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
                + "Collors: " + Collors[j] + "\n";
            }

            else if (((PC.color.white >= 2) && (Collors[j] === "white"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[j] + "\n";
            }
        }
    }
}

console.log(offer);```

Written code find the best offers, but could someone tell why acer in the output duplicates itself and how is possible to repair it?

Many thanks for all help,

答:
You loop over Collors. For acer both black and white have >2. So the first rule that checks black and white matches once for black and once for white.

A solution is to not loop over Collors at all but check black and white separately directly:

 var pcs = [
 { "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
 { "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
 { "model":"toshiba", "price":256, "color":{"melyna":3,"green":1} },
 { "model":"dell", "price":697, "color":{"black":1,"white":2} },
 { "model":"acer", "price":620, "color":{"black":4,"white":2} },
 { "model":"apple", "price":2560, "color":{"white":3,"black":1} },
 { "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
 PC,
 Collors,
 offer = [],
 colors;

for (var i = 0; i < pcs.length; i++) {
 colors = [];
 PC = pcs[i];
 if (PC.color.black >= 2) {
  colors.push("black");
 }
 if (PC.color.white >= 2) {
  colors.push("white");
 }
 if (PC.price * 2 <= 1600 && colors.length > 0) {
  offer.push({
   "model": PC.model,
   "total price": PC.price * 2,
   "color": colors
  });
 }
}

console.log(JSON.stringify(offer, undefined, "\t"));```

Body:
Here is the problem:

Client wants to buy 2 same name PCs both color white or black with the total price less than 1600. Write a JavaScript program that would read given array var pcs and would find him the best offers.

var pcs = [
 { "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
 { "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
 { "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
 { "model":"dell", "price":697, "color":{"black":1,"white":2} },
 { "model":"acer", "price":620, "color":{"black":4,"white":2} },
 { "model":"apple", "price":2560, "color":{"white":3,"black":1} },
 { "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
    PC,
    Collors,
    offer = "Offers: " + "\n";

for (var i = 0; i < pcs.length; i++) {
    PC = pcs[i];
    Collors = Object.keys(PC.color);

    if ((((PC.price) * 2) <= 1600) && (PC.color.black >= 2 || PC.color.white >= 2)) {

        for ( var j = 0; j < Collors.length; j++) {

            if ((PC.color.black >= 2) && (PC.color.white >= 2)) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[0] + " and " + Collors[1] + "\n";
            }

            else if (((PC.color.black >= 2) && (Collors[j] === "black"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
                + "Collors: " + Collors[j] + "\n";
            }

            else if (((PC.color.white >= 2) && (Collors[j] === "white"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[j] + "\n";
            }
        }
    }
}

console.log(offer);

Written code find the best offers, but could someone tell why acer in the output duplicates itself and how is possible to repair it?

Many thanks for all help,