问:
MySQL: using random function in existing table for generating derived column
i have a table 'product' with column 'category' which consists of 10 different categories without a column category_id. i want to derive a table with new column category_id for each category.

```<code>select product_id,description,category, round(rand(10)) as category_id from product;
select product_id,description,category, rand( over partition by 10) from product;
</code>```

using above query i have tried "round(rand())" however this gives only 0 and 1, but i want it to allocate category_id for 10 products from 1 to 10.

Also i want to retrieve the products from two random category

答:
Use FLOOR(1+ rand() * 10)  this will give you a number between 1 and 10</p>

```<code>select product_id,description,category,FLOOR(1+ rand() * 10) as category_id from product;
</code>```

Body:
i have a table 'product' with column 'category' which consists of 10 different categories without a column category_id. i want to derive a table with new column category_id for each category.

select product_id,description,category, round(rand(10)) as category_id from product;
select product_id,description,category, rand( over partition by 10) from product;

using above query i have tried "round(rand())" however this gives only 0 and 1, but i want it to allocate category_id for 10 products from 1 to 10.

Also i want to retrieve the products from two random category

Body:
Use FLOOR(1+ rand() * 10)  this will give you a number between 1 and 10

select product_id,description,category,FLOOR(1+ rand() * 10) as category_id from product;


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: How to create a list from a string

Body:
I have the following question;

Given this string:

(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334, -9.175614100000001 38.7277934, -9.174941499999999 38.7276969, -9.174286 38.7273452, -9.1739754 38.7269114, -9.173853299999999 38.7266373, -9.173908000000001 38.726382, -9.174462200000001 38.725427, -9.174693700000001 38.7252121, -9.1753494 38.7249695, -9.1772258 38.724483, -9.177979300000001 38.7241841, -9.1781305 38.7240326, -9.178122200000001 38.7237591, -9.174915199999999 38.7229978, -9.172651999999999 38.7224599, -9.1716237 38.7223014, -9.170840099999999 38.7223315, -9.1661269 38.7232445, -9.1631047 38.7238009, -9.1621644 38.7239822, -9.1611914 38.7241708, -9.161030500000001 38.7242016, -9.1606402 38.7242798, -9.1605509 38.7242976, -9.1597224 38.7244719, -9.1588452 38.7246248, -9.1574752 38.7248025, -9.1563748 38.7248708, -9.157024399999999 38.7252864, -9.160008299999999 38.7284055, -9.158204400000001 38.7296856, -9.1554751 38.7316224, -9.158455399999999 38.7338999, -9.159123599999999 38.7336254, -9.159243399999999 38.733823, -9.1590688 38.734304, -9.1587736 38.7343032, -9.1585287 38.7344595, -9.1584726 38.7346586, -9.158265099999999 38.7346166, -9.157652300000001 38.7361352, -9.1579041 38.7362527, -9.1576316 38.7366198, -9.1577363 38.7366731, -9.1574563 38.7371094, -9.1564187 38.737462, -9.157724699999999 38.7388573, -9.1598056 38.7379811, -9.1602277 38.73791, -9.165917800000001 38.738966, -9.166425500000001 38.7392131, -9.167036400000001 38.7396749, -9.168542199999999 38.7416702, -9.169788499999999 38.740959, -9.170749499999999 38.7402073, -9.171019899999999 38.7398203, -9.1712919 38.7392233, -9.1716798 38.7391685, -9.1719215 38.7391826, -9.172312700000001 38.7392701, -9.1727472 38.7394396, -9.1738649 38.7388609, -9.174271299999999 38.7365449, -9.174486099999999 38.7343981, -9.1743024 38.734297, -9.174186000000001 38.7341419, -9.1741347 38.7338797, -9.174625199999999 38.7332609, -9.1749603 38.7329354, -9.175330799999999 38.7327162, -9.1756046 38.7326312, -9.176090200000001 38.7325687, -9.1776274 38.7328163, -9.177988300000001 38.7328404, -9.178248099999999 38.7328097, -9.1799505 38.7322568, -9.1801505 38.7320159)

How can I turn it into a list of lists?

For instance this string:(-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334) would become this:

[[-9.1801505, 38.7320159], [-9.1800081, 38.7316384], [-9.1760106, 38.7280334]]

Body:
Try converting the whole data to a string and use the split function :

data = "-9.1801505 38.7320159, -9.1800081 38.7316384, -9.1760106 38.7280334, -9.175614100000001 38.7277934, -9.174941499999999 38.7276969, -9.174286 38.7273452, -9.1739754 38.7269114, -9.173853299999999 38.7266373, -9.173908000000001 38.726382, -9.174462200000001 38.725427, -9.174693700000001 38.7252121, -9.1753494 38.7249695, -9.1772258 38.724483, -9.177979300000001 38.7241841, -9.1781305 38.7240326, -9.178122200000001 38.7237591, -9.174915199999999 38.7229978, -9.172651999999999 38.7224599, -9.1716237 38.7223014, -9.170840099999999 38.7223315, -9.1661269 38.7232445, -9.1631047 38.7238009, -9.1621644 38.7239822, -9.1611914 38.7241708, -9.161030500000001 38.7242016, -9.1606402 38.7242798, -9.1605509 38.7242976, -9.1597224 38.7244719, -9.1588452 38.7246248, -9.1574752 38.7248025, -9.1563748 38.7248708, -9.157024399999999 38.7252864, -9.160008299999999 38.7284055, -9.158204400000001 38.7296856, -9.1554751 38.7316224, -9.158455399999999 38.7338999, -9.159123599999999 38.7336254, -9.159243399999999 38.733823, -9.1590688 38.734304, -9.1587736 38.7343032, -9.1585287 38.7344595, -9.1584726 38.7346586, -9.158265099999999 38.7346166, -9.157652300000001 38.7361352, -9.1579041 38.7362527, -9.1576316 38.7366198, -9.1577363 38.7366731, -9.1574563 38.7371094, -9.1564187 38.737462, -9.157724699999999 38.7388573, -9.1598056 38.7379811, -9.1602277 38.73791, -9.165917800000001 38.738966, -9.166425500000001 38.7392131, -9.167036400000001 38.7396749, -9.168542199999999 38.7416702, -9.169788499999999 38.740959, -9.170749499999999 38.7402073, -9.171019899999999 38.7398203, -9.1712919 38.7392233, -9.1716798 38.7391685, -9.1719215 38.7391826, -9.172312700000001 38.7392701, -9.1727472 38.7394396, -9.1738649 38.7388609, -9.174271299999999 38.7365449, -9.174486099999999 38.7343981, -9.1743024 38.734297, -9.174186000000001 38.7341419, -9.1741347 38.7338797, -9.174625199999999 38.7332609, -9.1749603 38.7329354, -9.175330799999999 38.7327162, -9.1756046 38.7326312, -9.176090200000001 38.7325687, -9.1776274 38.7328163, -9.177988300000001 38.7328404, -9.178248099999999 38.7328097, -9.1799505 38.7322568, -9.1801505 38.7320159"

for i in data.split(','):
    print(i.split())

I've the just printed the elements, which are of the form :
['-9.1712919', '38.7392233']

ps : remove the brackets before converting it to a string.


问:
How to Toggle Classname in ReactJS when button is Clicked?
I want to change the hamburger style of menu when I click the button. The toggle for opening the menu is already okay but I'm having a problem when changing the className of my hamburger menu.

This is my constructor and function

```<code>constructor(props) {
    super(props)

    this.state = { menuOpen: true }
    this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
    const {show} = this.state;
    this.setState({show : !show});
}
</code>```

I am binding my toggleMenu function in this section here:

```<code><div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
<div className="hamburger-inner"></div>
</div>
</div>
</code>```

I created a class Component called NavMenu and pass that function when user will click the hamburger menu.

```<code>class NavMenu extends Component {
    render() {
        return (
            <nav className="isMobile">
                <ul>
                    <li><a href="#about">About Us</a></li>
                    <li><a href="#bottom2">Services</a></li>
                    <li><a href="/">Clients</a></li>
                    <li><a href="/">Contact</a></li>
                    <li><a href="/">Login</a></li>
                </ul>
             </nav>
        )
    }
}
</code>```

And here is my whole class component to fully understand the process.
Class Component Source Code

```<code>import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (
<div id="nav_area">
<div className="nav_toggle_button">
<div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
<div className="hamburger-box">
    <div className="hamburger-inner"></div>
</div>
</div>
</div>
<nav className="isWeb">
<ul>
    <li><a href="#about">About Us</a></li>
    <li><a href="#bottom2">Services</a></li>
    <li><a href="/">Clients</a></li>
    <li><a href="/">Contact</a></li>
    <li><a href="/">Login</a></li>
</ul>
</nav>
{this.state.show && <NavMenu/>}
</div>
)
}
}

class NavMenu extends Component {
render() {
return (
<nav className="isMobile">
<ul>
<li><a href="#about">About Us</a></li>
<li><a href="#bottom2">Services</a></li>
<li><a href="/">Clients</a></li>
<li><a href="/">Contact</a></li>
<li><a href="/">Login</a></li>
</ul>
</nav>
)
}
}

export default nav
</code>```

What seems to be lacking in this end in order to change the className when clicked? What I'm trying to solve is when the hamburger menu is Clicked it will show the navigation items and also changed the hambuger from hamburger hamburger--emphatic-r to hamburger hamburger--emphatic-r is-Active.

答:
Your ternary condition should be this.state.show:

```<code><div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
</code>```

should be

```<code><div className={this.state.show ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>
</code>```

And also in the constructor you're using the wrong name. It should be:

```<code>this.state = { show: true }
</code>```

Body:
I want to change the hamburger style of menu when I click the button. The toggle for opening the menu is already okay but I'm having a problem when changing the className of my hamburger menu.

This is my constructor and function

constructor(props) {
    super(props)

    this.state = { menuOpen: true }
    this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
    const {show} = this.state;
    this.setState({show : !show});
}

I am binding my toggleMenu function in this section here:

I created a class Component called NavMenu and pass that function when user will click the hamburger menu.

class NavMenu extends Component {
    render() {
        return (

About Us

Services

Clients

Contact

Login

        )
    }
}

And here is my whole class component to fully understand the process.
Class Component Source Code

import React, { Component } from 'react'

class nav extends Component {

constructor(props) {
super(props)

this.state = { menuOpen: true }
this.toggleMenu = this.toggleMenu.bind(this);
}

toggleMenu = () => {
const {show} = this.state;
this.setState({show : !show});
}

render() {
console.log(this.toggleMenu);
return (

About Us

Services

Clients

Contact

Login

{this.state.show && <NavMenu/>}

)
}
}

class NavMenu extends Component {
render() {
return (

About Us

Services

Clients

Contact

Login

)
}
}

export default nav

What seems to be lacking in this end in order to change the className when clicked? What I'm trying to solve is when the hamburger menu is Clicked it will show the navigation items and also changed the hambuger from hamburger hamburger--emphatic-r to hamburger hamburger--emphatic-r is-Active.

Body:
Your ternary condition should be this.state.show:

<div className={this.toggleMenu ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>

should be

<div className={this.state.show ? "hamburger hamburger--emphatic-r" : "hamburger hamburger--emphatic-r is-Active"} onClick={this.toggleMenu}>

And also in the constructor you're using the wrong name. It should be:

this.state = { show: true }


问:
Cast and Case statement with query in Oracle SQL
I am currently editing a view and trying to cast the field "Doctorate" as Yes, No, or Unknown, based on a case statement that is joined by 2 tables, then joined to the view.

I have an error near the from clause "Expecting ) or AS" but I still get an error when adding those characters. Any help is appreciated! Thanks

Please see the excerpt of my code below:

```<code> CAST (
            CASE
                WHEN D.DEGREE_HIERARCHY >= 40
                    THEN 'Yes'

                WHEN D.DEGREE_HIERARCHY < 40
                    THEN 'No'

                WHEN D.DEGREE_HIERARCHY IS NULL
                    THEN 'Unknown'
                ELSE
                    NULL
            END

        FROM DEGREE_CROSSWALK D, VPAA V
            WHERE
                V.FACULTY_DEGREE_CODE = D.DEGREE_CODE
                   AND V.PERSON_SKEY = SRC.PERSON_SKEY
                   AND V.CURRENT_DEGREE = '1'

        AS VARCHAR2 (50))
                DOCTORATE,
</code>```

答:
First finish the cast function by casting it to a datatype or either remove the cast.    </p>

```<code>SELECT CAST((SELECT CASE WHEN D.DEGREE_HIERARCHY >= 40
                         THEN 'Yes'
                         WHEN D.DEGREE_HIERARCHY < 40
                         THEN 'No'
                         WHEN D.DEGREE_HIERARCHY IS NULL
                         THEN 'Unknown'
                         ELSE NULL
                         END
             FROM DEGREE_CROSSWALK D, VPAA V
             WHERE V.FACULTY_DEGREE_CODE = D.DEGREE_CODE
             AND V.PERSON_SKEY = SRC.PERSON_SKEY
             AND V.CURRENT_DEGREE = '1') AS VARCHAR2 (50)) AS DOCTORATE
FROM DUAL
</code>```

Body:
I am currently editing a view and trying to cast the field "Doctorate" as Yes, No, or Unknown, based on a case statement that is joined by 2 tables, then joined to the view.

I have an error near the from clause "Expecting ) or AS" but I still get an error when adding those characters. Any help is appreciated! Thanks

Please see the excerpt of my code below:

 CAST (
            CASE
                WHEN D.DEGREE_HIERARCHY >= 40
                    THEN 'Yes'

                WHEN D.DEGREE_HIERARCHY < 40
                    THEN 'No'

                WHEN D.DEGREE_HIERARCHY IS NULL
                    THEN 'Unknown'
                ELSE
                    NULL
            END

        FROM DEGREE_CROSSWALK D, VPAA V
            WHERE
                V.FACULTY_DEGREE_CODE = D.DEGREE_CODE
                   AND V.PERSON_SKEY = SRC.PERSON_SKEY
                   AND V.CURRENT_DEGREE = '1'

        AS VARCHAR2 (50))
                DOCTORATE,

Body:
First finish the cast function by casting it to a datatype or either remove the cast.

SELECT CAST((SELECT CASE WHEN D.DEGREE_HIERARCHY >= 40
                         THEN 'Yes'
                         WHEN D.DEGREE_HIERARCHY < 40
                         THEN 'No'
                         WHEN D.DEGREE_HIERARCHY IS NULL
                         THEN 'Unknown'
                         ELSE NULL
                         END
             FROM DEGREE_CROSSWALK D, VPAA V
             WHERE V.FACULTY_DEGREE_CODE = D.DEGREE_CODE
             AND V.PERSON_SKEY = SRC.PERSON_SKEY
             AND V.CURRENT_DEGREE = '1') AS VARCHAR2 (50)) AS DOCTORATE
FROM DUAL


问:
How can this MYSQL query be better
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

```<code>SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)
</code>```

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?

答:
Use this sql query.</p>

```<code>SELECT COUNT(*)
    FROM photos p
        INNER JOIN users u
            ON p.user_id = u.user_id
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can this MYSQL query be better

Body:
I have a table that has all the photos from a user. For some reason (dont care why) some users can be deleted (using DELETE FROM) from the users table, but the photos are kept on the photos tables.

I need to know how many photos are from users that actually exists on the users table.

The first solution I came up with is this:

SELECT COUNT(DISTINCT user_id) FROM photos WHERE user_id IN (SELECT id FROM users)

But I'm not sure if doing two Queries is the best one. Is there a better way to do this?

Body:
Use this sql query.

SELECT COUNT(*)
    FROM photos p
        INNER JOIN users u
            ON p.user_id = u.user_id


问:
javax.persistence.NonUniqueResultException: query did not return a unique result: 3
```<code>**hi big community! someone can help me**
 **here: Role entity**

        @Entity
        @Table(name="roles")
        public class Role implements Serializable {
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        private String obser;
        public Role() {
            super();
        }

    public Role(Integer id, String obser) {
        super();
        this.id = id;
        this.obser = obser;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getObser() {
        return obser;
    }

    public void setObser(String obser) {
        this.obser = obser;
    }}

    @Entity
    @Table(name="users")
    public class User implements Serializable{

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private Boolean active;
    private String email;

      @ManyToMany
      @JoinTable(name="USERS_ROLES",
              joinColumns={@JoinColumn(name="username", referencedColumnName="username")},
               inverseJoinColumns={@JoinColumn(name="obser", referencedColumnName="obser")}

              )
    private Collection<Role>roles;
    public Collection<Role> getRoles() {
        return roles;
    }
    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }
    public User() {
        super();
    }
    public User(Integer id,String username, String password, Boolean active, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.active = active;
        this.email = email;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Boolean getActive() {
        return active;
    }
    public void setActive(Boolean active) {
        this.active = active;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }}

**here is y Role RoleRepository:**

    public interface RoleRepository extends JpaRepository<Role, Integer> {
        List<Role> findAll();
        Role findByObser(String obser);
    }

**here is my User RoleRepository:**

    public interface UserRepository extends JpaRepository<User, Integer> {
        User findByUsername(String username);
    }

**here is my function AddRoleToUser in  my UserService:**
**When I want to add a role to a user, I use this method**

    @RequestMapping(value="/addRoleToUser")
    public User addRoleToUser(String username, String role) {
        User u = userRepository.findByUsername(username);
        Role r = roleRepository.findByObser(role);

      u.getRoles().add(r);
              userRepository.save(u);
            return u;
    }
</code>```

Unfortunately, it does not assign the role to the user and it creates an exception of type:
query did not return a unique result: 3; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 3
then I ask if there is someone who can help me
the other method like add role, add user its mace its problem

答: This might  be because you might have more then one user with same username, so either you can set username as unique or use user_id for all the transactions or persistence.

Body:
**hi big community! someone can help me**
 **here: Role entity**

        @Entity
        @Table(name="roles")
        public class Role implements Serializable {
        @Id @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        private String obser;
        public Role() {
            super();
        }

    public Role(Integer id, String obser) {
        super();
        this.id = id;
        this.obser = obser;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getObser() {
        return obser;
    }

    public void setObser(String obser) {
        this.obser = obser;
    }}

    @Entity
    @Table(name="users")
    public class User implements Serializable{

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private Boolean active;
    private String email;

      @ManyToMany
      @JoinTable(name="USERS_ROLES",
              joinColumns={@JoinColumn(name="username", referencedColumnName="username")},
               inverseJoinColumns={@JoinColumn(name="obser", referencedColumnName="obser")}

              )
    private Collection<Role>roles;
    public Collection<Role> getRoles() {
        return roles;
    }
    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }
    public User() {
        super();
    }
    public User(Integer id,String username, String password, Boolean active, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.active = active;
        this.email = email;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Boolean getActive() {
        return active;
    }
    public void setActive(Boolean active) {
        this.active = active;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }}

**here is y Role RoleRepository:**

    public interface RoleRepository extends JpaRepository<Role, Integer> {
        List<Role> findAll();
        Role findByObser(String obser);
    }

**here is my User RoleRepository:**

    public interface UserRepository extends JpaRepository<User, Integer> {
        User findByUsername(String username);
    }

**here is my function AddRoleToUser in  my UserService:**
**When I want to add a role to a user, I use this method**

    @RequestMapping(value="/addRoleToUser")
    public User addRoleToUser(String username, String role) {
        User u = userRepository.findByUsername(username);
        Role r = roleRepository.findByObser(role);

      u.getRoles().add(r);
              userRepository.save(u);
            return u;
    }

Unfortunately, it does not assign the role to the user and it creates an exception of type:
query did not return a unique result: 3; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 3
then I ask if there is someone who can help me
the other method like add role, add user its mace its problem


问:
Grouping data in ChartJS and PHP
Hi have a data table which i am trying to draw a graph of using ChartJS. The data array looks like below

```<code>Array
(
    [0] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P1
            [Count] => 7
        )

    [1] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P2
            [Count] => 3
        )

    [2] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P3
            [Count] => 4
        )

    [3] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P4
            [Count] => 3
        )

    [4] => Array
        (
            [Sort] => 3
            [Weeks] => 2-3 weeks
            [Severity] => P1
            [Count] => 1
        )

    [5] => Array
        (
            [Sort] => 4
            [Weeks] => >4 weeks
            [Severity] => No Value
            [Count] => 1
        )

    [6] => Array
        (
            [Sort] => 4
            [Weeks] => >4 weeks
            [Severity] => P1
            [Count] => 1
        )

    [7] => Array
        (
            [Sort] => 4
            [Weeks] => >4 weeks
            [Severity] => P3
            [Count] => 1
        )

)
</code>```

I converted that array compatible with ChartJS like below

```<code>Array
(
    [labels] => Array
        (
            [0] => >4 weeks
            [1] => 2-3 weeks
            [2] => 1-2 Weeks
        )

    [datasets] => Array
        (
            [0] => Array
                (
                    [label] => No Value
                    [backgroundColor] => #F00
                    [borderColor] => #F00
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 1
                        )

                )

            [1] => Array
                (
                    [label] => P1
                    [backgroundColor] => #84a4d4
                    [borderColor] => #84a4d4
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 1
                            [1] => 1
                            [2] => 7
                        )

                )

            [2] => Array
                (
                    [label] => P3
                    [backgroundColor] => #eb8d22
                    [borderColor] => #eb8d22
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 1
                            [1] => 4
                        )

                )

            [3] => Array
                (
                    [label] => P2
                    [backgroundColor] => #FBCEB1
                    [borderColor] => #FBCEB1
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 3
                        )

                )

            [4] => Array
                (
                    [label] => P4
                    [backgroundColor] => #7FFFD4
                    [borderColor] => #7FFFD4
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 3
                        )

                )

        )

)
</code>```

But the data gets scrambled when it is plotted to Chart. The data gets arranged like this

This is the real data and how the graph should look like

Here is my code

```<code>function chart(){
        $ar= RNCPHP\AnalyticsReport::fetch('Open tickets Ageing by priority');
        $arr= $ar->run(0, $filters);

        $chartInit  =   array();
        $chartArr['data']   =   array();

        // push the report data into an array
        for ( $ii = $arr->count(); $ii--; ) {
            $row = $arr->next();

            if($row['Severity'] == null || $row['Severity'] == "") {
                $row['Severity']    =   "No Value";
            }

            $row['Sort']    =   $row['Sort'];

            array_push($chartInit, $row);
        }
        echo "```";
        print_r($chartInit);

        array_multisort(array_map(function($element) {
            return $element['Sort'];
        }, $chartInit), SORT_DESC, $chartInit);

        $chartDataArr   =   array();
        $sevArr =   array();

        foreach($chartInit as $k => $v) {
            if(!isset($chartDataArr[$v['Weeks']])) {
                $chartDataArr[$v['Weeks']]  =   array();
            }

            array_push($chartDataArr[$v['Weeks']], $v);

            if(!in_array($v['Severity'], $sevArr)) {
                array_push($sevArr, $v['Severity']);
            }
        }

        $mapLabels  =   array();

        $parsedAry  =   array();
        $parsedAry['labels']    =   array();
        $parsedAry['datasets']  =   array();

        for($i = 0; $i < count($sevArr); $i++) {
            $parsedAry['datasets'][$i]  =   array();

            $parsedAry['datasets'][$i]['label'] =   $sevArr[$i];
            $parsedAry['datasets'][$i]['backgroundColor']   =   $this->getColor($i);
            $parsedAry['datasets'][$i]['borderColor']   =   $this->getColor($i);
            $parsedAry['datasets'][$i]['borderWidth']   =   1;
            $parsedAry['datasets'][$i]['maxBarThickness']   =   50;

            $parsedAry['datasets'][$i]['data']  =   array();
        }

        foreach($chartDataArr as $k => $v) {
            array_push($parsedAry['labels'], $k);

            foreach($v as $k1 => $v1) {
                $keySev =   "";
                foreach($parsedAry['datasets'] as $k2 => $v2) {
                    if($v2['label'] == $v1['Severity']) {
                        $keySev =   $k2;
                    }
                }

                if($v1['Count'] == null || $v1['Count'] == "") {
                    $v1['Count']    =   0;
                }

                array_push($parsedAry['datasets'][$keySev]['data'], $v1['Count']);
            }
        }

        echo "```";
        print_r($parsedAry);
        echo "```";

        $chartArr['data']   =   $parsedAry;

        return $chartArr;
    }
```

<p>In my view page i'm displaying data with ChartJS Function</p>

```<canvas id="chart6"></canvas>

```

Please Help.

答:
Your code has several problems.

First, your datasets should has data in numbers of labels so you can't ignore empty places without filling them. To fix this problem you need to change
$parsedAry['datasets'][$i]['data']  =   array(); to $parsedAry['datasets'][$i]['data'] = array(0, 0, 0, 0, 0);

This will add 5 empty spot in your datasets.

Second you have to put numbers in right places for this one you have to add a counter for your last loop to identify right places.

Finally your code should look like this.

```<code>function chart()
{
    $ar = RNCPHP\AnalyticsReport::fetch('Open tickets Ageing by priority');
    $arr = $ar->run(0, $filters);

    $chartInit = array();
    $chartArr['data'] = array();

    // push the report data into an array
    for ($ii = $arr->count(); $ii--;) {
        $row = $arr->next();

        if ($row['Severity'] == null || $row['Severity'] == "") {
            $row['Severity'] = "No Value";
        }

        $row['Sort'] = $row['Sort'];

        array_push($chartInit, $row);
    }
    echo "```";
    print_r($chartInit);

    array_multisort(array_map(function ($element) {
        return $element['Sort'];
    }, $chartInit), SORT_DESC, $chartInit);

    $chartDataArr = array();
    $sevArr = array();

    foreach ($chartInit as $k => $v) {
        if (!isset($chartDataArr[$v['Weeks']])) {
            $chartDataArr[$v['Weeks']] = array();
        }

        array_push($chartDataArr[$v['Weeks']], $v);

        if (!in_array($v['Severity'], $sevArr)) {
            array_push($sevArr, $v['Severity']);
        }
    }

    $mapLabels = array();

    $parsedAry = array();
    $parsedAry['labels'] = array();
    $parsedAry['datasets'] = array();

    for ($i = 0; $i < count($sevArr); $i++) {
        $parsedAry['datasets'][$i] = array();

        $parsedAry['datasets'][$i]['label'] = $sevArr[$i];
        $parsedAry['datasets'][$i]['backgroundColor'] = $this->getColor($i);
        $parsedAry['datasets'][$i]['borderColor'] = $this->getColor($i);
        $parsedAry['datasets'][$i]['borderWidth'] = 1;
        $parsedAry['datasets'][$i]['maxBarThickness'] = 50;

        $parsedAry['datasets'][$i]['data'] = array(0, 0, 0, 0, 0);
    }

    $labelsNo = 0;
    foreach ($chartDataArr as $k => $v) {
        array_push($parsedAry['labels'], $k);

        foreach ($v as $k1 => $v1) {
            $keySev = "";
            foreach ($parsedAry['datasets'] as $k2 => $v2) {
                if ($v2['label'] == $v1['Severity']) {
                    $keySev = $k2;
                }
            }

            if ($v1['Count'] == null || $v1['Count'] == "") {
                $v1['Count'] = 0;
            }

            $parsedAry['datasets'][$keySev]['data'][$labelsNo] = $v1['Count'];
        }
        $labelsNo++;
    }

    echo "```";
    print_r($parsedAry);
    echo "```";

    $chartArr['data'] = $parsedAry;

    return $chartArr;
}
```

Title: Grouping data in ChartJS and PHP

Body:
Hi have a data table which i am trying to draw a graph of using ChartJS. The data array looks like below

Array
(
    [0] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P1
            [Count] => 7
        )

    [1] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P2
            [Count] => 3
        )

    [2] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P3
            [Count] => 4
        )

    [3] => Array
        (
            [Sort] => 2
            [Weeks] => 1-2 Weeks
            [Severity] => P4
            [Count] => 3
        )

    [4] => Array
        (
            [Sort] => 3
            [Weeks] => 2-3 weeks
            [Severity] => P1
            [Count] => 1
        )

    [5] => Array
        (
            [Sort] => 4
            [Weeks] => >4 weeks
            [Severity] => No Value
            [Count] => 1
        )

    [6] => Array
        (
            [Sort] => 4
            [Weeks] => >4 weeks
            [Severity] => P1
            [Count] => 1
        )

    [7] => Array
        (
            [Sort] => 4
            [Weeks] => >4 weeks
            [Severity] => P3
            [Count] => 1
        )

)

I converted that array compatible with ChartJS like below

Array
(
    [labels] => Array
        (
            [0] => >4 weeks
            [1] => 2-3 weeks
            [2] => 1-2 Weeks
        )

    [datasets] => Array
        (
            [0] => Array
                (
                    [label] => No Value
                    [backgroundColor] => #F00
                    [borderColor] => #F00
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 1
                        )

                )

            [1] => Array
                (
                    [label] => P1
                    [backgroundColor] => #84a4d4
                    [borderColor] => #84a4d4
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 1
                            [1] => 1
                            [2] => 7
                        )

                )

            [2] => Array
                (
                    [label] => P3
                    [backgroundColor] => #eb8d22
                    [borderColor] => #eb8d22
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 1
                            [1] => 4
                        )

                )

            [3] => Array
                (
                    [label] => P2
                    [backgroundColor] => #FBCEB1
                    [borderColor] => #FBCEB1
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 3
                        )

                )

            [4] => Array
                (
                    [label] => P4
                    [backgroundColor] => #7FFFD4
                    [borderColor] => #7FFFD4
                    [borderWidth] => 1
                    [maxBarThickness] => 50
                    [data] => Array
                        (
                            [0] => 3
                        )

                )

        )

)

But the data gets scrambled when it is plotted to Chart. The data gets arranged like this

This is the real data and how the graph should look like

Here is my code

function chart(){
        $ar= RNCPHP\AnalyticsReport::fetch('Open tickets Ageing by priority');
        $arr= $ar->run(0, $filters);

        $chartInit  =   array();
        $chartArr['data']   =   array();

        // push the report data into an array
        for ( $ii = $arr->count(); $ii--; ) {
            $row = $arr->next();

            if($row['Severity'] == null || $row['Severity'] == "") {
                $row['Severity']    =   "No Value";
            }

            $row['Sort']    =   $row['Sort'];

            array_push($chartInit, $row);
        }
        echo "
";
        print_r($chartInit);

        array_multisort(array_map(function($element) {
            return $element['Sort'];
        }, $chartInit), SORT_DESC, $chartInit);

        $chartDataArr   =   array();
        $sevArr =   array();

        foreach($chartInit as $k => $v) {
            if(!isset($chartDataArr[$v['Weeks']])) {
                $chartDataArr[$v['Weeks']]  =   array();
            }

            array_push($chartDataArr[$v['Weeks']], $v);

            if(!in_array($v['Severity'], $sevArr)) {
                array_push($sevArr, $v['Severity']);
            }
        }

        $mapLabels  =   array();

        $parsedAry  =   array();
        $parsedAry['labels']    =   array();
        $parsedAry['datasets']  =   array();

        for($i = 0; $i < count($sevArr); $i++) {
            $parsedAry['datasets'][$i]  =   array();

            $parsedAry['datasets'][$i]['label'] =   $sevArr[$i];
            $parsedAry['datasets'][$i]['backgroundColor']   =   $this->getColor($i);
            $parsedAry['datasets'][$i]['borderColor']   =   $this->getColor($i);
            $parsedAry['datasets'][$i]['borderWidth']   =   1;
            $parsedAry['datasets'][$i]['maxBarThickness']   =   50;

            $parsedAry['datasets'][$i]['data']  =   array();
        }

        foreach($chartDataArr as $k => $v) {
            array_push($parsedAry['labels'], $k);

            foreach($v as $k1 => $v1) {
                $keySev =   "";
                foreach($parsedAry['datasets'] as $k2 => $v2) {
                    if($v2['label'] == $v1['Severity']) {
                        $keySev =   $k2;
                    }
                }

                if($v1['Count'] == null || $v1['Count'] == "") {
                    $v1['Count']    =   0;
                }

                array_push($parsedAry['datasets'][$keySev]['data'], $v1['Count']);
            }
        }

        echo "
";
        print_r($parsedAry);
        echo "
";

        $chartArr['data']   =   $parsedAry;

        return $chartArr;
    }

In my view page i'm displaying data with ChartJS Function

<canvas id="chart6"></canvas>

Please Help.

Body:
Your code has several problems.

First, your datasets should has data in numbers of labels so you can't ignore empty places without filling them. To fix this problem you need to change
$parsedAry['datasets'][$i]['data']  =   array(); to $parsedAry['datasets'][$i]['data'] = array(0, 0, 0, 0, 0);

This will add 5 empty spot in your datasets.

Second you have to put numbers in right places for this one you have to add a counter for your last loop to identify right places.

Finally your code should look like this.

function chart()
{
    $ar = RNCPHP\AnalyticsReport::fetch('Open tickets Ageing by priority');
    $arr = $ar->run(0, $filters);

    $chartInit = array();
    $chartArr['data'] = array();

    // push the report data into an array
    for ($ii = $arr->count(); $ii--;) {
        $row = $arr->next();

        if ($row['Severity'] == null || $row['Severity'] == "") {
            $row['Severity'] = "No Value";
        }

        $row['Sort'] = $row['Sort'];

        array_push($chartInit, $row);
    }
    echo "<pre>";
    print_r($chartInit);

    array_multisort(array_map(function ($element) {
        return $element['Sort'];
    }, $chartInit), SORT_DESC, $chartInit);

    $chartDataArr = array();
    $sevArr = array();

    foreach ($chartInit as $k => $v) {
        if (!isset($chartDataArr[$v['Weeks']])) {
            $chartDataArr[$v['Weeks']] = array();
        }

        array_push($chartDataArr[$v['Weeks']], $v);

        if (!in_array($v['Severity'], $sevArr)) {
            array_push($sevArr, $v['Severity']);
        }
    }

    $mapLabels = array();

    $parsedAry = array();
    $parsedAry['labels'] = array();
    $parsedAry['datasets'] = array();

    for ($i = 0; $i < count($sevArr); $i++) {
        $parsedAry['datasets'][$i] = array();

        $parsedAry['datasets'][$i]['label'] = $sevArr[$i];
        $parsedAry['datasets'][$i]['backgroundColor'] = $this->getColor($i);
        $parsedAry['datasets'][$i]['borderColor'] = $this->getColor($i);
        $parsedAry['datasets'][$i]['borderWidth'] = 1;
        $parsedAry['datasets'][$i]['maxBarThickness'] = 50;

        $parsedAry['datasets'][$i]['data'] = array(0, 0, 0, 0, 0);
    }

    $labelsNo = 0;
    foreach ($chartDataArr as $k => $v) {
        array_push($parsedAry['labels'], $k);

        foreach ($v as $k1 => $v1) {
            $keySev = "";
            foreach ($parsedAry['datasets'] as $k2 => $v2) {
                if ($v2['label'] == $v1['Severity']) {
                    $keySev = $k2;
                }
            }

            if ($v1['Count'] == null || $v1['Count'] == "") {
                $v1['Count'] = 0;
            }

            $parsedAry['datasets'][$keySev]['data'][$labelsNo] = $v1['Count'];
        }
        $labelsNo++;
    }

    echo "<pre>";
    print_r($parsedAry);
    echo "</pre>";

    $chartArr['data'] = $parsedAry;

    return $chartArr;
}


答:
I believe you need this:

```<code>select CASE WHEN D.DEGREE_HIERARCHY >= 40 THEN
                 cast('Yes' as varchar(20))
            WHEN D.DEGREE_HIERARCHY < 40 THEN
                 cast('No' as varchar(20))
            WHEN D.DEGREE_HIERARCHY IS NULL THEN
                 cast('Unknown' as varchar(20))
            ELSE
                 NULL
       END name_of_column -- Here the case clause ends and you can name the column
FROM DEGREE_CROSSWALK D --add other tables and join condition here
WHERE --add other conditions of the where clause
</code>```

Also I suggest you do not join tables like this:

```<code>FROM DEGREE_CROSSWALK D, VPAA V
WHERE V.FACULTY_DEGREE_CODE = D.DEGREE_CODE
</code>```

but like this(just an example):

```<code>FROM DEGREE_CROSSWALK D
JOIN VPAA V ON V.FACULTY_DEGREE_CODE = D.DEGREE_CODE
</code>```

Title: Cast and Case statement with query in Oracle SQL

Body:
I believe you need this:

select CASE WHEN D.DEGREE_HIERARCHY >= 40 THEN
                 cast('Yes' as varchar(20))
            WHEN D.DEGREE_HIERARCHY < 40 THEN
                 cast('No' as varchar(20))
            WHEN D.DEGREE_HIERARCHY IS NULL THEN
                 cast('Unknown' as varchar(20))
            ELSE
                 NULL
       END name_of_column -- Here the case clause ends and you can name the column
FROM DEGREE_CROSSWALK D --add other tables and join condition here
WHERE --add other conditions of the where clause

Also I suggest you do not join tables like this:

FROM DEGREE_CROSSWALK D, VPAA V
WHERE V.FACULTY_DEGREE_CODE = D.DEGREE_CODE

but like this(just an example):

FROM DEGREE_CROSSWALK D
JOIN VPAA V ON V.FACULTY_DEGREE_CODE = D.DEGREE_CODE


问:
Add Autocomplete Address
Add Autocomplete Address

I have a problem with the code.
No results found

I'm doing a job application form.

Controller

```<code>public JsonResult Getprovinces()
    {
        List<mydistrict> provincel = new List<mydistrict>();
        provincel = (from p in _auc.mytable
                     select p).ToList();

        return Json(provincel);
    }

    public JsonResult Getamphoes(int province_code)
    {
        List<mydistrict> amphoelist = new List<mydistrict>();

        amphoelist = (from Provinces in _auc.mytable
                            where Provinces.province_code == province_code

                      select Provinces).ToList();
        return Json(amphoelist);
    }
    public JsonResult Getdistrict(int province_code, string amphoe_code)
    {
        List<mydistrict> districtslist = new List<mydistrict>();

        districtslist = (from district in _auc.mytable
                         where district.province_code == province_code
                         where district.amphoe_code == amphoe_code
                         select district).ToList();
        return Json(districtslist);
    }

    public JsonResult detail(int province_code, string amphoe_code,string district_code)
    {
        List<mydistrict> detail = new List<mydistrict>();

        detail = (from de in _auc.mytable
                         where de.province_code == province_code
                         where de.amphoe_code == amphoe_code
                  where de.district_code == district_code
                  select de).ToList();
        return Json(detail);
    }
</code>```

view

```<code><select id="mydistrict_province" onchange="showAmphoes()" class="form-control">
    <option value=""></option>
</select><br />
<select id="mydistrict_amphoe" onchange="showDistricts()" class="form-control">
    <option value=""></option>
</select><br />
 <select id="mydistrict_district" onchange="showZipcode()" class="form-control">
    <option value=""></option>
</select><br />
<input id="mydistrict_zipcode" class="form-control" />
</code>```

script

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

    showProvinces();

});

function showProvinces() {
    var url = '@Url.Content("~/")' + "Employee/Getprovinces";
    var callback = function (result) {
        $("#mydistrict_province").empty();
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_province").append(
                $('<option></option>')
                    .attr("value", "" + result[i].province_code)
                    .html("" + result[i].province)
            );
        }
        showAmphoes();
    };
    ajax(url, callback);
}

function showAmphoes() {
    var province_code = $("#mydistrict_province").val();
    var url = '@Url.Content("~/")' + "Employee/Getamphoes";
    var callback = function (result) {
        console.log(result);
        $("#mydistrict_amphoe").empty();
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_amphoe").append(
                $('<option></option>')
                    .attr("value", "" + result[i].amphoe_code)
                    .html("" + result[i].amphoe)
            );
        }
        showDistricts();
    };
    ajax(url, callback);
}

function showDistricts() {
    var province_code = $("#mydistrict_province").val();
    var amphoe_code = $("#mydistrict_amphoe").val();
    var url = '@Url.Content("~/")' + "Employee/Getdistrict";
    var callback = function (result) {
        $("#mydistrict_district").empty();
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_district").append(
                $('<option></option>')
                    .attr("value", "" + result[i].district_code)
                    .html("" + result[i].district)
            );
        }
        showZipcode();
    };
    ajax(url, callback);
}

function showZipcode() {
    var province_code = $("#mydistrict_province").val();
    var amphoe_code = $("#mydistrict_amphoe").val();
    var district_code = $("#mydistrict_district").val();
    var url = '@Url.Content("~/")' + "Employee/Getdetail";
    var callback = function (result) {
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_zipcode").val(result[i].zipcode);
        }
    };
    ajax(url, callback);
}

function ajax(url, callback) {
    $.ajax({
        "url": url,
        "type": "GET",
        "dataType": "json",
    })
        .done(callback);
}
</code>```

Result
enter image description here

Help me please, Thanks

答:
Your problem is that you don't send any parameter to your method so you can use below code to send parameter for showAmphoes:

```<code> var url = '@Url.Action("Getamphoes","Employee")' + '/?province_code=' + province_code;
</code>```

and for showDistricts:

```<code>var url = '@Url.Action("Getdistrict", "Employee")' + '/?province_code=' + province_code + '&amphoe_code=' + amphoe_code;
</code>```

Title: Add Autocomplete Address

Body:
Add Autocomplete Address

I have a problem with the code.
No results found

I'm doing a job application form.

Controller

public JsonResult Getprovinces()
    {
        List<mydistrict> provincel = new List<mydistrict>();
        provincel = (from p in _auc.mytable
                     select p).ToList();

        return Json(provincel);
    }

    public JsonResult Getamphoes(int province_code)
    {
        List<mydistrict> amphoelist = new List<mydistrict>();

        amphoelist = (from Provinces in _auc.mytable
                            where Provinces.province_code == province_code

                      select Provinces).ToList();
        return Json(amphoelist);
    }
    public JsonResult Getdistrict(int province_code, string amphoe_code)
    {
        List<mydistrict> districtslist = new List<mydistrict>();

        districtslist = (from district in _auc.mytable
                         where district.province_code == province_code
                         where district.amphoe_code == amphoe_code
                         select district).ToList();
        return Json(districtslist);
    }

    public JsonResult detail(int province_code, string amphoe_code,string district_code)
    {
        List<mydistrict> detail = new List<mydistrict>();

        detail = (from de in _auc.mytable
                         where de.province_code == province_code
                         where de.amphoe_code == amphoe_code
                  where de.district_code == district_code
                  select de).ToList();
        return Json(detail);
    }

view

<select id="mydistrict_province" onchange="showAmphoes()" class="form-control">
    <option value=""></option>
</select>

<select id="mydistrict_amphoe" onchange="showDistricts()" class="form-control">
    <option value=""></option>
</select>

 <select id="mydistrict_district" onchange="showZipcode()" class="form-control">
    <option value=""></option>
</select>

<input id="mydistrict_zipcode" class="form-control" />

script

$(document).ready(function () {

    showProvinces();

});

function showProvinces() {
    var url = '@Url.Content("~/")' + "Employee/Getprovinces";
    var callback = function (result) {
        $("#mydistrict_province").empty();
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_province").append(
                $('<option></option>')
                    .attr("value", "" + result[i].province_code)
                    .html("" + result[i].province)
            );
        }
        showAmphoes();
    };
    ajax(url, callback);
}

function showAmphoes() {
    var province_code = $("#mydistrict_province").val();
    var url = '@Url.Content("~/")' + "Employee/Getamphoes";
    var callback = function (result) {
        console.log(result);
        $("#mydistrict_amphoe").empty();
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_amphoe").append(
                $('<option></option>')
                    .attr("value", "" + result[i].amphoe_code)
                    .html("" + result[i].amphoe)
            );
        }
        showDistricts();
    };
    ajax(url, callback);
}

function showDistricts() {
    var province_code = $("#mydistrict_province").val();
    var amphoe_code = $("#mydistrict_amphoe").val();
    var url = '@Url.Content("~/")' + "Employee/Getdistrict";
    var callback = function (result) {
        $("#mydistrict_district").empty();
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_district").append(
                $('<option></option>')
                    .attr("value", "" + result[i].district_code)
                    .html("" + result[i].district)
            );
        }
        showZipcode();
    };
    ajax(url, callback);
}

function showZipcode() {
    var province_code = $("#mydistrict_province").val();
    var amphoe_code = $("#mydistrict_amphoe").val();
    var district_code = $("#mydistrict_district").val();
    var url = '@Url.Content("~/")' + "Employee/Getdetail";
    var callback = function (result) {
        for (var i = 0; i < result.length; i++) {
            $("#mydistrict_zipcode").val(result[i].zipcode);
        }
    };
    ajax(url, callback);
}

function ajax(url, callback) {
    $.ajax({
        "url": url,
        "type": "GET",
        "dataType": "json",
    })
        .done(callback);
}

Result
enter image description here

Help me please, Thanks

Body:
Your problem is that you don't send any parameter to your method so you can use below code to send parameter for showAmphoes:

 var url = '@Url.Action("Getamphoes","Employee")' + '/?province_code=' + province_code;

and for showDistricts:

var url = '@Url.Action("Getdistrict", "Employee")' + '/?province_code=' + province_code + '&amphoe_code=' + amphoe_code;


问:
How to get grid cell value given column name in jquery for kendo grid
Is there a equivalent for below code in kendo grid:

```<code>var gridCell = $('.grid-row-selected td.grid-cell[data-name= ' + columnName + ']');
</code>```

Above code is for the mvc grid, where it automatically gives HTML tag on grid-row-selected on selecting a cell.

答:
If anyone still looking for an answer then you can try using following steps:

First get specific row from which you want to get value of specific
column by name. In my requirement found row using row's UID with
specific column class name.

```<code>var grid = $("#grid").data("kendoGrid");
var row = grid.dataSource.getByUid("your-row-uid");
</code>```

And at last get your selected row specific cell value by it's class
name.

$(row).find("td.column_className").text();

Body:
Is there a equivalent for below code in kendo grid:

var gridCell = $('.grid-row-selected td.grid-cell[data-name= ' + columnName + ']');

Above code is for the mvc grid, where it automatically gives HTML tag on grid-row-selected on selecting a cell.

Body:
If anyone still looking for an answer then you can try using following steps:

First get specific row from which you want to get value of specific
column by name. In my requirement found row using row's UID with
specific column class name.

var grid = $("#grid").data("kendoGrid");
var row = grid.dataSource.getByUid("your-row-uid");

And at last get your selected row specific cell value by it's class
name.

$(row).find("td.column_className").text();


问:
Unable to install wsgiref in python 3.x
I can't install wsgiref in python 3. I got these errors.
I am using python 3, but I can't install wsgiref
I tried pip install wsgiref and pip install wsgiref==0.1.2

```<code>E:\CodeWork\Machine Learning\SWATI-The-Assistant-master\SWATI-The-Assistant-master>pip install wsgiref==0.1.2
Collecting wsgiref==0.1.2
  Using cached https://files.pythonhosted.org/packages/41/9e/309259ce8dff8c596e8c26df86dbc4e848b9249fd36797fd60be456f03fc/wsgiref-0.1.2.zip
    ERROR: Command errored out with exit status 1:
     command: 'c:\program files\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-h2ydr_0e\\wsgiref\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-h2ydr_0e\\wsgiref\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\pip-egg-info'
         cwd: C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\setup.py", line 5, in <module>
        import ez_setup
      File "C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\ez_setup\__init__.py", line 170
        print "Setuptools version",version,"or greater has been installed."
                                 ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Setuptools version",version,"or greater has been installed.")?
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.```
```

答: The reason the pip 3 install is erroring is the syntax of one of the print statements in the setup process is old python 2 style with no parentheses. The good news is that wsgiref is already included in the python 3 library by default. Fire up a python 3 shell and try typing 'import wsgiref', that should succeed with no error.</p>

Title: Unable to install wsgiref in python 3.x

Body:
I can't install wsgiref in python 3. I got these errors.
I am using python 3, but I can't install wsgiref
I tried pip install wsgiref and pip install wsgiref==0.1.2

E:\CodeWork\Machine Learning\SWATI-The-Assistant-master\SWATI-The-Assistant-master>pip install wsgiref==0.1.2
Collecting wsgiref==0.1.2
  Using cached https://files.pythonhosted.org/packages/41/9e/309259ce8dff8c596e8c26df86dbc4e848b9249fd36797fd60be456f03fc/wsgiref-0.1.2.zip
    ERROR: Command errored out with exit status 1:
     command: 'c:\program files\python37\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-h2ydr_0e\\wsgiref\\setup.py'"'"'; __file__='"'"'C:\\Users\\hp\\AppData\\Local\\Temp\\pip-install-h2ydr_0e\\wsgiref\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\pip-egg-info'
         cwd: C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\setup.py", line 5, in <module>
        import ez_setup
      File "C:\Users\hp\AppData\Local\Temp\pip-install-h2ydr_0e\wsgiref\ez_setup\__init__.py", line 170
        print "Setuptools version",version,"or greater has been installed."
                                 ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Setuptools version",version,"or greater has been installed.")?
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.```


问:
how to do unit test elegant on graph operator
I have a application deal with graph computation. I want cover unit test on to it, but I found it is hard to do the test.

The main class is shown as follows:

Grid store the graph strcture

GridInput parse inputfile and save into Grid.

GridOperatorA do some operation on Grid.

GridOperatorB do some operation on Grid.

the production code is some thing like

```<code>string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
GridOperatorA a;
a.operator(grid);
GridOpeartorB b;
b.operator(grid);
</code>```

I found the code is hard to test.

My unit test code shown as follow

```<code>// unit test for grid input
string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
// check grid status from input file
assert(grid.someAttribute(1) == {1,2,3,4,...,100}); // long int array hard to understand
...
assert(grid.someAttribute(5) == {100,101,102,...,200}); // long int array hard to understand
</code>```

```<code>// unit test for operator A
string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
GridOperatorA a;
a.operator(grid);
// check grid status after opeator A
assert(grid.someAttribute(1) == {1,3,,7,4,...,46}); // long int array hard to understand
...
assert(grid.someAttribute(5) == {59,78,...,32}); // long int array hard to understand
</code>```

```<code>// unit test for operator B
string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
GridOperatorA a;
a.operator(grid);
GridOperatorA b;
b.operator(grid);
// check grid status after opeator B
assert(grid.someAttribute(1) == {3,2,7,9,...,23}); // long int array hard to understand
...
assert(grid.someAttribute(5) == {38,76,...,13}); // long int array hard to understand
</code>```

In my option, my unit test is not good, it have many backness

the unit test is slow, in order to test OperatorA,OperatorB it need to do file IO

the unit test is not clear, they need to check the grid status after operator, but check a lot of array is hard for programmer to understand what the array stand for. a few days later, programmer can not understand what have happened.

the unit test is only for one configure file, if I need to test grid from many configure file, there will be even more array hard to understand.

I have read some technique to break dependency, such as mock object. I can mock the grid read from configure file. But the mock data is just like the data store in configure file. I can mock the Grid after operatorA, but the mock data is just like the grid status after operatorA. They will also leads to a lot of array hard to understand.

I do not know how to do unit test elegant in my situation. Any voice is appreciate. Thanks for your time.

答:
To get rid of the io

you can pass something like a data provider to GridInput. In you production code it will read the file. In test code you can replace it with a test double (stub) that does provide hardcoded data. You already mention that above.

you could also let "someone else" (i.e. other code) take care of loading the file and just pass the loaded data to the grid. Just looking at the Grid, testing gets simpler because there is no file handling required at all.

To make the test more readable you can do some of this:

use nice test method names that are not just testMethod. Name them after what you are testing. You could use your comments as method names. Test only one aspect in a single test.

replace the inline array with properly named constants. The name of the constants can help to understand what is checked at a given assertion.

same holds for the parameters to the someAttribute() method.

another option is to create you own assert methods to hide some of the details. Something like assertThatMySpecialConditionIsMet(grid).

You could also write a test data generator to avoid hardcoding the arrays. Not something i would suggest for the first test. After a couple of tests a pattern ight get visible that can be moved to a generator.

Just a couple of hints to get you started.... :-)

Body:
I have a application deal with graph computation. I want cover unit test on to it, but I found it is hard to do the test.

The main class is shown as follows:

Grid store the graph strcture

GridInput parse inputfile and save into Grid.

GridOperatorA do some operation on Grid.

GridOperatorB do some operation on Grid.

the production code is some thing like

string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
GridOperatorA a;
a.operator(grid);
GridOpeartorB b;
b.operator(grid);

I found the code is hard to test.

My unit test code shown as follow

// unit test for grid input
string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
// check grid status from input file
assert(grid.someAttribute(1) == {1,2,3,4,...,100}); // long int array hard to understand
...
assert(grid.someAttribute(5) == {100,101,102,...,200}); // long int array hard to understand

// unit test for operator A
string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
GridOperatorA a;
a.operator(grid);
// check grid status after opeator A
assert(grid.someAttribute(1) == {1,3,,7,4,...,46}); // long int array hard to understand
...
assert(grid.someAttribute(5) == {59,78,...,32}); // long int array hard to understand

// unit test for operator B
string configure_file = "data.txt";
GridInput input(configure_file);
Grid grid = input.parseGrid();
GridOperatorA a;
a.operator(grid);
GridOperatorA b;
b.operator(grid);
// check grid status after opeator B
assert(grid.someAttribute(1) == {3,2,7,9,...,23}); // long int array hard to understand
...
assert(grid.someAttribute(5) == {38,76,...,13}); // long int array hard to understand

In my option, my unit test is not good, it have many backness

the unit test is slow, in order to test OperatorA,OperatorB it need to do file IO

the unit test is not clear, they need to check the grid status after operator, but check a lot of array is hard for programmer to understand what the array stand for. a few days later, programmer can not understand what have happened.

the unit test is only for one configure file, if I need to test grid from many configure file, there will be even more array hard to understand.

I have read some technique to break dependency, such as mock object. I can mock the grid read from configure file. But the mock data is just like the data store in configure file. I can mock the Grid after operatorA, but the mock data is just like the grid status after operatorA. They will also leads to a lot of array hard to understand.

I do not know how to do unit test elegant in my situation. Any voice is appreciate. Thanks for your time.


问:
Use NumPy cleverly to speed up this loop
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

```<code>M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])
</code>```

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

答:
I tried to move computation out of the loop. It seems that the bottom expression is a simple matrix substraction so I took it out entirely.

```<code>sqrt_dt = np.sqrt(dt)
A = 0.5*(sigma_Z**2)*dt
B = sigma_Z* sqrt_dt
C = sigma_Y * sqrt_dt * (rho*Wt_1 + np.sqrt(1 - rho**2)*Wt_2)

Y[:,1:N+1] = Y[:,0:N] - C[:,0:N]

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - A + B  * Wt_1[:,i-1]
</code>```

Hopefully, this helps !

Body:
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

Body:
I tried to move computation out of the loop. It seems that the bottom expression is a simple matrix substraction so I took it out entirely.

sqrt_dt = np.sqrt(dt)
A = 0.5*(sigma_Z**2)*dt
B = sigma_Z* sqrt_dt
C = sigma_Y * sqrt_dt * (rho*Wt_1 + np.sqrt(1 - rho**2)*Wt_2)

Y[:,1:N+1] = Y[:,0:N] - C[:,0:N]

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - A + B  * Wt_1[:,i-1]

Hopefully, this helps !


问:
TypeError: '>' not supported between instances of 'list' and 'int' can't solve with len(list)
I have this simple problem and I have looked similar responses. The problem is that apparently I'm comparing a list with an int and many say that the solution is just to use len(list). The thing is that I did that and the problem stays the same. What is weird though, is that if I change > for < the problem is solved. The thing, of course, is that I need >, not <. If I change the positions of the elements. Happens the other way around.

The exercise is this:

-Make a list with 3 employee names

-Make another list and put in a sublist the days of the month of their absence in the workplace.

-Print the names of the employees and the days he/she were absent
 Show the employee with the quantity of inasistances

-Show the name -or the names- with the employees that were absent less days.

Here is the problem

```<code>employees = ["Nicolás", "Gonzalo", "Tomás"]

absences = [[1, 5, 9], [2], [3, 6, 12, 17]]

for x in range(len(employees)):
    print(employees[x], absences[x])

for x in range(len(employees)):
    print(employees[x], len(absences[x]))

minorposition = 0
less_absences = int(len(absences[0]))
quantity = 1

for x in range(1, len(employees)):
    absences_per_emp = len(absences[x])

    if less_absences > absences_per_emp:              -----> here is the problem
        less_absences = absences[x]
        minorposition = x
    elif less_absences == absences[x]:
        quantity = quantity + 1

if quantity == 1:
    print("The employee with less absences is:")
    print(employees[minorposition])
else:
    print("The employees with minor absences:")
    for x in range(len(employees)):
        if absences[x] == menor:
            print(employees[x])
</code>```

EDIT: Now I discover sth, if I replace the variable with what's on it, the code runs just fine:

```<code>empleados = ["Nicolás", "Gonzalo", "Tomás"]

faltas = [[1, 5, 9], [2], [3, 6, 12, 17]]

posmenor = 0
menor = len(faltas[0])
cantidad = 1

for x in range(1, len(empleados)):
    if menor > len(faltas[x]):              If I change the menor variable here
        menor = faltas[x]                    for len(faltas[0]) the code runs
        posmenor = x                          correctly. Why this happens?
    elif menor == faltas[x]:
        cantidad = cantidad + 1

</code>```

答:
The issue is that you first assign menor to len(faltas[x]) which is an integer, so the first iteration of your for loop will work fine; but then you reassign menor to faltas[x] which is an array. You should instead assign it to len(faltas[x]) as you did the first time:

```<code>for x in range(1, len(empleados)):
    if menor > len(faltas[x]):
        menor = len(faltas[x])
        posmenor = x
    elif menor == faltas[x]:
        cantidad = cantidad + 1
</code>```

Body:
I have this simple problem and I have looked similar responses. The problem is that apparently I'm comparing a list with an int and many say that the solution is just to use len(list). The thing is that I did that and the problem stays the same. What is weird though, is that if I change > for < the problem is solved. The thing, of course, is that I need >, not <. If I change the positions of the elements. Happens the other way around.

The exercise is this:

-Make a list with 3 employee names

-Make another list and put in a sublist the days of the month of their absence in the workplace.

-Print the names of the employees and the days he/she were absent
 Show the employee with the quantity of inasistances

-Show the name -or the names- with the employees that were absent less days.

Here is the problem

employees = ["Nicolás", "Gonzalo", "Tomás"]

absences = [[1, 5, 9], [2], [3, 6, 12, 17]]

for x in range(len(employees)):
    print(employees[x], absences[x])

for x in range(len(employees)):
    print(employees[x], len(absences[x]))

minorposition = 0
less_absences = int(len(absences[0]))
quantity = 1

for x in range(1, len(employees)):
    absences_per_emp = len(absences[x])

    if less_absences > absences_per_emp:              -----> here is the problem
        less_absences = absences[x]
        minorposition = x
    elif less_absences == absences[x]:
        quantity = quantity + 1

if quantity == 1:
    print("The employee with less absences is:")
    print(employees[minorposition])
else:
    print("The employees with minor absences:")
    for x in range(len(employees)):
        if absences[x] == menor:
            print(employees[x])

EDIT: Now I discover sth, if I replace the variable with what's on it, the code runs just fine:

empleados = ["Nicolás", "Gonzalo", "Tomás"]

faltas = [[1, 5, 9], [2], [3, 6, 12, 17]]

posmenor = 0
menor = len(faltas[0])
cantidad = 1

for x in range(1, len(empleados)):
    if menor > len(faltas[x]):              If I change the menor variable here
        menor = faltas[x]                    for len(faltas[0]) the code runs
        posmenor = x                          correctly. Why this happens?
    elif menor == faltas[x]:
        cantidad = cantidad + 1

Body:
The issue is that you first assign menor to len(faltas[x]) which is an integer, so the first iteration of your for loop will work fine; but then you reassign menor to faltas[x] which is an array. You should instead assign it to len(faltas[x]) as you did the first time:

for x in range(1, len(empleados)):
    if menor > len(faltas[x]):
        menor = len(faltas[x])
        posmenor = x
    elif menor == faltas[x]:
        cantidad = cantidad + 1


问:
How can I have access into *argv[ ] in C?
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!</p>

```<code>int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}
</code>```

答:
You don't. As the popular phrase goes, every problem in computer science can be solved by an extra layer of indirection. In this case the indirection is that you define a clean interface for opening a file and pass it a char const*. But this pointer doesn't have to be argv[1].

You have to malloc your own buffer (because none exists) and write to it. Using scanf("%s",...) for this purpose will likely create a buffer overrun as you cannot know in advance how large your buffer needs to be.

Edit: Every single answer given to you suggesting to use char buffer[NUMBER] as the buffer for scanf will blow up in your face.

Body:
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!

int main (int argc, char **argv)
{
    if (argc != 3)
    {
        printf("You did not enter two files.\n");
        printf("You can now enter those two files.\n");
        printf("file 1: ");
        scanf("%s", argv[1]);
        printf("file 2: ");
        scanf("%s ", argv[2]);
    }

    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);

    FILE *file1 = fopen(argv[1], "r");
    FILE *file2 = fopen(argv[2], "r");
}


问:
How to create an incrementing variable with 2 variables in R?
I would like to create an incrementing variable (Id1 or Id2) from 2 others variables (Var1 and Var2).

Thank you.
Elodie

EDIT (reproductible example for Aaron Montgomery)
I want to create an incrementing variable : "Id". The value of "Id" changes if VarA is a new value and if VarB is a new value. See in particular when Id = 4 in the expected table.

```<code>data_example <- data.table::fread("
VarA    VarB
A1  B1
A1  B2
A1  B3
A1  B4
A2  B5
A3  B6
A4  B7
A5  B7
A5  B8
A6  B9
A7  B10
A8  B10
A9  B10")
</code>```

Expected table

```<code>VarA    VarB    Id
A1  B1  1
A1  B2  1
A1  B3  1
A1  B4  1
A2  B5  2
A3  B6  3
A4  B7  4
A5  B7  4
A5  B8  4
A6  B9  5
A7  B10 6
A8  B10 6
A9  B10 6
</code>```

Body:
I would like to create an incrementing variable (Id1 or Id2) from 2 others variables (Var1 and Var2).

Thank you.
Elodie

EDIT (reproductible example for Aaron Montgomery)
I want to create an incrementing variable : "Id". The value of "Id" changes if VarA is a new value and if VarB is a new value. See in particular when Id = 4 in the expected table.

data_example <- data.table::fread("
VarA    VarB
A1  B1
A1  B2
A1  B3
A1  B4
A2  B5
A3  B6
A4  B7
A5  B7
A5  B8
A6  B9
A7  B10
A8  B10
A9  B10")

Expected table

VarA    VarB    Id
A1  B1  1
A1  B2  1
A1  B3  1
A1  B4  1
A2  B5  2
A3  B6  3
A4  B7  4
A5  B7  4
A5  B8  4
A6  B9  5
A7  B10 6
A8  B10 6
A9  B10 6

Body:
Here is one solution using the tidyverse

library(tidyverse)
data_example <- data.table::fread("
Var1    Var2    Id1 Id2
604211  1001    3   1
604211  1093    3   1
604211  1146    3   1
604211  1319    3   1
635348  1002    5   2
634849  1005    5   2
620861  1004    4   3
622281  1004    4   3
622281  1041    4   3
600044  1100    1   4
600049  1033    2   5
607692  1033    2   5
612595  1033    2   5")

data_example %>%
  arrange(Var1,Var2) %>%
  group_by(Var1) %>%
  mutate(id1 = group_indices()) %>%
  group_by(Var2) %>%
  mutate(id2 = group_indices())


问:
How GROUP BY and OVER WINDOW differ in FlinkSQL?
One can use windows in Flink in two different manners

```<code>SELECT key, MAX(value)
  FROM table
 GROUP BY key, TUMBLE(ts, INTERVAL '5' MINUTE)
</code>```

and

```<code>SELECT key, MAX(value) OVER w
  FROM table
 WINDOW w AS (PARTITION BY key ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
</code>```

I wonder if those two mechanisms can express the same thing or what's the main difference and possible use cases for both?

答:
Both queries compute different results that correspond to the semantics of regular SQL. So the difference is not Flink specific but defined by the SQL Standard.

The first query

```<code>SELECT key, MAX(value)
  FROM table
 GROUP BY key, TUMBLE(ts, INTERVAL '5' MINUTE)
</code>```

groups records per key and 5 minute buckets. Every 5 minutes the query produces one row per key value with the maximum value. For each group, multiple rows are aggregated to a single row.

The second query

```<code>SELECT key, MAX(value) OVER w
  FROM table
 WINDOW w AS (PARTITION BY key ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
</code>```

produces one row for every row of the input (table). A result row has the maximum value for the key value that was observed so far (rows are ordered by ts). Note that multiple rows are not aggregated to a single row; each input row results in one output row. Moreover, the range of the maximum aggregation can be more than 5 minutes. In fact it's the whole key partition in this example.

Body:
One can use windows in Flink in two different manners

SELECT key, MAX(value)
  FROM table
 GROUP BY key, TUMBLE(ts, INTERVAL '5' MINUTE)

and

SELECT key, MAX(value) OVER w
  FROM table
 WINDOW w AS (PARTITION BY key ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

I wonder if those two mechanisms can express the same thing or what's the main difference and possible use cases for both?

Body:
Both queries compute different results that correspond to the semantics of regular SQL. So the difference is not Flink specific but defined by the SQL Standard.

The first query

SELECT key, MAX(value)
  FROM table
 GROUP BY key, TUMBLE(ts, INTERVAL '5' MINUTE)

groups records per key and 5 minute buckets. Every 5 minutes the query produces one row per key value with the maximum value. For each group, multiple rows are aggregated to a single row.

The second query

SELECT key, MAX(value) OVER w
  FROM table
 WINDOW w AS (PARTITION BY key ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

produces one row for every row of the input (table). A result row has the maximum value for the key value that was observed so far (rows are ordered by ts). Note that multiple rows are not aggregated to a single row; each input row results in one output row. Moreover, the range of the maximum aggregation can be more than 5 minutes. In fact it's the whole key partition in this example.


问:
tsconfig path and webpack alias - cannot find module issue

myCustom and ToDo are each react app and want to import MyCustom as a module inside ToDo app.

so following was my trial / folder structure:

```<code>[api]
|
[client]
|- [MyCustom]
|- [ToDo]
|  |- [src] (in src, will use - import {} from 'myCustom')
|  |- tsconfig.json (added "paths": { "myCustom": ["../myCustom/src"] })
|  |- package.json (added dependency - "myCustom": "1.0.0")
</code>```

and in ToDo app, when I try npm install, it says myCustom is not in the npm registry.

can you point out what's wrong here, please?

_____________________________

on TODO webpack.config.js file, I've added

```<code>resolve: {
   modules: ['../MyCustom/src']
},
resolveLoader: {
   modules: ['../MyCustom/src', 'myCustom']
}
</code>```

and built failed with following error:

 Module not found: Error: Can't resolve 'source-map-loader'.

 Am I using a loader wrong?

答:
resolve is a main topic in webpack.

please read how to resolve alias and don't work with '../' in webpack

then define where modules can be found

define where loaders can be found

```
  <code>
    // https://github.com/unic/darvin-webpack-boilerplate/blob/master/webpack.config.js
    const webpackConfigProd ={
        resolve: {
          modules: ['node_modules', '@yourAlias/yourCustomDir']
        },
        resolveLoader: {
          modules: ['node_modules', '@yourAlias/loaderDir']
        }
    };
  </code>
```

Body:
myCustom and ToDo are each react app and want to import MyCustom as a module inside ToDo app.

so following was my trial / folder structure:

[api]
|
[client]
|- [MyCustom]
|- [ToDo]
|  |- [src] (in src, will use - import {} from 'myCustom')
|  |- tsconfig.json (added "paths": { "myCustom": ["../myCustom/src"] })
|  |- package.json (added dependency - "myCustom": "1.0.0")

and in ToDo app, when I try npm install, it says myCustom is not in the npm registry.

can you point out what's wrong here, please?

_____________________________

on TODO webpack.config.js file, I've added

resolve: {
   modules: ['../MyCustom/src']
},
resolveLoader: {
   modules: ['../MyCustom/src', 'myCustom']
}

and built failed with following error:

 Module not found: Error: Can't resolve 'source-map-loader'.

 Am I using a loader wrong?

Body:
resolve is a main topic in webpack.

please read how to resolve alias and don't work with '../' in webpack

then define where modules can be found

define where loaders can be found

    // https://github.com/unic/darvin-webpack-boilerplate/blob/master/webpack.config.js
    const webpackConfigProd ={
        resolve: {
          modules: ['node_modules', '@yourAlias/yourCustomDir']
        },
        resolveLoader: {
          modules: ['node_modules', '@yourAlias/loaderDir']
        }
    };


问:
c# send mail to multiple recipients
I use this to send mails, I've defined some package variables which contains values:

```<code>public MailProperties(ScriptObjectModel dts)
        {
            if (
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailFrom"].Value) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailTo"].Value) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailPwd"].GetSensitiveValue()) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailSmtp"].Value) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailPort"].Value)

             )
            {
                fromMail = (string)dts.Variables["$Package::mailFrom"].Value;
                toMail = (string)dts.Variables["$Package::mailTo"].Value;
                bccMail = (string)dts.Variables["$Package::mailBcc"].Value;
                accountPassword = (string)dts.Variables["$Package::mailPwd"].GetSensitiveValue();
                accountSmtp = (string)dts.Variables["$Package::mailSmtp"].Value;
                accountSmtpPort = (string)dts.Variables["$Package::mailPort"].Value;
                useSSL = (bool)dts.Variables["$Package::useSSL"].Value;

                pathAttachment = new List<string>();
                pathAttachment.Add((string)dts.Variables["User::pathFileReject"].Value);
                pathAttachment.Add((string)dts.Variables["User::pathFileReject2"].Value);
            }
            else
            {
                throw new Exception("error text...");
            }

        }
</code>```

I need to send mail to more people, so I set mailTo with mail1@gmail.com, mailBcc as mail2@gmail.com and it works, but if I set mailBcc as "mail2@gmail.com, mail3@gmail.com" or "mail2@gmail.com; mail3@gmail.com" it doesn't work, how I can do that?

EDIT: this is the sendMail function

```<code>public static void sendMail(MailProperties mailProperties, ReportETL reportETL)
        {
            MimeMessage message = new MimeMessage();
            message.From.Add(new MailboxAddress("text..", mailProperties.fromMail));
            message.To.Add(new MailboxAddress(mailProperties.toMail));
            message.Subject = "text...";

            if (!string.IsNullOrEmpty(mailProperties.bccMail))
            {
                message.Bcc.Add(new MailboxAddress(mailProperties.bccMail));
            }

            BodyBuilder bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = ReportETLService.getHtmlFromReporETL(reportETL);

            mailProperties.pathAttachment.Where(x => File.Exists(x)).ToList().ForEach(y => bodyBuilder.Attachments.Add(y));

            message.Body = bodyBuilder.ToMessageBody();

            try
            {
                SmtpClient smtpClient = new SmtpClient();

                smtpClient.Connect(mailProperties.accountSmtp, int.Parse(mailProperties.accountSmtpPort), mailProperties.useSSL);
                smtpClient.Authenticate(mailProperties.fromMail, mailProperties.accountPassword);
                smtpClient.Send(message);

                smtpClient.Disconnect(true);
            }
            catch (Exception e) { throw new Exception("text... " + e.Message); }

        }
</code>```

答:
Well, assuming that your toMail, ccMail, and bccMail properties are just strings and not lists of strings, you could do something like this:

```<code>InternetAddressList list;

if (!string.IsNullOrEmpty(mailProperties.toMail) && InternetAddressList.TryParse (mailProperties.toMail, out list))
    message.To.AddRange(list);

if (!string.IsNullOrEmpty(mailProperties.ccMail) && InternetAddressList.TryParse (mailProperties.ccMail, out list))
    message.Cc.AddRange(list);

if (!string.IsNullOrEmpty(mailProperties.bccMail) && InternetAddressList.TryParse (mailProperties.bccMail, out list))
    message.Bcc.AddRange(list);
</code>```

Title: c# send mail to multiple recipients

Body:
I use this to send mails, I've defined some package variables which contains values:

public MailProperties(ScriptObjectModel dts)
        {
            if (
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailFrom"].Value) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailTo"].Value) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailPwd"].GetSensitiveValue()) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailSmtp"].Value) &&
             !string.IsNullOrEmpty((string)dts.Variables["$Package::mailPort"].Value)

             )
            {
                fromMail = (string)dts.Variables["$Package::mailFrom"].Value;
                toMail = (string)dts.Variables["$Package::mailTo"].Value;
                bccMail = (string)dts.Variables["$Package::mailBcc"].Value;
                accountPassword = (string)dts.Variables["$Package::mailPwd"].GetSensitiveValue();
                accountSmtp = (string)dts.Variables["$Package::mailSmtp"].Value;
                accountSmtpPort = (string)dts.Variables["$Package::mailPort"].Value;
                useSSL = (bool)dts.Variables["$Package::useSSL"].Value;

                pathAttachment = new List<string>();
                pathAttachment.Add((string)dts.Variables["User::pathFileReject"].Value);
                pathAttachment.Add((string)dts.Variables["User::pathFileReject2"].Value);
            }
            else
            {
                throw new Exception("error text...");
            }

        }

I need to send mail to more people, so I set mailTo with mail1@gmail.com, mailBcc as mail2@gmail.com and it works, but if I set mailBcc as "mail2@gmail.com, mail3@gmail.com" or "mail2@gmail.com; mail3@gmail.com" it doesn't work, how I can do that?

EDIT: this is the sendMail function

public static void sendMail(MailProperties mailProperties, ReportETL reportETL)
        {
            MimeMessage message = new MimeMessage();
            message.From.Add(new MailboxAddress("text..", mailProperties.fromMail));
            message.To.Add(new MailboxAddress(mailProperties.toMail));
            message.Subject = "text...";

            if (!string.IsNullOrEmpty(mailProperties.bccMail))
            {
                message.Bcc.Add(new MailboxAddress(mailProperties.bccMail));
            }

            BodyBuilder bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = ReportETLService.getHtmlFromReporETL(reportETL);

            mailProperties.pathAttachment.Where(x => File.Exists(x)).ToList().ForEach(y => bodyBuilder.Attachments.Add(y));

            message.Body = bodyBuilder.ToMessageBody();

            try
            {
                SmtpClient smtpClient = new SmtpClient();

                smtpClient.Connect(mailProperties.accountSmtp, int.Parse(mailProperties.accountSmtpPort), mailProperties.useSSL);
                smtpClient.Authenticate(mailProperties.fromMail, mailProperties.accountPassword);
                smtpClient.Send(message);

                smtpClient.Disconnect(true);
            }
            catch (Exception e) { throw new Exception("text... " + e.Message); }

        }

Body:
Well, assuming that your toMail, ccMail, and bccMail properties are just strings and not lists of strings, you could do something like this:

InternetAddressList list;

if (!string.IsNullOrEmpty(mailProperties.toMail) && InternetAddressList.TryParse (mailProperties.toMail, out list))
    message.To.AddRange(list);

if (!string.IsNullOrEmpty(mailProperties.ccMail) && InternetAddressList.TryParse (mailProperties.ccMail, out list))
    message.Cc.AddRange(list);

if (!string.IsNullOrEmpty(mailProperties.bccMail) && InternetAddressList.TryParse (mailProperties.bccMail, out list))
    message.Bcc.AddRange(list);