问:
Query and Orderby multiple ACF Fields
I have a custom post type called "property".

Each property has an ACF checkbox fields called "property_status" with the following options:

rent : For Rent

rented : Rented

sale : For Sale

sold : Sold Homes

new : Under Construction

Each property also has a featured listing ACF radio button field called "property_featured" with the following options:

no : No

yes : Yes

I have successfully queried the posts to show up using the following code:

```<code>$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
    'post_type' => 'property',
    'posts_per_page' => 12,
    'meta_key' => 'property_status',
    'orderby'    => array(
        'property_featured' => 'ASC',
        'property_status' => 'ASC'
    ),
    'order' => 'ASC',
    'paged' => $paged
    );
$wp_query = new WP_Query( $args );
</code>```

I need to order my posts by calling the featured properties with a radio button selection of "yes : Yes", then display the other posts under "properties" by their 'property_status' of rent, rent and new, sale, then sale and new.  Some properties can have 2 check boxes selected in the "property_status" field such as a property for rent, but that is all "new" under construction.

I have tried several different query declarations to try and display these custom posts by the order I need, but have not had any success.  The code above is what I am using.

答:
As described in the WP_Query documentation, if you wish to order by two different pieces of postmeta (for example, property_featured first and property_status second), you need to combine and link your meta query to your orderby array using 'named meta queries'.

Below is your code modified :

```<code>$args = array(
    'post_type'      => 'property',
    'posts_per_page' => 12,
    'paged'          => $paged,

    'meta_query'     => array(
        'relation' => 'AND',
        'featured_clause' => array(
            'key' => 'property_featured',
            'compare' => 'EXISTS'
        ),
        'status_clause' => array(
            'key' => 'property_status',
            'compare' => 'EXISTS'
        )
    ),

    'orderby'    => array(
        'featured_clause' => 'ASC',
        'status_clause' => 'ASC'
    )

);
</code>```

Title: Query and Orderby multiple ACF Fields

Body:
I have a custom post type called "property".

Each property has an ACF checkbox fields called "property_status" with the following options:

rent : For Rent

rented : Rented

sale : For Sale

sold : Sold Homes

new : Under Construction

Each property also has a featured listing ACF radio button field called "property_featured" with the following options:

no : No

yes : Yes

I have successfully queried the posts to show up using the following code:

$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
    'post_type' => 'property',
    'posts_per_page' => 12,
    'meta_key' => 'property_status',
    'orderby'    => array(
        'property_featured' => 'ASC',
        'property_status' => 'ASC'
    ),
    'order' => 'ASC',
    'paged' => $paged
    );
$wp_query = new WP_Query( $args );

I need to order my posts by calling the featured properties with a radio button selection of "yes : Yes", then display the other posts under "properties" by their 'property_status' of rent, rent and new, sale, then sale and new.  Some properties can have 2 check boxes selected in the "property_status" field such as a property for rent, but that is all "new" under construction.

I have tried several different query declarations to try and display these custom posts by the order I need, but have not had any success.  The code above is what I am using.

Body:
As described in the WP_Query documentation, if you wish to order by two different pieces of postmeta (for example, property_featured first and property_status second), you need to combine and link your meta query to your orderby array using 'named meta queries'.

Below is your code modified :

$args = array(
    'post_type'      => 'property',
    'posts_per_page' => 12,
    'paged'          => $paged,

    'meta_query'     => array(
        'relation' => 'AND',
        'featured_clause' => array(
            'key' => 'property_featured',
            'compare' => 'EXISTS'
        ),
        'status_clause' => array(
            'key' => 'property_status',
            'compare' => 'EXISTS'
        )
    ),

    'orderby'    => array(
        'featured_clause' => 'ASC',
        'status_clause' => 'ASC'
    )

);


来源: stackexchange

问:
How to preset (programmatically) the filter value in primeng datatable
Using angular (4.1.3) and primeng (4.0.3) datatable I need to set the filter value (e.g. from URL parameter).

There is a pretty good docu on custom filters by primeng (https://www.primefaces.org/primeng/#/datatable/filter).
I've tried to implement it similarly with a primeng InputText component as a custom filter:

```<code><p-dataTable
      [value]="licenses" scrollable="true"
      exportFilename="licenses"
      sscrollHeight="60vh" [paginator]="true" [rows]="20"  [pageLinks]="10" [rowsPerPageOptions]="[5,10,20,50,100,999999]" #dt>

        <p-column [style]="{'width':'180px'}" [sortable]="true" field="customerId" header="Customer ID" [filter]="true" filterMatchMode="contains" filterPlaceholder="Search">

          <ng-template pTemplate="filter" let-col>
            <input type="text" pInputText [(ngModel)]="custFilter" style="width:100%" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" class="ui-column-filter"/>
          </ng-template>

        </p-column>

        ...

</p-dataTable>
</code>```

Now I have an input field, which looks like the "regular" one and even has a "custFilter" model from my component as pre-selected filter value.

The only issue is, this custom filter does not work. It just does not filter regardless of which value I enter (in opposite to the "regular" primeng datatable filter).
Here is a screenshot

答:
While further debugging the type script code I have found a way to do the filtering. The input should be like following:

```<code><input #filtr type="text" pInputText [(ngModel)]="custFilter" style="width:100%" (input)="dt.filter($event.srcElement.value,col.field,col.filterMatchMode);" class="ui-column-filter"/>
</code>```

The main difference is, the (input) instead of (onChange) and "$event.srcElement.value" instead of just "$event.value"

Furthermore to achieve initial filtering after the page and data is initially loaded an input event has to be dispatched from within an according component:

```<code>...
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
...
export class DataComponent implements OnInit {
  @ViewChild(('dt')) dt: DataTable;
  @ViewChild(('filtr')) filtr: ElementRef;
    private initData(): void {
        this.dataService
          .getData()
          .then(data => {
            this.data = data;

            //After the data is loaded, the filtering has to be triggered.
            //A timeout is needed to avoid weird browser console logs if data isn't fully loaded into datatable yet before filtering
            setTimeout(() => {
              //console.log(this.filtr);
              var event = new Event('input', {
                  'bubbles': true,
                  'cancelable': true
              });
              this.filtr.nativeElement.dispatchEvent(event);

              //One could also call "filter" directly instead of dispatching an input event
              //Working example: this.dt.filter(this.custFilter,"customerId", "contains");
              //But emmiting an event seems to be better, because no filterMatchMode has to be
              //hardcoded and is taken from template
            }, 50);
          }).catch(this.handleError);
      }

      ngOnInit(): void {
        this.initLicenses();
      }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using angular (4.1.3) and primeng (4.0.3) datatable I need to set the filter value (e.g. from URL parameter).

There is a pretty good docu on custom filters by primeng (https://www.primefaces.org/primeng/#/datatable/filter).
I've tried to implement it similarly with a primeng InputText component as a custom filter:

          <ng-template pTemplate="filter" let-col>
            <input type="text" pInputText [(ngModel)]="custFilter" style="width:100%" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" class="ui-column-filter"/>
          </ng-template>

        ...

Now I have an input field, which looks like the "regular" one and even has a "custFilter" model from my component as pre-selected filter value.

The only issue is, this custom filter does not work. It just does not filter regardless of which value I enter (in opposite to the "regular" primeng datatable filter).
Here is a screenshot

Body:
While further debugging the type script code I have found a way to do the filtering. The input should be like following:

<input #filtr type="text" pInputText [(ngModel)]="custFilter" style="width:100%" (input)="dt.filter($event.srcElement.value,col.field,col.filterMatchMode);" class="ui-column-filter"/>

The main difference is, the (input) instead of (onChange) and "$event.srcElement.value" instead of just "$event.value"

Furthermore to achieve initial filtering after the page and data is initially loaded an input event has to be dispatched from within an according component:

...
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
...
export class DataComponent implements OnInit {
  @ViewChild(('dt')) dt: DataTable;
  @ViewChild(('filtr')) filtr: ElementRef;
    private initData(): void {
        this.dataService
          .getData()
          .then(data => {
            this.data = data;

            //After the data is loaded, the filtering has to be triggered.
            //A timeout is needed to avoid weird browser console logs if data isn't fully loaded into datatable yet before filtering
            setTimeout(() => {
              //console.log(this.filtr);
              var event = new Event('input', {
                  'bubbles': true,
                  'cancelable': true
              });
              this.filtr.nativeElement.dispatchEvent(event);

              //One could also call "filter" directly instead of dispatching an input event
              //Working example: this.dt.filter(this.custFilter,"customerId", "contains");
              //But emmiting an event seems to be better, because no filterMatchMode has to be
              //hardcoded and is taken from template
            }, 50);
          }).catch(this.handleError);
      }

      ngOnInit(): void {
        this.initLicenses();
      }


问:
Auto indent Javascript code in Emacs (bsd style aka Allman style)
I can't set Emacs to work with Javascript. I want Emacs makes auto indent, when I press "{" and "}". When I write code on C, it works very well. When I press "}" the parenthesis tooks its place.
I'd like to see something like this:

very good styles

But I get this:

it's my problem here

I don't understand why parenthesis remain in place.

Could you tell me, what should I do to make it right, please?

I think, I need to add something to my .emacs file, aren't I?

Here is my .emacs:

```<code>(setq c-default-style "bsd"
      c-basic-offset 4)
(setq-default c-basic-offset 4
              tab-width 4
              indent-tabs-mode nil)

(setq make-backup-files nil
      auto-save-default nil
      auto-save-list-file-name nil)

(global-set-key (kbd "RET") 'newline-and-indent)

(show-paren-mode t) ; Highlight expression between {}, (), []
(setq show-paren-style 'parenthesis) ; parenthesis | expression | mixed

(add-hook 'html-mode-hook
            (lambda ()
                  ;; Default indentation is usually 2 spaces, changing to 4.
                  (set (make-local-variable 'sgml-basic-offset) 2)
                  (setq tab-width 2)
            )
)

(setq font-lock-maximum-decoration
      '((html-mode . 1)))

(setq column-number-mode t)

;(electric-pair-mode t)
;(setq electric-pair-preserve-balance nil)
;(electric-indent-mode -1)

; 80 letters rule (highlight)
(setq-default
  whitespace-line-column 78
   whitespace-style       '(face lines-tail))
(add-hook 'prog-mode-hook #'whitespace-mode) ; only if I write code
(add-hook 'text-mode-hook #'whitespace-mode) ; and the other cases

; Use all c-mode settings when I code on javascript (indent, tab-width, ...)
;(add-hook 'js-mode-hook 'c-mode)

;(add-hook 'js-mode-hook #'c-default-style)

;(add-to-list 'auto-mode-alist '("\\.js\\'" . c-mode))
</code>```

答:
Try js2-mode. That has better style and indentation.
BTW you should probably not write everything in the .emacs like this.
The file structure could be something like

```<code>|.emacs
| -- <your mode files.el>
</code>```

I have my own .emacs and the helper files here:

```<code>https://bitbucket.org/tdatta/ansible_plays
</code>```

its under

```<code>roles--> emacs --> files
</code>```

you can have have a look at  one for reference. It's not perfect but still better structured.

Body:
I can't set Emacs to work with Javascript. I want Emacs makes auto indent, when I press "{" and "}". When I write code on C, it works very well. When I press "}" the parenthesis tooks its place.
I'd like to see something like this:

very good styles

But I get this:

it's my problem here

I don't understand why parenthesis remain in place.

Could you tell me, what should I do to make it right, please?

I think, I need to add something to my .emacs file, aren't I?

Here is my .emacs:

(setq c-default-style "bsd"
      c-basic-offset 4)
(setq-default c-basic-offset 4
              tab-width 4
              indent-tabs-mode nil)

(setq make-backup-files nil
      auto-save-default nil
      auto-save-list-file-name nil)

(global-set-key (kbd "RET") 'newline-and-indent)

(show-paren-mode t) ; Highlight expression between {}, (), []
(setq show-paren-style 'parenthesis) ; parenthesis | expression | mixed

(add-hook 'html-mode-hook
            (lambda ()
                  ;; Default indentation is usually 2 spaces, changing to 4.
                  (set (make-local-variable 'sgml-basic-offset) 2)
                  (setq tab-width 2)
            )
)

(setq font-lock-maximum-decoration
      '((html-mode . 1)))

(setq column-number-mode t)

;(electric-pair-mode t)
;(setq electric-pair-preserve-balance nil)
;(electric-indent-mode -1)

; 80 letters rule (highlight)
(setq-default
  whitespace-line-column 78
   whitespace-style       '(face lines-tail))
(add-hook 'prog-mode-hook #'whitespace-mode) ; only if I write code
(add-hook 'text-mode-hook #'whitespace-mode) ; and the other cases

; Use all c-mode settings when I code on javascript (indent, tab-width, ...)
;(add-hook 'js-mode-hook 'c-mode)

;(add-hook 'js-mode-hook #'c-default-style)

;(add-to-list 'auto-mode-alist '("\\.js\\'" . c-mode))

Body:
Try js2-mode. That has better style and indentation.
BTW you should probably not write everything in the .emacs like this.
The file structure could be something like

|.emacs
| -- <your mode files.el>

I have my own .emacs and the helper files here:

https://bitbucket.org/tdatta/ansible_plays

its under

roles--> emacs --> files

you can have have a look at  one for reference. It's not perfect but still better structured.


问:
jQuery Shimmer Button Effect
Is there a way to create a shimmer effect on an HTML element, using jQuery, simulating a moving lightsource? I see this on Flash components, but haven't seen one with jQuery yet. Want to avoid having to make shimmering GIFs if I can.

EDIT1: I imagine I'll have to capture the hover event and then use animate to stack a white fuzzy diagonal image on top of an IMG or DIV tag's boundaries, moving it from left to right once.

答:
Just made an example: http://www.jsfiddle.net/gaby/pZm2m/

is this similar to what you are looking for ?

It does what you mention .. animate a diagonal semi transparent image.

I used the Background-Position-Animation plugin found at http://plugins.jquery.com/project/backgroundPosition-Effect

ContentLicense: CC BY-SA 2.5

Title: jQuery Shimmer Button Effect


问:
Conditionally create resources with terraform
I’m trying to write a module to deploy Sensu on AWS, the plan was to use elasticache for Redis but now I’m facing an edge case. Some of our VPCs have tenancy set to dedicated and we can’t use elasticache there(http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AmazonVPC.EC.html), I thought I could work around this by conditionally using elasticache or deploying a redis cluster in a ASG. I’ve written the code and used:

```<code>count = "${replace(replace(var.vpc_instance_tenancy,"/.*dedicated.*/","0"),"/(.*default.*|^$)/","1")}"
</code>```

to decide if I should create the elasticahe cluster or the ASG, the problem is that I need to pass a hostname or IP address to the Sensu servers and api nodes so that they can connect to Redis, was planning to use:

```<code>redis_host = "${coalesce(aws_elasticache_cluster.redis_cluster.cache_nodes.0.address,aws_elb.redis_lb.dns_name)}"
</code>```

but this always fails because one of the resources never gets created and I can’t reference it in the coalesce function. Any ideas?

答:
I managed to get this working, looks like we can reference inexistent resources if we use the splat variable format, like this:

```<code>redis_host = "${element(concat(aws_elasticache_cluster.redis_cluster.*.cache_nodes.0.address, aws_elb.redis_lb.*.dns_name), 0)}"
redis_port = "${element(concat(aws_elasticache_cluster.redis_cluster.*.cache_nodes.0.port, list(var.redis_port)), 0)}"
</code>```

so the nonexistent resource will return an empty list and the other one will return a single element list, I concat them both together and get the first element.

Body:
I’m trying to write a module to deploy Sensu on AWS, the plan was to use elasticache for Redis but now I’m facing an edge case. Some of our VPCs have tenancy set to dedicated and we can’t use elasticache there(http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AmazonVPC.EC.html), I thought I could work around this by conditionally using elasticache or deploying a redis cluster in a ASG. I’ve written the code and used:

count = "${replace(replace(var.vpc_instance_tenancy,"/.*dedicated.*/","0"),"/(.*default.*|^$)/","1")}"

to decide if I should create the elasticahe cluster or the ASG, the problem is that I need to pass a hostname or IP address to the Sensu servers and api nodes so that they can connect to Redis, was planning to use:

redis_host = "${coalesce(aws_elasticache_cluster.redis_cluster.cache_nodes.0.address,aws_elb.redis_lb.dns_name)}"

but this always fails because one of the resources never gets created and I can’t reference it in the coalesce function. Any ideas?

Body:
I managed to get this working, looks like we can reference inexistent resources if we use the splat variable format, like this:

redis_host = "${element(concat(aws_elasticache_cluster.redis_cluster.*.cache_nodes.0.address, aws_elb.redis_lb.*.dns_name), 0)}"
redis_port = "${element(concat(aws_elasticache_cluster.redis_cluster.*.cache_nodes.0.port, list(var.redis_port)), 0)}"

so the nonexistent resource will return an empty list and the other one will return a single element list, I concat them both together and get the first element.


问:
How to check if the inputted data exist in database
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.

For example:

If TextField1 == to the data in the database.

Output: Swept by GSW.

```<code>Connection con = connect.getConnection();
        String query = "SELECT * FROM item_list WHERE id = ?";

        Statement st;
        ResultSet rs;
        int id;

        try{
            st = con.createStatement();
            rs = st.executeQuery(query);

            while(rs.next()){
              id = rs.getInt("id");

              if(Integer.parseInt(TF[0].getText()) == id){
                System.out.println(id);
                }
            }
        }catch(SQLException exc){
            System.out.println("Not Found!");
        }
</code>```

Kindly Check the Image Output.
I attached the image file below.

Sample Output

答:
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.

Appreciated all your help.

```<code>Connection con = connect.getConnection();
        String query = "SELECT * FROM item_list";

        Statement st;
        ResultSet rs;
        int id;

        try{
            st = con.createStatement();
            rs = st.executeQuery(query);

            while(rs.next()){
              id = rs.getInt("id");

              if(Integer.parseInt(TF[0].getText()) == id){
                System.out.println(id);

                JOptionPane.showMessageDialog(null, "FOUND!");
                }
              else{
                  JOptionPane.showMessageDialog(null, "Not Found!");
              }
            }
        }catch(SQLException exc){
            JOptionPane.showMessageDialog(null, exc.getMessage());

        }
</code>```

ID Found!

Body:
I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.

For example:

If TextField1 == to the data in the database.

Output: Swept by GSW.

Connection con = connect.getConnection();
        String query = "SELECT * FROM item_list WHERE id = ?";

        Statement st;
        ResultSet rs;
        int id;

        try{
            st = con.createStatement();
            rs = st.executeQuery(query);

            while(rs.next()){
              id = rs.getInt("id");

              if(Integer.parseInt(TF[0].getText()) == id){
                System.out.println(id);
                }
            }
        }catch(SQLException exc){
            System.out.println("Not Found!");
        }

Kindly Check the Image Output.
I attached the image file below.

Sample Output

Body:
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.

Appreciated all your help.

Connection con = connect.getConnection();
        String query = "SELECT * FROM item_list";

        Statement st;
        ResultSet rs;
        int id;

        try{
            st = con.createStatement();
            rs = st.executeQuery(query);

            while(rs.next()){
              id = rs.getInt("id");

              if(Integer.parseInt(TF[0].getText()) == id){
                System.out.println(id);

                JOptionPane.showMessageDialog(null, "FOUND!");
                }
              else{
                  JOptionPane.showMessageDialog(null, "Not Found!");
              }
            }
        }catch(SQLException exc){
            JOptionPane.showMessageDialog(null, exc.getMessage());

        }

ID Found!


问:
SQL Server Management Studio  error "Saved settings file cannot be found"
Here is my problem:
Every time I start the "Microsoft SQL Server Management Studio", I get a warning

```<code>The automatically saved settings file "\\Settings\CurrentSettings-2012-02-13.vssettings' cannot be found.
</code>```

The message goes on to say :

```<code>"You can change this file on the 'Import and Export Settings' Tools Options page". The IDE will use your most recent settings for this session.
</code>```

Where is this setting? How to fix this?

thanks!

答:
I found a lot of solutions which suggested to edit the following registry: HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\100\Tools\Shell\VisualStudioLocation

If there are people(like me) who do not have that entry, I managed to fix it by editing this one:
HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\100\Tools\Shell\Profile\AutoSaveFile

I run MS SQL Server 2008 R2

Body:
Here is my problem:
Every time I start the "Microsoft SQL Server Management Studio", I get a warning

The automatically saved settings file "\\Settings\CurrentSettings-2012-02-13.vssettings' cannot be found.

The message goes on to say :

"You can change this file on the 'Import and Export Settings' Tools Options page". The IDE will use your most recent settings for this session.

Where is this setting? How to fix this?

thanks!


问:
Conversion of oracle timestamp to postgres timestamp?
oracle timestamp example: 26-APR-17 09.40.13.243356000

Hi i have a scenario I am converting oracle timestamp to postgres timestamp but the output is not expected .

Query run in psql

```<code>migration=# SELECT TO_TIMESTAMP('26-APR-17 09.40.13.243356000','DD-MON-YY HH24.MI.SS:MS') :: timestamp without time zone;
        to_timestamp
----------------------------
   2017-04-26 09:15:55.864128                  ----- this is output
(1 row)
</code>```

The output should be: 2017-04-26 09:40:13.243356

答:
The error is a result of the invalid value for the milliseconds format mask MS.

As documented in the manual the allowed values for milliseconds are from 000 to 999

.243356000 is however also not valid for microseconds (US format mask) because of the trailing zeroes.

If you want to use that format, you have to remove the zeros from the input string, e.g: using rtrim()

psql (9.6.3)
Type "help" for help.

postgres> SELECT TO_TIMESTAMP(rtrim('26-APR-17 09.40.13.243356000','0'),'DD-MON-YY HH24.MI.SS.US');
         to_timestamp
-------------------------------
 2017-04-26 09:40:13.243356+02
(1 row)

postgres>
```

I also agree with PanagiotisKanavos that it would be better to use a locale independent format (i.e. numbers for the month and a 4 digit year), preferably an ISO standard for timestamp values.

Body:
oracle timestamp example: 26-APR-17 09.40.13.243356000

Hi i have a scenario I am converting oracle timestamp to postgres timestamp but the output is not expected .

Query run in psql

migration=# SELECT TO_TIMESTAMP('26-APR-17 09.40.13.243356000','DD-MON-YY HH24.MI.SS:MS') :: timestamp without time zone;
        to_timestamp
----------------------------
   2017-04-26 09:15:55.864128                  ----- this is output
(1 row)

The output should be: 2017-04-26 09:40:13.243356

Body:
The error is a result of the invalid value for the milliseconds format mask MS.

As documented in the manual the allowed values for milliseconds are from 000 to 999

.243356000 is however also not valid for microseconds (US format mask) because of the trailing zeroes.

If you want to use that format, you have to remove the zeros from the input string, e.g: using rtrim()

psql (9.6.3)
Type "help" for help.

postgres> SELECT TO_TIMESTAMP(rtrim('26-APR-17 09.40.13.243356000','0'),'DD-MON-YY HH24.MI.SS.US');
         to_timestamp
-------------------------------
 2017-04-26 09:40:13.243356+02
(1 row)

postgres>

I also agree with PanagiotisKanavos that it would be better to use a locale independent format (i.e. numbers for the month and a 4 digit year), preferably an ISO standard for timestamp values.


问:
md-datepicker shows error when date entered manually
I am using md-datepicker, when i put date manually it is showing invalid date but if i select date from this control then it is validated. for this i have used following code</p>

```<code>    <md-datepicker name="FromDate" ng-model="vm.user.FromDate" ng-required="true" id="FromDate" md-is-error="login.ToDate.$invalid && login..$submitted" md-placeholder="FromDate"></md-datepicker>
<div ng-messages="login.FromDate.$error" md-auto-hide="false" ng-show="login.FromDate.$touched ||login.FromDate.$submitted">
<div ng-message="required">Please enter FromDate.</div>                    </div>
</code>```

答: please check the format of the date that you are entering the default format is mm/dd/yyyy </p>

Body:
I am using md-datepicker, when i put date manually it is showing invalid date but if i select date from this control then it is validated. for this i have used following code

    <md-datepicker name="FromDate" ng-model="vm.user.FromDate" ng-required="true" id="FromDate" md-is-error="login.ToDate.$invalid && login..$submitted" md-placeholder="FromDate"></md-datepicker>

Please enter FromDate.


问:
how to copy a ftBlob with firedac arrayDML
I use Delphi Berlin.

I am trying to make a function/procedure to copy data from a FireDac query (connected to a database) to another FireDac query (connected to another database) using ArrayDML. first database is firebird and the other is MSSQL in the first care, but in another case both databases are Firebird.

So far so good and almost all datatype are working correct except ftBlob.

Here is the body of the function:

```<code>while not querySource.Eof do begin
  paramPosition := -1;
  Inc(mIndex);

  for i := 0 to querySource.FieldCount - 1 do begin
    Inc(paramPosition);
    // daca exista o valoare
    if querySource.FieldByName(querySource.Fields[i].FieldName).AsVariant <> Null then begin
      case querySource.Fields[i].DataType of
        ftDateTime, ftDate, ftTime, ftTimeStamp : queryInsert.Params[paramPosition].AsDateTimes[mIndex] := querySource.FieldByName(querySource.Fields[i].FieldName).AsDateTime;
        ftFloat, ftCurrency, ftBCD, ftFMTBcd    : queryInsert.Params[paramPosition].AsFloats[mIndex]    := querySource.FieldByName(querySource.Fields[i].FieldName).AsFloat;
        ftSmallint, ftInteger, ftLargeint       : queryInsert.Params[paramPosition].AsIntegers[mIndex]  := querySource.FieldByName(querySource.Fields[i].FieldName).AsInteger;
        ftString                                : queryInsert.Params[paramPosition].AsStrings[mIndex]   := querySource.FieldByName(querySource.Fields[i].FieldName).AsString;
        ftBlob, ftMemo, ftGraphic               : queryInsert.Params[paramPosition].AsBlobs[mIndex]     := querySource.FieldByName(querySource.Fields[i].FieldName).AsVariant;
      end;
    end;
  end;
</code>```

the blob value is not copy the correct value from the source.

how to use the arrayDML in this case? any workaround?

答:
I won't answer your question but suggest you to use the TFDBatchMove component because you are reinventing wheel here. TFDBatchMove is just for what you want to do, for moving data from one database to another (and not only that).

You simply setup the TFDBatchMoveSQLReader as Reader and Writer, write SQL queries for both and the component will automatically map the fields by matching names. If the queries won't have matching field names, you can fine tune this by the Mappings property. Then you just call Execute.

Body:
I use Delphi Berlin.

I am trying to make a function/procedure to copy data from a FireDac query (connected to a database) to another FireDac query (connected to another database) using ArrayDML. first database is firebird and the other is MSSQL in the first care, but in another case both databases are Firebird.

So far so good and almost all datatype are working correct except ftBlob.

Here is the body of the function:

while not querySource.Eof do begin
  paramPosition := -1;
  Inc(mIndex);

  for i := 0 to querySource.FieldCount - 1 do begin
    Inc(paramPosition);
    // daca exista o valoare
    if querySource.FieldByName(querySource.Fields[i].FieldName).AsVariant <> Null then begin
      case querySource.Fields[i].DataType of
        ftDateTime, ftDate, ftTime, ftTimeStamp : queryInsert.Params[paramPosition].AsDateTimes[mIndex] := querySource.FieldByName(querySource.Fields[i].FieldName).AsDateTime;
        ftFloat, ftCurrency, ftBCD, ftFMTBcd    : queryInsert.Params[paramPosition].AsFloats[mIndex]    := querySource.FieldByName(querySource.Fields[i].FieldName).AsFloat;
        ftSmallint, ftInteger, ftLargeint       : queryInsert.Params[paramPosition].AsIntegers[mIndex]  := querySource.FieldByName(querySource.Fields[i].FieldName).AsInteger;
        ftString                                : queryInsert.Params[paramPosition].AsStrings[mIndex]   := querySource.FieldByName(querySource.Fields[i].FieldName).AsString;
        ftBlob, ftMemo, ftGraphic               : queryInsert.Params[paramPosition].AsBlobs[mIndex]     := querySource.FieldByName(querySource.Fields[i].FieldName).AsVariant;
      end;
    end;
  end;

the blob value is not copy the correct value from the source.

how to use the arrayDML in this case? any workaround?


问:
MySQL on OSX Sierra can't start: The server quit without updating PID file
Several problems with mysql since last Sierra Update.
Reinstalled several times with brew or mysql dmg and followd many many "solutions" on SO.

Finally it worked but after a Mac Crash, I face the same problem.

MySql won't start from preference panel

Mysql won't start from terminal: Can't connect through /tmp/mysql.sock...of course, mysqld is not running

trying to start mysqld:

sudo /usr/local/mysql/support-files/mysql.server start

ERROR! The server quit without updating PID file (/usr/local/mysql/data/My-iMac.local.pid)

sudo /usr/local/mysql/bin/mysqld several errors and shutdown

a bit stuck

答:
Just tried this

```<code>sudo /usr/local/mysql/bin/mysqld_safe
mysqld_safe Logging to '/usr/local/mysql/data/My-iMac.local.err'.
Starting mysqld daemon with databases from /usr/local/mysql/data
mysqld_safe mysqld from pid file /usr/local/mysql/data/My-iMac.local.pid ended
</code>```

And now looking at error log, the explanation is clear:

```<code>tail /usr/local/mysql/data/My-iMac.local.err
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
</code>```

So I added in my.cnf

```<code>[mysqld]
innodb_force_recovery = 1
</code>```

and now it starts!

It was probably due to previous Mac Crash

Body:
Just tried this

sudo /usr/local/mysql/bin/mysqld_safe
mysqld_safe Logging to '/usr/local/mysql/data/My-iMac.local.err'.
Starting mysqld daemon with databases from /usr/local/mysql/data
mysqld_safe mysqld from pid file /usr/local/mysql/data/My-iMac.local.pid ended

And now looking at error log, the explanation is clear:

tail /usr/local/mysql/data/My-iMac.local.err
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.

So I added in my.cnf

[mysqld]
innodb_force_recovery = 1

and now it starts!

It was probably due to previous Mac Crash


问:
Ungoogleble machine-code or otherwise hard to read EUID part
Not sure whether obfuscated, machine-code or something else. Please, let me know what the part is for and how to read it. The part is from the file.

```<code>###############################################################################
# Set prompt based on EUID
################################################################################
if (( EUID == 0 )); then
    PROMPT=$'%{\e[01;31m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%# '
else
    PROMPT=$'%{\e[01;32m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%% '
fi
</code>```

could someone break it a bit more into parts?

What does the conditional EUID == 0 do?

I get an error about pc_scm_f, using OBSD, is it some sort of value in other OS?

the \e starts some sort of logical part, what do the rest do?

答:
I found this link which seems to contain the whole thing in proper context.
Also tells me Ferruccio is right: It's an ANSI escape string, used to change the style of the command-prompt. \e starts the escape codes, the rest is the code itself. Used to be very popular in the old DOS time, especially with a game called NetHack. It's just pretty-print for your console.</p>

Body:
Not sure whether obfuscated, machine-code or something else. Please, let me know what the part is for and how to read it. The part is from the file.

###############################################################################
# Set prompt based on EUID
################################################################################
if (( EUID == 0 )); then
    PROMPT=$'%{\e[01;31m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%# '
else
    PROMPT=$'%{\e[01;32m%}%n@%m%{\e[0m%}[%{\e[01;34m%}%3~%{\e[0;m%}]$(pc_scm_f)%% '
fi

could someone break it a bit more into parts?

What does the conditional EUID == 0 do?

I get an error about pc_scm_f, using OBSD, is it some sort of value in other OS?

the \e starts some sort of logical part, what do the rest do?


问:
lazyloader does not works on AOT production mode angular-cli
I am using angular-cli and lazyloader for routing.

ng serve works for me, but after building project as Production mode, then it does not work at all.

Here is my app.routing.ts

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent } from './main/main.component';
import { AuthGuard } from './core/guards/index';
//Layouts
import { LoginComponent } from './login/login.component';

export const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '',
    component: MainComponent,
    children: [
      {
        path: '',
        loadChildren: './main/main.module#MainModule'
      }
    ],
    canActivate: [AuthGuard]
  },{
    path: '**',
    redirectTo: 'login'
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

And this is error I got after ng build --prod --aot or ng serve --prod.

```<code>ERROR Error: Uncaught (in promise): Error: Cannot find module './app/main/main.module'.
Error: Cannot find module './app/main/main.module'.
    at t (main.1f6da18….bundle.js:1)
    at t.loadAndCompile (vendor.490f84a….bundle.js:379)
    at t.load (vendor.490f84a….bundle.js:379)
    at t.loadModuleFactory (vendor.490f84a….bundle.js:428)
    at t.load (vendor.490f84a….bundle.js:428)
    at e.project (vendor.490f84a….bundle.js:428)
    at e.XO5T.e._tryNext (vendor.490f84a….bundle.js:897)
    at e.XO5T.e._next (vendor.490f84a….bundle.js:897)
    at e.next (vendor.490f84a….bundle.js:897)
    at e.RRVv.e._subscribe (vendor.490f84a….bundle.js:736)
    at t (main.1f6da18….bundle.js:1)
    at t.loadAndCompile (vendor.490f84a….bundle.js:379)
    at t.load (vendor.490f84a….bundle.js:379)
    at t.loadModuleFactory (vendor.490f84a….bundle.js:428)
    at t.load (vendor.490f84a….bundle.js:428)
    at e.project (vendor.490f84a….bundle.js:428)
    at e.XO5T.e._tryNext (vendor.490f84a….bundle.js:897)
    at e.XO5T.e._next (vendor.490f84a….bundle.js:897)
    at e.next (vendor.490f84a….bundle.js:897)
    at e.RRVv.e._subscribe (vendor.490f84a….bundle.js:736)
    at u (polyfills.1e19b2c….bundle.js:43)
    at u (polyfills.1e19b2c….bundle.js:43)
    at polyfills.1e19b2c….bundle.js:43
    at t.invokeTask (polyfills.1e19b2c….bundle.js:36)
    at Object.onInvokeTask (vendor.490f84a….bundle.js:365)
    at t.invokeTask (polyfills.1e19b2c….bundle.js:36)
    at r.runTask (polyfills.1e19b2c….bundle.js:36)
    at o (polyfills.1e19b2c….bundle.js:36)
</code>```

Here is screenshot of browser console.

What is wrong on my routing configuration? PP : ng serve is working with out any errors.

答:
This issue is coming from angular2-busy module.

https://www.npmjs.com/package/angular2-busy

Removing this from project solved issue.

Body:
I am using angular-cli and lazyloader for routing.

ng serve works for me, but after building project as Production mode, then it does not work at all.

Here is my app.routing.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent } from './main/main.component';
import { AuthGuard } from './core/guards/index';
//Layouts
import { LoginComponent } from './login/login.component';

export const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '',
    component: MainComponent,
    children: [
      {
        path: '',
        loadChildren: './main/main.module#MainModule'
      }
    ],
    canActivate: [AuthGuard]
  },{
    path: '**',
    redirectTo: 'login'
  }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

And this is error I got after ng build --prod --aot or ng serve --prod.

ERROR Error: Uncaught (in promise): Error: Cannot find module './app/main/main.module'.
Error: Cannot find module './app/main/main.module'.
    at t (main.1f6da18….bundle.js:1)
    at t.loadAndCompile (vendor.490f84a….bundle.js:379)
    at t.load (vendor.490f84a….bundle.js:379)
    at t.loadModuleFactory (vendor.490f84a….bundle.js:428)
    at t.load (vendor.490f84a….bundle.js:428)
    at e.project (vendor.490f84a….bundle.js:428)
    at e.XO5T.e._tryNext (vendor.490f84a….bundle.js:897)
    at e.XO5T.e._next (vendor.490f84a….bundle.js:897)
    at e.next (vendor.490f84a….bundle.js:897)
    at e.RRVv.e._subscribe (vendor.490f84a….bundle.js:736)
    at t (main.1f6da18….bundle.js:1)
    at t.loadAndCompile (vendor.490f84a….bundle.js:379)
    at t.load (vendor.490f84a….bundle.js:379)
    at t.loadModuleFactory (vendor.490f84a….bundle.js:428)
    at t.load (vendor.490f84a….bundle.js:428)
    at e.project (vendor.490f84a….bundle.js:428)
    at e.XO5T.e._tryNext (vendor.490f84a….bundle.js:897)
    at e.XO5T.e._next (vendor.490f84a….bundle.js:897)
    at e.next (vendor.490f84a….bundle.js:897)
    at e.RRVv.e._subscribe (vendor.490f84a….bundle.js:736)
    at u (polyfills.1e19b2c….bundle.js:43)
    at u (polyfills.1e19b2c….bundle.js:43)
    at polyfills.1e19b2c….bundle.js:43
    at t.invokeTask (polyfills.1e19b2c….bundle.js:36)
    at Object.onInvokeTask (vendor.490f84a….bundle.js:365)
    at t.invokeTask (polyfills.1e19b2c….bundle.js:36)
    at r.runTask (polyfills.1e19b2c….bundle.js:36)
    at o (polyfills.1e19b2c….bundle.js:36)

Here is screenshot of browser console.

What is wrong on my routing configuration? PP : ng serve is working with out any errors.


问:
maven resource filtering skipping files
I got a Vaadin project with the following structure:

```<code>Project-Root
  src
    main
    resources
      properties.json
      META-INF
        persistance.xml
    webapp
      WEB-INF
        classes
          hibernate-dashboard.cfg.xml
          quartz.properties
</code>```

Until now I built my project from my IDE (IntelliJ)

```<code>mvn vaadin:compile vaadin:compile-theme -P development
</code>```

and then packaged the WAR with 'Build' -> 'Build Artifacts...' and deployed the WAR.

My resource filtering is the following:

```<code>..
<build>
 <resources>
     <resource>
         <directory>src/main/webapp/WEB-INF/classes/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/META-INF</directory>
         <filtering>true</filtering>
     </resource>
 </resources>
 <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.6</version>
     <configuration>
         <encoding>${project.encoding}</encoding>
     </configuration>
 </plugin>
</code>```

Problem: When I try to build the whole project with maven

```<code>mvn clean package -P development
</code>```

the resources under webapp/WEB-INF/classes get skipped, they are in the target/Project/WEB-INF/classes directory, but the variables are ${..} (hibernate-dashboard.cfg.xml and quartz.properties)

The remaining resources (properties.json and persistance.xml) get filtered correctly.

Question: How can I filter all my resources and build/package my project with maven?

答:
The real problem here is that you're doing something very odd and should probably chose to change things so as to do things differently. The directory:

```<code>src/main/webapp/WEB-INF/classes
</code>```

should not exist -- you should not have a classes directory on that path. If you want filtered files to be placed into target/.../WEB-INF/classes then put those files in src/main/resources and maven will copy them to the appropriate target directory, and if you ask it nicely it'll filter them (populate the templates with values from the current context at the time of copying).

The only thing you really need is:

```<code><resources>
    <resource>
        <directory>src/main/resources/</directory>
        <filtering>true</filtering>
    </resource>
</resources>
</code>```

If you think that you need a classes directory under there then you've probably made a mistake and the quickest way to fix this problem is by not doing the wrong thing any more, rather than trying to configure maven in this way.

Title: maven resource filtering skipping files

Body:
I got a Vaadin project with the following structure:

Project-Root
  src
    main
    resources
      properties.json
      META-INF
        persistance.xml
    webapp
      WEB-INF
        classes
          hibernate-dashboard.cfg.xml
          quartz.properties

Until now I built my project from my IDE (IntelliJ)

mvn vaadin:compile vaadin:compile-theme -P development

and then packaged the WAR with 'Build' -> 'Build Artifacts...' and deployed the WAR.

My resource filtering is the following:

..
<build>
 <resources>
     <resource>
         <directory>src/main/webapp/WEB-INF/classes/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/</directory>
         <filtering>true</filtering>
     </resource>
     <resource>
         <directory>src/main/resources/META-INF</directory>
         <filtering>true</filtering>
     </resource>
 </resources>
 <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.6</version>
     <configuration>
         <encoding>${project.encoding}</encoding>
     </configuration>
 </plugin>

Problem: When I try to build the whole project with maven

mvn clean package -P development

the resources under webapp/WEB-INF/classes get skipped, they are in the target/Project/WEB-INF/classes directory, but the variables are ${..} (hibernate-dashboard.cfg.xml and quartz.properties)

The remaining resources (properties.json and persistance.xml) get filtered correctly.

Question: How can I filter all my resources and build/package my project with maven?

Body:
The real problem here is that you're doing something very odd and should probably chose to change things so as to do things differently. The directory:

src/main/webapp/WEB-INF/classes

should not exist -- you should not have a classes directory on that path. If you want filtered files to be placed into target/.../WEB-INF/classes then put those files in src/main/resources and maven will copy them to the appropriate target directory, and if you ask it nicely it'll filter them (populate the templates with values from the current context at the time of copying).

The only thing you really need is:

<resources>
    <resource>
        <directory>src/main/resources/</directory>
        <filtering>true</filtering>
    </resource>
</resources>

If you think that you need a classes directory under there then you've probably made a mistake and the quickest way to fix this problem is by not doing the wrong thing any more, rather than trying to configure maven in this way.


问:
Protecting POST request between PHP and AJAX - No user input
I have a simple component on a website that is performing a query of all the prod ids from a cluster of products on the page and storing them into an array in jquery. I then send that array to PHP via AJAX as a POST which will ultimately perform a db query on all the ids.

My question is, how can I protect the array coming from the AJAX/JS file into the PHP file in the POST, against user manipulation... meaning I can find the ids in the source code and change them to some random value or even something malicious.

Normally in a user input scenario, you could do a real escape string or similar functionality in the PHP to cover the incoming data. Since I'm sending over an array of numeric values, what would be the best to way to secure that POST request?

Thank you,

-S

答:
Let's assume, that you want to receive array of integer values from a client.

If you write on a raw PHP, then your code can look like this:

```<code>if (isset($_POST['ids']) && is_array($_POST['ids'])) {
    $ids = array_map('intval', $_POST['ids']);
    $ids = array_unique($ids); // Optional.
    print(implode(', ', $ids)); // Print values.
}
</code>```

Sample of user input:

```<code>ids[]=1&ids[]=2&ids[]=3&ids[]=malicious_input&ids[]=1
</code>```

Output:

```<code>1, 2, 3, 0
</code>```

intval takes argument and returns it's integer representation. malicious_input becomes 0 and it's safe for using it in SQL queries.

Some related links:

PHP Prepared Statements.

I have an array of integers, how do I use each one in a mysql query (in php)?

Body:
Let's assume, that you want to receive array of integer values from a client.

If you write on a raw PHP, then your code can look like this:

if (isset($_POST['ids']) && is_array($_POST['ids'])) {
    $ids = array_map('intval', $_POST['ids']);
    $ids = array_unique($ids); // Optional.
    print(implode(', ', $ids)); // Print values.
}

Sample of user input:

ids[]=1&ids[]=2&ids[]=3&ids[]=malicious_input&ids[]=1

Output:

1, 2, 3, 0

intval takes argument and returns it's integer representation. malicious_input becomes 0 and it's safe for using it in SQL queries.

Some related links:

PHP Prepared Statements.

I have an array of integers, how do I use each one in a mysql query (in php)?


问:
FancyBox iFrame body background-color
Hey everyone I'm trying to change the body background-color of the body in the iFrame generated by FancyBox.

It currently looks like this:

Of course this is not what I want, so this is why I'm trying to change the background color to something like transparent.

答:
To change the CSS property of an iFrame , you can use jQuery.</p>

```<code>$('#yourIframe').load(function(){
    $(this).contents().find('body').css({
        background-color: '#333333'
    });
});
</code>```

Title: FancyBox iFrame body background-color

Body:
To change the CSS property of an iFrame , you can use jQuery.

$('#yourIframe').load(function(){
    $(this).contents().find('body').css({
        background-color: '#333333'
    });
});


问:
Convert date/time into timestamp
I want to convert following date and time, into a timestamp 13 digits. Note I use strict mode.

Date:

Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)

Time:
03:00

I tried to use Date.parse() but it was not working. What is the best way to do this?

答:
Create the date object, add time as you wish and then use the getTime() function:

"use strict";
var date = new Date('Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)');
date.setHours(parseInt('03'),[parseInt('00')]); //apply hours and minutes
console.log(date.toString());
console.log(date.getTime()); //use of getTime()```

Title: Convert date/time into timestamp


问:
jquery can't alert ajax response
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

```<code>    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }
</code>```

However, if the above code was written without

```<code>    if (response == 'false') {

    }
</code>```

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

答:
Try taking off the quotes from around the 'false'

```<code>   if (response == false) {

    }
</code>```

or just

```<code>   if (!response) {

    }
</code>```

Title: jquery can't alert ajax response

Body:
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }

However, if the above code was written without

    if (response == 'false') {

    }

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

Body:
Try taking off the quotes from around the 'false'

   if (response == false) {

    }

or just

   if (!response) {

    }


问:
jQuery code to get text of children
I am trying to use jQuery to get the text of child elements.

I must be doing something wrong, been working on this for 2 days now.

If someone has a moment to take a look, I would be very grateful!

CODE:

```<code>function generateRemoveSectionDropDown() {
    var dropDown = document.getElementById('RemoveSectionId');
    var agendaDiv = $("[name='agenda-nestable']");
    var agendaSections = $(agendaDiv).find("ol#agenda-root>li");
    for (var i = 0; i < agendaSections.length; i++) {
        var optValue = null;
        var optText = null;
        var section = agendaSections[i];
        var sectionChildren = $(agendaSections[i]).children();
        for (var j = 0; j < sectionChildren.length; j++) {
            alert('The text from child is: ' + sectionChildren[j].text);
            optValue = j;
            optText = sectionChildren[j].text;
        }

        var opt = document.createElement('option');
        opt.value = optValue;
        opt.innerText = optText;
        dropDown.appendChild(opt);
    }
}
</code>```

PLUNK: http://plnkr.co/edit/jLi9epblNAtMbzezcRSY?p=preview (if you click the "Run Method", my code will run)

Note: Updated code.I had been hacking around with it, putting it back in a good state.

答:
Try to use either-one purely (javascript/jQuery)

Working example:-

function generateRemoveSectionDropDown() {
  $("[name='agenda-nestable'] ol#agenda-root>li").each(function(){ // iterate over li
    $('#RemoveSectionId').append('<option value=' + $(this).attr('id') + '>' + $(this).children('div').text() + '</option>');//create options and append to select-box
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <h1>Hello Plunker!</h1>
  <div class="dd" name="agenda-nestable" id="nestable">
    <ol id="agenda-root" class="dd-list">
      <li class="dd-item" id="2879">
        <div class="dd-handle">Section123</div>
      </li>
      <li class="dd-item" id="2880">
        <div class="dd-handle">Section 4</div>
      </li>
      <li class="dd-item" id="2881">
        <div class="dd-handle">Section 5</div>
      </li>
    </ol>
  </div>
  <button value onclick='generateRemoveSectionDropDown()'>Run method</button><br/><br/>
  <select id="RemoveSectionId"></select><!-- need to add it -->
</body>

</html></code>```

Title: jQuery code to get text of children

Body:
I am trying to use jQuery to get the text of child elements.

I must be doing something wrong, been working on this for 2 days now.

If someone has a moment to take a look, I would be very grateful!

CODE:

function generateRemoveSectionDropDown() {
    var dropDown = document.getElementById('RemoveSectionId');
    var agendaDiv = $("[name='agenda-nestable']");
    var agendaSections = $(agendaDiv).find("ol#agenda-root>li");
    for (var i = 0; i < agendaSections.length; i++) {
        var optValue = null;
        var optText = null;
        var section = agendaSections[i];
        var sectionChildren = $(agendaSections[i]).children();
        for (var j = 0; j < sectionChildren.length; j++) {
            alert('The text from child is: ' + sectionChildren[j].text);
            optValue = j;
            optText = sectionChildren[j].text;
        }

        var opt = document.createElement('option');
        opt.value = optValue;
        opt.innerText = optText;
        dropDown.appendChild(opt);
    }
}

PLUNK: http://plnkr.co/edit/jLi9epblNAtMbzezcRSY?p=preview (if you click the "Run Method", my code will run)

Note: Updated code.I had been hacking around with it, putting it back in a good state.

Body:
Try to use either-one purely (javascript/jQuery)

Working example:-

function generateRemoveSectionDropDown() {
  $("[name='agenda-nestable'] ol#agenda-root>li").each(function(){ // iterate over li
    $('#RemoveSectionId').append('<option value=' + $(this).attr('id') + '>' + $(this).children('div').text() + '</option>');//create options and append to select-box
  });
}

<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <h1>Hello Plunker!</h1>
  <div class="dd" name="agenda-nestable" id="nestable">
    <ol id="agenda-root" class="dd-list">
      <li class="dd-item" id="2879">
        <div class="dd-handle">Section123</div>
      </li>
      <li class="dd-item" id="2880">
        <div class="dd-handle">Section 4</div>
      </li>
      <li class="dd-item" id="2881">
        <div class="dd-handle">Section 5</div>
      </li>
    </ol>
  </div>
  <button value onclick='generateRemoveSectionDropDown()'>Run method</button><br/><br/>
  <select id="RemoveSectionId"></select><!-- need to add it -->
</body>

</html>


问:
Accessing documents packaged in a jar file
Im trying to get the file path of a document that is packaged as a resource in a jar file so that i can display it in a swing application.  The way I have it now works when I run it from eclipse but if I export it to a runnable jar file I can't access the the documents that are packaged in the jar file.  How can I get the file path of the document when its inside the jar file?

Here is the line of code showing how I am trying to access the document:

```<code>File document = new File(getClass().getResource("/resources/documents/document.pdf").getPath());
</code>```

答: The only kind of "file path" that exists for something inside a JAR file is the path relative to the root of the JAR. But in your case it seems that you know it already (it's "/resources/documents/document.pdf"). Files inside a JAR file have no path that you can use to access them directly as they don't exist within the real file system. You need to use either getResource() or getResourceAsStream() to access them. I don't remember right now which classes are used for images in Swing, but look closely at those classes - they should have overloaded methods that accept something like InputStream or URL instead of file path.</p>

Body:
Im trying to get the file path of a document that is packaged as a resource in a jar file so that i can display it in a swing application.  The way I have it now works when I run it from eclipse but if I export it to a runnable jar file I can't access the the documents that are packaged in the jar file.  How can I get the file path of the document when its inside the jar file?

Here is the line of code showing how I am trying to access the document:

File document = new File(getClass().getResource("/resources/documents/document.pdf").getPath());


问:
synapse PHP API sandbox mode showing error "None is not of type 'string'"
I am working with synapse and having issue while uploading user doc attachment, actually same thing is working on our live server but not working with test server in sandbox mode
If any one can help :)

Reference URL: https://docs.synapsepay.com/v3/docs/attach-document

API URL: https://sandbox.synapsepay.com/api/3/user/doc/attachments/add

Response: Array ( [error] => Array ( [en] => None is not of type 'string' ) [error_code] => 200 [http_code] => 400 [success] => )

Code as Below:

```<code>$url = "https://sandbox.synapsepay.com/api/v3/user/doc/attachments/add";

 // KYC Documentation

$payload = array(
    "login" => array(
        //Oauth_key of the user to add KYC doc
        "oauth_key" => "hTUCH4kO89qGZDpyEdoq55ODYugwwRsd57ti8ohZ"
    ),
    "user" => array(
        //doc data
        "doc" => array(
            'attachment' => 'data:text/csv;base64,SUQsTmFtZSxUb3RhbCAoaW4gJCksRmVlIChpbiAkKSxOb3RlLFRyYW5zYWN0aW9uIFR5cGUsRGF0ZSxTdGF0dXMNCjUxMTksW0RlbW9dIEJlbHogRW50ZXJwcmlzZXMsLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0MzMxNjMwNTEsU2V0dGxlZA0KNTExOCxbRGVtb10gQmVseiBFbnRlcnByaXNlcywtMS4wMCwwLjAwLCxCYW5rIEFjY291bnQsMTQzMzE2MjkxOSxTZXR0bGVkDQo1MTE3LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0xLjAwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDMzMTYyODI4LFNldHRsZWQNCjUxMTYsW0RlbW9dIEJlbHogRW50ZXJwcmlzZXMsLTEuMDAsMC4wMCwsQmFuayBBY2NvdW50LDE0MzMxNjI2MzQsU2V0dGxlZA0KNTExNSxbRGVtb10gQmVseiBFbnRlcnByaXNlcywtMS4wMCwwLjAwLCxCYW5rIEFjY291bnQsMTQzMzE2MjQ5OCxTZXR0bGVkDQo0ODk1LFtEZW1vXSBMRURJQyBBY2NvdW50LC03LjAwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDMyMjUwNTYyLFNldHRsZWQNCjQ4MTIsS2FyZW4gUGF1bCwtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQzMTk5NDAzNixTZXR0bGVkDQo0NzgwLFNhbmthZXQgUGF0aGFrLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDMxODQ5NDgxLFNldHRsZWQNCjQzMTUsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjk3NzU5MzcsU2V0dGxlZA0KNDMxNCxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyOTc3NTQzNCxTZXR0bGVkDQo0MzEzLFNhbmthZXQgUGF0aGFrLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI5Nzc1MzY0LFNldHRsZWQNCjQzMTIsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjk3NzUyNTAsU2V0dGxlZA0KNDMxMSxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyOTc3NTAxMyxTZXR0bGVkDQo0MjM1LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI5MzMxODA2LFNldHRsZWQNCjQxMzYsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjg4OTA4NjMsU2V0dGxlZA0KNDAzMCxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyODIxNTM5NixTZXR0bGVkDQo0MDE0LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI4MTI1MzgwLENhbmNsZWQNCjM4MzIsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0MjcxMDc0NzAsU2V0dGxlZA0KMzgyNixTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyNzAzNTM5MixTZXR0bGVkDQozODI1LFNhbmthZXQgUGF0aGFrLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI3MDMyOTM3LFNldHRsZWQNCg=='
        ),
        "fingerprint" => "suasusau21324redakufejfjsf",
    )
);

$options = array(
    'http' => array(
        'method' => 'POST',
        'content' => json_encode( $payload ),
        'header' => "Content-Type: application/json\r\n" .
            "Accept: application/json\r\n"
    )
);

$data_string = json_encode($payload);

curlIT($url, $data_string);

function curlIT($url, $fields){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json')
    );

    $result = curl_exec($ch);

    print_r($result);
}

exit;

?>
</code>```

答:
Synapse api changed you need to send auth key and client id in headers
Take a look of new document
https://docs.synapsepay.com/docs/adding-documents</p>

Body:
I am working with synapse and having issue while uploading user doc attachment, actually same thing is working on our live server but not working with test server in sandbox mode
If any one can help :)

Reference URL: https://docs.synapsepay.com/v3/docs/attach-document

API URL: https://sandbox.synapsepay.com/api/3/user/doc/attachments/add

Response: Array ( [error] => Array ( [en] => None is not of type 'string' ) [error_code] => 200 [http_code] => 400 [success] => )

Code as Below:

$url = "https://sandbox.synapsepay.com/api/v3/user/doc/attachments/add";

 // KYC Documentation

$payload = array(
    "login" => array(
        //Oauth_key of the user to add KYC doc
        "oauth_key" => "hTUCH4kO89qGZDpyEdoq55ODYugwwRsd57ti8ohZ"
    ),
    "user" => array(
        //doc data
        "doc" => array(
            'attachment' => 'data:text/csv;base64,SUQsTmFtZSxUb3RhbCAoaW4gJCksRmVlIChpbiAkKSxOb3RlLFRyYW5zYWN0aW9uIFR5cGUsRGF0ZSxTdGF0dXMNCjUxMTksW0RlbW9dIEJlbHogRW50ZXJwcmlzZXMsLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0MzMxNjMwNTEsU2V0dGxlZA0KNTExOCxbRGVtb10gQmVseiBFbnRlcnByaXNlcywtMS4wMCwwLjAwLCxCYW5rIEFjY291bnQsMTQzMzE2MjkxOSxTZXR0bGVkDQo1MTE3LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0xLjAwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDMzMTYyODI4LFNldHRsZWQNCjUxMTYsW0RlbW9dIEJlbHogRW50ZXJwcmlzZXMsLTEuMDAsMC4wMCwsQmFuayBBY2NvdW50LDE0MzMxNjI2MzQsU2V0dGxlZA0KNTExNSxbRGVtb10gQmVseiBFbnRlcnByaXNlcywtMS4wMCwwLjAwLCxCYW5rIEFjY291bnQsMTQzMzE2MjQ5OCxTZXR0bGVkDQo0ODk1LFtEZW1vXSBMRURJQyBBY2NvdW50LC03LjAwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDMyMjUwNTYyLFNldHRsZWQNCjQ4MTIsS2FyZW4gUGF1bCwtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQzMTk5NDAzNixTZXR0bGVkDQo0NzgwLFNhbmthZXQgUGF0aGFrLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDMxODQ5NDgxLFNldHRsZWQNCjQzMTUsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjk3NzU5MzcsU2V0dGxlZA0KNDMxNCxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyOTc3NTQzNCxTZXR0bGVkDQo0MzEzLFNhbmthZXQgUGF0aGFrLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI5Nzc1MzY0LFNldHRsZWQNCjQzMTIsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjk3NzUyNTAsU2V0dGxlZA0KNDMxMSxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyOTc3NTAxMyxTZXR0bGVkDQo0MjM1LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI5MzMxODA2LFNldHRsZWQNCjQxMzYsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0Mjg4OTA4NjMsU2V0dGxlZA0KNDAzMCxTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyODIxNTM5NixTZXR0bGVkDQo0MDE0LFtEZW1vXSBCZWx6IEVudGVycHJpc2VzLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI4MTI1MzgwLENhbmNsZWQNCjM4MzIsU2Fua2FldCBQYXRoYWssLTAuMTAsMC4wMCwsQmFuayBBY2NvdW50LDE0MjcxMDc0NzAsU2V0dGxlZA0KMzgyNixTYW5rYWV0IFBhdGhhaywtMC4xMCwwLjAwLCxCYW5rIEFjY291bnQsMTQyNzAzNTM5MixTZXR0bGVkDQozODI1LFNhbmthZXQgUGF0aGFrLC0wLjEwLDAuMDAsLEJhbmsgQWNjb3VudCwxNDI3MDMyOTM3LFNldHRsZWQNCg=='
        ),
        "fingerprint" => "suasusau21324redakufejfjsf",
    )
);

$options = array(
    'http' => array(
        'method' => 'POST',
        'content' => json_encode( $payload ),
        'header' => "Content-Type: application/json\r\n" .
            "Accept: application/json\r\n"
    )
);

$data_string = json_encode($payload);

curlIT($url, $data_string);

function curlIT($url, $fields){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json')
    );

    $result = curl_exec($ch);

    print_r($result);
}

exit;

?>


问:
How to use ECS placementConstraints in CloudFormation
I am trying to use placementConstraints in my service definition using CloudFormation, but it does not exist as property in the AWS::ECS::Service resource. Is there a workaround?

ECS Service: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_definition_paramters.html

CloudFormation ECS Service Resource: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html

答:
This works for me ! If you using yaml wrong indentation can lead to this error.

```<code>  ApplicationService:
    Type: AWS::ECS::Service
    DependsOn:
      - ALBListener
      - ApplicationTaskDefinition
      - ALBTargetGroup
    Properties:
      Cluster:
        'Fn::ImportValue': !Sub ecs-${EnvironmentName}-clustername
      DesiredCount: 15
      LoadBalancers:
        - ContainerName: !Sub ${AWS::StackName}-app
          ContainerPort: 8080
          TargetGroupArn: !Ref ALBTargetGroup
      Role:
        'Fn::ImportValue': !Sub ecs-${EnvironmentName}-servicerole-arn
      TaskDefinition: !Ref ApplicationTaskDefinition
      PlacementConstraints:
      - Expression: attribute:ecs.instance-type == t2.medium
        Type: memberOf
      PlacementStrategies:
      - Type: spread
        Field: attribute:ecs.availability-zone
</code>```

If this not working for you please post your cfn file here !

Body:
This works for me ! If you using yaml wrong indentation can lead to this error.

  ApplicationService:
    Type: AWS::ECS::Service
    DependsOn:
      - ALBListener
      - ApplicationTaskDefinition
      - ALBTargetGroup
    Properties:
      Cluster:
        'Fn::ImportValue': !Sub ecs-${EnvironmentName}-clustername
      DesiredCount: 15
      LoadBalancers:
        - ContainerName: !Sub ${AWS::StackName}-app
          ContainerPort: 8080
          TargetGroupArn: !Ref ALBTargetGroup
      Role:
        'Fn::ImportValue': !Sub ecs-${EnvironmentName}-servicerole-arn
      TaskDefinition: !Ref ApplicationTaskDefinition
      PlacementConstraints:
      - Expression: attribute:ecs.instance-type == t2.medium
        Type: memberOf
      PlacementStrategies:
      - Type: spread
        Field: attribute:ecs.availability-zone

If this not working for you please post your cfn file here !


问:
And condition for jQuery doesn't work
I am developing a multipage form. I am trying to write an if condition:

```<code>$('.next').click(function() {
    if ($('input[required]:visible').each().val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});
</code>```

jsFiddle

This works fine with input type=text. Then I am trying to add the same condition for <textarea>:

```<code>$('.next').click(function() {
    if ($('input[required]:visible').val() == false && $('textarea[required]:visible').val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});
</code>```

jsFiddle for this

Now it requires textarea OR input to be filled, but should work with both, shouldn't it? What am I doing wrong?

答:
In your jsFiddle, you have content in the textarea (empty spaces). I think your best bet would be to trim the values before checking them and then comparing them to the empty string ''.

```<code>if ($('input[required]:visible').val().trim() == '' || $('textarea[required]:visible').val().trim() == '') {
    ...
}
</code>```

Also, I changed your and to an or, which is what I think you need.

ContentLicense: CC BY-SA 4.0

Title: And condition for jQuery doesn't work

Body:
I am developing a multipage form. I am trying to write an if condition:

$('.next').click(function() {
    if ($('input[required]:visible').each().val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});

jsFiddle

This works fine with input type=text. Then I am trying to add the same condition for <textarea>:

$('.next').click(function() {
    if ($('input[required]:visible').val() == false && $('textarea[required]:visible').val() == false) {
        alert('Not all required fields are filled');
    } else {
        $('.next').show();
        $('form.idealforms').idealforms('nextStep');
    }
});

jsFiddle for this

Now it requires textarea OR input to be filled, but should work with both, shouldn't it? What am I doing wrong?

Body:
In your jsFiddle, you have content in the textarea (empty spaces). I think your best bet would be to trim the values before checking them and then comparing them to the empty string ''.

if ($('input[required]:visible').val().trim() == '' || $('textarea[required]:visible').val().trim() == '') {
    ...
}

Also, I changed your and to an or, which is what I think you need.


问:
how can i convert my web site wordpress to an android app?
Is there a simple way to transform My web site which i create with wordpress to an android application ? I have not found a plugin that does
someone can hepl me Knowing that I am a beginner in android</p>

答:
You can install jetpack plugin on wordpress to get your site api and then implement it in your application and make the design.

If you wish you can implement web view and just give your site url and make it but your site needs to be full responsive but that is not recommended cus its like opening a site in your browser and it's really slow.


问:
Are there any .NET data providers for Oracle that do not require the Oracle Client to be installed?
I am developing a rich client application that will use the Entity Framework (with DevArt's DotConnect for Oracle) to connect to a central Oracle database.  However, I have found that this scenario requires every client machine to have the Oracle client installed in order to connect to the Oracle 10g server.  Is there an easy way around this?  Do the other types of Oracle providers (ODP.NET, EntLib Data, MS .NET Oracle provider) have the same requirements?

EDIT: Thanks to tuinstoel, I've done more research and confirmed that DevArt's dotConnect can be run in Direct mode which does not require the Oracle Client software to be installed.  This should solve my issue of connecting to Oracle using the Entity Framework.  I also plan to connect to Oracle using a DbConnection, for which I can also use DevArt's Oracle provider.  My issue now is that I cannot get the Direct mode to work.

答:
Yes there are third party providers... see
this one</p>

OwnerDisplayName: Charles Bretana


问:
module.exports = Promise.all not working inside tests
I want to just make sure that my server is running before I create PR's locally to test that nothing is broken.

worker.js

My server exports a promise

```<code>module.exports = Promise.all([
    hbsPartialsLoaded,
])
.then(() => {
    let server;

    if (!isTestEnvironment) {
        server = app.listen(config.port);
    }

    return { server, app };
});
</code>```

tests

```<code>let { expect, request } = require('chai')
    .use(require('chai-http'))
    .use(require('chai-cheerio'));
const config = require('../../app/config');
const worker = require('../../app/worker');

describe('server response', function () {
    worker.then(() => {
        before(function () {
            server.listen(config.port);
        });

        it('should return 200', function (done) {
            request.get(`http://localhost:${config.port}`, function (err, res, body){
                expect(res.statusCode).to.equal(200);
                done();
            });
        });

        after(function () {
            worker.close();
        });
    })
});
</code>```

Running Tests

```<code> NODE_ENV=test mocha --timeout 20000 --recursive test/ --compilers js:babel-core/register

  0 passing (1ms)
</code>```

My tests are never run. How can I get it so I wait for sever.js to finish its promises before the tests are run?

答:
You didn't export the promise correctly, so the calling is bad, because you may not get callback if the require("worker.js") finished before calling .then, it should be worker().then not worker.then, but that's not the only problem.

The worker.js should return a function that launches the Promise.all. So change the module.exports = Promise.all... to module.exports = () => Promise.all...

Use before to launch the server and call it synchronously. Inside it you can use the asynchronous functions as you want.

The server.listen has a callback on second argument, that tells you when it finishes, so you can use promise and resolve it there.

An example:

```<code>var expect = require('chai').expect;

describe('x', () => {
    before(() => new Promise((resolve, reject) => setTimeout(resolve, 500)));

    it('should work', (done) => setTimeout(() => expect(0).to.be.above(0), 500));
});
</code>```

Better example for your case:

```<code>var expect = require('chai').expect;

var app = require('express')();

describe('x', () => {
    before(() => new Promise((resolve, reject) => {
        app.listen(3000, () => {
            console.log('The server launched');
            resolve();
        });
    }));

    it('should work', (done) => {
        console.log('I got called after the server got launched! :)');
        setTimeout(() => expect(1).to.be.above(0), 500)
    });
});
</code>```

Body:
I want to just make sure that my server is running before I create PR's locally to test that nothing is broken.

worker.js

My server exports a promise

module.exports = Promise.all([
    hbsPartialsLoaded,
])
.then(() => {
    let server;

    if (!isTestEnvironment) {
        server = app.listen(config.port);
    }

    return { server, app };
});

tests

let { expect, request } = require('chai')
    .use(require('chai-http'))
    .use(require('chai-cheerio'));
const config = require('../../app/config');
const worker = require('../../app/worker');

describe('server response', function () {
    worker.then(() => {
        before(function () {
            server.listen(config.port);
        });

        it('should return 200', function (done) {
            request.get(`http://localhost:${config.port}`, function (err, res, body){
                expect(res.statusCode).to.equal(200);
                done();
            });
        });

        after(function () {
            worker.close();
        });
    })
});

Running Tests

 NODE_ENV=test mocha --timeout 20000 --recursive test/ --compilers js:babel-core/register

  0 passing (1ms)

My tests are never run. How can I get it so I wait for sever.js to finish its promises before the tests are run?

Body:
You didn't export the promise correctly, so the calling is bad, because you may not get callback if the require("worker.js") finished before calling .then, it should be worker().then not worker.then, but that's not the only problem.

The worker.js should return a function that launches the Promise.all. So change the module.exports = Promise.all... to module.exports = () => Promise.all...

Use before to launch the server and call it synchronously. Inside it you can use the asynchronous functions as you want.

The server.listen has a callback on second argument, that tells you when it finishes, so you can use promise and resolve it there.

An example:

var expect = require('chai').expect;

describe('x', () => {
    before(() => new Promise((resolve, reject) => setTimeout(resolve, 500)));

    it('should work', (done) => setTimeout(() => expect(0).to.be.above(0), 500));
});

Better example for your case:

var expect = require('chai').expect;

var app = require('express')();

describe('x', () => {
    before(() => new Promise((resolve, reject) => {
        app.listen(3000, () => {
            console.log('The server launched');
            resolve();
        });
    }));

    it('should work', (done) => {
        console.log('I got called after the server got launched! :)');
        setTimeout(() => expect(1).to.be.above(0), 500)
    });
});


问:
SQL Server substring w/o custom functions
I have a dilemma regarding how to extract a sub string from a larger string without using custom functions
The string is of this form:

```<code>"    [1].[2]"
"        [1].[2].[3]"
"            [1].[2].[3].[4]"
</code>```

Basically, it's a hierarchy that has 4 leading spaces for every child of a node. The task is to maintain those 4 leading spaces for every node, but get only the child in the end, without the full path

So, the final result should be something like this:

```<code>"    [2]"
"        [3]"
"            [4]"
</code>```

Could anyone help me?

Edit: or, if it's the case, should I modify the CTE that is building the result set?

The CTE is like the one below:

```<code>WITH Hierarchy(cid, cname, parent_id, Parents, nname)
AS
(
    SELECT map_id, name, parent_id, CAST('' AS VARCHAR(MAX)), CAST(''+name AS VARCHAR(MAX))
        FROM tblMapping AS tm1
        WHERE parent_id = 0
    UNION ALL
    SELECT tm.map_id, tm.name, Parent.cid,
    CAST(CASE WHEN Parent.Parents = ''
        THEN(CAST(tm.parent_id AS VARCHAR(MAX)))
        ELSE(Parent.Parents + '.' + CAST(tm.parent_id AS VARCHAR(MAX)))
    END AS VARCHAR(MAX)),
    -- add the formated column description
    CAST(CASE WHEN Parent.Parents = ''
        THEN(Parent.cname)
        ELSE('    '+Parent.nname+ '.'+tm.name)
    END AS VARCHAR(MAX))
        FROM tblMapping AS tm
        INNER JOIN Hierarchy AS Parent ON tm.parent_id = Parent.cid
)
SELECT *
    FROM Hierarchy
ORDER BY ltrim(nname)
OPTION(MAXRECURSION 32767)
</code>```

Thank you!

答:
Try something like this

UPDATED: Inlcudes a root node now...

```<code>DECLARE @mockup TABLE(YourString VARCHAR(100));
INSERT INTO @mockup VALUES
 (' [1]')
,('    [1].[2]')
,('        [1].[2].[3]')
,('            [1].[2].[3].[4]');

SELECT LEFT(YourString,CHARINDEX('[',YourString)-1)
      +SUBSTRING(YourString,LEN(YourString)+1-CHARINDEX('[',REVERSE(YourString)),1000)
FROM @mockup;
</code>```

Body:
I have a dilemma regarding how to extract a sub string from a larger string without using custom functions
The string is of this form:

"    [1].[2]"
"        [1].[2].[3]"
"            [1].[2].[3].[4]"

Basically, it's a hierarchy that has 4 leading spaces for every child of a node. The task is to maintain those 4 leading spaces for every node, but get only the child in the end, without the full path

So, the final result should be something like this:

"    [2]"
"        [3]"
"            [4]"

Could anyone help me?

Edit: or, if it's the case, should I modify the CTE that is building the result set?

The CTE is like the one below:

WITH Hierarchy(cid, cname, parent_id, Parents, nname)
AS
(
    SELECT map_id, name, parent_id, CAST('' AS VARCHAR(MAX)), CAST(''+name AS VARCHAR(MAX))
        FROM tblMapping AS tm1
        WHERE parent_id = 0
    UNION ALL
    SELECT tm.map_id, tm.name, Parent.cid,
    CAST(CASE WHEN Parent.Parents = ''
        THEN(CAST(tm.parent_id AS VARCHAR(MAX)))
        ELSE(Parent.Parents + '.' + CAST(tm.parent_id AS VARCHAR(MAX)))
    END AS VARCHAR(MAX)),
    -- add the formated column description
    CAST(CASE WHEN Parent.Parents = ''
        THEN(Parent.cname)
        ELSE('    '+Parent.nname+ '.'+tm.name)
    END AS VARCHAR(MAX))
        FROM tblMapping AS tm
        INNER JOIN Hierarchy AS Parent ON tm.parent_id = Parent.cid
)
SELECT *
    FROM Hierarchy
ORDER BY ltrim(nname)
OPTION(MAXRECURSION 32767)

Thank you!

Body:
Try something like this

UPDATED: Inlcudes a root node now...

DECLARE @mockup TABLE(YourString VARCHAR(100));
INSERT INTO @mockup VALUES
 (' [1]')
,('    [1].[2]')
,('        [1].[2].[3]')
,('            [1].[2].[3].[4]');

SELECT LEFT(YourString,CHARINDEX('[',YourString)-1)
      +SUBSTRING(YourString,LEN(YourString)+1-CHARINDEX('[',REVERSE(YourString)),1000)
FROM @mockup;


问:
Laravel Auth Login by company name, username, and password
I like user to login by company name, username, and password - they need to enter all those fields.

username, and password fields are in the users table.
company_name are in the companies table.

username can be duplicated in the users table but each username is belong to different company name. company_id is defined in users table.

How can I Auth against company name, username, and password?

I had a look at the attemptLogin() method.

```<code> protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }
</code>```

I can't override this because I need to pass specific user that is belong to company then do auth check.

Update:

```<code>protected function authenticated(Request $request, User $user)
{
    if (!$user->enable) {
        Auth::logout();

        return redirect('/login')->with('status', 'Account is disabled');
    }

    return redirect()->intended('/');
}
</code>```

答:
You can DIY the login Request or Controller , such like that

```<code>// find user
$user = User::where...

// check user
// ...

// make he login
auth()->login($user);
</code>```

Also, if you have the company_id field in users table.

It's belongs to  One To One eloquent-relationships.

https://laravel.com/docs/5.4/eloquent-relationships#one-to-one

So you can use this method.

```<code>   $user_company_name =  User::first()->company_name;
</code>```

you could be check this thing .

Body:
I like user to login by company name, username, and password - they need to enter all those fields.

username, and password fields are in the users table.
company_name are in the companies table.

username can be duplicated in the users table but each username is belong to different company name. company_id is defined in users table.

How can I Auth against company name, username, and password?

I had a look at the attemptLogin() method.

 protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

I can't override this because I need to pass specific user that is belong to company then do auth check.

Update:

protected function authenticated(Request $request, User $user)
{
    if (!$user->enable) {
        Auth::logout();

        return redirect('/login')->with('status', 'Account is disabled');
    }

    return redirect()->intended('/');
}

Body:
You can DIY the login Request or Controller , such like that

// find user
$user = User::where...

// check user
// ...

// make he login
auth()->login($user);

Also, if you have the company_id field in users table.

It's belongs to  One To One eloquent-relationships.

https://laravel.com/docs/5.4/eloquent-relationships#one-to-one

So you can use this method.

   $user_company_name =  User::first()->company_name;

you could be check this thing .


问:
How to Create an RSS 2.0 Feed with Java
Howto Create an RSS 2.0 Feed with JAVA.Using Strust2  development.</p>

答: I would check out the fantastic Rome library:  http://wiki.java.net/bin/view/Javawsxml/Rome</p>

Title: How to Create an RSS 2.0 Feed with Java


问:
How to select a class name knowing only a part of name in Javascript
In Javascript with editor.selection.getContent() function i get the image selected in the wp editor:

```<code><img class="alignnone wp-image-xxx size-large" src="http://....." alt="" />
</code>```

i need to select the class wp-image-xxx and replace it with a class that include a new id (xxx).

With classList i can get all classes:

```<code>var imgselected = editor.selection.getNode();
var classes = imgselected.classList;
</code>```

But how can i select in javascript the class wp-image-xxx without knowing the xxx value so to be able after to replace it?

答:
Here is the most basic way that is applicable in your case:

```<code>//Replaces the first class that matches the name given as its "start" of string with a new class name;
function replaceClass(element, searchClassName, replacementClassName) {
  element.classList.remove(findClassName(document.getElementById('foo'), searchClassName));
  element.classList.add(replacementClassName)

  //used to find a className
  function findClassName(element, searchPhrase) {
    var classNameFound = "";
    element.classList.forEach(function(className) {
      if (className.substring(0, searchPhrase.length) === searchPhrase) {
        //Element found
        if (!classNameFound)
          classNameFound = className;
      }
    });
    return classNameFound;
  }
}
</code>```

just run it with something like:

```<code>replaceClass(document.getElementById('foo'), 'wp-image', 'newClassName');
</code>```

Body:
In Javascript with editor.selection.getContent() function i get the image selected in the wp editor:

i need to select the class wp-image-xxx and replace it with a class that include a new id (xxx).

With classList i can get all classes:

var imgselected = editor.selection.getNode();
var classes = imgselected.classList;

But how can i select in javascript the class wp-image-xxx without knowing the xxx value so to be able after to replace it?

Body:
Here is the most basic way that is applicable in your case:

//Replaces the first class that matches the name given as its "start" of string with a new class name;
function replaceClass(element, searchClassName, replacementClassName) {
  element.classList.remove(findClassName(document.getElementById('foo'), searchClassName));
  element.classList.add(replacementClassName)

  //used to find a className
  function findClassName(element, searchPhrase) {
    var classNameFound = "";
    element.classList.forEach(function(className) {
      if (className.substring(0, searchPhrase.length) === searchPhrase) {
        //Element found
        if (!classNameFound)
          classNameFound = className;
      }
    });
    return classNameFound;
  }
}

just run it with something like:

replaceClass(document.getElementById('foo'), 'wp-image', 'newClassName');


答:
Use:

```<code>if (response) {
       alert(response);
} else { alert("Some Error Message"); }
</code>```

Title: jquery can't alert ajax response

Body:
I'm trying to alert the Ajax response from the code below but somehow nothing gets alerted.

    function get_fee(){
        if ( $('#type').val() == 'hardcopy' ) {
            setTimeout(function(){
                var title = $('#title').val();
                $.ajax({
                    type: 'POST',
                    url: 'convert.php',
                    data: {hardcopy: '1', title: title},
                    success: function(response) {
                        if (response == 'false') {
                            alert(response);
                        }
                    }
                });
            }, 1000);
        }
    }

However, if the above code was written without

    if (response == 'false') {

    }

and the alert( response ) is called, it works flawlessly. I would have adopted the later approach but unfortunately the value of var response can either be true or false.

Body:
Use:

if (response) {
       alert(response);
} else { alert("Some Error Message"); }


问:
How to make .htaccess redirect to subdomain with parameters
How do I make a redirect from all pages following /react-api, such as:

```<code>www.example.com/react-api/workout?id=123
www.example.com/react-api/another-site/?id=321
</code>```

to:

```<code>app.example.com/react-api
</code>```

and I wan't to keep the folder and parameters.

This is what I have tried:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^react-api/(.*) app.example.com/$1 [R=301,L]

</IfModule>

# END WordPress
</code>```

But it doesn't work.

Please help

答:
You need to use http:// in your target URL and also change order of your rules and keep redirect rule at the top:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^react-api(/.*)?$ http://app.example.com%{REQUEST_URI} [R=301,NE,NC,L]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

</IfModule>

# END WordPress
</code>```

Body:
How do I make a redirect from all pages following /react-api, such as:

www.example.com/react-api/workout?id=123
www.example.com/react-api/another-site/?id=321

to:

app.example.com/react-api

and I wan't to keep the folder and parameters.

This is what I have tried:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^react-api/(.*) app.example.com/$1 [R=301,L]

</IfModule>

# END WordPress

But it doesn't work.

Please help

Body:
You need to use http:// in your target URL and also change order of your rules and keep redirect rule at the top:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^react-api(/.*)?$ http://app.example.com%{REQUEST_URI} [R=301,NE,NC,L]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

</IfModule>

# END WordPress


问:
How to use compass in phpstorm?
I'm aware of this question:
How to add Compass syntax support to Jetbrains PhpStorm? but it doesn't help.

I just opted for copying the files over, much easier in my project. But phpstorm still complains about compass. Without compass it compiles scss using ruby 1.9.3 without problems. Is my set up correct?

EDIT:

This is for PhpStorm 6-

Compass is supported in PhpStorm 7+

答:
I am using PhpStorm 2017.1.4

Setting the Ruby path variable and enabling compass in PhpStorm did not work out for me.

I could not use compass from the project directory ("Failed to run Compass") because the terminal could not resolve the command compass with the executable from the Ruby instal dir.

Thus, I permanently set a windows (using win10) environment variable following this explanation.

Quick explanation:

Assuming you have already installed ruby and compass.

Go to: Control Panel -> System -> Advanced System Settings -> Environment Variables...

Add C:\Ruby22\bin to your PATH variable

Restart PhpStorm

Further advice:

If you imported your Project from a different system it might help if you delete your config.rb filed and run compass init from your project root.

Title: How to use compass in phpstorm?


问:
Javascript array length of 0
I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0:

```<code>var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})
</code>```

And this is shown in the inspector, the "length: 42" belongs to line 115.

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?

答:
Array Length returns 0

It seems you are trying to find the length of an object, not an actual array.

Title: Javascript array length of 0

Body:
I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0:

var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})

And this is shown in the inspector, the "length: 42" belongs to line 115.

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?


问:
How detect rain on camera vision using OpenCV in C++
How to recognize rain on camera vision using with OpenCV in C++?

Or if somebody stick a sticker on a camera how recognize it with OpenCV in C++?
Or if somebody throw color to the camera how can i detect it with OpenCV in C++?

Detect these on camera vision:

Rain

Sticker

Color

Here is an example video of sticker!

Camera Vision-Sticker

答:
In case of a sticker, you're just looking for a large dark area that doesn't change in time.

In case of color, analyze image color stats - if somebody sprays some paint on a camera (is that what you mean by "throwing color"?), some color is going to be dominant over all the others.

You can also try to handle both cases by subtracting frames and detecting image areas that don't change in time that way.

You may want to use machine learning for finding threshold values (e.g. area size, its shape properties, such as width/length ratio, continuousness etc.) used to decide when to consider something to be a sticker/color or something else.

As for the rain, I guess there's no simple answer that can be given in a few sentences. There are some articles available in the web though. That said, I would guess it would be simpler and cheaper to detect rain by just installing external rain sensors (like the ones activating wipers in a car) rather than trying to do it by developing your own computer vision algorithm for that purpose.


问:
change current menu item color
Hello i have a website with two menus, one on scroll and  another that shows when the header is at top
 i am trying to change the current menu item color when the header is at top

screenshot below

```<code>http://skyechopencil.com/home-newest/
</code>```

this is what i have tried but it only affects the menu item when on scroll not when fixed at the top

```<code>body .container .navigation ul .current-menu-item a {
color: #ff9900 !important;
text-decoration: underline;
}
</code>```

can someone help in correctin me

答:
I tried to add the markup with Chrome dev tools on the link you provided and it works fine.

Maybe you are overwriting it somewhere else later down the line.

Try to place your code at the very end of your stylesheet and see if it works.

Title: change current menu item color

Body:
Hello i have a website with two menus, one on scroll and  another that shows when the header is at top
 i am trying to change the current menu item color when the header is at top

screenshot below

http://skyechopencil.com/home-newest/

this is what i have tried but it only affects the menu item when on scroll not when fixed at the top

body .container .navigation ul .current-menu-item a {
color: #ff9900 !important;
text-decoration: underline;
}

can someone help in correctin me