问:
Toggle that reveal text one at a time by click
I have a problem with my code. The goal is to have a text that appear when a user click on the link. But I want also that when he clicks on the link the only text that show is the text underneath and not in all the cells. Can someone has a clue on what I did wrong? I will probable add other links (more than 2) and I want to be sure that it will work every time.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();
    $('.cat' + $(this).attr('data-prod-cat')).toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}</code>```

SOCIÉTÉS: 230

              + En savoir plus

              Part CAC 40 : 40

              Part Filiales +100MK€: 190

CONTACTS: 16 700

              + En savoir plus

              Part CAC 40 : 10 000

              Part Filiales +100MK€: 6 700

EMAIL NOMINATIF

OPT OUT

LIGNES DIRECTES/MOBILES

```

答:
You need to get the parent of  first then get that parent which is
. Finally filter on cat1 class to toggle all siblings containing the cat1 class.

```<code>$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();
    $(this).parent().parent().siblings().filter(".cat1").toggle();
  });
});
</code>```

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();
    $(this).parent().parent().siblings().filter(".cat1").toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}</code>```

SOCIÉTÉS: 230

              + En savoir plus

              Part CAC 40 : 40

              Part Filiales +100MK€: 190

CONTACTS: 16 700

              + En savoir plus

              Part CAC 40 : 10 000

              Part Filiales +100MK€: 6 700

EMAIL NOMINATIF

OPT OUT

LIGNES DIRECTES/MOBILES

```

Body:
I have a problem with my code. The goal is to have a text that appear when a user click on the link. But I want also that when he clicks on the link the only text that show is the text underneath and not in all the cells. Can someone has a clue on what I did wrong? I will probable add other links (more than 2) and I want to be sure that it will work every time.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();
    $('.cat' + $(this).attr('data-prod-cat')).toggle();
  });
});

a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}

SOCIÉTÉS: 230

              + En savoir plus

              Part CAC 40 : 40

              Part Filiales +100MK€: 190

CONTACTS: 16 700

              + En savoir plus

              Part CAC 40 : 10 000

              Part Filiales +100MK€: 6 700

EMAIL NOMINATIF

OPT OUT

LIGNES DIRECTES/MOBILES

Body:
You need to get the parent of <a> first then get that parent which is <tr>. Finally filter on cat1 class to toggle all siblings containing the cat1 class.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();
    $(this).parent().parent().siblings().filter(".cat1").toggle();
  });
});

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();
    $(this).parent().parent().siblings().filter(".cat1").toggle();
  });
});

a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table cellpadding="0" cellspacing="5" style="table-layout: fixed; width:100%" width="100%">
  <tbody>
    <tr>
      <td>
        <table style="width: 100%;text-align:center;">
          <tbody>
            <tr>
              <td>
                <p>SOCIÉTÉS: 230</p>
              </td>
            </tr>
            <tr>
              <td><a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part CAC 40 : 40</td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part Filiales +100MK€: 190</td>
            </tr>
          </tbody>
        </table>
      </td>
      <td>
        <table style="width: 100%;text-align:center;">
          <tbody>
            <tr>
              <td>
                <p>CONTACTS: 16 700</p>
              </td>
            </tr>
            <tr>
              <td><a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part CAC 40 : 10 000</td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part Filiales +100MK€: 6 700</td>
            </tr>
          </tbody>
        </table>
      </td>
      <td>
        <p>EMAIL NOMINATIF</p>
      </td>
      <td>
        <p>OPT OUT</p>
      </td>
      <td>
        <p>LIGNES DIRECTES/MOBILES</p>
      </td>
    </tr>
  </tbody>
</table>


来源: stackexchange

问:
Angular2 update all clients UI after backend change by 1 client
I have an Angular2 application that communicates with a c# WebApi. Upon loading I make a GET call to retrieve a list of objects, subscribe them to an array and display the list using ng2-smart-table. My application works for a single user without any problems, but I don't get the correct behaviour when I add more site users.

Based on whichever type of user is logged in I display 2 different views, both views use the same component and thus have access to the same lists. The role type of the user determines which parameters he/she can change.

Imagine the following scenario:
I have 2 users; User A and User B. Both are logged in in a different browser tab/window, have a different role type and see the 2 different views.

Step 1: User A actions
On loading the webpage the browser for User A calls the Get method to fill the lists which are displayed on their screen. User A then clicks on the "Mark" button for a certain object in the list, this sets a boolean property to True in the backend for that object. The updated object is then send back to the frontend and updated in the list.

So far so good. User A himself sees the UI updated as the object is now "Marked".

Step 2: User B actions
User B had already loaded the page and thus has already called the Get method to fill the lists on his end. But since User A has since updated an item, User B must also see that that specific item is now set to "Marked". This however doesn't happen, the list in User B's browser is different from the one in User A's browser.

Question
How do I implement this scenario, so that when any updates to the objects by 1 user are also preceived by the other users?

Other Info: All api calls that edit an object return the edited object, as displayed in the example below.

Edit: I was able to implement the function by following this post: http://beyondscheme.com/2016/angular2-discussion-portal . However I want to avoid calling the GET All API call constantly as it would create massive data flows that are seemingly waisted as all I need is 1 item.

order-information.component

GET

```<code>ngOnInit() {
    this.orderInformationAddEditList = new LocalDataSource();
    this.orderInformationListDataSource = new LocalDataSource();
    if (this.AuthService.isLoggedIn()) {
      this.OrderInformationService.getAll().subscribe(orderInfo => {
        this.orderInformationList = orderInfo;
        this.orderInformationListDataSource.load(this.orderInformationList);
        //this.NotificationsService.success("Success", "Loaded all items.", { timeOut: 2000, clickToClose: true, showProgressBar: true });
        console.log("Loaded all items");

        if (!this.AuthService.hasRole("desk")) {
          this.userIsDesk = false;
        }
      },
        e => {
          console.log("Error: " + e);
          if (e.status == 0) {
            this.NotificationsService.error("Error", "Unable to connect to API", { timeOut: 0, clickToClose: true });
          }
          if (e.status == 500) {
            console.log(e.json().data);
            this.NotificationsService.error(e.json().data.Name, e.json().data.Message, { timeOut: 0, clickToClose: true });
          }
        })
    } else {
      this.router.navigate(['']);
    }
  }
</code>```

Mark

```<code>markOrderInformation(id: number, event: any) {
this.apiAttempts++;

this.OrderInformationService.markOrderInformation(id).subscribe(orderInfo => {
  console.log("Marked: " + orderInfo.id);
  this.NotificationsService.success("Success", "Marked: " + orderInfo.id, { timeOut: 2000, clickToClose: true, showProgressBar: true });
  this.updateOrderList(orderInfo, false);
  event.confirm.resolve(orderInfo);
  this.apiAttempts = 0;

},
  e => {
    var data = e.json();
    if (e.status == 0) {
      this.NotificationsService.error("Error", "Unable to connect to API. Please try again later..", { timeOut: 0, clickToClose: true });
    }
    if (e.status == 401) {
      this.NotificationsService.error(data.Name, data.message, { timeOut: 0, clickToClose: true });
    }
    if (e.status == 500) {
      if (this.apiAttempts < 4) {
        this.NotificationsService.error("Error", "Verify your input and try again. Attempts: " + this.apiAttempts, { timeOut: 0, clickToClose: true });
      } else {
        this.NotificationsService.error(data.Name, data.Message, { timeOut: 0, clickToClose: true });
        this.apiAttempts = 0;
      }
    }
  })
}
</code>```

order-information.service

GET

```<code>  getAll(): Observable<OrderInformation[]> {
    return this.http.get(`${this.baseUrl}`, new RequestOptions({ headers: this.getAuthorizationHeaders() }))
    .map(mapOrderInformationList);
  }
</code>```

Mark

```<code>  markOrderInformation(id: number) {
    return this.http.put(`${this.baseUrl}/` + id + `/mark`, {
    },
    { headers: this.getAuthorizationHeaders() })
    .map(mapOrderInformation);
  }
</code>```

答:
Thanks to the tutorial I found here: http://beyondscheme.com/2016/angular2-discussion-portal , I was able to send a GET request every 5 seconds. This was however extremely expensive as I'm sending alot of data accross the web.

I fixed this by returning a smaller list that holds objects that were only edited recently. I did this by adding a new DateTime column to my Sql entity called: lastUpdated. Now whenever I update an object I change the lastUpdated attribute to DateTime.Now().

Finally I created a new GET request method in the Api called GetUpdatedList, that returns all items that were updated within a specific time frame, I took 3 minutes cause I wasn't sure about how big latency can be but I think 1 minute is more than enough. The list received from the Api is then parsed and edited into the existing array in Angular2.

```<code>public List<Object> GetUpdatedList() {
 try {
    DateTime now = DateTime.Now;
    DateTime before = now.AddMinutes(-3);
    return context.Xdock_controle.Where(order => order.lastUpdated != null && order.lastUpdated <= now && order.lastUpdated >= before).ToList();
 } catch (Exception ex) {
    Logger.log(ex.Message);
    throw ex;
 }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an Angular2 application that communicates with a c# WebApi. Upon loading I make a GET call to retrieve a list of objects, subscribe them to an array and display the list using ng2-smart-table. My application works for a single user without any problems, but I don't get the correct behaviour when I add more site users.

Based on whichever type of user is logged in I display 2 different views, both views use the same component and thus have access to the same lists. The role type of the user determines which parameters he/she can change.

Imagine the following scenario:
I have 2 users; User A and User B. Both are logged in in a different browser tab/window, have a different role type and see the 2 different views.

Step 1: User A actions
On loading the webpage the browser for User A calls the Get method to fill the lists which are displayed on their screen. User A then clicks on the "Mark" button for a certain object in the list, this sets a boolean property to True in the backend for that object. The updated object is then send back to the frontend and updated in the list.

So far so good. User A himself sees the UI updated as the object is now "Marked".

Step 2: User B actions
User B had already loaded the page and thus has already called the Get method to fill the lists on his end. But since User A has since updated an item, User B must also see that that specific item is now set to "Marked". This however doesn't happen, the list in User B's browser is different from the one in User A's browser.

Question
How do I implement this scenario, so that when any updates to the objects by 1 user are also preceived by the other users?

Other Info: All api calls that edit an object return the edited object, as displayed in the example below.

Edit: I was able to implement the function by following this post: http://beyondscheme.com/2016/angular2-discussion-portal . However I want to avoid calling the GET All API call constantly as it would create massive data flows that are seemingly waisted as all I need is 1 item.

order-information.component

GET

ngOnInit() {
    this.orderInformationAddEditList = new LocalDataSource();
    this.orderInformationListDataSource = new LocalDataSource();
    if (this.AuthService.isLoggedIn()) {
      this.OrderInformationService.getAll().subscribe(orderInfo => {
        this.orderInformationList = orderInfo;
        this.orderInformationListDataSource.load(this.orderInformationList);
        //this.NotificationsService.success("Success", "Loaded all items.", { timeOut: 2000, clickToClose: true, showProgressBar: true });
        console.log("Loaded all items");

        if (!this.AuthService.hasRole("desk")) {
          this.userIsDesk = false;
        }
      },
        e => {
          console.log("Error: " + e);
          if (e.status == 0) {
            this.NotificationsService.error("Error", "Unable to connect to API", { timeOut: 0, clickToClose: true });
          }
          if (e.status == 500) {
            console.log(e.json().data);
            this.NotificationsService.error(e.json().data.Name, e.json().data.Message, { timeOut: 0, clickToClose: true });
          }
        })
    } else {
      this.router.navigate(['']);
    }
  }

Mark

markOrderInformation(id: number, event: any) {
this.apiAttempts++;

this.OrderInformationService.markOrderInformation(id).subscribe(orderInfo => {
  console.log("Marked: " + orderInfo.id);
  this.NotificationsService.success("Success", "Marked: " + orderInfo.id, { timeOut: 2000, clickToClose: true, showProgressBar: true });
  this.updateOrderList(orderInfo, false);
  event.confirm.resolve(orderInfo);
  this.apiAttempts = 0;

},
  e => {
    var data = e.json();
    if (e.status == 0) {
      this.NotificationsService.error("Error", "Unable to connect to API. Please try again later..", { timeOut: 0, clickToClose: true });
    }
    if (e.status == 401) {
      this.NotificationsService.error(data.Name, data.message, { timeOut: 0, clickToClose: true });
    }
    if (e.status == 500) {
      if (this.apiAttempts < 4) {
        this.NotificationsService.error("Error", "Verify your input and try again. Attempts: " + this.apiAttempts, { timeOut: 0, clickToClose: true });
      } else {
        this.NotificationsService.error(data.Name, data.Message, { timeOut: 0, clickToClose: true });
        this.apiAttempts = 0;
      }
    }
  })
}

order-information.service

GET

  getAll(): Observable<OrderInformation[]> {
    return this.http.get(`${this.baseUrl}`, new RequestOptions({ headers: this.getAuthorizationHeaders() }))
    .map(mapOrderInformationList);
  }

Mark

  markOrderInformation(id: number) {
    return this.http.put(`${this.baseUrl}/` + id + `/mark`, {
    },
    { headers: this.getAuthorizationHeaders() })
    .map(mapOrderInformation);
  }

Body:
Thanks to the tutorial I found here: http://beyondscheme.com/2016/angular2-discussion-portal , I was able to send a GET request every 5 seconds. This was however extremely expensive as I'm sending alot of data accross the web.

I fixed this by returning a smaller list that holds objects that were only edited recently. I did this by adding a new DateTime column to my Sql entity called: lastUpdated. Now whenever I update an object I change the lastUpdated attribute to DateTime.Now().

Finally I created a new GET request method in the Api called GetUpdatedList, that returns all items that were updated within a specific time frame, I took 3 minutes cause I wasn't sure about how big latency can be but I think 1 minute is more than enough. The list received from the Api is then parsed and edited into the existing array in Angular2.

public List<Object> GetUpdatedList() {
 try {
    DateTime now = DateTime.Now;
    DateTime before = now.AddMinutes(-3);
    return context.Xdock_controle.Where(order => order.lastUpdated != null && order.lastUpdated <= now && order.lastUpdated >= before).ToList();
 } catch (Exception ex) {
    Logger.log(ex.Message);
    throw ex;
 }
}


问:
DIV height like having some text inside
On one of my web pages I have a DIV element, containing string of text inside, which is of, say, 1.1em size. For example:

```<code><div id="displaydiv">
    <b>Hello World</b>
</div>
</code>```

Another page has the same DIV element, but with no text inside it at all. And that's why this DIV has the visual height of less value than the one on the first page.

```<code><div id="displaydiv">

</div>
</code>```

What is the recommended way of keeping the DIV element on the second page of the same height as on the first one?

答:
```
<div id="displaydiv" style="height: 1.1em">

</div>
```

and nbsp; also is patch solution, because you need to remember to take it off when you got text inside and not ruin you aligment

ContentLicense: CC BY-SA 2.5

Title: DIV height like having some text inside

Body:
On one of my web pages I have a DIV element, containing string of text inside, which is of, say, 1.1em size. For example:

    Hello World

Another page has the same DIV element, but with no text inside it at all. And that's why this DIV has the visual height of less value than the one on the first page.

What is the recommended way of keeping the DIV element on the second page of the same height as on the first one?

Body:
<div id="displaydiv" style="height: 1.1em">

</div>

and nbsp; also is patch solution, because you need to remember to take it off when you got text inside and not ruin you aligment


答:
You have just to go up to the parent table using closest('table') function and then select all the text's related to the current clicked .toggler using .find('[class^="cat"]') like :

```<code>$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});
</code>```

Hope this helps.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}</code>```

SOCIÉTÉS: 230

              + En savoir plus

              Part CAC 40 : 40

              Part Filiales +100MK€: 190

CONTACTS: 16 700

                + En savoir plus

              Part CAC 40 : 10 000

              Part Filiales +100MK€: 6 700

EMAIL NOMINATIF

OPT OUT

LIGNES DIRECTES/MOBILES

```

Title: Toggle that reveal text one at a time by click

Body:
You have just to go up to the parent table using closest('table') function and then select all the text's related to the current clicked .toggler using .find('[class^="cat"]') like :

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});

Hope this helps.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();

    $(this).closest('table').find('[class^="cat"]').toggle();
  });
});

a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table cellpadding="0" cellspacing="5" style="table-layout: fixed; width:100%" width="100%">
  <tbody>
    <tr>
      <td>
        <table style="width: 100%;text-align:center;">
          <tbody>
            <tr>
              <td>
                <p>SOCIÉTÉS: 230</p>
              </td>
            </tr>
            <tr>
              <td><a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part CAC 40 : 40</td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part Filiales +100MK€: 190</td>
            </tr>
          </tbody>
        </table>
      </td>
      <td>
        <table style="width: 100%;text-align:center;">
          <tbody>
            <tr>
              <td>
                <p>CONTACTS: 16 700</p>
              </td>
            </tr>
            <tr>
              <td>
                <a class="toggler" data-prod-cat="1" href="#">+ En savoir plus</a></td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part CAC 40 : 10 000</td>
            </tr>
            <tr class="cat1" style="display:none">
              <td>Part Filiales +100MK€: 6 700</td>
            </tr>
          </tbody>
        </table>
      </td>
      <td>
        <p>EMAIL NOMINATIF</p>
      </td>
      <td>
        <p>OPT OUT</p>
      </td>
      <td>
        <p>LIGNES DIRECTES/MOBILES</p>
      </td>
    </tr>
  </tbody>
</table>


问:
The object of class [class java.lang.String], could not be converted to [class java.lang.Integer]
This is the code:

```<code>public viewGUI() {
    initComponents();
    combobox();
    combobox1();
}

private void initComponents() {

    entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("atul?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
    membersQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT m FROM Members m");
    membersList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : membersQuery.getResultList();
    cb3 = new javax.swing.JButton();
    cb1 = new javax.swing.JComboBox<>();
    cb2 = new javax.swing.JComboBox<>();
    jButton4 = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    t1 = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("View Members");
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    cb3.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    cb3.setText("View");
    cb3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cb3ActionPerformed(evt);
        }
    });
    getContentPane().add(cb3, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 30, -1, -1));

    cb1.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    cb1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Package-name" }));
    cb1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cb1ActionPerformed(evt);
        }
    });
    getContentPane().add(cb1, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 30, -1, -1));

    cb2.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    cb2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Session-id" }));
    cb2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cb2ActionPerformed(evt);
        }
    });
    getContentPane().add(cb2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 30, -1, -1));

    jButton4.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    jButton4.setText("Back");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 30, -1, -1));

    t1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "member-id", "email", "fname", "lname", "phone", "session-id", "package name"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
    });
    jScrollPane2.setViewportView(t1);

    getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 80, 660, 340));

    setSize(new java.awt.Dimension(803, 530));
    setLocationRelativeTo(null);
}// </editor-fold>

private void cb3ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel t=(DefaultTableModel) t1.getModel();
    t.setRowCount(0);
    try{
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from members;";
        ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String id=rs.getString("member_id");
            String em=rs.getString("email");
            String fn=rs.getString("fname");
            String ln=rs.getString("lname");
            String ph=rs.getString("phone");
            String ses=rs.getString("session_id");
            String pac=rs.getString("pack_name");
            Object row[]={id,em,fn,ln,ph,ses,pac};
            t.addRow(row);
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}

private void cb1ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel t=(DefaultTableModel) t1.getModel();
    t.setRowCount(0);
    Object s=(String) cb1.getSelectedItem();
    try{
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from members where pack_name='"+s+"';";
        ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String id=rs.getString("member_id");
            String em=rs.getString("email");
            String fn=rs.getString("fname");
            String ln=rs.getString("lname");
            String ph=rs.getString("phone");
            String ses=rs.getString("session_id");
            String pac=rs.getString("pack_name");
            Object row[]={id,em,fn,ln,ph,ses,pac};
            t.addRow(row);
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage());
    }

}

private void cb2ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel t=(DefaultTableModel) t1.getModel();
    t.setRowCount(0);
    Object s=cb2.getSelectedItem();
    try{
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from members where session_id='"+s+"';";
        ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String id=rs.getString("member_id");
            String em=rs.getString("email");
            String fn=rs.getString("fname");
            String ln=rs.getString("lname");
            String ph=rs.getString("phone");
            String ses=rs.getString("session_id");
            String pac=rs.getString("pack_name");
            Object row[]={id,em,fn,ln,ph,ses,pac};
            t.addRow(row);
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    FirstGUI F= new FirstGUI();
    this.dispose();
    F.setVisible(true);
}
private void combobox() {
    try {
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from packages;";
         ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String name=rs.getString("pname");
            cb1.addItem(name);
        }
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}
private void combobox1() {
    try {
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from batch;";
         ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String name=rs.getString("session_id");
            cb2.addItem(name);
        }
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}
/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Windows".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new viewGUI().setVisible(true);
        }
    });
}
</code>```

This jframe I am creating to view all the values of my members table. Initially members table's column member-id was of datatype integer and it was working perfectly but now when I have changed it to datatype varchar and inserted one string 'm11' it's giving me that java.objeect error. And if I delete that string value, it works perfectly fine. Can anyone tell me what the error is?
This is the error:

```<code>Exception Description: The object [m11], of class [class java.lang.String],
could not be converted to [class java.lang.Integer].
Internal Exception: java.lang.NumberFormatException: For input string: "m11"
Exception in thread "AWT-EventQueue-0"
javax.persistence.PersistenceException: Exception [EclipseLink-3001]
(Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd):
org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [m11], of class [class java.lang.String],
could not be converted to [class java.lang.Integer].
Internal Exception: java.lang.NumberFormatException: For input string: "m11"
at

 org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:480)
at apppackage.viewGUI.initComponents(viewGUI.java:41)
at apppackage.viewGUI.<init>(viewGUI.java:25)
at apppackage.viewGUI$6.run(viewGUI.java:261)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311).......
</code>```

答:
org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:480)
   at apppackage.viewGUI.initComponents(viewGUI.java:41)

The error is in the getResultList(...) method which I would guess is reading data from your database and creating your TableModel

```<code>Class[] types = new Class []
{
    java.lang.String.class, java.lang.String.class, java.lang.String.class,
    java.lang.String.class, java.lang.Integer.class, java.lang.String.class,
    java.lang.String.class
}
</code>```

Note from your custom TableModel code you say that the 5th column contains Integer data!

But your error message says:

The object [m11], of class [class java.lang.String], could not be converted to [class java.lang.Integer].

So this tells me the data in your database is a String, so you need to change your getColumnClass(..) method to return a String for that column, not Ingeter.

ContentLicense: CC BY-SA 4.0

Body:
This is the code:

public viewGUI() {
    initComponents();
    combobox();
    combobox1();
}

private void initComponents() {

    entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("atul?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
    membersQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT m FROM Members m");
    membersList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : membersQuery.getResultList();
    cb3 = new javax.swing.JButton();
    cb1 = new javax.swing.JComboBox<>();
    cb2 = new javax.swing.JComboBox<>();
    jButton4 = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    t1 = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("View Members");
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    cb3.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    cb3.setText("View");
    cb3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cb3ActionPerformed(evt);
        }
    });
    getContentPane().add(cb3, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 30, -1, -1));

    cb1.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    cb1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Package-name" }));
    cb1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cb1ActionPerformed(evt);
        }
    });
    getContentPane().add(cb1, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 30, -1, -1));

    cb2.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    cb2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Session-id" }));
    cb2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cb2ActionPerformed(evt);
        }
    });
    getContentPane().add(cb2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 30, -1, -1));

    jButton4.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
    jButton4.setText("Back");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });
    getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 30, -1, -1));

    t1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "member-id", "email", "fname", "lname", "phone", "session-id", "package name"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
    });
    jScrollPane2.setViewportView(t1);

    getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 80, 660, 340));

    setSize(new java.awt.Dimension(803, 530));
    setLocationRelativeTo(null);
}// </editor-fold>

private void cb3ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel t=(DefaultTableModel) t1.getModel();
    t.setRowCount(0);
    try{
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from members;";
        ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String id=rs.getString("member_id");
            String em=rs.getString("email");
            String fn=rs.getString("fname");
            String ln=rs.getString("lname");
            String ph=rs.getString("phone");
            String ses=rs.getString("session_id");
            String pac=rs.getString("pack_name");
            Object row[]={id,em,fn,ln,ph,ses,pac};
            t.addRow(row);
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}

private void cb1ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel t=(DefaultTableModel) t1.getModel();
    t.setRowCount(0);
    Object s=(String) cb1.getSelectedItem();
    try{
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from members where pack_name='"+s+"';";
        ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String id=rs.getString("member_id");
            String em=rs.getString("email");
            String fn=rs.getString("fname");
            String ln=rs.getString("lname");
            String ph=rs.getString("phone");
            String ses=rs.getString("session_id");
            String pac=rs.getString("pack_name");
            Object row[]={id,em,fn,ln,ph,ses,pac};
            t.addRow(row);
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage());
    }

}

private void cb2ActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel t=(DefaultTableModel) t1.getModel();
    t.setRowCount(0);
    Object s=cb2.getSelectedItem();
    try{
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from members where session_id='"+s+"';";
        ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String id=rs.getString("member_id");
            String em=rs.getString("email");
            String fn=rs.getString("fname");
            String ln=rs.getString("lname");
            String ph=rs.getString("phone");
            String ses=rs.getString("session_id");
            String pac=rs.getString("pack_name");
            Object row[]={id,em,fn,ln,ph,ses,pac};
            t.addRow(row);
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    FirstGUI F= new FirstGUI();
    this.dispose();
    F.setVisible(true);
}
private void combobox() {
    try {
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from packages;";
         ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String name=rs.getString("pname");
            cb1.addItem(name);
        }
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}
private void combobox1() {
    try {
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","root");
        Statement st=(Statement) con.createStatement();
        String query="select * from batch;";
         ResultSet rs=st.executeQuery(query);
        while(rs.next()){
            String name=rs.getString("session_id");
            cb2.addItem(name);
        }
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(this, e.getMessage());
    }
}
/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Windows".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(viewGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new viewGUI().setVisible(true);
        }
    });
}

This jframe I am creating to view all the values of my members table. Initially members table's column member-id was of datatype integer and it was working perfectly but now when I have changed it to datatype varchar and inserted one string 'm11' it's giving me that java.objeect error. And if I delete that string value, it works perfectly fine. Can anyone tell me what the error is?
This is the error:

Exception Description: The object [m11], of class [class java.lang.String],
could not be converted to [class java.lang.Integer].
Internal Exception: java.lang.NumberFormatException: For input string: "m11"
Exception in thread "AWT-EventQueue-0"
javax.persistence.PersistenceException: Exception [EclipseLink-3001]
(Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd):
org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [m11], of class [class java.lang.String],
could not be converted to [class java.lang.Integer].
Internal Exception: java.lang.NumberFormatException: For input string: "m11"
at

 org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:480)
at apppackage.viewGUI.initComponents(viewGUI.java:41)
at apppackage.viewGUI.<init>(viewGUI.java:25)
at apppackage.viewGUI$6.run(viewGUI.java:261)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311).......

Body:
org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:480)
   at apppackage.viewGUI.initComponents(viewGUI.java:41)

The error is in the getResultList(...) method which I would guess is reading data from your database and creating your TableModel

Class[] types = new Class []
{
    java.lang.String.class, java.lang.String.class, java.lang.String.class,
    java.lang.String.class, java.lang.Integer.class, java.lang.String.class,
    java.lang.String.class
}

Note from your custom TableModel code you say that the 5th column contains Integer data!

But your error message says:

The object [m11], of class [class java.lang.String], could not be converted to [class java.lang.Integer].

So this tells me the data in your database is a String, so you need to change your getColumnClass(..) method to return a String for that column, not Ingeter.


问:
Use sed to find and replace a number following by its successor in bash
I have a string that contains multiple occurrences of number ranges, which are separated by a comma, e.g.,

2-12,59-89,90-102,103-492,593-3990,3991-4930

Now I would like to remove all directly neighbouring ranges and remove them from the string, i.e., remove anything that is of the form -(x),(x+1), to get something like this:

2-12,59-492,593-4930

Can anyone think of a method to accomplish this? I can honestly not post anything that I have tried, because all my tries were highly unsuccessful. To me it seems like it is not possible to actually find anything of the form -(x),(x+1) using sed, since that would require doing operations or comparisons of a found number by another number that has to be part of the command that is currently searching for numbers.

If everybody agrees that sed is NOT the correct tool for doing this, I will do it another way, but I am still interested if it's possible.

答:
with awk

```<code>awk -F, -v RS="-" -v ORS="-" '$2!=$1+1' file
</code>```

with appropriate separator setting, print the record when second field is not +1.

RS is the record separator and ORS is the outpout record separator.

test:

```<code>> awk -F, -v RS="-" -v ORS="-"
 '$2!=$1+1' <<< "2-12,59-89,90-102,103-492,593-3990,3991-4930"

2-12,59-492,593-4930
</code>```

Body:
with awk

awk -F, -v RS="-" -v ORS="-" '$2!=$1+1' file

with appropriate separator setting, print the record when second field is not +1.

RS is the record separator and ORS is the outpout record separator.

test:

> awk -F, -v RS="-" -v ORS="-"
 '$2!=$1+1' <<< "2-12,59-89,90-102,103-492,593-3990,3991-4930"

2-12,59-492,593-4930


问:
Add multiple values to array through function
I'm trying to make a function which accepts a value and echo them in the end.

Here's an example:

```<code>function number_of_files ($name) {
    $name_of_files = array($name);
    var_dump ($name_of_files);
}
</code>```

And I'm using this function as

```<code>number_of_files("file.png");
number_of_files("audio.mp3");
</code>```

I'm expecting the following output:

```<code>  Array (
    [0] => file.png
    [1] => audio.mp3
)
</code>```

Any suggestions why is it not working?

答:
Nope. You are overwrite your $name_of_files every time. That variable in the functions scope.

Use this:

```<code>function number_of_files ($name, &$name_of_files) {
    array_push($name_of_files, $name);
}

$name_of_files = number_of_files('file.mpg', $name_of_files);
$name_of_files = number_of_files('audio.mp3', $name_of_files);
var_dump ($name_of_files);
</code>```

Now you are using your array as a reference.

EDIT:

If you do not want to overwrite your original array, you can return:

```<code>function number_of_files ($name, $name_of_files) {
    array_push($name_of_files, $name);
    return $name_of_files;
}
</code>```

But let's note, in the second case I did not used the & sign before the $name_of_files function argument. That is the reference marker.

You can read it here: http://php.net/manual/en/language.references.pass.php

Body:
I'm trying to make a function which accepts a value and echo them in the end.

Here's an example:

function number_of_files ($name) {
    $name_of_files = array($name);
    var_dump ($name_of_files);
}

And I'm using this function as

number_of_files("file.png");
number_of_files("audio.mp3");

I'm expecting the following output:

  Array (
    [0] => file.png
    [1] => audio.mp3
)

Any suggestions why is it not working?

Body:
Nope. You are overwrite your $name_of_files every time. That variable in the functions scope.

Use this:

function number_of_files ($name, &$name_of_files) {
    array_push($name_of_files, $name);
}

$name_of_files = number_of_files('file.mpg', $name_of_files);
$name_of_files = number_of_files('audio.mp3', $name_of_files);
var_dump ($name_of_files);

Now you are using your array as a reference.

EDIT:

If you do not want to overwrite your original array, you can return:

function number_of_files ($name, $name_of_files) {
    array_push($name_of_files, $name);
    return $name_of_files;
}

But let's note, in the second case I did not used the & sign before the $name_of_files function argument. That is the reference marker.

You can read it here: http://php.net/manual/en/language.references.pass.php


问:
Creating objects during runtime in Python
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person()

What I have trouble understanding now is how I would design a model that creates a new object during runtime? I'm aware that my phrasing is probably faulty since all objects are generated during runtime but what I mean is that if I were to start my application in a terminal or UI how would I create new objects and manage them. I can't really define new variable names on the fly right?

An example application where I run into this design issue would be a database storing people. The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

Please excuse my poor understanding of the OPP model. I'm currently reading up on classes and OOP but I feel like I need to understand what my error is here before moving on. Please let me know if there is anything I should clarify.

答: You would never do Bob = Person() in a real program. Any example that shows that is arguably a bad example; it is essentially hard-coding. You will more often (in real code) do person = Person(id, name) or something like that, to construct the object using data you obtained elsewhere (read from a file, received interactively from a user, etc.). Even better would be something like employee = Person(id, name).


问:
RemotePlayer CanPause is always set to false
I am using the Chromecast Chrome API alongside the Default Receiver for integrating chromecast into a project. I am creating the RemotePlayer and RemoteController.

Recently we lost the ability to play, pause and adjust the volume so I looked into what was going on. I cam now see that the RemotePlayer is initialised it has the values of RemotePlayer.canPause and RemotePlayer.canControlVolume set to true. but after the instantiation of the RemoteController these values change to false

```<code>if (!this._remotePlayer) {
  this._remotePlayer = new cast.framework.RemotePlayer();
  this._remotePlayer.canControlVolume = true;
  this._remotePlayer.canPause = true;
  this._remotePlayer.canSeek = this.isLive() ? false : true;
}

// settings are correct canPause => true, canControlVolume => true

if (!this._remoteController) {
  this._remoteController = new cast.framework.RemotePlayerController(this._remotePlayer);
  // settings are incorrect canPause => false, canControlVolume => false
}
</code>```

I am stuck as to how to inform the receiver that it should allow play and pause and volume adjustments.

答: In an attempt to stop others who may have this headache in the future, you need to wait until loadMedia has resolved successfully before creating your instances of the RemotePlayer and RemoteController

Body:
I am using the Chromecast Chrome API alongside the Default Receiver for integrating chromecast into a project. I am creating the RemotePlayer and RemoteController.

Recently we lost the ability to play, pause and adjust the volume so I looked into what was going on. I cam now see that the RemotePlayer is initialised it has the values of RemotePlayer.canPause and RemotePlayer.canControlVolume set to true. but after the instantiation of the RemoteController these values change to false

if (!this._remotePlayer) {
  this._remotePlayer = new cast.framework.RemotePlayer();
  this._remotePlayer.canControlVolume = true;
  this._remotePlayer.canPause = true;
  this._remotePlayer.canSeek = this.isLive() ? false : true;
}

// settings are correct canPause => true, canControlVolume => true

if (!this._remoteController) {
  this._remoteController = new cast.framework.RemotePlayerController(this._remotePlayer);
  // settings are incorrect canPause => false, canControlVolume => false
}

I am stuck as to how to inform the receiver that it should allow play and pause and volume adjustments.


问:
Python assert isinstance() Vector
I am trying to implement a Vector3 class in python. If I would write the Vector3 class in c++ or c# i would have X, Y, and Z members stored as floats but in python I read that ducktyping is the way to go. So according to my c++/c# knowledge I wrote something like this:

```<code>class Vector3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        assert (isinstance(x, float) or isinstance(x, int)) and (isinstance(y, float) or isinstance(y, int)) and \
               (isinstance(z, float) or isinstance(z, int))
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
</code>```

The question is regarding the assert statements: Would you use them or not in this instance (a Vector3 implementation for math). I also used it for the operations like

```<code>def __add__(self, other):
    assert isinstance(other, Vector3)
    return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
</code>```

Would you use assert in these instances or not?
According to this website : https://wiki.python.org/moin/UsingAssertionsEffectively it should not be overused but for me as someone who used static typing all along, not checking for the same datatype is extremely weird.

答:
assert is better used for debugging than left loafing around in production code. You can instead create properties for the vector attributes x, y and z, and raise ValueError when the passed values are not of the required type:

```<code>class Vector3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = x
        self.y = y
        self.z = z

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, val):
        if not isinstance(val, (int, float)):
            raise TypeError('Inappropriate type: {} for x whereas a float \
            or int is expected'.format(type(val)))
        self._x = float(val)

    ...
</code>```

Notice how isinstance also takes a tuple of types.

In the __add__ operator, you'll want to raise TypeError also, including an appropriate message:

```<code>def __add__(self, other):
    if not isinstance(other, Vector3):
        raise TypeError('Object of type Vector3 expected, \
        however type {} was passed'.format(type(other)))
    ...
</code>```

Title: Python assert isinstance() Vector

Body:
I am trying to implement a Vector3 class in python. If I would write the Vector3 class in c++ or c# i would have X, Y, and Z members stored as floats but in python I read that ducktyping is the way to go. So according to my c++/c# knowledge I wrote something like this:

class Vector3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        assert (isinstance(x, float) or isinstance(x, int)) and (isinstance(y, float) or isinstance(y, int)) and \
               (isinstance(z, float) or isinstance(z, int))
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)

The question is regarding the assert statements: Would you use them or not in this instance (a Vector3 implementation for math). I also used it for the operations like

def __add__(self, other):
    assert isinstance(other, Vector3)
    return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)

Would you use assert in these instances or not?
According to this website : https://wiki.python.org/moin/UsingAssertionsEffectively it should not be overused but for me as someone who used static typing all along, not checking for the same datatype is extremely weird.

Body:
assert is better used for debugging than left loafing around in production code. You can instead create properties for the vector attributes x, y and z, and raise ValueError when the passed values are not of the required type:

class Vector3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = x
        self.y = y
        self.z = z

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, val):
        if not isinstance(val, (int, float)):
            raise TypeError('Inappropriate type: {} for x whereas a float \
            or int is expected'.format(type(val)))
        self._x = float(val)

    ...

Notice how isinstance also takes a tuple of types.

In the __add__ operator, you'll want to raise TypeError also, including an appropriate message:

def __add__(self, other):
    if not isinstance(other, Vector3):
        raise TypeError('Object of type Vector3 expected, \
        however type {} was passed'.format(type(other)))
    ...


问:
Whitelist AWS self in inbound connection
I am deploying a laravel installation in AWS, everything runs perfectly when I allow it to recieve all inbound traffic (EC2>Network&Security>Security Groups>Edit inbound rules.), if I turn off inbound traffic and limit it to an IP it doesnt load the webpage it gives me this error:

PDO Exception SQLSTATE[HY000] [2002] Connection timed out

However for security reasons I dont want this setup like this, I dont want anyone being able to even try to reach my webapp. Everything is being hosted in AWS, I dont have any external entities, its running in RDS and EC2. I added en elastic IP address and whitelisted it, but that didnt work either. I followed every step in this tutorial : http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/php-laravel-tutorial.html#php-laravel-tutorial-generate

Environmental variables are working as well as dependencies, well.. pretty much everything unless I restrict inbound traffic as I mentioned.

How do I whitelist AWS own instance then to make this work with better security?

Thank you!

答:
I think part of this answer is what you may be looking for.

You should enable inbound access from the EC2 security group associated with your EC2 instance, instead of the EC2 IP address.


问:
How to create an attribute conditionally in AngularJS
I am trying to create aria-current attribute in an anchor only if the anchors href is equal to the current windows path. Basically, I want aria-current="page" IF the anchor in question has an href equal to the window in views path. And I do not want to create an aria-current attribute if the anchor in question does not have an href equal to the window in view path.

Is there a way to write an conditional statement inline that will create or not create an attribute in AngularJS (Angular1)?

答:
I think there is no "inline way" to do this, but for this case you can create a directive

Here an Example:

```<code>yourmodule.directive('myexampleblabla', function() {
  return {
    link: function(scope, elem, attr) {
        if(elem.attr('href') === windows.location.href){
            elem.attr('aria-current', true)
        }
    },
    restrict: 'E',
  };
});
</code>```

HTML:

```<code><a href="sample/path#a123" myexampleblabla>Your Anchor</a>
</code>```

Be aware: This code in untested, but it should bring you a few steps forward.

For every case where you want to modify the DOM within a angular application you should create a directive. Read more about directives here:
https://docs.angularjs.org/guide/directive

Body:
I think there is no "inline way" to do this, but for this case you can create a directive

Here an Example:

yourmodule.directive('myexampleblabla', function() {
  return {
    link: function(scope, elem, attr) {
        if(elem.attr('href') === windows.location.href){
            elem.attr('aria-current', true)
        }
    },
    restrict: 'E',
  };
});

HTML:

<a href="sample/path#a123" myexampleblabla>Your Anchor</a>

Be aware: This code in untested, but it should bring you a few steps forward.

For every case where you want to modify the DOM within a angular application you should create a directive. Read more about directives here:
https://docs.angularjs.org/guide/directive


问:
Lambda expressions support in VS2008 SP1
Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something?

```<code>#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v;

  for (int i = 0; i < 10; ++i)
  {
    v.push_back(i);
  }

  for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
  cout << endl;
}
</code>```

Thank you in advance.

答:
See Stackoverflow question #146381

Simply put: no. Visual Studio 2010 will support C++0x to some extent, but I'm unsure if that will include lambda expressions.

OwnerDisplayName: Jarek

Body:
Is there support for lambda expressions from C++ 0x in Visual Studio 2008 SP1? Example below throws me syntax errors. Is there any '-Cpp0x' flag for compiler or something?

#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v;

  for (int i = 0; i < 10; ++i)
  {
    v.push_back(i);
  }

  for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
  cout << endl;
}

Thank you in advance.

LastEditorDisplayName: Serge

OwnerDisplayName: DrJokepu


问:
Math needed for Sql Server
I've been working in Sql server jobs since 2 years now. Although I like it, sometimes I get the feeling that at certain times, I stall too much on some tasks, and I seem to be discouraged easily from things that involve relatively simple logic. It's like, at some point I must repeat a logical condition inside my head more than 2 or 3 times in order to understand it completely.

I have the feeling that this might be of my lack of math knowledge. Can anyone please let me know what area of mathematics I can study, that would improve my Sql server coding skills?

Thank you.

答: I recommend you study symbolic logic.</p>

OwnerDisplayName: anon

LastEditorDisplayName: anon

Title: Math needed for Sql Server

Body: I recommend you study symbolic logic.


问:
Ruby Sass returning color as name
I have the following code to mix colours:

```<code>color = Sass::Script::Parser.parse("mix(#000000, #000000, 75%)", 0, 0).perform(Sass::Environment.new)
color.to_s
</code>```

When the calculated colour is black, Sass uses the name black:

```<code>color => 'black'
</code>```

I want it to be #000000. How do I do this?

I've even tried to change the style (as apparently compress mode causes this) e.g. color = Sass::Script::Parser.parse("mix(#000000, #000000, 75%)", 0, 0, {:style => :nested}).perform(Sass::Environment.new)

Currently we're having to handle this with:

```<code>color = hex_color_value(color)

def hex_color_value(sass_color)
  case sass_color
  when 'black'
    '#000000'
  when 'white'
    '#ffffff'
  else
    sass_color
  end
end
</code>```

答: i don't think that it's possible, the parser seems to be converting it right away, but you can at least use COLOR_NAMES constant to translate back.</p>

Title: Ruby Sass returning color as name

Body:
I have the following code to mix colours:

color = Sass::Script::Parser.parse("mix(#000000, #000000, 75%)", 0, 0).perform(Sass::Environment.new)
color.to_s

When the calculated colour is black, Sass uses the name black:

color => 'black'

I want it to be #000000. How do I do this?

I've even tried to change the style (as apparently compress mode causes this) e.g. color = Sass::Script::Parser.parse("mix(#000000, #000000, 75%)", 0, 0, {:style => :nested}).perform(Sass::Environment.new)

Currently we're having to handle this with:

color = hex_color_value(color)

def hex_color_value(sass_color)
  case sass_color
  when 'black'
    '#000000'
  when 'white'
    '#ffffff'
  else
    sass_color
  end
end


问:
How do I disable the horizontal scrollbar in a Panel
I have a panel (Windows Forms) and I want to disable a panels horizontal scrollbar. I tried this:

```<code>HorizontalScroll.Enabled = false;
</code>```

But that wouldn't work.

How can I do this?

答:
I was looking for an answer to the question how to add a scrollbar to a box when needed and remove it when not needed. This is the solution i came up with for a textbox, with maximum allowed width and height, resized for the text displayed.</p>

```<code>private void txtOutput_TextChanged(object sender, EventArgs e)
    {
        // Set the scrollbars to none. If the content fits within textbox maximum size no scrollbars are needed.
        txtOutput.ScrollBars = ScrollBars.None;

        // Calculate the width and height the text will need to fit inside the box
        Size size = TextRenderer.MeasureText(txtOutput.Text, txtOutput.Font);

        // Size the box accordingly (adding a bit of extra margin cause i like it that way)
        txtOutput.Width = size.Width + 20;
        txtOutput.Height = size.Height + 30;

        // If the box would need to be larger than maximum size we need scrollbars

        // If height needed exceeds maximum add vertical scrollbar
        if (size.Height > txtOutput.MaximumSize.Height)
        {

            txtOutput.ScrollBars = ScrollBars.Vertical;

            // If it also exceeds maximum width add both scrollbars
            // (You can't add vertical first and then horizontal if you wan't both. You would end up with just the horizontal)
            if (size.Width > txtOutput.MaximumSize.Width)
            {
                txtOutput.ScrollBars = ScrollBars.Both;
            }
        }

        // If width needed exceeds maximum add horosontal scrollbar
        else if (size.Width > txtOutput.MaximumSize.Width)
        {
            txtOutput.ScrollBars = ScrollBars.Horizontal;
        }
    }
</code>```

Body:
I have a panel (Windows Forms) and I want to disable a panels horizontal scrollbar. I tried this:

HorizontalScroll.Enabled = false;

But that wouldn't work.

How can I do this?

Body:
I was looking for an answer to the question how to add a scrollbar to a box when needed and remove it when not needed. This is the solution i came up with for a textbox, with maximum allowed width and height, resized for the text displayed.

private void txtOutput_TextChanged(object sender, EventArgs e)
    {
        // Set the scrollbars to none. If the content fits within textbox maximum size no scrollbars are needed.
        txtOutput.ScrollBars = ScrollBars.None;

        // Calculate the width and height the text will need to fit inside the box
        Size size = TextRenderer.MeasureText(txtOutput.Text, txtOutput.Font);

        // Size the box accordingly (adding a bit of extra margin cause i like it that way)
        txtOutput.Width = size.Width + 20;
        txtOutput.Height = size.Height + 30;

        // If the box would need to be larger than maximum size we need scrollbars

        // If height needed exceeds maximum add vertical scrollbar
        if (size.Height > txtOutput.MaximumSize.Height)
        {

            txtOutput.ScrollBars = ScrollBars.Vertical;

            // If it also exceeds maximum width add both scrollbars
            // (You can't add vertical first and then horizontal if you wan't both. You would end up with just the horizontal)
            if (size.Width > txtOutput.MaximumSize.Width)
            {
                txtOutput.ScrollBars = ScrollBars.Both;
            }
        }

        // If width needed exceeds maximum add horosontal scrollbar
        else if (size.Width > txtOutput.MaximumSize.Width)
        {
            txtOutput.ScrollBars = ScrollBars.Horizontal;
        }
    }


答:
Based on your code, I guess you are trying to use data-prod-cat attribute to know which block needs to appear.

But in both of your block you have data-prod-cat="1" which means that you will activate both blocks on every action.

Try changing the 2nd block attribute to :

```<code>data-prod-cat="2"
</code>```

You'll also need to update the css class in your other

Body:
I have a problem with my code. The goal is to have a text that appear when a user click on the link. But I want also that when he clicks on the link the only text that show is the text underneath and not in all the cells. Can someone has a clue on what I did wrong? I will probable add other links (more than 2) and I want to be sure that it will work every time.

$(document).ready(function() {
  $(".toggler").click(function(e) {
    e.preventDefault();
    $('.cat' + $(this).attr('data-prod-cat')).toggle();
  });
});

a {
  color: #002642;
}

.center {
  text-align: center;
}

.toggler,
.cat1 {
  font-family: 'Varela Round';
  color: white;
}

td {
  display: block;
  width: auto;
  border: 1px dotted #c4a77d;
  background-color: #c4a77d;
  color: white;
  margin-bottom: 10px;
}

@media only screen and (min-width: 70em) {
  td {
    display: table-cell;
    border: 1px dotted #c4a77d;
    background-color: #c4a77d;
    color: white;
    margin-bottom: 0px;
  }
}

p {
  font-family: 'Varela Round';
  font-weight: bold;
  text-align: center;
}

SOCIÉTÉS: 230

              + En savoir plus

              Part CAC 40 : 40

              Part Filiales +100MK€: 190

CONTACTS: 16 700

              + En savoir plus

              Part CAC 40 : 10 000

              Part Filiales +100MK€: 6 700

EMAIL NOMINATIF

OPT OUT

LIGNES DIRECTES/MOBILES

Body:
Based on your code, I guess you are trying to use data-prod-cat attribute to know which block needs to appear.

But in both of your block you have data-prod-cat="1" which means that you will activate both blocks on every action.

Try changing the 2nd block attribute to :

data-prod-cat="2"

You'll also need to update the css class in your other <tr>


问:
Combining regexes using a loop in Perl 6
Here I make a regex manually from Regex elements of an array.

my Regex @reg =
  / foo /,
  / bar /,
  / baz /,
  / pun /
  ;

my $r0 = @reg[0];
my $r1 = @reg[1];

my Regex $r = / 0 $r0 | 1 $r1 /;

"0foo_1barz" ~~ m:g/<$r>/;
say $/;  # (｢0foo｣ ｢1bar｣)
```

How to do it with for @reg {...}?

答:
```<code>my @reg =
  /foo/,
  /bar/,
  /baz/,
  /pun/
  ;

my $i = 0;

my $reg = @reg
  .map({ $_ = .perl; $_.substr(1, $_.chars - 2); })
  .map({ "{$i++}{$_}" })
  .join('|');

my @match = "foo", "0foo_1barz" ~~ m:g/(<{$reg}>) /;

say @match[1][0].Str;
say @match[1][1].Str;

# 0foo
# 2baz
</code>```

See the docs

Edit: Actually read the docs myself. Changed implicit eval to $() construct.

Edit: Rewrote answer to something that actually works

Edit: Changed answer to a terrible, terrible hack

Body:
Here I make a regex manually from Regex elements of an array.

my Regex @reg =
  / foo /,
  / bar /,
  / baz /,
  / pun /
  ;

my $r0 = @reg[0];
my $r1 = @reg[1];

my Regex $r = / 0 $r0 | 1 $r1 /;

"0foo_1barz" ~~ m:g/<$r>/;
say $/;  # (｢0foo｣ ｢1bar｣)

How to do it with for @reg {...}?

Body:
my @reg =
  /foo/,
  /bar/,
  /baz/,
  /pun/
  ;

my $i = 0;

my $reg = @reg
  .map({ $_ = .perl; $_.substr(1, $_.chars - 2); })
  .map({ "{$i++}{$_}" })
  .join('|');

my @match = "foo", "0foo_1barz" ~~ m:g/(<{$reg}>) /;

say @match[1][0].Str;
say @match[1][1].Str;

# 0foo
# 2baz

See the docs

Edit: Actually read the docs myself. Changed implicit eval to $() construct.

Edit: Rewrote answer to something that actually works

Edit: Changed answer to a terrible, terrible hack


问:
Ignoring Duplicate Records SQL
In need of some help :)

So I have a table of records with the following columns:

```<code>Key (PK, FK, int) DT (smalldatetime) Value (real)
</code>```

The DT is a datetime for every half hour of the day with an associated value

E.g.

```<code>Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100
</code>```

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

```<code>SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT
</code>```

This results in

```<code>Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00
</code>```

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?

答:
Change the JOIN to an APPLY.

The APPLY operation will allow you to limit the connected relation to just one result for each source relation.

```<code>SELECT v.[Key], cast(v.DT As Date) as "Date", v.[Value], cast(v.DT as Time(0)) as "HH"
FROM
(   -- First a projection to get just the exact dates you want
    SELECT DISTINCT [Key], CAST(DT as DATE) as DT
    FROM Table_1
    WHERE [Key] = '1000' AMD DT > '20161106'
) dates
CROSS APPLY (
    -- Then use APPLY rather than JOIN to find just the exact one record you need for each date
    SELECT TOP 1 *
    FROM Table_1
    WHERE [Key] = dates.[Key] AND cast(DT as DATE) = dates.DT ORDER BY [Value] DESC
) v
</code>```

A final note: Both this query and your sample query in the question will include values from Nov 6, 2016. The query says > 2016-11-05 with an exlusive inequality, but the original was still comparing using full DateTime values, meaning there is a implied 0 as a time component. So 12:01 AM on Nov 6 is still greater than 12:00:00.001 AM on Nov 6. If you want to exclude all Nov 6 dates from the query, you either need to change this to use a time value at the end of the date, or cast to date before making that > comparison.

Title: Ignoring Duplicate Records SQL

Body:
In need of some help :)

So I have a table of records with the following columns:

Key (PK, FK, int) DT (smalldatetime) Value (real)

The DT is a datetime for every half hour of the day with an associated value

E.g.

Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT

This results in

Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?

Body:
Change the JOIN to an APPLY.

The APPLY operation will allow you to limit the connected relation to just one result for each source relation.

SELECT v.[Key], cast(v.DT As Date) as "Date", v.[Value], cast(v.DT as Time(0)) as "HH"
FROM
(   -- First a projection to get just the exact dates you want
    SELECT DISTINCT [Key], CAST(DT as DATE) as DT
    FROM Table_1
    WHERE [Key] = '1000' AMD DT > '20161106'
) dates
CROSS APPLY (
    -- Then use APPLY rather than JOIN to find just the exact one record you need for each date
    SELECT TOP 1 *
    FROM Table_1
    WHERE [Key] = dates.[Key] AND cast(DT as DATE) = dates.DT ORDER BY [Value] DESC
) v

A final note: Both this query and your sample query in the question will include values from Nov 6, 2016. The query says > 2016-11-05 with an exlusive inequality, but the original was still comparing using full DateTime values, meaning there is a implied 0 as a time component. So 12:01 AM on Nov 6 is still greater than 12:00:00.001 AM on Nov 6. If you want to exclude all Nov 6 dates from the query, you either need to change this to use a time value at the end of the date, or cast to date before making that > comparison.


问:
Custom UITableViewCell trouble with UIAccessibility elements
No matter what I try, I can't keep my custom UITableViewCell from acting like it should under the default rules for UIAccessiblity.  I don't want this cell to act like an accessibility container (per se), so following this guide I should be able to make all of my subviews accessible, right?!  It says to make each element accessible separately and make sure the cell itself is not accessible.

```<code>- (BOOL)isAccessibilityElement
{
    return NO;
}

- (NSString *)accessibilityLabel
{
    return nil;
}

- (NSInteger)accessibilityElementCount
{
    return 0;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier //cells use this reusage stuff
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        [self setIsAccessibilityElement:NO];
        sub1 = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1,1)];
        [sub1 setAccessibilityLanguage:@"es"];
        [sub1 setIsAccessibilityElement:YES];
        [sub1 setAccessibilityLabel:sub1.text]

        sub2 = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1,1)];
        [sub2 setAccessibilityLanguage:@"es"];
        [sub2 setIsAccessibilityElement:YES];
        [sub2 setAccessibilityLabel:sub2.text]
</code>```

The voice over system reads the contents of the whole cell all at once, even though I'm trying to stop that behavior.  I could say

```<code>        [sub2 setIsAccessibilityElement:NO];
</code>```

but that would would make this element entirely unreadable.  I want to keep it readable, but not have the whole cell be treated like a container (and assumed to be the English language).  There does not appear to be a lot of information out there on this, so at the very least I'd like to document it.

答:
If you have 2 separate elements (sub1 and sub2), you could override methods of the UIAccessibilityContainer informal protocol.

```<code>- (NSInteger)accessibilityElementCount {
    return 2;
}

- (id)accessibilityElementAtIndex:(NSInteger)index {
    if (index == 0) {
        return sub1;
    } else if (index == 1) {
        return sub2;
    }
    return nil;
}

- (NSInteger)indexOfAccessibilityElement:(id)element {
    if (element == sub1) {
        return 0;
    } else if (element == sub2) {
        return 1;
    }
    return NSNotFound;
}
</code>```

Body:
No matter what I try, I can't keep my custom UITableViewCell from acting like it should under the default rules for UIAccessiblity.  I don't want this cell to act like an accessibility container (per se), so following this guide I should be able to make all of my subviews accessible, right?!  It says to make each element accessible separately and make sure the cell itself is not accessible.

- (BOOL)isAccessibilityElement
{
    return NO;
}

- (NSString *)accessibilityLabel
{
    return nil;
}

- (NSInteger)accessibilityElementCount
{
    return 0;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier //cells use this reusage stuff
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        [self setIsAccessibilityElement:NO];
        sub1 = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1,1)];
        [sub1 setAccessibilityLanguage:@"es"];
        [sub1 setIsAccessibilityElement:YES];
        [sub1 setAccessibilityLabel:sub1.text]

        sub2 = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1,1)];
        [sub2 setAccessibilityLanguage:@"es"];
        [sub2 setIsAccessibilityElement:YES];
        [sub2 setAccessibilityLabel:sub2.text]

The voice over system reads the contents of the whole cell all at once, even though I'm trying to stop that behavior.  I could say

        [sub2 setIsAccessibilityElement:NO];

but that would would make this element entirely unreadable.  I want to keep it readable, but not have the whole cell be treated like a container (and assumed to be the English language).  There does not appear to be a lot of information out there on this, so at the very least I'd like to document it.

Body:
If you have 2 separate elements (sub1 and sub2), you could override methods of the UIAccessibilityContainer informal protocol.

- (NSInteger)accessibilityElementCount {
    return 2;
}

- (id)accessibilityElementAtIndex:(NSInteger)index {
    if (index == 0) {
        return sub1;
    } else if (index == 1) {
        return sub2;
    }
    return nil;
}

- (NSInteger)indexOfAccessibilityElement:(id)element {
    if (element == sub1) {
        return 0;
    } else if (element == sub2) {
        return 1;
    }
    return NSNotFound;
}


问:
Capturing first group and separately third + fourth group (REGEX)
I'm trying to create two separate regexes that capture two specific parts of a string:

Example string: 3027-20171110020655-test-5

I need to capture first: 3027 and second: test-5
The second group may not always have a hyphen in it.

I have so far created: [^\-]+
This creates 4 separate capture groups -- I'm not sure how to narrow it down further.

答:
Add the ^ token to mark the beginning of the string:

```<code>^[^\-]+
</code>```

Then, depending on how your input is formatted, you don't need separate regex's, just put whatever you are trying to capture into capturing groups, using parentheses (())

```<code>^([^\-]+)-\d+-(.*)
</code>```

Test it here

Body:
Add the ^ token to mark the beginning of the string:

^[^\-]+

Then, depending on how your input is formatted, you don't need separate regex's, just put whatever you are trying to capture into capturing groups, using parentheses (())

^([^\-]+)-\d+-(.*)

Test it here


问:
Route requests from external ip to another server
I got stuck at the point:

The php script makes curl request to another php script on external ip,
like

```<code>$ip = "111.222.333.444";
curl_setopt($ch, CURLOPT_URL, $this->ip . "/index.php");
</code>```

I cannot modify the first script and unfortunately external ip is down forever.

So, I need to route all requests to the new same script on my server, but cannot understand how to do it better.

If there is domain name instead of ip, I can change hosts file.
But it's not that case.

I googled about iptables, but how can I connect requests to exact script on my server? What changes do I need to do there?

答:
if this is all happening on your local machine you can use iptables to redirect. This is not an optimal solution as iptables over time can do things you you aren't expecting anylonger and you may forget that iptables are affecting traffic.

However if you have access to the server on the server where script B resides, you can use a server redirect.

For instance if you are running Apache you can drop a RewriteRule in an htaccess file that resides in the same dir as script B that simply looks for any request to assets in the dir, or a specific request depending on need, and redirect to resource C

RewriteEngine on
RewriteRule (.*) http://www.newdomain.com/ [R=301,L]

Body:
I got stuck at the point:

The php script makes curl request to another php script on external ip,
like

$ip = "111.222.333.444";
curl_setopt($ch, CURLOPT_URL, $this->ip . "/index.php");

I cannot modify the first script and unfortunately external ip is down forever.

So, I need to route all requests to the new same script on my server, but cannot understand how to do it better.

If there is domain name instead of ip, I can change hosts file.
But it's not that case.

I googled about iptables, but how can I connect requests to exact script on my server? What changes do I need to do there?


问:
Error while changing/altering column name in MySql?
I am trying to change column Customer_email to customerEmail but it gives error

The code which is giving error is

```<code>alter table getCustomer
change Customer_email customerEmail varchar;
</code>```

The code is working fine with "int" type columns.

答: For the type VARCHAR, you have to give the maximum length of the string, e.g., VARCHAR(50).

Body:
I am trying to change column Customer_email to customerEmail but it gives error

The code which is giving error is

alter table getCustomer
change Customer_email customerEmail varchar;

The code is working fine with "int" type columns.


问:
In dub, how do I set a custom optimization level to only certain files?
I have some files that are several megabytes generated code. I would like to compile those files only with optimization level 0, and all other files with optimization level 3. How would I specify this in dub?

If the generated code files compile at -O3, they never finish compiling.

答: dub is not set up to have you list specific files. It pulls in every file in whatever source directories you set. As such, it really isn't set up to have some files compiled one way and some another. However, you could always create a sub-package just for those files, and have its dub configuration set with flags to optimize it differently. However, at that point, it is technically a separate library, so your actual code has to be organized in a way for that separation to work.</p>


问:
Android App Cannot connect to Rocket Chat server
I followed the below guide to setup Rocket Chat:
https://www.digitalocean.com/community/tutorials/how-to-install-configure-and-deploy-rocket-chat-on-ubuntu-14-04

It works as expected through the browser.

When trying to connect it to the Android Mobile App downloaded from the play store, the message received is that it cannot connect.  SSL cert is from Let's Encrypt.

From searching online I am at a loss if it is the let's encrypt cert that is the issue or something else?  I have been using Let's Encrypt on other projects without issue.

Is there some in particular that I am required to enter into the NGINX reverse proxy?

答:
That's probably because your web server is not updated, try updating it and see if works. Look at this warning the apps repositories:

Make sure your server supports WebSocket. These are the minimum requirements for Apache 2.4 and Nginx 1.3 or greater.

For more information:

iOS repository

Android repository


问:
Mongo DB put newer results at top of query with aggregate
I'm pulling a bunch of results from a collection. I want to display all entries made in the last 30 days first, then sort the rest by number of downloads. Only 10 are loaded at a time, and more are loaded as you scroll.

```<code>Data.aggregate([
      {'$match': match},
      {"$sort": {downloads : -1, createdAt: -1}},
      {"$skip": page * entriesPerPage},
      {"$limit": entriesPerPage},
      {"$lookup": {
        "from": "examples",
        "localField": "_id",
        "foreignField": "docId",
        "as": "examples"
      }},
    ]).exec(function(err, docs) {});
</code>```

Right now I'm trying to do it manually by getting all the results and then dividing them into two arrays, but am now realizing that means I'll have to do the $skip part manually too. Also isn't great that I have to load and look through all the results.

Is there a way to do this just as part of the aggregate query?

EDIT: here is a document:

```<code>{ "_id" : ObjectId("58ddc3f76853d8286b22bc7b"),
"updatedAt" : ISODate("2017-11-12T09:39:22.031Z"),
"createdAt" : ISODate("2017-03-31T02:50:31.631Z"),
"name" : "Dragon",
"slug" : "dragon",
"description" : "A dragon is a legendary creature, typically scaled or fire-spewing and with serpentine, reptilian or avian traits, that features in the myths of many cultures around world.",
"downloads" : 18,
"type" : "monster",
"numberOfColors" : 16, "__v" : 1,
"tags" : [ "monster" ] }
</code>```

There is currently about 100. Again I want to show all where createdAt was within the last 30 days first, then show the rest by number of downloads.

答:
You will need a temporary helper field for that which you can get by using the $addFields pipeline stage (or $project for MongoDB versions < 3.4):</p>

```<code>var thirtyDaysInMilliSeconds = 30 * 24 * 60 * 60 * 1000;

Data.aggregate([
      {"$match": match},
      {'$addFields': { // let's add a field that contains either 0 or 1 depending on whether the "createdAt" value is greater than "today - 30 days"
          "sortHelperField": { $cond: [ { $gt: [ "$createdAt", { $subtract: [ new Date(), thirtyDaysInMilliSeconds ] } ] }, "$createdAt", 0] }
      }},
      {"$sort": {"sortHelperField": -1, downloads: -1}}, // then we can sort by that field, too, and make it the field with the highest priority
      /* all the rest of your stages can stay the way the are */
    ]);
</code>```

Body:
I'm pulling a bunch of results from a collection. I want to display all entries made in the last 30 days first, then sort the rest by number of downloads. Only 10 are loaded at a time, and more are loaded as you scroll.

Data.aggregate([
      {'$match': match},
      {"$sort": {downloads : -1, createdAt: -1}},
      {"$skip": page * entriesPerPage},
      {"$limit": entriesPerPage},
      {"$lookup": {
        "from": "examples",
        "localField": "_id",
        "foreignField": "docId",
        "as": "examples"
      }},
    ]).exec(function(err, docs) {});

Right now I'm trying to do it manually by getting all the results and then dividing them into two arrays, but am now realizing that means I'll have to do the $skip part manually too. Also isn't great that I have to load and look through all the results.

Is there a way to do this just as part of the aggregate query?

EDIT: here is a document:

{ "_id" : ObjectId("58ddc3f76853d8286b22bc7b"),
"updatedAt" : ISODate("2017-11-12T09:39:22.031Z"),
"createdAt" : ISODate("2017-03-31T02:50:31.631Z"),
"name" : "Dragon",
"slug" : "dragon",
"description" : "A dragon is a legendary creature, typically scaled or fire-spewing and with serpentine, reptilian or avian traits, that features in the myths of many cultures around world.",
"downloads" : 18,
"type" : "monster",
"numberOfColors" : 16, "__v" : 1,
"tags" : [ "monster" ] }

There is currently about 100. Again I want to show all where createdAt was within the last 30 days first, then show the rest by number of downloads.

Body:
You will need a temporary helper field for that which you can get by using the $addFields pipeline stage (or $project for MongoDB versions < 3.4):

var thirtyDaysInMilliSeconds = 30 * 24 * 60 * 60 * 1000;

Data.aggregate([
      {"$match": match},
      {'$addFields': { // let's add a field that contains either 0 or 1 depending on whether the "createdAt" value is greater than "today - 30 days"
          "sortHelperField": { $cond: [ { $gt: [ "$createdAt", { $subtract: [ new Date(), thirtyDaysInMilliSeconds ] } ] }, "$createdAt", 0] }
      }},
      {"$sort": {"sortHelperField": -1, downloads: -1}}, // then we can sort by that field, too, and make it the field with the highest priority
      /* all the rest of your stages can stay the way the are */
    ]);


问:
Prism Template Pack 2.0, IllegalArgumentException
An error occurs when building with Prism Template Pack 2.0.

I created a project of Xamarin.Forms (Android / iOS).

Next, I installed Xam.Plugin.Media using NuGet.

And when I ran the build, I get an error java.lang.IllegalArgumentException: already added.

In order to avoid this error, I attempted to modify the packages.config file, but the file does not exist anywhere.

(In the case of Prism Template Pack 1.x, problems could be avoided by modifying the packages.config file)

How can I avoid the problem?

答: The Prism Template Pack 2.0 is using the new .NET Standard based project system.  This means that there is no more packages.config.  The Nugets are defined within the csproj file of the project.  You also do not need to add the Nuget packages to every project in the solution.  Just add it to the main XF project and the Android/iOS projects will inherit the NuGet references automatically.</p>