问:
OrientDB: export/import throws exception: "Invalid format. Found unsupported tag 'brokenRids'"
Trying to use OrientDB's export/import functionality, but I keep getting errors, both from command line client and by using the JavaAPI

Creating a database with minimal content, then calling

```<code>export database /tmp/db.export -excludeAll -includeClass="asdf"
</code>```

then importing with

```<code>import database /tmp/db.export.gz
</code>```

yields the error message Invalid format. Found unsupported tag 'brokenRids'. Here is the full console session to reproduce:

```<code>OrientDB console v.2.2.30 (build 43d850df23c0fd1edca7279761c2238fdc6cc576, branch 2.2.x) https://www.orientdb.com
Type 'help' to display all the supported commands.
orientdb> create database plocal:/var/tmp/databases/test_export_import

Creating database [plocal:/var/tmp/databases/test_export_import] using the storage type [plocal]...Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Auto configuration of disk cache size.
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: 2095874048 B/1998 MB/1 GB of physical memory were detected on machine
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Soft memory limit for this process is set to -1 B/-1 MB/-1 GB
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Hard memory limit for this process is set to -1 B/-1 MB/-1 GB
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Path to 'memory' cgroup is '/docker/f88c313794174ac8b8d7ad7d9b5fe396aea8033a1588e7eb6a3f903773081b81'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Mounting path for memory cgroup controller is '/sys/fs/memory'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Can not find '/sys/fs/memory/docker/f88c313794174ac8b8d7ad7d9b5fe396aea8033a1588e7eb6a3f903773081b81' path for memory cgroup, it is supposed that process is running in container, will try to read root '/sys/fs/memory' memory cgroup data
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Can not read memory soft limit for cgroup '/sys/fs/memory'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Can not read memory hard limit for cgroup '/sys/fs/memory'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Detected memory limit for current process is 2095874048 B/1998 MB/1 GB
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: OrientDB auto-config DISKCACHE=444MB (heap=444MB direct=444MB os=1,998MB)
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Lowering disk cache size from 444MB to 442MB.
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Lowering memory chunk size from 465,567,744B to 463,470,592B.
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: $ANSI{green {db=test_export_import}} Storage 'plocal:/var/tmp/databases/test_export_import' is created under OrientDB distribution : 2.2.30 (build 43d850df23c0fd1edca7279761c2238fdc6cc576, branch 2.2.x)

Database created successfully.

Current database is: plocal:/var/tmp/databases/test_export_import
orientdb {db=test_export_import}> create class asdf

Class created successfully. Total classes in database now: 11.

orientdb {db=test_export_import}> insert into asdf content {"one": "two", "three": "four"}

Inserted record 'asdf#17:0{one:two,three:four} v1' in 0.009000 sec(s).

orientdb {db=test_export_import}> select from asdf

+----+-----+------+------+------+
|#   |@RID |@CLASS|one   |three |
+----+-----+------+------+------+
|0   |#17:0|asdf  |two   |four  |
+----+-----+------+------+------+

1 item(s) found. Query executed in 0.005 sec(s).
orientdb {db=test_export_import}> export database /tmp/test_export_import.export -excludeAll -includeClass="asdf"
Exporting current database to: database /tmp/test_export_import.export -excludeAll -includeClass="asdf" in GZipped JSON format ...

Started export of database 'test_export_import' to /tmp/test_export_import.export.gz...
Exporting records...
- Cluster 'internal' (id=0)...OK (records=0/3)
- Cluster 'index' (id=1)...OK (records=0/0)
- Cluster 'manindex' (id=2)...OK (records=0/0)
- Cluster 'default' (id=3)...OK (records=0/0)
- Cluster 'orole' (id=4)...OK (records=0/3)
- Cluster 'ouser' (id=5)...OK (records=0/3)
- Cluster 'ofunction' (id=6)...OK (records=0/0)
- Cluster 'osequence' (id=7)...OK (records=0/0)
- Cluster 'oschedule' (id=8)...OK (records=0/0)
- Cluster 'v' (id=9)...OK (records=0/0)
- Cluster 'v_1' (id=10)...OK (records=0/0)
- Cluster 'v_2' (id=11)...OK (records=0/0)
- Cluster 'v_3' (id=12)...OK (records=0/0)
- Cluster 'e' (id=13)...OK (records=0/0)
- Cluster 'e_1' (id=14)...OK (records=0/0)
- Cluster 'e_2' (id=15)...OK (records=0/0)
- Cluster 'e_3' (id=16)...OK (records=0/0)
- Cluster 'asdf' (id=17)...OK (records=1/1)
- Cluster 'asdf_1' (id=18)...OK (records=0/0)
- Cluster 'asdf_2' (id=19)...OK (records=0/0)
- Cluster 'asdf_3' (id=20)...OK (records=0/0)

Done. Exported 1 of total 10 records. 0 records were detected as broken

Database export completed in 14ms
orientdb {db=test_export_import}> delete from asdf

Delete record(s) '1' in 0.004000 sec(s).

orientdb {db=test_export_import}> import database /tmp/test_export_import.export.gz

Importing database database /tmp/test_export_import.export.gz...
Started import of database 'plocal:/var/tmp/databases/test_export_import' from /tmp/test_export_import.export.gz...
Non merge mode (-merge=false): removing all default non security classes
- Class E was removed.
- Class V was removed.
- Class OTriggered was removed.
- Class ORestricted was removed.
- Class OSchedule was removed.
- Class asdf was removed.
- Class OSequence was removed.
- Class OFunction was removed.
Removed 8 classes.

Importing records...

Started migration of links (-migrateLinks=true). Links are going to be updated according to new RIDs:
- Cluster asdf_3... Completed migration of 0 records in current cluster
- Cluster ouser... Completed migration of 3 records in current cluster
- Cluster asdf_2... Completed migration of 0 records in current cluster
- Cluster asdf_1... Completed migration of 0 records in current cluster
- Cluster default... Completed migration of 0 records in current cluster
- Cluster orole... Completed migration of 3 records in current cluster
- Cluster asdf... Completed migration of 1 records in current cluster
Total links updated: 7

Done. Imported 1 records in 0.05 secs
Error on database import happened just before line 0, column 116
com.orientechnologies.orient.core.db.tool.ODatabaseImportException: Invalid format. Found unsupported tag 'brokenRids'
at com.orientechnologies.orient.core.db.tool.ODatabaseImport.importDatabase(ODatabaseImport.java:189)
at com.orientechnologies.orient.console.OConsoleDatabaseApp.importDatabase(OConsoleDatabaseApp.java:2188)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.orientechnologies.common.console.OConsoleApplication.execute(OConsoleApplication.java:405)
at com.orientechnologies.common.console.OConsoleApplication.executeCommands(OConsoleApplication.java:260)
at com.orientechnologies.common.console.OConsoleApplication.run(OConsoleApplication.java:131)
at com.orientechnologies.orient.console.OConsoleDatabaseApp.main(OConsoleDatabaseApp.java:145)

Error: com.orientechnologies.orient.core.db.tool.ODatabaseExportException: Error on importing database 'test_export_import' from file: /tmp/test_export_import.export.gz

Error: com.orientechnologies.orient.core.db.tool.ODatabaseImportException: Invalid format. Found unsupported tag 'brokenRids'
</code>```

Any help much appreciated.

EDIT: the exported data looks like this:

```<code>gunzip -c /tmp/test_export_import.export.gz
{"records":[{"@type":"d","@rid":"#17:0","@version":1,"@class":"asdf","one":"two","three":"four"}],"brokenRids":[]}
</code>```

答: it means that you try to import data which were exported by an older version of ODB. We do not support compatibility from the future to the past versions, but support compatibility in opposite way, of course.</p>

Body:
Trying to use OrientDB's export/import functionality, but I keep getting errors, both from command line client and by using the JavaAPI

Creating a database with minimal content, then calling

export database /tmp/db.export -excludeAll -includeClass="asdf"

then importing with

import database /tmp/db.export.gz

yields the error message Invalid format. Found unsupported tag 'brokenRids'. Here is the full console session to reproduce:

OrientDB console v.2.2.30 (build 43d850df23c0fd1edca7279761c2238fdc6cc576, branch 2.2.x) https://www.orientdb.com
Type 'help' to display all the supported commands.
orientdb> create database plocal:/var/tmp/databases/test_export_import

Creating database [plocal:/var/tmp/databases/test_export_import] using the storage type [plocal]...Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Auto configuration of disk cache size.
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: 2095874048 B/1998 MB/1 GB of physical memory were detected on machine
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Soft memory limit for this process is set to -1 B/-1 MB/-1 GB
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Hard memory limit for this process is set to -1 B/-1 MB/-1 GB
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Path to 'memory' cgroup is '/docker/f88c313794174ac8b8d7ad7d9b5fe396aea8033a1588e7eb6a3f903773081b81'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Mounting path for memory cgroup controller is '/sys/fs/memory'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Can not find '/sys/fs/memory/docker/f88c313794174ac8b8d7ad7d9b5fe396aea8033a1588e7eb6a3f903773081b81' path for memory cgroup, it is supposed that process is running in container, will try to read root '/sys/fs/memory' memory cgroup data
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Can not read memory soft limit for cgroup '/sys/fs/memory'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Can not read memory hard limit for cgroup '/sys/fs/memory'
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Detected memory limit for current process is 2095874048 B/1998 MB/1 GB
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: OrientDB auto-config DISKCACHE=444MB (heap=444MB direct=444MB os=1,998MB)
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Lowering disk cache size from 444MB to 442MB.
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: Lowering memory chunk size from 465,567,744B to 463,470,592B.
Dec 04, 2017 8:57:36 AM com.orientechnologies.common.log.OLogManager log
INFO: $ANSI{green {db=test_export_import}} Storage 'plocal:/var/tmp/databases/test_export_import' is created under OrientDB distribution : 2.2.30 (build 43d850df23c0fd1edca7279761c2238fdc6cc576, branch 2.2.x)

Database created successfully.

Current database is: plocal:/var/tmp/databases/test_export_import
orientdb {db=test_export_import}> create class asdf

Class created successfully. Total classes in database now: 11.

orientdb {db=test_export_import}> insert into asdf content {"one": "two", "three": "four"}

Inserted record 'asdf#17:0{one:two,three:four} v1' in 0.009000 sec(s).

orientdb {db=test_export_import}> select from asdf

+----+-----+------+------+------+
|#   |@RID |@CLASS|one   |three |
+----+-----+------+------+------+
|0   |#17:0|asdf  |two   |four  |
+----+-----+------+------+------+

1 item(s) found. Query executed in 0.005 sec(s).
orientdb {db=test_export_import}> export database /tmp/test_export_import.export -excludeAll -includeClass="asdf"
Exporting current database to: database /tmp/test_export_import.export -excludeAll -includeClass="asdf" in GZipped JSON format ...

Started export of database 'test_export_import' to /tmp/test_export_import.export.gz...
Exporting records...
- Cluster 'internal' (id=0)...OK (records=0/3)
- Cluster 'index' (id=1)...OK (records=0/0)
- Cluster 'manindex' (id=2)...OK (records=0/0)
- Cluster 'default' (id=3)...OK (records=0/0)
- Cluster 'orole' (id=4)...OK (records=0/3)
- Cluster 'ouser' (id=5)...OK (records=0/3)
- Cluster 'ofunction' (id=6)...OK (records=0/0)
- Cluster 'osequence' (id=7)...OK (records=0/0)
- Cluster 'oschedule' (id=8)...OK (records=0/0)
- Cluster 'v' (id=9)...OK (records=0/0)
- Cluster 'v_1' (id=10)...OK (records=0/0)
- Cluster 'v_2' (id=11)...OK (records=0/0)
- Cluster 'v_3' (id=12)...OK (records=0/0)
- Cluster 'e' (id=13)...OK (records=0/0)
- Cluster 'e_1' (id=14)...OK (records=0/0)
- Cluster 'e_2' (id=15)...OK (records=0/0)
- Cluster 'e_3' (id=16)...OK (records=0/0)
- Cluster 'asdf' (id=17)...OK (records=1/1)
- Cluster 'asdf_1' (id=18)...OK (records=0/0)
- Cluster 'asdf_2' (id=19)...OK (records=0/0)
- Cluster 'asdf_3' (id=20)...OK (records=0/0)

Done. Exported 1 of total 10 records. 0 records were detected as broken

Database export completed in 14ms
orientdb {db=test_export_import}> delete from asdf

Delete record(s) '1' in 0.004000 sec(s).

orientdb {db=test_export_import}> import database /tmp/test_export_import.export.gz

Importing database database /tmp/test_export_import.export.gz...
Started import of database 'plocal:/var/tmp/databases/test_export_import' from /tmp/test_export_import.export.gz...
Non merge mode (-merge=false): removing all default non security classes
- Class E was removed.
- Class V was removed.
- Class OTriggered was removed.
- Class ORestricted was removed.
- Class OSchedule was removed.
- Class asdf was removed.
- Class OSequence was removed.
- Class OFunction was removed.
Removed 8 classes.

Importing records...

Started migration of links (-migrateLinks=true). Links are going to be updated according to new RIDs:
- Cluster asdf_3... Completed migration of 0 records in current cluster
- Cluster ouser... Completed migration of 3 records in current cluster
- Cluster asdf_2... Completed migration of 0 records in current cluster
- Cluster asdf_1... Completed migration of 0 records in current cluster
- Cluster default... Completed migration of 0 records in current cluster
- Cluster orole... Completed migration of 3 records in current cluster
- Cluster asdf... Completed migration of 1 records in current cluster
Total links updated: 7

Done. Imported 1 records in 0.05 secs
Error on database import happened just before line 0, column 116
com.orientechnologies.orient.core.db.tool.ODatabaseImportException: Invalid format. Found unsupported tag 'brokenRids'
at com.orientechnologies.orient.core.db.tool.ODatabaseImport.importDatabase(ODatabaseImport.java:189)
at com.orientechnologies.orient.console.OConsoleDatabaseApp.importDatabase(OConsoleDatabaseApp.java:2188)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.orientechnologies.common.console.OConsoleApplication.execute(OConsoleApplication.java:405)
at com.orientechnologies.common.console.OConsoleApplication.executeCommands(OConsoleApplication.java:260)
at com.orientechnologies.common.console.OConsoleApplication.run(OConsoleApplication.java:131)
at com.orientechnologies.orient.console.OConsoleDatabaseApp.main(OConsoleDatabaseApp.java:145)

Error: com.orientechnologies.orient.core.db.tool.ODatabaseExportException: Error on importing database 'test_export_import' from file: /tmp/test_export_import.export.gz

Error: com.orientechnologies.orient.core.db.tool.ODatabaseImportException: Invalid format. Found unsupported tag 'brokenRids'

Any help much appreciated.

EDIT: the exported data looks like this:

gunzip -c /tmp/test_export_import.export.gz
{"records":[{"@type":"d","@rid":"#17:0","@version":1,"@class":"asdf","one":"two","three":"four"}],"brokenRids":[]}


来源: stackexchange

问:
ServiceStack AutoQuery - Check for null in nullable DateTime-field
I user ServiceStack autoquery to load information. I have a class like this one:

```<code>public class QueryItem: QueryDb<Item>
{
    public string Name { get; set; }
    public DateTime? BirthdayNotEqualTo { get; set; }
}
</code>```

As written in the documentation, I should be able to receive all items that are not null in the Birthday column like this:

```<code>QueryResponse<Item> item = jsonServiceClient.Get(new QueryItem {
    BirthdayNotEqualTo = null
});
</code>```

However, I receive all items, regardless of the null-filter above. How can I change that? The values in  the database are correctly set to null.

答:
It's not possible to send a null value using the ServiceClient. A null value, like default(DateTime?) means no value, so there's no "null filter" sent and your query is the same and indistinguishable from sending an Empty QueryItem DTO.

You'd need to use a Custom AutoQuery Implementation or a Customizable Query like:

```<code>[QueryDbField(Template = "{Field} IS NOT NULL", Field = "Birthday")]
public bool? BirthdayIsNotNull { get; set; }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I user ServiceStack autoquery to load information. I have a class like this one:

public class QueryItem: QueryDb<Item>
{
    public string Name { get; set; }
    public DateTime? BirthdayNotEqualTo { get; set; }
}

As written in the documentation, I should be able to receive all items that are not null in the Birthday column like this:

QueryResponse<Item> item = jsonServiceClient.Get(new QueryItem {
    BirthdayNotEqualTo = null
});

However, I receive all items, regardless of the null-filter above. How can I change that? The values in  the database are correctly set to null.

Body:
It's not possible to send a null value using the ServiceClient. A null value, like default(DateTime?) means no value, so there's no "null filter" sent and your query is the same and indistinguishable from sending an Empty QueryItem DTO.

You'd need to use a Custom AutoQuery Implementation or a Customizable Query like:

[QueryDbField(Template = "{Field} IS NOT NULL", Field = "Birthday")]
public bool? BirthdayIsNotNull { get; set; }


问:
JQGrid Pivot - Aggregate with string values
Is it possible to convert integer/numeric data to string values in aggregate:? I just need to convert the data in a pivot format and display the aggregate data in string format. Right now I'm getting NaN for string values in aggregator columns. Is there any option to do this or any workaround.</p>

答:
In case of using Guriddo jqGrid aggregator can be a custom function.
In the same documentation page you can see example of using custom aggregates.</p>


问:
Angular 5 animation - state transition for multiple buttons
I am working with PWA application using angular material and angular 5 animations. I'm using stepper component and have 2 buttons in each step. I would like to create a state (inactive/active) animation during hover event for each button. I am able to achieve this using variable/state binding for each button separately. But it looks like a lot of code in HTML. Is there any way i can achieve this using HostListener & hostbinding and avoid those html scripts.

app.component.html

step - 1

```<code><button id="login-form" [@buttonStateAnimation]="states.loginButton" (mouseenter)="toggleState('loginButton')" (mouseleave)="toggleState('loginButton')"
          [disabled]="!loginForm.valid" mat-raised-button (click)="loginEmail()" color="primary">
          <span>Login</span>
        </button>
        <button mat-raised-button (click)="signup()" [@buttonStateAnimation]="states.signupButton" (mouseenter)="toggleState('signupButton')"
          (mouseleave)="toggleState('signupButton')" matTooltip="New user? Sign up">
          <span>Sign up</span>
        </button>
</code>```

step - 2

```<code><button matTooltip="Login with Facebook" [@socialButtonsAnimation]="states.facebookButton" (mouseenter)="toggleState('facebookButton')"
          (mouseleave)="toggleState('facebookButton')" mat-mini-fab color="primary" (click)="loginFacebook()">
          <mat-icon class="fa-lg" fontSet="fontawesome" fontIcon="fa-facebook-square"></mat-icon>
        </button>
        <button matTooltip="Login with Google" [@socialButtonsAnimation]="states.googleButton" (mouseenter)="toggleState('googleButton')"
          (mouseleave)="toggleState('googleButton')" mat-mini-fab color="warn" (click)="loginGoogle()">
          <mat-icon class="fa-lg" fontSet="fontawesome" fontIcon="fa-google"></mat-icon>
        </button>
        <button matTooltip="Login with Twitter" [@socialButtonsAnimation]="states.twitterButton" (mouseenter)="toggleState('twitterButton')"
          (mouseleave)="toggleState('twitterButton')" mat-mini-fab color="primary" (click)="loginTwitter()">
          <mat-icon class="fa-lg" fontSet="fontawesome" fontIcon="fa-twitter"></mat-icon>
        </button>
</code>```

app.component.ts

```<code>export class LoginComponent implements OnInit {
  private states: any;
  ngOnInit() {
    this.states = {
      loginButton: "inactive",
      signupButton: "inactive",
      facebookButton: "inactive",
      googleButton: "inactive",
      twitterButton: "inactive"
   }
 }
}
</code>```

animations.ts

```<code>export const buttonStateAnimation =

 trigger('buttonStateAnimation', [
    state('inactive', style({ transform: 'translateX(0) scale(1)' })),
    state('active', style({ transform: 'translateX(0) scale(1.2)' })),
    transition('inactive => active', animate('200ms ease-in')),
    transition('active => inactive', animate('200ms ease-out')),
    transition(
      ':enter', [
        style({ transform: 'scale(.7)', opacity: 0 }),
        animate('0.3s', style({ opacity: 1, transform: 'scale(1)' })),
      ]
    ),
    transition(
      ':leave', [
        style({ opacity: 1, transform: 'scale(1)' }),
        animate('5.3s', style({ opacity: 0, transform: 'scale(.7)' })),
      ]
    )
  ])
</code>```

Now the above code looks repetitive and ugly in html. Is there any way this can be avoided and handled with host binding and at the same time maintain state for each buttons separately. Please help!!

答:
Yes! You should be able to achieve all of that using a directive and hostbindings and hostlisteners. Here is a rough (untested) example:

import { Directive, ElementRef, HostListener, HostBinding } from '@angular/core';

@Directive({
  selector: '[socialButton]',
})
export class SocialButtonDirective {

  constructor(private ref: ElementRef) {}

  @HostBinding('@socialButtonsAnimation') private state = 'inactive';

  @HostListener('mouseenter')
  @HostListener('mouseleave')
  private toggleState() {
    this.state = this.state === 'inactive' ? 'active': 'inactive';
  }
}
```

You will still need to import the animation definition into the component where this directive is used for it to work correctly.

Body:
I am working with PWA application using angular material and angular 5 animations. I'm using stepper component and have 2 buttons in each step. I would like to create a state (inactive/active) animation during hover event for each button. I am able to achieve this using variable/state binding for each button separately. But it looks like a lot of code in HTML. Is there any way i can achieve this using HostListener & hostbinding and avoid those html scripts.

app.component.html

step - 1

<button id="login-form" [@buttonStateAnimation]="states.loginButton" (mouseenter)="toggleState('loginButton')" (mouseleave)="toggleState('loginButton')"
          [disabled]="!loginForm.valid" mat-raised-button (click)="loginEmail()" color="primary">
          Login
        </button>
        <button mat-raised-button (click)="signup()" [@buttonStateAnimation]="states.signupButton" (mouseenter)="toggleState('signupButton')"
          (mouseleave)="toggleState('signupButton')" matTooltip="New user? Sign up">
          Sign up
        </button>

step - 2

<button matTooltip="Login with Facebook" [@socialButtonsAnimation]="states.facebookButton" (mouseenter)="toggleState('facebookButton')"
          (mouseleave)="toggleState('facebookButton')" mat-mini-fab color="primary" (click)="loginFacebook()">
          <mat-icon class="fa-lg" fontSet="fontawesome" fontIcon="fa-facebook-square"></mat-icon>
        </button>
        <button matTooltip="Login with Google" [@socialButtonsAnimation]="states.googleButton" (mouseenter)="toggleState('googleButton')"
          (mouseleave)="toggleState('googleButton')" mat-mini-fab color="warn" (click)="loginGoogle()">
          <mat-icon class="fa-lg" fontSet="fontawesome" fontIcon="fa-google"></mat-icon>
        </button>
        <button matTooltip="Login with Twitter" [@socialButtonsAnimation]="states.twitterButton" (mouseenter)="toggleState('twitterButton')"
          (mouseleave)="toggleState('twitterButton')" mat-mini-fab color="primary" (click)="loginTwitter()">
          <mat-icon class="fa-lg" fontSet="fontawesome" fontIcon="fa-twitter"></mat-icon>
        </button>

app.component.ts

export class LoginComponent implements OnInit {
  private states: any;
  ngOnInit() {
    this.states = {
      loginButton: "inactive",
      signupButton: "inactive",
      facebookButton: "inactive",
      googleButton: "inactive",
      twitterButton: "inactive"
   }
 }
}

animations.ts

export const buttonStateAnimation =

 trigger('buttonStateAnimation', [
    state('inactive', style({ transform: 'translateX(0) scale(1)' })),
    state('active', style({ transform: 'translateX(0) scale(1.2)' })),
    transition('inactive => active', animate('200ms ease-in')),
    transition('active => inactive', animate('200ms ease-out')),
    transition(
      ':enter', [
        style({ transform: 'scale(.7)', opacity: 0 }),
        animate('0.3s', style({ opacity: 1, transform: 'scale(1)' })),
      ]
    ),
    transition(
      ':leave', [
        style({ opacity: 1, transform: 'scale(1)' }),
        animate('5.3s', style({ opacity: 0, transform: 'scale(.7)' })),
      ]
    )
  ])

Now the above code looks repetitive and ugly in html. Is there any way this can be avoided and handled with host binding and at the same time maintain state for each buttons separately. Please help!!

Body:
Yes! You should be able to achieve all of that using a directive and hostbindings and hostlisteners. Here is a rough (untested) example:

import { Directive, ElementRef, HostListener, HostBinding } from '@angular/core';

@Directive({
  selector: '[socialButton]',
})
export class SocialButtonDirective {

  constructor(private ref: ElementRef) {}

  @HostBinding('@socialButtonsAnimation') private state = 'inactive';

  @HostListener('mouseenter')
  @HostListener('mouseleave')
  private toggleState() {
    this.state = this.state === 'inactive' ? 'active': 'inactive';
  }
}

You will still need to import the animation definition into the component where this directive is used for it to work correctly.


问:
OpenCV in Python
Code runs but instead of posting my name during the detector.py it says unknown. Anyone have any solutions?

```<code>import cv2
import numpy as np

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
font = cv2.FONT_HERSHEY_SIMPLEX
cam = cv2.VideoCapture(0)

while True:
    ret, im =cam.read()
    gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, 1.2,5)

for(x,y,w,h) in faces:
   cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)
   Id = recognizer.predict(gray[y:y+h,x:x+w])
    if(Id == 1):
        Id = "Alec"
    elif(Id == 2):
         Id = "Chase"
    else:
        Id = "Unknown"
    cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)
    cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3)
if cv2.waitKey(10) & 0xFF == ord('q'):
    break

cam.release()
cv2.destroyAllWindows()
</code>```

It is not showing any types of error. I have commented out the If(id==X) code just to see what it would print on the screen. The program printed (1, 30-40). So I'm guessing the 1 is my ID. I have the DataSet and trainer program if I need to provide it.

答:
Confidence is standard set to 50.
However the Id has 2 values in it. the int(ID) and double(Conf).
https://docs.opencv.org/3.0.0/dd/d65/classcv_1_1face_1_1FaceRecognizer.html#aede3fa2ec7a4ee35e67bc998df23883b
getting the first value with Id[1] would work

```<code>for(x,y,w,h) in faces:
  cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)
  Id = recognizer.predict(gray[y:y+h,x:x+w])
    if(Id[1] == 1):
       Id = "Alec"
    elif(Id[1] == 2):
       Id = "Chase"
    else:
       Id = "Unknown"
  cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)
  cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3)
if cv2.waitKey(10) & 0xFF == ord('q'):
   break
</code>```

or

```<code>for(x,y,w,h) in faces:
   cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)
   Id,conf = recognizer.predict(gray[y:y+h,x:x+w])
     if(Id == 1):
        Id = "Alec"
     elif(Id == 2):
        Id = "Chase"
     else:
        Id = "Unknown"
  cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)
  cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3)
if cv2.waitKey(10) & 0xFF == ord('q'):
    break
</code>```

Title: OpenCV in Python

Body:
Code runs but instead of posting my name during the detector.py it says unknown. Anyone have any solutions?

import cv2
import numpy as np

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
font = cv2.FONT_HERSHEY_SIMPLEX
cam = cv2.VideoCapture(0)

while True:
    ret, im =cam.read()
    gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, 1.2,5)

for(x,y,w,h) in faces:
   cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)
   Id = recognizer.predict(gray[y:y+h,x:x+w])
    if(Id == 1):
        Id = "Alec"
    elif(Id == 2):
         Id = "Chase"
    else:
        Id = "Unknown"
    cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)
    cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3)
if cv2.waitKey(10) & 0xFF == ord('q'):
    break

cam.release()
cv2.destroyAllWindows()

It is not showing any types of error. I have commented out the If(id==X) code just to see what it would print on the screen. The program printed (1, 30-40). So I'm guessing the 1 is my ID. I have the DataSet and trainer program if I need to provide it.

Body:
Confidence is standard set to 50.
However the Id has 2 values in it. the int(ID) and double(Conf).
https://docs.opencv.org/3.0.0/dd/d65/classcv_1_1face_1_1FaceRecognizer.html#aede3fa2ec7a4ee35e67bc998df23883b
getting the first value with Id[1] would work

for(x,y,w,h) in faces:
  cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)
  Id = recognizer.predict(gray[y:y+h,x:x+w])
    if(Id[1] == 1):
       Id = "Alec"
    elif(Id[1] == 2):
       Id = "Chase"
    else:
       Id = "Unknown"
  cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)
  cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3)
if cv2.waitKey(10) & 0xFF == ord('q'):
   break

or

for(x,y,w,h) in faces:
   cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4)
   Id,conf = recognizer.predict(gray[y:y+h,x:x+w])
     if(Id == 1):
        Id = "Alec"
     elif(Id == 2):
        Id = "Chase"
     else:
        Id = "Unknown"
  cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1)
  cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3)
if cv2.waitKey(10) & 0xFF == ord('q'):
    break


问:
Self Updating app?
I'm new to Android development and I would like to ask if a self-updating feature could be possible. The details are:

The application is designed as an In House App, not going to be published on Google Play.

Will need to run only in Kiosk mode.

The self-updating feature will have to work as following: In the settings screen, there will be an Update button that will start downloading the new version of apk. After the apk will be downloaded, it will have to start the updating process automatically.

Is this even possible?

答: Yes, it's possible, furthermore, there are services that can do this for you, such as HockeyApp's update manager</p>

Title: Self Updating app?


问:
How do bash's logical operators work (or why don't they work here)?
I have the following wrapper script:

```<code>#!/bin/bash

$local_time=`date +%H%M`
if [ $local_time -ge 1430 ] && [ $local_time -le 2230 ] ||
   [ $local_time -ge 0300 ] && [ $local_time -le 0400 ]
then
   echo 'pass'
else
   echo 'skip'
fi
</code>```

The idea being to create a wrapper script that runs a script between two disjoint time intervals. Each of the expressions being OR'd is evaluated correctly, however, when I OR both expressions, the test fails.

How do I fix this?

答:
bash does not have "logical operators"; those are "conditional chains". Logic belongs in the test.</p>

```<code>if [[ ( 10#${local_time} -ge 10#1430 && 10#${local_time} -le 10#2230 ) || \
      ( 10#${local_time} -ge 10#0300 && 10#${local_time} -le 10#0400 ) ]]
then
 ...
</code>```

Body:
I have the following wrapper script:

#!/bin/bash

$local_time=`date +%H%M`
if [ $local_time -ge 1430 ] && [ $local_time -le 2230 ] ||
   [ $local_time -ge 0300 ] && [ $local_time -le 0400 ]
then
   echo 'pass'
else
   echo 'skip'
fi

The idea being to create a wrapper script that runs a script between two disjoint time intervals. Each of the expressions being OR'd is evaluated correctly, however, when I OR both expressions, the test fails.

How do I fix this?

Body:
bash does not have "logical operators"; those are "conditional chains". Logic belongs in the test.

if [[ ( 10#${local_time} -ge 10#1430 && 10#${local_time} -le 10#2230 ) || \
      ( 10#${local_time} -ge 10#0300 && 10#${local_time} -le 10#0400 ) ]]
then
 ...


问:
Vue router clear history API when going back from a default view?
I am using the vue-router for overlay menu's on mobile. This means when a user selects a filter link a full overlay will slide in from the left with filters options.

A user can of course select a filter from the default view, go back to the default view and select a filter again. This will cause the history to contain:

Default view

Filter view

Default view

Filter view

When a user clicks back multiple times it will iterate through the actions in reverse while preferably if there is an overlay active it should go back to the default view and then simply omit the history API data and continue with the default history data.

To get this done I guess I could use named routes and differentiate from a root(default) route between a non-root(overlay). If I want to go back on a root I should then delete the history API data?

Any thoughts on how to get this done?

The browser history can not be manipulated so how do I go back to a state before all the manipulation that has been done by the vue-router?

答: Try navigating around the filter views by calling this.$router.replace(). That way, back will take you to the page before default.


问:
CMake project linking Yaml-cpp and Armadillo shared libraries
I'm working on Linux (leap 42.3). I want to write a CMakeList.txt file which creates my shared library containing my code and also yaml-cpp and armadillo libraries in order to use it in another code. So:

Is it better to first compile and install separately Yaml-cpp and Armadillo from their respective packages and CMakeList.txt files or to build and compile everything together from my CMake project?

At the moment I followed the second way, but I end up with my library which doesn't link well yaml nor armadillo, if I do nm or ldd.

The structure of my project is the following:

In the "upper level" I have:

```<code>cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(myproject CXX)

set(CMAKE_INSTALL_PREFIX "../install" CACHE STRING
"Install path prefix, prepended onto install directories." FORCE)
mark_as_advanced(CMAKE_INSTALL_PREFIX)

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I all my include files ")

include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/all my src file directories)
add_subdirectory(src)

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")

find_package(Yaml REQUIRED)
add_library(Yaml INTERFACE IMPORTED)
set_property(TARGET Yaml PROPERTY
INTERFACE_INCLUDE_DIRECTORIES ${YAML_INCLUDE_DIR})
include_directories(${YAML_INCLUDE_DIRS})

find_package(BlasLapack)

find_package(Armadillo REQUIRED)
add_library(Armadillo INTERFACE IMPORTED)
set_property(TARGET Armadillo PROPERTY
INTERFACE_INCLUDE_DIRECTORIES ${ARMADILLO_INCLUDE_DIR})
include_directories(${ARMADILLO_INCLUDE_DIRS})
</code>```

In the "middle level" I have:

```<code>cmake_minimum_required(VERSION 2.8 FATAL_ERROR)

function (add_sources target)
get_property(prop_defined GLOBAL PROPERTY ${target}_SRCS DEFINED)
if(NOT prop_defined)
  define_property(GLOBAL PROPERTY ${target}_SRCS
  BRIEF_DOCS "Sources for the ${target} target"
  FULL_DOCS "List of source files for the ${target} target")
endif()

set(SRCS)
foreach(src IN LISTS ARGN)
 if(NOT IS_ABSOLUTE "${src}")
  get_filename_component(src "${src}" ABSOLUTE)
 endif()
 list(APPEND SRCS "${src}")
endforeach()

set_property(GLOBAL APPEND PROPERTY "${target}_SRCS" "${SRCS}")
endfunction()

add_subdirectory(all my src directories)

get_property(myproject_SRCS GLOBAL PROPERTY myproject_SRCS)
add_library(myproject SHARED ${myproject_SRCS})
install(TARGETS myproject DESTINATION lib)
</code>```

And finally in the "inner level" I have:

```<code>cmake_minimum_required(VERSION 2.8 FATAL_ERROR)

add_sources(myproject
            mysource.cpp)

install(FILES mysource.hpp DESTINATION include/myproject)
</code>```

So, what's missing? How can I incorporate Yaml-cpp and Armadillo shared libraries in mine? Thank you.

答:
Typically, CMake find commands like find_package(Yaml REQUIRED) sets variables like YAML_LIBRARIES. For details, see the source code FindYAML.cmake.

To link with the YAML shared library, use this variable:

```<code>target_link_libraries(myproject ${YAML_LIBRARIES})
</code>```

Body:
I'm working on Linux (leap 42.3). I want to write a CMakeList.txt file which creates my shared library containing my code and also yaml-cpp and armadillo libraries in order to use it in another code. So:

Is it better to first compile and install separately Yaml-cpp and Armadillo from their respective packages and CMakeList.txt files or to build and compile everything together from my CMake project?

At the moment I followed the second way, but I end up with my library which doesn't link well yaml nor armadillo, if I do nm or ldd.

The structure of my project is the following:

In the "upper level" I have:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(myproject CXX)

set(CMAKE_INSTALL_PREFIX "../install" CACHE STRING
"Install path prefix, prepended onto install directories." FORCE)
mark_as_advanced(CMAKE_INSTALL_PREFIX)

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I all my include files ")

include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/all my src file directories)
add_subdirectory(src)

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake")

find_package(Yaml REQUIRED)
add_library(Yaml INTERFACE IMPORTED)
set_property(TARGET Yaml PROPERTY
INTERFACE_INCLUDE_DIRECTORIES ${YAML_INCLUDE_DIR})
include_directories(${YAML_INCLUDE_DIRS})

find_package(BlasLapack)

find_package(Armadillo REQUIRED)
add_library(Armadillo INTERFACE IMPORTED)
set_property(TARGET Armadillo PROPERTY
INTERFACE_INCLUDE_DIRECTORIES ${ARMADILLO_INCLUDE_DIR})
include_directories(${ARMADILLO_INCLUDE_DIRS})

In the "middle level" I have:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)

function (add_sources target)
get_property(prop_defined GLOBAL PROPERTY ${target}_SRCS DEFINED)
if(NOT prop_defined)
  define_property(GLOBAL PROPERTY ${target}_SRCS
  BRIEF_DOCS "Sources for the ${target} target"
  FULL_DOCS "List of source files for the ${target} target")
endif()

set(SRCS)
foreach(src IN LISTS ARGN)
 if(NOT IS_ABSOLUTE "${src}")
  get_filename_component(src "${src}" ABSOLUTE)
 endif()
 list(APPEND SRCS "${src}")
endforeach()

set_property(GLOBAL APPEND PROPERTY "${target}_SRCS" "${SRCS}")
endfunction()

add_subdirectory(all my src directories)

get_property(myproject_SRCS GLOBAL PROPERTY myproject_SRCS)
add_library(myproject SHARED ${myproject_SRCS})
install(TARGETS myproject DESTINATION lib)

And finally in the "inner level" I have:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)

add_sources(myproject
            mysource.cpp)

install(FILES mysource.hpp DESTINATION include/myproject)

So, what's missing? How can I incorporate Yaml-cpp and Armadillo shared libraries in mine? Thank you.

Body:
Typically, CMake find commands like find_package(Yaml REQUIRED) sets variables like YAML_LIBRARIES. For details, see the source code FindYAML.cmake.

To link with the YAML shared library, use this variable:

target_link_libraries(myproject ${YAML_LIBRARIES})


问:
Override value from ui-iconpicker Library - Angular
I'm using the following library to be able to select an icon in an input field for angular.

https://github.com/justin-lau/ui-iconpicker

What I've tried

```<code><!-- Generates iconpicker button -->
<ui-iconpicker ng-model="icon"
               groups="font-awesome">
</ui-iconpicker>

<!-- input field with icon string that will be stored in DB -->
<input ng-model="icon"
       type="text"
       class="form-control"
       placeholder="Select Icon"
       name="icon"
       disabled>
</code>```

I have this JSON string stored in my database

```<code>"icon":"fa fa-lg fa-heart"
</code>```

But somehow I can't or don't know how to override the default value from this ui-iconpicker library.

My ng-model icon will be set to fa fa-lg fa-glass by loading my page again and overrides my "fa fa-lg fa-heart"

To get the data I have an initialise function that will get the object with the icon by the way. But that gets ignored or overrided by the library functionality. What I would like is to override this value in the controller again.

Any help is appreciated.

答:
Maybe if your have </p>

```<code>var icon = {"icon":"fa fa-lg fa-heart"};
</code>```

<p>then </p>

```<code><ui-iconpicker ng-model="icon.icon"
               groups="font-awesome">
</ui-iconpicker>
</code>```

Body:
I'm using the following library to be able to select an icon in an input field for angular.

https://github.com/justin-lau/ui-iconpicker

What I've tried

<ui-iconpicker ng-model="icon"
               groups="font-awesome">
</ui-iconpicker>

<input ng-model="icon"
       type="text"
       class="form-control"
       placeholder="Select Icon"
       name="icon"
       disabled>

I have this JSON string stored in my database

"icon":"fa fa-lg fa-heart"

But somehow I can't or don't know how to override the default value from this ui-iconpicker library.

My ng-model icon will be set to fa fa-lg fa-glass by loading my page again and overrides my "fa fa-lg fa-heart"

To get the data I have an initialise function that will get the object with the icon by the way. But that gets ignored or overrided by the library functionality. What I would like is to override this value in the controller again.

Any help is appreciated.

Body:
Maybe if your have

var icon = {"icon":"fa fa-lg fa-heart"};

then

<ui-iconpicker ng-model="icon.icon"
               groups="font-awesome">
</ui-iconpicker>


问:
change the bootstrap 4 dropdown-menu option to show and hide divs in html
I have a dropdowm-menu bar with 3 option. when i change the options I need to hide/show the div's. Can you please suggest me how to do in jquery.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

      Options 1
      Option 2
      Option 3

 Selected Option1

 Selected Option2

 Selected Option3
```

答:
$(function(){
                 $("#option1").click(function () {
                  alert("Service");
                  $('#serviceCharts').show();
                  $('#option-2').hide();
                  $('#option-3').hide();
                  $('#about-us').text($(this).text());

                 });

                 $("#option2").click(function () {
                  alert("Sales");
                  $('#option-1').hide();
                  $('#option-2').show();
                  $('#option-3').hide();
                  $('#about-us').text($(this).text());

                 });

                 $("#option3").click(function () {
                  alert("Recall");
                  $('#option-1').hide();
                  $('#option-2').hide();
                  $('#option-3').show();
                  $('#about-us').text($(this).text());

                 });

               });

   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row col-xl-12  justify-content-center  align-items-center" style="padding: 0 0 100px;">
                      <div class=" dropdown m-auto justify-content-center snapshotdropmenu">
                          <span class="selectprogram">Select Program:</span>
                          <button class="btn btn-salesbtn dropdown-toggle" type="button" id="about-us" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                          </button>
                      <div class="dropdown-menu dropdown-menu-right" aria-labelledby="about-us">
                          option1
                          option2
                          option3
                      </div>
                      </div>
                  </div>

            <div id="option-1" class="group">Red</div>
            <div id="option-2" class="group" style="display:none">Blue</div>
            <div id="option-3" class="group" style="display:none">Green</div></code>```

Body:
$(function(){
                 $("#option1").click(function () {
                  alert("Service");
                  $('#serviceCharts').show();
                  $('#option-2').hide();
                  $('#option-3').hide();
                  $('#about-us').text($(this).text());

                 });

                 $("#option2").click(function () {
                  alert("Sales");
                  $('#option-1').hide();
                  $('#option-2').show();
                  $('#option-3').hide();
                  $('#about-us').text($(this).text());

                 });

                 $("#option3").click(function () {
                  alert("Recall");
                  $('#option-1').hide();
                  $('#option-2').hide();
                  $('#option-3').show();
                  $('#about-us').text($(this).text());

                 });

               });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row col-xl-12  justify-content-center  align-items-center" style="padding: 0 0 100px;">
                      <div class=" dropdown m-auto justify-content-center snapshotdropmenu">
                          <span class="selectprogram">Select Program:</span>
                          <button class="btn btn-salesbtn dropdown-toggle" type="button" id="about-us" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                          </button>
                      <div class="dropdown-menu dropdown-menu-right" aria-labelledby="about-us">
                          <a class="dropdown-item" id="option1">option1</a>
                          <a class="dropdown-item" id="option2">option2</a>
                          <a class="dropdown-item" id="option3">option3</a>
                      </div>
                      </div>
                  </div>

            <div id="option-1" class="group">Red</div>
            <div id="option-2" class="group" style="display:none">Blue</div>
            <div id="option-3" class="group" style="display:none">Green</div>


问:
How to use DSL plugin to download source code from VSTS
I am maintaining my source code in VSTS (Version Control is GIT). For CI process I am using Jenkins.

I would like create a dynamic job using DSL plugin and that dynamic job should download the code from VSTS.

So how can I pass credentials to download code from VSTS?

答:
Try something like credentials binding plugin for build jobs
https://support.cloudbees.com/hc/en-us/articles/203802500-Injecting-Secrets-into-Jenkins-Build-Jobs</p>


问:
Need to change selected item in dropdown list when selected item in another dropdown list changes
I have a windows form application with two Combo boxes (Dropdownlist style). The first combo box gets the data from a List of AppTable object, like so:

```<code>foreach (AppTable table in appTableList)
            cbxSelectName.Items.Add(table.App);
</code>```

I have set up a trigger for when the selected item in this dropdown is changed:

```<code>this.cbxSelectName.SelectedIndexChanged +=new EventHandler(cbxSelectName_SelectedIndexChanged);
</code>```

And finally, here is the definition of the method the trigger calls. Please note, the value in tbxNewWikiWord textbox changes as the selected item is changed. However, the same does not happen in the second dropdown list ( cbxUpdateAppType):

```<code>private void cbxSelectName_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (AppTable table in appTableList)
        {
            if (table.App == cbxSelectName.SelectedItem.ToString())
            {
                this.tbxNewWikiWord.Text = table.WikiWord;
                this.cbxUpdateAppType.SelectedItem = table.Type;
                break;
            }
        }

    }
</code>```

This is how AppTable looks:

```<code>class AppTable
{
    public string App { get; set; }
    public string Type { get; set; }
    public string WikiWord { get; set; }

}
</code>```

Am I missing something?

答:
Adding values to cbxUpdateAppType from the AppTable object fixed it. I'm not sure why since in either case, I was adding Strings.

I just needed to check for duplicates so I don't end up with multiple instances of the same value in my dropdown box.

```<code>foreach (AppTable table in appTableList)
        {
            if (!cbxUpdateAppType.Items.Contains(table.Type))
                cbxUpdateAppType.Items.Add(table.Type);
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a windows form application with two Combo boxes (Dropdownlist style). The first combo box gets the data from a List of AppTable object, like so:

foreach (AppTable table in appTableList)
            cbxSelectName.Items.Add(table.App);

I have set up a trigger for when the selected item in this dropdown is changed:

this.cbxSelectName.SelectedIndexChanged +=new EventHandler(cbxSelectName_SelectedIndexChanged);

And finally, here is the definition of the method the trigger calls. Please note, the value in tbxNewWikiWord textbox changes as the selected item is changed. However, the same does not happen in the second dropdown list ( cbxUpdateAppType):

private void cbxSelectName_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (AppTable table in appTableList)
        {
            if (table.App == cbxSelectName.SelectedItem.ToString())
            {
                this.tbxNewWikiWord.Text = table.WikiWord;
                this.cbxUpdateAppType.SelectedItem = table.Type;
                break;
            }
        }

    }

This is how AppTable looks:

class AppTable
{
    public string App { get; set; }
    public string Type { get; set; }
    public string WikiWord { get; set; }

}

Am I missing something?

Body:
Adding values to cbxUpdateAppType from the AppTable object fixed it. I'm not sure why since in either case, I was adding Strings.

I just needed to check for duplicates so I don't end up with multiple instances of the same value in my dropdown box.

foreach (AppTable table in appTableList)
        {
            if (!cbxUpdateAppType.Items.Contains(table.Type))
                cbxUpdateAppType.Items.Add(table.Type);
        }


问:
How to identify Html and Controller completed loading in angular js

Hi,

I am displaying an unsaved changes popup when user enters something and changing his route to another page without saving data.

I used $watch to identify data change event and checking form is dirty or not. If form is dirty I am displaying unsaved changes popup.

My issue is onload some of the forms are become dirty. Unsaved changed popup is displaying user is not done any change also.

I have two approaches to resolve this issue:

$watch should execute once html and controller is completes loading.

I have to identify an event that html and controller is completes loading.

I used angular.element(document).ready(function () {}); to identify document loaded event. It is not working. It is executing first time of the page load.

Can anyone tell me the solution for this?

答:
You can use something like this, every time your controller will load, init function will fire and will set the form state to untouched and pristine :

```<code>angular.module('myApp')
.controller('Controller1', function ($scope) {
    $scope.init = function () {
        // $setPristine() sets the form's $pristine state to true,
        // the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
        // Additionally, it sets the $submitted state to false.
        $scope.form.$setPristine();

        //Sets the form to its untouched state.
        $scope.form.$setUntouched();
    }
    $scope.init();
})
.controller('Controller2', function ($scope) {
    $scope.init = function () {

        // $setPristine() sets the form's $pristine state to true,
        // the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
        // Additionally, it sets the $submitted state to false.
        $scope.form.$setPristine();

        //Sets the form to its untouched state.
        $scope.form.$setUntouched();
    }

    $scope.init();

});
</code>```

Body:
You can use something like this, every time your controller will load, init function will fire and will set the form state to untouched and pristine :

angular.module('myApp')
.controller('Controller1', function ($scope) {
    $scope.init = function () {
        // $setPristine() sets the form's $pristine state to true,
        // the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
        // Additionally, it sets the $submitted state to false.
        $scope.form.$setPristine();

        //Sets the form to its untouched state.
        $scope.form.$setUntouched();
    }
    $scope.init();
})
.controller('Controller2', function ($scope) {
    $scope.init = function () {

        // $setPristine() sets the form's $pristine state to true,
        // the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
        // Additionally, it sets the $submitted state to false.
        $scope.form.$setPristine();

        //Sets the form to its untouched state.
        $scope.form.$setUntouched();
    }

    $scope.init();

});


问:
Remove part of string but getting the deleted part as result
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

```<code>var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20
</code>```

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

Body:
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

Body:
var teste = '10/12/2017'.replace(/(?=....$)../, '');
console.log(teste);


问:
Tornadofx Custom Table Cell
how to insert a button or any other kind of component in javafx tableview cell using tornadofx ?
I am in a situation where i have a column header "Action". I need to render several action buttons in the table view .</p>

答:
Use the cellFormat function and assign a container with the buttons to the graphic property of the cell:

```<code>column("Name", SomeObject::someproperty).cellFormat {
    graphic = hbox(spacing = 5) {
        button("Action 1").action { doSomething() }
        button("Action 2").action { doSomethingElse() }
    }
}
</code>```

Title: Tornadofx Custom Table Cell

Body:
Use the cellFormat function and assign a container with the buttons to the graphic property of the cell:

column("Name", SomeObject::someproperty).cellFormat {
    graphic = hbox(spacing = 5) {
        button("Action 1").action { doSomething() }
        button("Action 2").action { doSomethingElse() }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Is micro-optimization worth the time?
I am a PHP developer and I have always thought that micro-optimizations are not worth the time. If you really need that extra performance, you would either write your software so that it's architecturally faster, or you write a C++ extension to handle slow tasks (or better yet, compile the code using HipHop). However, today a work mate told me that there is a big difference in

```<code>is_array($array)
</code>```

and

```<code>$array === (array) $array
</code>```

and I was like "eh, that's a pointless comparison really", but he wouldn't agree with me.. and he is the best developer in our company and is taking charge of a website that does about 50 million SQL queries per day -- for instance. So, I am wondering here: could he be wrong or is micro-optimization really worth the time and when?

答:
IMHO, micro-optimizations are actually even more relevant than algorithmic optimizations today if you are working in a performance-critical field. This might be a big if because many people don't actually work in performance-critical areas even for performance-critical software since they might just be making high-level calls into a third party library which does the actual performance-critical work. For example, many people these days trying to write an image or video software might write non-performance-critical code expressing they want at the image level, not having to manually loop through several million pixels themselves at 100+ frames per second. The library does that for them.

When I say that micro-optimizations are more relevant than algorithmic ones today, I don't mean that, say, parallelized SIMD code that minimizes cache misses applying a bubble sort will beat an introsort or radix sort. What I mean is that professionals don't bubble sort large input sizes.

If you take any reasonably high-level language today, of which I include C++, you already have your share of reasonably efficient general-purpose data structures and algorithms at your fingertips. There's no excuse unless you're a beginning computer science student just getting your feet wet and reinventing the most primitive of wheels to be applying quadratic complexity sorts to massive input sizes or linear-time searches which can be accomplished in constant-time with the appropriate data structures.

So once you get past this beginner level, performance-critical applications still have wildly varying performance characteristics. Why? Why would one video processing software have three times the frame rate and more interactive video previews than the other when the developers aren't doing anything extremely dumb algorithmically? Why would one server doing a very similar thing be able to handle ten times the queries with the same hardware? Why would this software load a scene in 5 seconds while the other takes 5 minutes loading the same data? Why would this beautiful game have silky smooth and consistent frame rates while the other one is uglier, more primitive-looking with its graphics and lighting, and stutters here and there while taking twice the memory?

And that boils down to micro-optimizations, not algorithmic differences. Furthermore our memory hierarchy today is so skewed in performance, making previous algorithms that were thought to be good a couple of decades ago no longer as good if they exhibit poor locality of reference.

So if you want to write competitively-efficient software today, far more often than not, that will boil down to things like multithreading, SIMD, GPU, GPGPU, improving locality of reference with better memory access patterns (loop tiling, SoA, hot/cold field splitting, etc.), maybe even optimizing for branch prediction in extreme cases, and so forth, not so much algorithmic breakthroughs unless you're tackling an extremely unexplored territory where no programmers have ventured before.

There are still occasionally algorithmic breakthroughs that are potential game changers, like voxel-cone tracing recently. But those are exceptions and the people who come up with these often invest their lives to R&D (they're generally not people writing and maintaining large scale codebases), and it still boils down to micro-optimizations whether voxel-cone tracing can be applied to real-time environments like games or not. If you aren't good at micro-optimizations, you simply won't get the adequate framerates even using these algorithmic breakthroughs.

Title: Is micro-optimization worth the time?

Body:
I am a PHP developer and I have always thought that micro-optimizations are not worth the time. If you really need that extra performance, you would either write your software so that it's architecturally faster, or you write a C++ extension to handle slow tasks (or better yet, compile the code using HipHop). However, today a work mate told me that there is a big difference in

is_array($array)

and

$array === (array) $array

and I was like "eh, that's a pointless comparison really", but he wouldn't agree with me.. and he is the best developer in our company and is taking charge of a website that does about 50 million SQL queries per day -- for instance. So, I am wondering here: could he be wrong or is micro-optimization really worth the time and when?


问:
Mypy rejects type objects created with `type(name, (bases,), {})`
I'm having some trouble getting mypy to accept type objects. I am
convinced I'm just doing it wrong but my google searches have not led me to any answers so far.

```<code>class Good(object):
    a = 1

def works(thing: Good):
    print(thing.a)

o = Good()
works(o)

Bad = type('Bad', (object, ), dict(a=1))

def fails_mypy(thing: Bad):
    print(thing.a)

s = Bad()
fails_mypy(s)
</code>```

Things constructed like 'Good' are ok, while things constructed like 'Bad' fail mypy checks with:

```<code>error: Invalid type "test.Bad"
error: Bad? has no attribute "a"
</code>```

答:
Based on the Unsupported Python Features section of mypys wiki, runtime creation of classes like this isn't currently supported. It cannot understand what Bad is in your function definition. Using reveal_type(Good) and reveal_type(Bad) when executing mypy should make this clear.

An approach to silence these is by using Any. Either using Python 3.6 variable annotation syntax:

```<code>Bad: Any = type('Bad', (), {'a':1})
</code>```

or, with Python < 3.6:

```<code>Bad = type('Bad', (), {'a':1}) # type: Any
</code>```

(in both cases Any should first be imported from typing)

of course, this basically means that your function now accepts anything. A price to pay, but that's what you get with dynamic languages; since Bar is defined at runtime, it can theoretically be anything :-)

Body:
I'm having some trouble getting mypy to accept type objects. I am
convinced I'm just doing it wrong but my google searches have not led me to any answers so far.

class Good(object):
    a = 1

def works(thing: Good):
    print(thing.a)

o = Good()
works(o)

Bad = type('Bad', (object, ), dict(a=1))

def fails_mypy(thing: Bad):
    print(thing.a)

s = Bad()
fails_mypy(s)

Things constructed like 'Good' are ok, while things constructed like 'Bad' fail mypy checks with:

error: Invalid type "test.Bad"
error: Bad? has no attribute "a"

Body:
Based on the Unsupported Python Features section of mypys wiki, runtime creation of classes like this isn't currently supported. It cannot understand what Bad is in your function definition. Using reveal_type(Good) and reveal_type(Bad) when executing mypy should make this clear.

An approach to silence these is by using Any. Either using Python 3.6 variable annotation syntax:

Bad: Any = type('Bad', (), {'a':1})

or, with Python < 3.6:

Bad = type('Bad', (), {'a':1}) # type: Any

(in both cases Any should first be imported from typing)

of course, this basically means that your function now accepts anything. A price to pay, but that's what you get with dynamic languages; since Bar is defined at runtime, it can theoretically be anything :-)


问:
GWT formpanel does not call onSubmitComplete
GWT: I can call the servlet in browser. When I call it by formpanel, it can call onSubmit. But it does not call onSubmitComplete. It wil also popup a new window, the uri is my servlet.</p>

```<code>String URL= GWT.getModuleBaseURL()+"getType";
         FormPanel formPanel = new FormPanel();
         formPanel.setAction(URL);
         formPanel.setEncoding(FormPanel.ENCODING_URLENCODED);
         formPanel.setMethod(FormPanel.METHOD_GET);

     formPanel.addSubmitHandler(new SubmitHandler(){

        @Override
        public void onSubmit(SubmitEvent event) {
            // TODO Auto-generated method stub
            System.out.println(event.getSource());
        }

     });
     formPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
            public void onSubmitComplete(SubmitCompleteEvent event) {
                System.out.println("in");
                System.out.println(event.getResults());
            }
        });
     formPanel.submit();

GWT.xml
 <servlet class="msp2.server.getType" path="/getType" />

web.xml
    <servlet >
<servlet-name>getType</servlet-name>
    <servlet-class>msp2.server.getType</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>getType</servlet-name>
    <url-pattern>/msp2_app/getType</url-pattern>
</servlet-mapping>
</code>```

答:
I also had the same issue it turns out to be I did not set the action URL of the FormPanel.</p>

```<code>final FormPanel formPanel = new FormPanel();
formPanel.setAction("/test");
</code>```

Body:
GWT: I can call the servlet in browser. When I call it by formpanel, it can call onSubmit. But it does not call onSubmitComplete. It wil also popup a new window, the uri is my servlet.

String URL= GWT.getModuleBaseURL()+"getType";
         FormPanel formPanel = new FormPanel();
         formPanel.setAction(URL);
         formPanel.setEncoding(FormPanel.ENCODING_URLENCODED);
         formPanel.setMethod(FormPanel.METHOD_GET);

     formPanel.addSubmitHandler(new SubmitHandler(){

        @Override
        public void onSubmit(SubmitEvent event) {
            // TODO Auto-generated method stub
            System.out.println(event.getSource());
        }

     });
     formPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
            public void onSubmitComplete(SubmitCompleteEvent event) {
                System.out.println("in");
                System.out.println(event.getResults());
            }
        });
     formPanel.submit();

GWT.xml
 <servlet class="msp2.server.getType" path="/getType" />

web.xml
    <servlet >
<servlet-name>getType</servlet-name>
    <servlet-class>msp2.server.getType</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>getType</servlet-name>
    <url-pattern>/msp2_app/getType</url-pattern>
</servlet-mapping>

Body:
I also had the same issue it turns out to be I did not set the action URL of the FormPanel.

final FormPanel formPanel = new FormPanel();
formPanel.setAction("/test");


问:
How to get files contained in a path
In the following path:

```<code>app/test/vehicle/
</code>```

there are several .js file. Is there any way in Javascript where I can get the number of .js file contains in the above-mentioned path?

I am using webStorm environment

答:
Where are you trying to get list of the files? On the client side it is impossible. JavaScript does not have access to the client file system. If you are trying to do it in the server side using for example node.js then you can do something like:</p>

```<code>var filesys = require('fs');
var files = filesys.readdirSync('/app/test/vehicle/');
</code>```

Title: How to get files contained in a path

Body:
In the following path:

app/test/vehicle/

there are several .js file. Is there any way in Javascript where I can get the number of .js file contains in the above-mentioned path?

I am using webStorm environment

Body:
Where are you trying to get list of the files? On the client side it is impossible. JavaScript does not have access to the client file system. If you are trying to do it in the server side using for example node.js then you can do something like:

var filesys = require('fs');
var files = filesys.readdirSync('/app/test/vehicle/');


问:
Why does Fabric mac app opens automatically when project is running?
As part of fabric integration I have installed Fabric mac app,
I found that whenever I run the project(I am running iOS app through XCode), the Fabric app also gets launched automatically,

My Questions are:

Why it automatically launches when running project ?

Is there a way I can stop this happening ?

FYI: The same happens even when the app is running in simulator.

答:
Mike from Fabric here. It's an odd behavior that you're seeing and is most likely due to an old version of the Run Script. Years ago, the run script build phase required the Fabric app to be present in order to handle the actual uploading of the dSYMs. We would move the dSYMs during the build of the app to a location that the Fabric app would then asynchronously upload them. That behavior was changed a long way back, but it's possible a new version never was included. The current version is: Fabric.framework/run 1.6.2 (205)

I'd check the version by running ./run -v from the project and update your Fabric and Crashlytics frameworks.

You can also remove Fabric.app completely from your system and switch to using CocoaPods or manual installation instructions. It hasn't been required to use for a couple of years.


问:
Why can't Traefik find a container on the same network?
I have setup Docker Swarm with 3 nodes. They are all configured as part of the cluster. The master node is also a host for containers.

Each node has an NFS mount to NFS to store centralised data.

I have created an ElasticSearch cluster that is global, so it runs on all the nodes. This is configured to run in Docker Swarm using DNS Round Robin (dnsrr) in the cluser. As dnsrr does not allow ports to be exposed I have an Nginx proxy server that listens for requests on 19200 and then proxies them to the service elasticsearch on port 9200.

The Traefik, ElasticSearch Proxy and ElasticSearch nodes are all attached to the same overlay network called elastic_cluster. The network is 10.0.10.0/24.

I have configured Traefik so that it has a named host and answers to elasticsearch.homenetwork.local (not real domain) on port 443. (Let's Encrypt is configured) and should forward to the Nginx proxy.

However when I try and hit https://elasticsearch.homenetwork.local I get an error in the Traefik logs:

```<code>time="2017-12-02T22:50:37Z" level=warning msg="Error forwarding to http://10.0.10.3:19200, err: dial tcp 10.0.10.3:19200: getsockopt: no route to host"
</code>```

Given that the Traefik service is on the 10.0.10.0/24 network I do not understand why I get this error. I am using Portainer to track the services and I can see that the Traefik service has an IP address of 10.0.10.4.

If I run an interactive session to the Nginx Proxy, which has an IP address of 10.0.10.7, I am able to ping 10.0.10.4 without issue.

The containers are all running Ubuntu. There is no iptables involved.

Has anyone seen something like this before? I am struggling to work out what is wrong here so if anyone has any suggestions I would be very grateful for them. What is really annoying is that this used to work. I do not recall changing anything but obviously something has.

ElasticSearch service command:

```<code>docker service create --name elasticsearch \
                      --network elastic_cluster \
                      --constraint "node.labels.app_role == "elasticsearch" \
                      --mode global \
                      --endpoint-mode dnsrr \
                      docker.elastic.co/elasticsearch/elasticsearch:5.4.2 \
                      elasticsearch
</code>```

ElasticSearch Proxy service command:

```<code>docker service create --name elasticsearch_proxy \
                      --network elastic_cluster \
                      --label traefik.enable=true \
                      --label traefik.backend=elasticsearch_proxy \
                      --label traefik.port=19200 \
                      --label traefik.frontend.rule=Host:elasticsearch.home.turtlesystems.co.uk \
                      --label traefik.docker.network=elastic_cluster \
                      nginx:1.13
</code>```

nginx.conf - https://pastebin.com/Q5sXw6aw

Traefik service command

```<code>docker service create --name reverse_proxy \
                      --network elastic_cluster \
                      --network traefik-net \
                      --constraint "node.role == manager" \
                      --publish 80:80 \
                      --publish 8080:8080 \
                      --publish 443:443 \
                      traefik
</code>```

traefik.toml - https://pastebin.com/GFPu8MYJ

答:
I think you have forgot to mention labels set on your services</p>

```<code>docker service create --name elasticsearch_proxy \
                      --label traefik.docker.network=elastic_cluster
                      --label traefik.enable=true
                      --label traefik.port=19200
                      --network elastic_cluster \
                      nginx:1.13
</code>```

Body:
I have setup Docker Swarm with 3 nodes. They are all configured as part of the cluster. The master node is also a host for containers.

Each node has an NFS mount to NFS to store centralised data.

I have created an ElasticSearch cluster that is global, so it runs on all the nodes. This is configured to run in Docker Swarm using DNS Round Robin (dnsrr) in the cluser. As dnsrr does not allow ports to be exposed I have an Nginx proxy server that listens for requests on 19200 and then proxies them to the service elasticsearch on port 9200.

The Traefik, ElasticSearch Proxy and ElasticSearch nodes are all attached to the same overlay network called elastic_cluster. The network is 10.0.10.0/24.

I have configured Traefik so that it has a named host and answers to elasticsearch.homenetwork.local (not real domain) on port 443. (Let's Encrypt is configured) and should forward to the Nginx proxy.

However when I try and hit https://elasticsearch.homenetwork.local I get an error in the Traefik logs:

time="2017-12-02T22:50:37Z" level=warning msg="Error forwarding to http://10.0.10.3:19200, err: dial tcp 10.0.10.3:19200: getsockopt: no route to host"

Given that the Traefik service is on the 10.0.10.0/24 network I do not understand why I get this error. I am using Portainer to track the services and I can see that the Traefik service has an IP address of 10.0.10.4.

If I run an interactive session to the Nginx Proxy, which has an IP address of 10.0.10.7, I am able to ping 10.0.10.4 without issue.

The containers are all running Ubuntu. There is no iptables involved.

Has anyone seen something like this before? I am struggling to work out what is wrong here so if anyone has any suggestions I would be very grateful for them. What is really annoying is that this used to work. I do not recall changing anything but obviously something has.

ElasticSearch service command:

docker service create --name elasticsearch \
                      --network elastic_cluster \
                      --constraint "node.labels.app_role == "elasticsearch" \
                      --mode global \
                      --endpoint-mode dnsrr \
                      docker.elastic.co/elasticsearch/elasticsearch:5.4.2 \
                      elasticsearch

ElasticSearch Proxy service command:

docker service create --name elasticsearch_proxy \
                      --network elastic_cluster \
                      --label traefik.enable=true \
                      --label traefik.backend=elasticsearch_proxy \
                      --label traefik.port=19200 \
                      --label traefik.frontend.rule=Host:elasticsearch.home.turtlesystems.co.uk \
                      --label traefik.docker.network=elastic_cluster \
                      nginx:1.13

nginx.conf - https://pastebin.com/Q5sXw6aw

Traefik service command

docker service create --name reverse_proxy \
                      --network elastic_cluster \
                      --network traefik-net \
                      --constraint "node.role == manager" \
                      --publish 80:80 \
                      --publish 8080:8080 \
                      --publish 443:443 \
                      traefik

traefik.toml - https://pastebin.com/GFPu8MYJ

Body:
I think you have forgot to mention labels set on your services

docker service create --name elasticsearch_proxy \
                      --label traefik.docker.network=elastic_cluster
                      --label traefik.enable=true
                      --label traefik.port=19200
                      --network elastic_cluster \
                      nginx:1.13


问:
How to do pagination in select box based on scroll
HTML

```<code><select class="form-control choice requiredField" id-available name="SelectData" ng-model="box.box_id" title="Select">
    <option value="" disabled selected>{{'_SELECT_BEACON_' | i18n}}</option>
    <option value="{{y.box_id}}" ng-repeat="y in dataList" class="nms">{{y.beacon_code}}</option>
</select>
</code>```

ANGULARJS

```<code>boxService.listUnassignedDevice(function(res) {
    $scope.dataList = res;
}, function(error) {
});
</code>```

Here I have large data in "dataList"(10000>). So I need to list data in select box after mouse scroll down. First I have to show 100 data, when mouse scroll down, I need to show next 100 data from API.

答:
you can use ngInfiniteScroll directive and add script tag then add module 'infinite-scroll'and then Use the directive by specifying an infinite-scroll attribute on an element.

```<code><div infinite-scroll="myPagingFunction()" infinite-scroll-distance="3"></div>
</code>```

ngInfiniteScroll will call myPagingFunction() any time the bottom of
  the element approaches the bottom of the browser window. See the API
  documentation for more information about what attributes are available
  for use, and take a look at the demos to see ngInfiniteScroll in
  action.

Body:
HTML

<select class="form-control choice requiredField" id-available name="SelectData" ng-model="box.box_id" title="Select">
    <option value="" disabled selected>{{'_SELECT_BEACON_' | i18n}}</option>
    <option value="{{y.box_id}}" ng-repeat="y in dataList" class="nms">{{y.beacon_code}}</option>
</select>

ANGULARJS

boxService.listUnassignedDevice(function(res) {
    $scope.dataList = res;
}, function(error) {
});

Here I have large data in "dataList"(10000>). So I need to list data in select box after mouse scroll down. First I have to show 100 data, when mouse scroll down, I need to show next 100 data from API.

Body:
you can use ngInfiniteScroll directive and add script tag then add module 'infinite-scroll'and then Use the directive by specifying an infinite-scroll attribute on an element.

<div infinite-scroll="myPagingFunction()" infinite-scroll-distance="3"></div>

ngInfiniteScroll will call myPagingFunction() any time the bottom of
  the element approaches the bottom of the browser window. See the API
  documentation for more information about what attributes are available
  for use, and take a look at the demos to see ngInfiniteScroll in
  action.


问:
XSLT: Change attribute value everywhere
I have XML files of unknown/different structure. I have to change the value of an attribute.

 This is just an example and the structure can be anything:

```<code><root>
    <SomeElement endTime='12:00:00' />
    <subLevel>
        <OtherElement endTime='14:00:00' />
    </subLevel>
</root>
</code>```

I need to change the endTime attribute everywhere it occurs. The output should be

```<code><root>
    <SomeElement endTime='11:59:59' />
    <subLevel>
        <OtherElement endTime='13:59:59' />
    </subLevel>
</root>
</code>```

I could do this if I knew the exact position of the attribute but how to do it if I just don't know the structure of the XML file and need to change it for every element in the file? Is that even possible?

答:
Well, if you know how to alter that value then write a template

```<code><xsl:template match="@endTime">
  <xsl:attribute name="{name()}">
   <!-- code to alter value here -->
  </xsl:attribute>
</xsl:template>
</code>```

and handle the rest with the identity transformation, i.e. in XSLT 3 with <xsl:mode on-no-match="shallow-copy"/> or in earlier versions with

```<code><xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>
</code>```

In XSLT 2 or 3 you can directly use the substraction between an xs:time value and a duration to implement the change:

```<code><xsl:template match="@endTime">
  <xsl:attribute name="{name()}" select="xs:time(.) - xs:dayTimeDuration('PT1S')"/>
</xsl:template>
</code>```

No need to create an xs:dateTime first.

Online example at http://xsltransform.hikmatu.com/b4GWV4

Title: XSLT: Change attribute value everywhere

Body:
I have XML files of unknown/different structure. I have to change the value of an attribute.

 This is just an example and the structure can be anything:

<root>
    <SomeElement endTime='12:00:00' />
    <subLevel>
        <OtherElement endTime='14:00:00' />
    </subLevel>
</root>

I need to change the endTime attribute everywhere it occurs. The output should be

<root>
    <SomeElement endTime='11:59:59' />
    <subLevel>
        <OtherElement endTime='13:59:59' />
    </subLevel>
</root>

I could do this if I knew the exact position of the attribute but how to do it if I just don't know the structure of the XML file and need to change it for every element in the file? Is that even possible?

Body:
Well, if you know how to alter that value then write a template

<xsl:template match="@endTime">
  <xsl:attribute name="{name()}">
   <!-- code to alter value here -->
  </xsl:attribute>
</xsl:template>

and handle the rest with the identity transformation, i.e. in XSLT 3 with <xsl:mode on-no-match="shallow-copy"/> or in earlier versions with

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

In XSLT 2 or 3 you can directly use the substraction between an xs:time value and a duration to implement the change:

<xsl:template match="@endTime">
  <xsl:attribute name="{name()}" select="xs:time(.) - xs:dayTimeDuration('PT1S')"/>
</xsl:template>

No need to create an xs:dateTime first.

Online example at http://xsltransform.hikmatu.com/b4GWV4


问:
Why wont my file open and how can I fix it?
Whenever I run my program the screen prints "cannot open file filename". I followed guidelines and methodology in my lecture notes and really can't figure out why it won't open. Any kind of help will be much appreciated.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define READONLY "r"

int main (void)
{
  FILE *ipfile;
  char filename[FILENAME_MAX+1];
  int *unsorted_details;
  int elements;

  printf("Enter the name of the input file:\n");
  scanf("%s", filename);

  if((ipfile=fopen(filename, READONLY)) == NULL){
    fprintf(stderr, "Couldn't open %s. \n", filename);
    exit(EXIT_FAILURE);
  }
  if (fscanf(ipfile, "%d", &elements) != 1){
    fprintf(stderr, "Couldn't read object details from %s\n",
filename);
    exit(EXIT_FAILURE);
  }
  if ((unsorted_details=(int *)malloc(elements * sizeof(int))) == NULL){
    fprintf(stderr, "Failed to allocate memory.\n");
    exit (EXIT_FAILURE);
  }
  /* Reading elements from file into unsorted array*/
    int i;
  for (i=0; i<elements; i++){
    if(!fscanf(ipfile, "%d", &unsorted_details[i])){
        fprintf(stderr, "Error reading element %d of the list\n", i+1);
        exit (EXIT_FAILURE);
    }

   }
  fclose(ipfile);
  free(unsorted_details);
  return (EXIT_SUCCESS);
}
</code>```

答:
Most library functions make use of an external variable called errno which is set when one of those functions fails and indicates the reason for the failure.

You can get a textual description of the error message either by calling perror, which prints the error message to stderr, or you can call strerror(errno) which returns a char * which points to the error message that you can subsequently put in your own error message.

In the case of the failed call to fopen, change your error message to the following:

```<code>fprintf(stderr, "Couldn't open %s: %s \n", filename, strerror(errno));
</code>```

You can make similar changes to your other error messages.  Once you do this, you'll know why the function failed and take appropriate action.

Body:
Whenever I run my program the screen prints "cannot open file filename". I followed guidelines and methodology in my lecture notes and really can't figure out why it won't open. Any kind of help will be much appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define READONLY "r"

int main (void)
{
  FILE *ipfile;
  char filename[FILENAME_MAX+1];
  int *unsorted_details;
  int elements;

  printf("Enter the name of the input file:\n");
  scanf("%s", filename);

  if((ipfile=fopen(filename, READONLY)) == NULL){
    fprintf(stderr, "Couldn't open %s. \n", filename);
    exit(EXIT_FAILURE);
  }
  if (fscanf(ipfile, "%d", &elements) != 1){
    fprintf(stderr, "Couldn't read object details from %s\n",
filename);
    exit(EXIT_FAILURE);
  }
  if ((unsorted_details=(int *)malloc(elements * sizeof(int))) == NULL){
    fprintf(stderr, "Failed to allocate memory.\n");
    exit (EXIT_FAILURE);
  }
  /* Reading elements from file into unsorted array*/
    int i;
  for (i=0; i<elements; i++){
    if(!fscanf(ipfile, "%d", &unsorted_details[i])){
        fprintf(stderr, "Error reading element %d of the list\n", i+1);
        exit (EXIT_FAILURE);
    }

   }
  fclose(ipfile);
  free(unsorted_details);
  return (EXIT_SUCCESS);
}

Body:
Most library functions make use of an external variable called errno which is set when one of those functions fails and indicates the reason for the failure.

You can get a textual description of the error message either by calling perror, which prints the error message to stderr, or you can call strerror(errno) which returns a char * which points to the error message that you can subsequently put in your own error message.

In the case of the failed call to fopen, change your error message to the following:

fprintf(stderr, "Couldn't open %s: %s \n", filename, strerror(errno));

You can make similar changes to your other error messages.  Once you do this, you'll know why the function failed and take appropriate action.


问:
How to create table and its structure using jquery for HTML
I have values coming from database in a variable by parsing it from JSON. Now I want to create a HTML table structure like below

```<code><table class="table dataList fiberEngg">
    <tbody>
        <tr>
            <td>
                <div class="row noPadding">
                    <div class="col-xs-6 colPadding">
                        MHBHNDMUNVMBSPN006_BU
                        <a class="button"><i class="fa fa-map-marker" aria-hidden="true"></i></a><a class="button"><i class="fa fa-list" aria-hidden="true"></i></a>
                    </div>
                    <div class="col-xs-6 colPadding">
                        <p><strong>Request Id :</strong>053214</p>
                        <p><strong>Last Updated by :</strong>Sameer Parab</p>
                        <p><strong>Status :</strong>Partial HOTO with Partial LIT</p>
                        <p><strong>Pending Since :</strong>1 Day</p>
                    </div>
                </div>
            </td>
        </tr>
    </tbody>
</table>
</code>```

and my JSON is below

```<code>[
    {
        "SPAN_ID": "GJVAPIMHKAKHSPN003_BU",
        "MAINTENANCEZONECODE": "INMUMIBH01",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "HARDIK1.SHAH",
        "STATUS_NAME": "HOTO without LIT",
        "PENDING_DAYS": 7.0
    }
]
</code>```

how can I create a table structure in below code

```<code> success: function (response) {

    var datalist = JSON.parse(response);
    var table = $("#tblFiberEngData");
    table.empty();

    datalist.forEach(function (dataRow) {
        //here i want to create structure
    });
}
</code>```

答:
In order to append elements dynamically using jQuery, try this:

$( "td" ).append( "

" );```

Body:
I have values coming from database in a variable by parsing it from JSON. Now I want to create a HTML table structure like below

                        MHBHNDMUNVMBSPN006_BU

Request Id :053214

Last Updated by :Sameer Parab

Status :Partial HOTO with Partial LIT

Pending Since :1 Day

and my JSON is below

[
    {
        "SPAN_ID": "GJVAPIMHKAKHSPN003_BU",
        "MAINTENANCEZONECODE": "INMUMIBH01",
        "REQ_ID": 4.0,
        "LAST_UPDATE_BY": "HARDIK1.SHAH",
        "STATUS_NAME": "HOTO without LIT",
        "PENDING_DAYS": 7.0
    }
]

how can I create a table structure in below code

 success: function (response) {

    var datalist = JSON.parse(response);
    var table = $("#tblFiberEngData");
    table.empty();

    datalist.forEach(function (dataRow) {
        //here i want to create structure
    });
}

Body:
In order to append elements dynamically using jQuery, try this:

$( "td" ).append( "<div></div>" );


问:
Matching ImplicitlyUnwrappedOptional in a switch statement
I'm trying to use a switch case to match a type of a generic, but I'm not sure how to match ImplicitlyUnwrappedOptional's.

Imagine the function:

```<code>enum AttributeName: String {
    case someFloat = "someFloat"
    case someTint = "SomeTint"
}

func defaultValue<T>(_ name: AttributeName) -> T {
    switch name {
        case .someFloat:
            return CGFloat(8.0) as! T
        case .someTint:
            return UIColor.blue as! T
    }
}

func attribute<T>(_ name: AttributeName) -> T? {

    let attributes: [AttributeName: Any] = [AttributeName.someFloat: 10.0,
                                            AttributeName.someTint: UIColor.red]

    switch T.self {
    case is CGFloat.Type:
        guard let aFloat = attributes[name] as? Float
            else { return nil }
        return CGFloat(aFloat) as? T
    case is CGColor.Type:
        guard let color = attributes[name] as? UIColor
            else { return nil }
        return color as? T
    default:
        guard let attribute = attributes[name] as? T
            else { return nil }
        return attribute
    }
}

let button = UIButton()
button.layer.cornerRadius = attribute(AttributeName.someFloat) ?? defaultValue(AttributeName.someFloat)
button.backgroundColor = attribute(AttributeName.someTint) ?? defaultValue(AttributeName.someTint)
button.tintColor = attribute(AttributeName.someTint)
</code>```

The above works fine if you try to call:

```<code>let button = UIButton()
button.layer.cornerRadius = attribute("float") // will be 10.0
button.backgroundColor = attribute("tint") // will be red
</code>```

But trying to assign the button's tintColor will return a nil because the type of T will be an ImplicitlyUnwrappedOptional<UIColor>. I.e:

```<code>button.tintColor = attribute("tint") // will be nil
</code>```

I think I know what an ImplicitlyUnwrappedOptional is and why Apple uses them (by reading this question). But how do I match tintColor in this case?

I could do: let tint: UIColor = attribute("tint") and assign tint to the button's tintColor.
But is manually creating a UIColor and assigning it to tintColor really the only way?

答:
How about using a better type to represent your data, sidestepping your issue? Perhaps something like this:</p>

```<code>struct ButtonStyle {
    // If some of these proprties need to be optional (i.e. they're not always
    // set as part of a style) then comment below and I'll modify this accordingly
    cornerRadius: CGFloat
    backgroundColor: UIColor

    init(cornerRadius: CGFloat, backgroundColor: UIColor) {
        self.cornerRadius = cornerRadius
        self.backgroundColor = backgroundColor
    }

    // If you need to initialize ButtonStyle objects from dictionaries
    // (e.g. from JSON), you can use this.
    // However, using `Codable` instead is ***greatly*** preferred.
    init?(fromDict dict: [String: Any] {
        guard let cornerRadius = dict["float"] as? CGFloat,
              let backgroundColor = dict["color"] as? UIColor {
            return nil
        }
        self.init(cornerRadius: cornerRadius, backgroundColor: backgroundColor)
    }
}

extension UIButton {
    var style: ButtonStyle {
        get {
            ButtonStyle(cornerRadius: self.layer.cornerRadius,
                        backgroundColor: self.backgroundColor)

        }
        set {
            self.layer.cornerRadius = newValue.cornerRadius
            self.backgroundColor = newValue.backgroundColor
        }
    }
}

let buttonStyle = ButtonStyle(cornerRadius: 10, backgroundColor: UIColor.red)
let button = UIButton()
button.style = buttonStyle
</code>```

Body:
I'm trying to use a switch case to match a type of a generic, but I'm not sure how to match ImplicitlyUnwrappedOptional's.

Imagine the function:

enum AttributeName: String {
    case someFloat = "someFloat"
    case someTint = "SomeTint"
}

func defaultValue<T>(_ name: AttributeName) -> T {
    switch name {
        case .someFloat:
            return CGFloat(8.0) as! T
        case .someTint:
            return UIColor.blue as! T
    }
}

func attribute<T>(_ name: AttributeName) -> T? {

    let attributes: [AttributeName: Any] = [AttributeName.someFloat: 10.0,
                                            AttributeName.someTint: UIColor.red]

    switch T.self {
    case is CGFloat.Type:
        guard let aFloat = attributes[name] as? Float
            else { return nil }
        return CGFloat(aFloat) as? T
    case is CGColor.Type:
        guard let color = attributes[name] as? UIColor
            else { return nil }
        return color as? T
    default:
        guard let attribute = attributes[name] as? T
            else { return nil }
        return attribute
    }
}

let button = UIButton()
button.layer.cornerRadius = attribute(AttributeName.someFloat) ?? defaultValue(AttributeName.someFloat)
button.backgroundColor = attribute(AttributeName.someTint) ?? defaultValue(AttributeName.someTint)
button.tintColor = attribute(AttributeName.someTint)

The above works fine if you try to call:

let button = UIButton()
button.layer.cornerRadius = attribute("float") // will be 10.0
button.backgroundColor = attribute("tint") // will be red

But trying to assign the button's tintColor will return a nil because the type of T will be an ImplicitlyUnwrappedOptional<UIColor>. I.e:

button.tintColor = attribute("tint") // will be nil

I think I know what an ImplicitlyUnwrappedOptional is and why Apple uses them (by reading this question). But how do I match tintColor in this case?

I could do: let tint: UIColor = attribute("tint") and assign tint to the button's tintColor.
But is manually creating a UIColor and assigning it to tintColor really the only way?

Body:
How about using a better type to represent your data, sidestepping your issue? Perhaps something like this:

struct ButtonStyle {
    // If some of these proprties need to be optional (i.e. they're not always
    // set as part of a style) then comment below and I'll modify this accordingly
    cornerRadius: CGFloat
    backgroundColor: UIColor

    init(cornerRadius: CGFloat, backgroundColor: UIColor) {
        self.cornerRadius = cornerRadius
        self.backgroundColor = backgroundColor
    }

    // If you need to initialize ButtonStyle objects from dictionaries
    // (e.g. from JSON), you can use this.
    // However, using `Codable` instead is ***greatly*** preferred.
    init?(fromDict dict: [String: Any] {
        guard let cornerRadius = dict["float"] as? CGFloat,
              let backgroundColor = dict["color"] as? UIColor {
            return nil
        }
        self.init(cornerRadius: cornerRadius, backgroundColor: backgroundColor)
    }
}

extension UIButton {
    var style: ButtonStyle {
        get {
            ButtonStyle(cornerRadius: self.layer.cornerRadius,
                        backgroundColor: self.backgroundColor)

        }
        set {
            self.layer.cornerRadius = newValue.cornerRadius
            self.backgroundColor = newValue.backgroundColor
        }
    }
}

let buttonStyle = ButtonStyle(cornerRadius: 10, backgroundColor: UIColor.red)
let button = UIButton()
button.style = buttonStyle