问:
How to redirect only select subdomains in HAProxy?
I have several domains such as abc.blah.com, xyz.blah.com, 2a.blah.com, 3b.blah.com and many more. In my haproxy.cfg file I would like to handle only a few of the domains and leave the rest to go their intended destination.

For example:

Redirect abc and xyz to different destinations

abc.blah.com == 10.1.1.11

xyz.blah.com == 10.1.1.12

But not 2a.blah.com or 3b.blah.com or *.blah.com. Let them be directed to the actual destination.

That means 2a.blah.com should go to 2a.blah.com

here is the haproxy.cfg

```<code>global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    user haproxy
    group haproxy
    daemon

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    contimeout 5000
    clitimeout 50000
    srvtimeout 50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

frontend http-in
    bind 0.0.0.0:80
    acl xyz hdr(host) -i xyz.blah.com
    acl abc hdr(host) -i abc.blah.com
    acl default hdr_end(host) -i .blah.com

    ## figure out which one to use
    use_backend xyz_cluster if xyz
    use_backend abc_cluster if abc
    use_backend direct_forward if default

# send it to xyz.blah.com
backend xyz_cluster
    option forwardfor
    server node1 10.1.1.12:8080

# send it to "abc.blah.com"
backend abc_cluster
    option forwardfor
    server node1 10.1.1.11:8080

# handle 2a.blah.com
# handle 3b.blah.com
# handle *.blah.com
# basically forwarding to the source itself
backend direct_forward
    option httpclose
    option http_proxy

listen  stats   :9000
    mode  http
    stats enable
    stats hide-version
    stats realm Haproxy\ Statistics
    stats uri  /stats
    stats auth test:test123
</code>```

With this configuration, the requests to xyz and abc are routed correctly.

```<code>curl -x 10.148.240.78:80  http://xyz.blah.com
</code>```

Works fine

But requests to 2a.blah.com are throwing 503

```<code>curl -x 10.148.240.78:80  http://2a.blah.com
<html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>
</code>```

The haproxy log shows the following,

```<code>Mar 30 16:48:17 ubuntu-ha-proxy-3289 haproxy[9105]: 10.254.184.246:54533 [30/Mar/2017:16:48:17.793] http-in direct_forward/<NOSRV> 2/-1/-1/-1/2 503 213 - - SC-- 0/0/0/0/0 0/0 "GET http://2a.blah.com HTTP/1.1"
</code>```

Basically the direct_forward backend needs to be configured to pass the requests to the source domains itself. But it is unclear how it is achieved in haproxy.

答:
Use default_backend <backend> when no "use_backend" rule has been matched.

When doing content-switching between frontend and backends using the
  "use_backend" keyword, it is often useful to indicate which backend will be
  used when no rule has matched. It generally is the dynamic backend which
  will catch all undetermined requests.

```<code>frontend http-in
    bind 0.0.0.0:80
    acl xyz hdr(host) -i xyz.blah.com
    acl abc hdr(host) -i abc.blah.com

    ## figure out which one to use
    use_backend xyz_cluster if xyz
    use_backend abc_cluster if abc

    default_backend direct_forward
</code>```

Source: https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#default_backend

Body:
I have several domains such as abc.blah.com, xyz.blah.com, 2a.blah.com, 3b.blah.com and many more. In my haproxy.cfg file I would like to handle only a few of the domains and leave the rest to go their intended destination.

For example:

Redirect abc and xyz to different destinations

abc.blah.com == 10.1.1.11

xyz.blah.com == 10.1.1.12

But not 2a.blah.com or 3b.blah.com or *.blah.com. Let them be directed to the actual destination.

That means 2a.blah.com should go to 2a.blah.com

here is the haproxy.cfg

global
    log /dev/log    local0
    log /dev/log    local1 notice
    chroot /var/lib/haproxy
    user haproxy
    group haproxy
    daemon

defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    contimeout 5000
    clitimeout 50000
    srvtimeout 50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

frontend http-in
    bind 0.0.0.0:80
    acl xyz hdr(host) -i xyz.blah.com
    acl abc hdr(host) -i abc.blah.com
    acl default hdr_end(host) -i .blah.com

    ## figure out which one to use
    use_backend xyz_cluster if xyz
    use_backend abc_cluster if abc
    use_backend direct_forward if default

# send it to xyz.blah.com
backend xyz_cluster
    option forwardfor
    server node1 10.1.1.12:8080

# send it to "abc.blah.com"
backend abc_cluster
    option forwardfor
    server node1 10.1.1.11:8080

# handle 2a.blah.com
# handle 3b.blah.com
# handle *.blah.com
# basically forwarding to the source itself
backend direct_forward
    option httpclose
    option http_proxy

listen  stats   :9000
    mode  http
    stats enable
    stats hide-version
    stats realm Haproxy\ Statistics
    stats uri  /stats
    stats auth test:test123

With this configuration, the requests to xyz and abc are routed correctly.

curl -x 10.148.240.78:80  http://xyz.blah.com

Works fine

But requests to 2a.blah.com are throwing 503

curl -x 10.148.240.78:80  http://2a.blah.com

503 Service Unavailable

No server is available to handle this request.

The haproxy log shows the following,

Mar 30 16:48:17 ubuntu-ha-proxy-3289 haproxy[9105]: 10.254.184.246:54533 [30/Mar/2017:16:48:17.793] http-in direct_forward/<NOSRV> 2/-1/-1/-1/2 503 213 - - SC-- 0/0/0/0/0 0/0 "GET http://2a.blah.com HTTP/1.1"

Basically the direct_forward backend needs to be configured to pass the requests to the source domains itself. But it is unclear how it is achieved in haproxy.

Body:
Use default_backend <backend> when no "use_backend" rule has been matched.

When doing content-switching between frontend and backends using the
  "use_backend" keyword, it is often useful to indicate which backend will be
  used when no rule has matched. It generally is the dynamic backend which
  will catch all undetermined requests.

frontend http-in
    bind 0.0.0.0:80
    acl xyz hdr(host) -i xyz.blah.com
    acl abc hdr(host) -i abc.blah.com

    ## figure out which one to use
    use_backend xyz_cluster if xyz
    use_backend abc_cluster if abc

    default_backend direct_forward

Source: https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#default_backend


来源: stackexchange

问:
How to convert a hexadecimal string of data to an ArrayBuffer in JavaScript
How do I convert the string 'AA5504B10000B5' to an ArrayBuffer?

答:
You could use regular expressions together with Array#map and parseInt(string, radix):

var hex = 'AA5504B10000B5'

var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
  return parseInt(h, 16)
}))

console.log(typedArray)
console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5])

var buffer = typedArray.buffer```

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Why are my Snort logs empty?
I am running macOS Sierra 10.12.3

```<code>$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.12.3
BuildVersion:   16D32
</code>```

I have installed snort using homebrew

```<code>$ brew install snort
$ brew ls --versions snort
snort 2.9.9.0
</code>```

I am running snort and with a user config file, -s syslog switch, and a tcpdump-file

```<code>$ sudo snort -c /etc/snort/snort.conf -s -r tcpdump.pcap
</code>```

my /etc/snort/snort.conf file has the following output settings:

```<code>output alert_syslog: LOG_AUTH LOG_ALERT
</code>```

When I execute,a blank file gets created at /var/log/snort/snort.log.1489953549

I know that my rules are working, because if I execute snort with an alert-mode of fast

```<code>$ sudo snort -c /etc/snort/snort.conf -A fast -r tcpdump.pcap
</code>```

a new blank /var/log/snort/snort.log.1489954258 is created, but a /var/log/snort/alert log file is also created, which contains the correct alert outputs.

I have seen others run into this issue because of permissions, but I don't believe that is my problem given that I am running snort as sudo and it is able to write to the alert log just fine.

I also do not have $NO_PACKET_LOG as far as I can tell. reference

It looks like brew installed some default snort config files under /usr/local/etc/snort, but I don't think that these are affecting me because I am using the -c switch to supply a user config file.

DISCLAIMER: This is my first time using snort, so it could be something very obvious that I am missing. Any and all help is much appreciated.

答:
TL;DR

Use tcpdump, snort, tshark, or Wireshark to read snort log files (how to view snort log files)

```<code>$ sudo tcpdump -r snort.log.1489953549
</code>```

My empty log file was never actually empty (note file sizes from ls)

```<code>$ ls -ltr /var/log/snort/
-rw-------  1 root  admin   56018718 Mar 19 15:03 snort.log.1489954258
-rw-------  1 root  admin   56018718 Mar 19 15:11 snort.log.1489953549
-rw-r--r--  1 root  admin   70202224 Mar 19 15:11 alert
</code>```

Snort log files must be read using the correct application

What type of file is it?

```<code>$ sudo file snort.log.1489953549
snort.log.1489953549: tcpdump capture file (little-endian) - version 2.4 (Ethernet, capture length 1514)
</code>```

Read the file with tcpdump

```<code>$ sudo tcpdump -r snort.log.1489954258
06:54:16.654692 IP 192.168.5.81.amt-blc-port > 100.100.100.212.6667: Flags [P.], seq 1304973037:1304973067, ack 1425084530, win 8011, options [nop,nop,TS val 14215752 ecr 2196036272], length 30
...
</code>```

Title: Why are my Snort logs empty?

Body:
I am running macOS Sierra 10.12.3

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.12.3
BuildVersion:   16D32

I have installed snort using homebrew

$ brew install snort
$ brew ls --versions snort
snort 2.9.9.0

I am running snort and with a user config file, -s syslog switch, and a tcpdump-file

$ sudo snort -c /etc/snort/snort.conf -s -r tcpdump.pcap

my /etc/snort/snort.conf file has the following output settings:

output alert_syslog: LOG_AUTH LOG_ALERT

When I execute,a blank file gets created at /var/log/snort/snort.log.1489953549

I know that my rules are working, because if I execute snort with an alert-mode of fast

$ sudo snort -c /etc/snort/snort.conf -A fast -r tcpdump.pcap

a new blank /var/log/snort/snort.log.1489954258 is created, but a /var/log/snort/alert log file is also created, which contains the correct alert outputs.

I have seen others run into this issue because of permissions, but I don't believe that is my problem given that I am running snort as sudo and it is able to write to the alert log just fine.

I also do not have $NO_PACKET_LOG as far as I can tell. reference

It looks like brew installed some default snort config files under /usr/local/etc/snort, but I don't think that these are affecting me because I am using the -c switch to supply a user config file.

DISCLAIMER: This is my first time using snort, so it could be something very obvious that I am missing. Any and all help is much appreciated.

Body:
TL;DR

Use tcpdump, snort, tshark, or Wireshark to read snort log files (how to view snort log files)

$ sudo tcpdump -r snort.log.1489953549

My empty log file was never actually empty (note file sizes from ls)

$ ls -ltr /var/log/snort/
-rw-------  1 root  admin   56018718 Mar 19 15:03 snort.log.1489954258
-rw-------  1 root  admin   56018718 Mar 19 15:11 snort.log.1489953549
-rw-r--r--  1 root  admin   70202224 Mar 19 15:11 alert

Snort log files must be read using the correct application

What type of file is it?

$ sudo file snort.log.1489953549
snort.log.1489953549: tcpdump capture file (little-endian) - version 2.4 (Ethernet, capture length 1514)

Read the file with tcpdump

$ sudo tcpdump -r snort.log.1489954258
06:54:16.654692 IP 192.168.5.81.amt-blc-port > 100.100.100.212.6667: Flags [P.], seq 1304973037:1304973067, ack 1425084530, win 8011, options [nop,nop,TS val 14215752 ecr 2196036272], length 30
...


问:
Best Practice: Access form elements by HTML id or name attribute?
As any seasoned JavaScript developer knows, there are many (too many) ways to do the same thing.  For example, say you have a text field as follows:

```<code><form name="myForm">
    <input type="text" name="foo" id="foo" />
</code>```

There are many way to access this in JavaScript:

```<code>[1]  document.forms[0].elements[0];
[2]  document.myForm.foo;
[3]  document.getElementById('foo');
[4]  document.getElementById('myForm').foo;
     ... and so on ...
</code>```

Methods [1] and [3] are well documented in the Mozilla Gecko documentation, but neither are ideal. [1] is just too general to be useful and [3] requires both an id and a name (assuming you will be posting the data to a server side language). Ideally, it would be best to have only an id attribute or a name attribute (having both is somewhat redundant, especially if the id isn't necessary for any css, and increases the likelihood of typos, etc).

[2] seems to be the most intuitive and it seems to be widely used, but I haven't seen it referenced in the Gecko documentation and I'm worried about both forwards compatibility and cross browser compatiblity (and of course I want to be as standards compliant as possible).

So what's best practice here?  Can anyone point to something in the DOM documentation or W3C specification that could resolve this?

Note I am specifically interested in a non-library solution (jQuery/Prototype).

答:
This is a bit old but I want to add a thing I think is relevant.

(I meant to comment on one or 2 threads above but it seems I need reputation 50 and I have only 21 at the time I'm writing this. :) )

Just want to say that there are times when it's much better to access the elements of a form by name rather than by id. I'm not talking about the form itself. The form, OK, you can give it an id and then access it by it. But if you have a radio button in a form, it's much easier to use it as a single object (getting and setting its value) and you can only do this by name, as far as I know.

Example:

```<code><form id="mainForm" name="mainForm">
    <input type="radio" name="R1" value="V1">choice 1<br/>
    <input type="radio" name="R1" value="V2">choice 2<br/>
    <input type="radio" name="R1" value="V3">choice 3
</form>
</code>```

You can get/set the checked value of the radio button R1 as a whole by using

document.mainForm.R1.value

or

document.getElementById("mainForm").R1.value

So if you want to have a unitary style, you might want to always use this method, regardless of the type of form element. Me, I'm perfectly comfortable accessing radio buttons by name and text boxes by id.

ContentLicense: CC BY-SA 2.5

Body:
As any seasoned JavaScript developer knows, there are many (too many) ways to do the same thing.  For example, say you have a text field as follows:

<form name="myForm">
    <input type="text" name="foo" id="foo" />

There are many way to access this in JavaScript:

[1]  document.forms[0].elements[0];
[2]  document.myForm.foo;
[3]  document.getElementById('foo');
[4]  document.getElementById('myForm').foo;
     ... and so on ...

Methods [1] and [3] are well documented in the Mozilla Gecko documentation, but neither are ideal. [1] is just too general to be useful and [3] requires both an id and a name (assuming you will be posting the data to a server side language). Ideally, it would be best to have only an id attribute or a name attribute (having both is somewhat redundant, especially if the id isn't necessary for any css, and increases the likelihood of typos, etc).

[2] seems to be the most intuitive and it seems to be widely used, but I haven't seen it referenced in the Gecko documentation and I'm worried about both forwards compatibility and cross browser compatiblity (and of course I want to be as standards compliant as possible).

So what's best practice here?  Can anyone point to something in the DOM documentation or W3C specification that could resolve this?

Note I am specifically interested in a non-library solution (jQuery/Prototype).

Body:
This is a bit old but I want to add a thing I think is relevant.

(I meant to comment on one or 2 threads above but it seems I need reputation 50 and I have only 21 at the time I'm writing this. :) )

Just want to say that there are times when it's much better to access the elements of a form by name rather than by id. I'm not talking about the form itself. The form, OK, you can give it an id and then access it by it. But if you have a radio button in a form, it's much easier to use it as a single object (getting and setting its value) and you can only do this by name, as far as I know.

Example:

<form id="mainForm" name="mainForm">
    <input type="radio" name="R1" value="V1">choice 1<br/>
    <input type="radio" name="R1" value="V2">choice 2<br/>
    <input type="radio" name="R1" value="V3">choice 3
</form>

You can get/set the checked value of the radio button R1 as a whole by using

document.mainForm.R1.value

or

document.getElementById("mainForm").R1.value

So if you want to have a unitary style, you might want to always use this method, regardless of the type of form element. Me, I'm perfectly comfortable accessing radio buttons by name and text boxes by id.


问:
batch file to execute a command in it every 1 minute
i want to create a batch file that executes command in it every 1 minute.

how can i go ahead with this ?

what i want to do is :

download a file from somedomain.com/updates.html to a new file every 1 min. or so
i don't have any .NET framework installed here, so i thought of going with batch files.

After googling a bit a got http://www.chami.com/tips/windows/062598W.html

now what i want is to call 1 command whic downloads & writes a new file every 1 minute.

答:
I recommend using Scheduled tasks in windows for this!
Don't add the scheduling/loop in your batch file!</p>


问:
Get Alfresco NodeRef by path
I want to get the NodeRef of a document (or space) stored in Alfresco.

My code is in Java, running within Alfresco (for instance in an AMP).

How to do?

答:
The following Java method gets the NodeRef of the Alfresco document or space you specify:

```<code>/**
 * Get a NodeRef by its path.
 * @path as displayed by the Node Browser.
 * @return the NodeRef, or null if no NodeRef matches this path.
 */
private NodeRef getNode(String path) {
    logger.debug("Getting NodeRef for path:\"" + path + "\"");
    ResultSet results = null;
    try {
        StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
        results = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
            "PATH:\"" + path + "\"");
        if (results.length() == 0) {
            logger.debug("Zero matches for path: " + path);
            return null;
        }
        NodeRef nodeRef = results.getNodeRef(0);
        logger.debug("NodeRef for \"" + path + "\" is " + nodeRef);
        return nodeRef;
    }
    catch(Exception e) {
        logger.debug("Exception while searching for path: " + path, e);
        if (results != null) {
            results.close();
        }
        return null; // The node does not exist
    }
    finally {
        if (results != null) {
            results.close();
        }
    }
}

private SearchService searchService; // Be sure to set this, probably via Spring.
</code>```

Be aware that each level in path must:

have a namespace

be escaped by ISO9075 (in Java code: ISO9075.encode(level))

Examples:

/app:company_home/app:dictionary/app:space_templates/cm:MyTemplate

/app:company_home/app:shared/cm:abc/cm:def/cm:My_x0020_Document.txt

/app:company_home/app:shared/cm:_x0031_23

To find out what is the path of a particular document or folder, the Node Browser (in Admin Tools) is your friend:

I make the method above public domain, please fix or comment if you notice anything that can be improved, thanks! :-)

Title: Get Alfresco NodeRef by path

Body:
The following Java method gets the NodeRef of the Alfresco document or space you specify:

/**
 * Get a NodeRef by its path.
 * @path as displayed by the Node Browser.
 * @return the NodeRef, or null if no NodeRef matches this path.
 */
private NodeRef getNode(String path) {
    logger.debug("Getting NodeRef for path:\"" + path + "\"");
    ResultSet results = null;
    try {
        StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
        results = searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
            "PATH:\"" + path + "\"");
        if (results.length() == 0) {
            logger.debug("Zero matches for path: " + path);
            return null;
        }
        NodeRef nodeRef = results.getNodeRef(0);
        logger.debug("NodeRef for \"" + path + "\" is " + nodeRef);
        return nodeRef;
    }
    catch(Exception e) {
        logger.debug("Exception while searching for path: " + path, e);
        if (results != null) {
            results.close();
        }
        return null; // The node does not exist
    }
    finally {
        if (results != null) {
            results.close();
        }
    }
}

private SearchService searchService; // Be sure to set this, probably via Spring.

Be aware that each level in path must:

have a namespace

be escaped by ISO9075 (in Java code: ISO9075.encode(level))

Examples:

/app:company_home/app:dictionary/app:space_templates/cm:MyTemplate

/app:company_home/app:shared/cm:abc/cm:def/cm:My_x0020_Document.txt

/app:company_home/app:shared/cm:_x0031_23

To find out what is the path of a particular document or folder, the Node Browser (in Admin Tools) is your friend:

I make the method above public domain, please fix or comment if you notice anything that can be improved, thanks! :-)


问:
How to have facebook messenger bot in local, staging and production
Context

I'm working on a facebook messenger bot and have a workflow issue.

To create it i used ngrok to make a facebook test application hook on my local and it worked fine.

Now the bot is in staging for test and an other application have the webhook pointing to the stage server.

For the production server i intend to do a production application that will have webhook pointing on it.

Question

But since an application has to be attached to a page to start a conversation to it, how can i test several bots ?
Do i need 3 pages (local test, staging test and production) ?

Or is there a Facebook way to it ? (test version of app is not working for now on messenger bot, known bug)

Or maybe a good practice ?

答:
You are looking for Test Apps in Facebook App Development. You can find this setting on the Developer Page on the top left where you can find a drop-down button to create a Test App.

I use to create my dev and staging environment.


问:
AngularJS - Confirm password validation is working only if Password field is valid
Please check this fiddle - https://jsfiddle.net/Ayyappu/1eh28db6/

```<code><body ng-app="app">
    <form name="form" ng-submit="form.$valid && vm.login()" novalidate>
        <div class="form-group" ng-class="{ 'has-error': form.$submitted && form.password.$invalid }">
            <label for="password">Password</label>
            <input type="password" name="password" class="form-control" ng-model="vm.password" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,15}" />
            <div ng-messages="form.$submitted && form.password.$error" class="help-block">
                <div ng-message="required">Password is required</div>
                <div ng-message="pattern">Invalid format</div>
            </div>
        </div>
        <div class="form-group" ng-class="{ 'has-error': form.$submitted && form.confirmPassword.$invalid }">
            <label for="confirmPassword">Confirm Password</label>
            <input type="password" name="confirmPassword" class="form-control" ng-model="vm.confirmPassword" required compare-to="vm.password" />
            <div ng-messages="form.$submitted && form.confirmPassword.$error" class="help-block">
                <div ng-message="required">Confirm Password is required</div>
                <div ng-message="compareTo">Passwords don't match</div>
            </div>
        </div>
        <div class="form-group">
            <button ng-disabled="vm.loading" class="btn btn-primary">Login</button>
        </div>
    </form>
</body>

var app = angular.module('app', ['ngMessages']);

app.directive("compareTo", function() {
    return {
      require: "ngModel",
      scope: {
        otherModelValue: "=compareTo"
      },
      link: function(scope, element, attributes, ngModel) {

        ngModel.$validators.compareTo = function(modelValue) {
          return modelValue == scope.otherModelValue;
        };

        scope.$watch("otherModelValue", function() {
          ngModel.$validate();
        });
      }
    };
  });
</code>```

Validations in the first textbox (Password)

Mandatory

The password must contain at least 1 lower case, 1 upper case, 1 number, 1 special character and its length should be between 8 and 15

Validations in the second textbox (Confirm Password)

Mandatory

It should match with the first textbox (Password)

Issue:

Mandatory validation is working fine in both the textboxes. Password policy is also working fine in the first textbox (Password). However, the password match validation in the second textbox (Confirm Password) is working only if the first textbox (Password) passes validation.

e.g., 'Ab1!efgh' is a valid password. If you enter this in both the textboxes, there are no validation errors in the form. However, if you enter just 'a' in the first textbox (Password) and the second textbox (Confirm Password), then there is an error in the second textbox (Confirm Password) saying that the passwords don't match. This clearly shows that 'Confirm password validation is working only if Password field is valid'

I want the password match validation in the second textbox (Confirm Password) to work even if the password you enter in the first textbox (Password) is invalid.

Please help.

答:
By default, vm.password won't update by ng-model if the pattern fails.

you have to use ng-model-options="{allowInvalid: true}" to allow value change if pattern valid fails.

see this plunker

Body:
Please check this fiddle - https://jsfiddle.net/Ayyappu/1eh28db6/

    <form name="form" ng-submit="form.$valid && vm.login()" novalidate>

            Password
            <input type="password" name="password" class="form-control" ng-model="vm.password" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,15}" />

Password is required

Invalid format

            Confirm Password
            <input type="password" name="confirmPassword" class="form-control" ng-model="vm.confirmPassword" required compare-to="vm.password" />

Confirm Password is required

Passwords don't match

            <button ng-disabled="vm.loading" class="btn btn-primary">Login</button>

    </form>

var app = angular.module('app', ['ngMessages']);

app.directive("compareTo", function() {
    return {
      require: "ngModel",
      scope: {
        otherModelValue: "=compareTo"
      },
      link: function(scope, element, attributes, ngModel) {

        ngModel.$validators.compareTo = function(modelValue) {
          return modelValue == scope.otherModelValue;
        };

        scope.$watch("otherModelValue", function() {
          ngModel.$validate();
        });
      }
    };
  });

Validations in the first textbox (Password)

Mandatory

The password must contain at least 1 lower case, 1 upper case, 1 number, 1 special character and its length should be between 8 and 15

Validations in the second textbox (Confirm Password)

Mandatory

It should match with the first textbox (Password)

Issue:

Mandatory validation is working fine in both the textboxes. Password policy is also working fine in the first textbox (Password). However, the password match validation in the second textbox (Confirm Password) is working only if the first textbox (Password) passes validation.

e.g., 'Ab1!efgh' is a valid password. If you enter this in both the textboxes, there are no validation errors in the form. However, if you enter just 'a' in the first textbox (Password) and the second textbox (Confirm Password), then there is an error in the second textbox (Confirm Password) saying that the passwords don't match. This clearly shows that 'Confirm password validation is working only if Password field is valid'

I want the password match validation in the second textbox (Confirm Password) to work even if the password you enter in the first textbox (Password) is invalid.

Please help.


问:
C# null check chain in method call
I suppose method call chain below.

```<code>void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}
</code>```

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

```<code>void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}
</code>```

答:
You can do

```<code>void DoSomething()
{
    CreateA()?.Foo();
}

ObjectA CreateA()
{
    return CreateB()?.ToA();
}
</code>```

Your other approach if you can't use C# 6, is don't return nulls, use null objects that way you never have to deal with null checking ( but you can still check if something is the null object )

Title: C# null check chain in method call

Body:
I suppose method call chain below.

void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}

Body:
You can do

void DoSomething()
{
    CreateA()?.Foo();
}

ObjectA CreateA()
{
    return CreateB()?.ToA();
}

Your other approach if you can't use C# 6, is don't return nulls, use null objects that way you never have to deal with null checking ( but you can still check if something is the null object )


问:
Extend text on hover
I'm  using two initials and I want that if a user hovers it it will show the rest of the text but I can't make it to display the rest of the text correctly: the part of the first letter it's being displayed next to the text of the second initial.

jsfiddle

```<code>#logo .short{
        position: relative;
        margin-top: 0;
        padding: 0 10px;
        font-size: 36px;
        display: inline-block;
        text-transform: uppercase;
      transition: all .3s ease-out;
}
  .short:after{
   position: relative;
    margin-left: -20px;
    content: "est1";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
}

 .short:hover:after{
        opacity: 1;
        display: inline-block;
      margin-left: -10px;
 }
#logo span{
    position: relative;
    transition: margin .3s ease-out;
}
span:hover{
        margin-left: 20px;
}
span:after{
   position: relative;
    margin-left: -20px;
    content: "est2";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
 }

span:hover:after{
  opacity: 1;
  margin-left: -10px;
 }
</code>```

答:
You set both letters within  element, use :nth-of-type() selector to set content of :after pseudo element

#logo .short {
  position: relative;
  margin-top: 0;
  padding: 0 10px;
  font-size: 36px;
  display: inline-block;
  text-transform: uppercase;
  transition: all .3s ease-out;
}

#logo span {
  position: relative;
  transition: margin .3s ease-out;
}

.short span:nth-of-type(1):after {
  position: relative;
  margin-left: -10px;
  content: "est1";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

.short span:nth-of-type(1):hover:after {
  opacity: 1;
  display: inline-block;
  margin-left: 0px;
}

span:hover {
  margin-left: 20px;
}

.short span:nth-of-type(2):after {
  position: relative;
  margin-left: 0px;
  content: "est2";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

.short span:hover:after {
  opacity: 1;
  margin-left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  <h1 class="short">
    <span>T</span><span>t</span>
   </h1>
</code>```

Title: Extend text on hover

Body:
I'm  using two initials and I want that if a user hovers it it will show the rest of the text but I can't make it to display the rest of the text correctly: the part of the first letter it's being displayed next to the text of the second initial.

jsfiddle

#logo .short{
        position: relative;
        margin-top: 0;
        padding: 0 10px;
        font-size: 36px;
        display: inline-block;
        text-transform: uppercase;
      transition: all .3s ease-out;
}
  .short:after{
   position: relative;
    margin-left: -20px;
    content: "est1";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
}

 .short:hover:after{
        opacity: 1;
        display: inline-block;
      margin-left: -10px;
 }
#logo span{
    position: relative;
    transition: margin .3s ease-out;
}
span:hover{
        margin-left: 20px;
}
span:after{
   position: relative;
    margin-left: -20px;
    content: "est2";
    opacity: 0;
    -webkit-transition: all .3s ease-out;
 }

span:hover:after{
  opacity: 1;
  margin-left: -10px;
 }

Body:
You set both letters within <span> element, use :nth-of-type() selector to set content of :after pseudo element

#logo .short {
  position: relative;
  margin-top: 0;
  padding: 0 10px;
  font-size: 36px;
  display: inline-block;
  text-transform: uppercase;
  transition: all .3s ease-out;
}

#logo span {
  position: relative;
  transition: margin .3s ease-out;
}

.short span:nth-of-type(1):after {
  position: relative;
  margin-left: -10px;
  content: "est1";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

.short span:nth-of-type(1):hover:after {
  opacity: 1;
  display: inline-block;
  margin-left: 0px;
}

span:hover {
  margin-left: 20px;
}

.short span:nth-of-type(2):after {
  position: relative;
  margin-left: 0px;
  content: "est2";
  opacity: 0;
  -webkit-transition: all .3s ease-out;
}

.short span:hover:after {
  opacity: 1;
  margin-left: 0px;
}

<a id="logo">
  <h1 class="short">
    <span>T</span><span>t</span>
   </h1>
</a>


问:
How do I check if a column is empty or null in MySQL?
I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?</p>

```<code>(e.g. null or '' or '  ' or '      ' and ...)
</code>```

答:
try this if the datatype are string and row is null

```<code>SELECT * FROM table WHERE column_name IS NULL OR column_name = ''
</code>```

if the datatype are int or column are 0 then try this

```<code>SELECT * FROM table WHERE column_name > = 0
</code>```

Body:
I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?

(e.g. null or '' or '  ' or '      ' and ...)

Body:
try this if the datatype are string and row is null

SELECT * FROM table WHERE column_name IS NULL OR column_name = ''

if the datatype are int or column are 0 then try this

SELECT * FROM table WHERE column_name > = 0


问:
When are nested functions generally appropriate in JavaScript?
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

```<code>var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();
</code>```

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

```<code>function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}
</code>```

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

答:
The toy example you show is not very compelling. The main advantage of writing it that way is that the array is only created once, rather than every time you call the function. This makes it a little faster, at the expense of keeping the array allocated for the entire session (a common time-space tradeoff). In practice, few people program this way.

The technique becomes more useful when you have multiple functions and they operate on shared data. If one of the functions modifies the variable, this is remembered in the closure, and visible to other functions when they're called later.

```<code>var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return {
    getDay: function(number) {
        return names[number];
    },
    setDay: function(number, newName) {
        names[number] = newName;
    }
  };
}();
</code>```

Now you can write:

```<code>console.log(dayName.getDay(3)); // prints "Wednesday"
dayObj.setDay(3, "Mercredi");
console.log(dayName.getDay(3)); // prints "Mercredi"
</code>```

You can't do this with your second form of the function, because it has no memory from one call to the next.

Body:
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

Body:
The toy example you show is not very compelling. The main advantage of writing it that way is that the array is only created once, rather than every time you call the function. This makes it a little faster, at the expense of keeping the array allocated for the entire session (a common time-space tradeoff). In practice, few people program this way.

The technique becomes more useful when you have multiple functions and they operate on shared data. If one of the functions modifies the variable, this is remembered in the closure, and visible to other functions when they're called later.

var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return {
    getDay: function(number) {
        return names[number];
    },
    setDay: function(number, newName) {
        names[number] = newName;
    }
  };
}();

Now you can write:

console.log(dayName.getDay(3)); // prints "Wednesday"
dayObj.setDay(3, "Mercredi");
console.log(dayName.getDay(3)); // prints "Mercredi"

You can't do this with your second form of the function, because it has no memory from one call to the next.


问:
Calling Visual Studio Excel add-ins from Excel 2007
I am very new Visual Studio (just downloaded version 2010 Professional), but I believe this is the right way to do web services in excel.

Have created a Excel 2007 Add-In called TestAPI within Visual Studio containing just one class ThisAddIn, the 2 default StartUp and Shutdown procedures and 2 functions I have written myself, say f1 and f2.

When I start Excel 2007 and check Excel Options i can see it as a COM add in, but how can I see these 2 functions within VBA? Any references to either ThisAddIn or TestAPI or f1 or f2 all fail, yet if I put something into the StartUp functions this will automatically be executed whenever I start Excel, which I do find quite annoying. It seems that COM Add-ins are switched on/off at Excel level whereas I cant seem to find the TestAPI anywhere on my list on References (where I could check or uncheck it as required depending on Excel sheet).

I am probably missing an (or multiple) point(s).

答:
Paul Stubbs has some information on calling VSTO UDFs from VBA on his blog.

Alternatively, you could try building a more vanilla COM add-in for Excel, as described by Eric Carter.

My personal preference for creating user defined functions is to use ExcelDna.


问:
Maven dependency not getting updated with LATEST version
I'm using intelij. I have multiple maven projects.
I deployed new version of maven Project_1, in the logs intelij showed version like this 1.0.0-20170331.023320-3.jar

Then in other Project_2 in pom file at  I set the version of Project_1 as LATEST and run install. And in the logs intelij shows that 1.0.0-20170330-253 version was downloaded. It has different timestamp and when I'm checking the file in the external libraries, it doesn't contain my recent changes.

Please, advise, what I'm doing wrong?

答:
First Please use mvn command line like mvn compile to find the problem.

Set the version to 1.0.0-SNAPSHOT not Latest, if you set the version to snapshot, if you using mvn compile command, I will check the dependency for the latest one in the maven repo. If you are using Intellij try to reimport the maven project.


问:
Stubborn Folder That Keeps Restoring Itself
I have a folder that every time I delete, it restores itself. I tried everything I can think of - even putting it back, moving it to the trash again, and deleting it permanently. I am on an 11in mid-2012 Macbook Air, running OSX Sierra 10.12.3.

When I click on the trash can in the doc I get this:

This is what the terminal says:

Now, this is where it gets really weird. When I run open . in the termnal, I get this:

It's different from the original trash folder! Here is a side by side:

My first guess is AI system are trying to take over the world, and my laptop is trying to kill me; however, I'm pretty sure that is at least a few years in the future. It's important to note that I am a developer, and I have installed lots of NPM modules, Brew kegs - I think they are called -, Ruby Gems, etc. Perhaps something I installed is causing the issue, but I think it could just as easily be a bug in OSX.

Please save me from the AI...

答:
The Finder presents a unified view of all trash folders across all volumes in its Trash view; it doesn't only show the contents of ~/.Trash (the differing folder icons in Finder's title bar provide a clue).

Drag your mystery item into a Terminal window to see its full path, which will tell you where it's stored.

In your case, the item turned out to be from the iCloud Drive's trash folder, whose underlying local filesystem cache location is:

```<code> ~/Library/Mobile Documents/com~apple~CloudDocs
</code>```

with hidden subfolder .Trash containing the iCloud Drive-specific trash.

It's better not to manipulate these automatically managed locations directly, but it's worth trying to use Finder in this case (not sure it will work):

Open Finder to the iCloud Drive folder.

If normally hidden subfolder .Trash isn't visible, press ⇧⌘. (Shift-Command-Period) to make Finder show all hidden items too.

Unfortunately, items cannot be deleted from this location through Finder, but you can try to move your phantom item elsewhere - such as by dragging it to your Desktop or to a non-trash location in your iCloud Drive - to see if that makes it disappear from the Trash. If so, you can then use the shell to rm -r the (moved) phantom folder, which bypasses the Trash.

Body:
The Finder presents a unified view of all trash folders across all volumes in its Trash view; it doesn't only show the contents of ~/.Trash (the differing folder icons in Finder's title bar provide a clue).

Drag your mystery item into a Terminal window to see its full path, which will tell you where it's stored.

In your case, the item turned out to be from the iCloud Drive's trash folder, whose underlying local filesystem cache location is:

 ~/Library/Mobile Documents/com~apple~CloudDocs

with hidden subfolder .Trash containing the iCloud Drive-specific trash.

It's better not to manipulate these automatically managed locations directly, but it's worth trying to use Finder in this case (not sure it will work):

Open Finder to the iCloud Drive folder.

If normally hidden subfolder .Trash isn't visible, press ⇧⌘. (Shift-Command-Period) to make Finder show all hidden items too.

Unfortunately, items cannot be deleted from this location through Finder, but you can try to move your phantom item elsewhere - such as by dragging it to your Desktop or to a non-trash location in your iCloud Drive - to see if that makes it disappear from the Trash. If so, you can then use the shell to rm -r the (moved) phantom folder, which bypasses the Trash.


问:
"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?
This is how my connection is set:

Connection conn = DriverManager.getConnection(url + dbName + "?useUnicode=true&characterEncoding=utf-8", userName, password);

And I'm getting the following error when tyring to add a row to a table:

Incorrect string value: '\xF0\x90\x8D\x83\xF0\x90...' for column 'content' at row 1

I'm inserting thousands of records, and I always get this error when the text contains \xF0 (i.e. the the incorrect string value always starts with \xF0).

The column's collation is utf8_general_ci.

What could be the problem?

答:
In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.

```<code>mysql  Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using  EditLine wrapper

Connection id:      12
Current database:   xxx
Current user:       yo@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/run/mysqld/mysqld.sock
Uptime:         42 min 49 sec

Threads: 1  Questions: 372  Slow queries: 0  Opens: 166  Flush tables: 1  Open tables: 30  Queries per second avg: 0.144
</code>```

so, I look up the column charset in every table

```<code>show create table company;
</code>```

It turns out the column charset is latin. That's why, I can not insert Chinese into database.

```<code> ALTER TABLE company CONVERT TO CHARACTER SET utf8;
</code>```

That might help you. :)

Body:
In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.

mysql  Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using  EditLine wrapper

Connection id:      12
Current database:   xxx
Current user:       yo@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/run/mysqld/mysqld.sock
Uptime:         42 min 49 sec

Threads: 1  Questions: 372  Slow queries: 0  Opens: 166  Flush tables: 1  Open tables: 30  Queries per second avg: 0.144

so, I look up the column charset in every table

show create table company;

It turns out the column charset is latin. That's why, I can not insert Chinese into database.

 ALTER TABLE company CONVERT TO CHARACTER SET utf8;

That might help you. :)


问:
Spark fails with ClassNotFoundException for SerializedLambda
I'm learning spark and my first program is a words counter and I have had problems executing the program in standalone mode

When I execute the code in local mode, I have no problems (setMaster("local")) but When I try to execute in standalone (with a master-slave) , It doesn't finish (I have run the script ./sbin/start-all.sh). The program runs. but collecting data, a exceptions happens. (in the line counter.collectAsMap() )

The error is the following:

```<code>15/01/30 15:23:54 WARN TaskSetManager: Lost task 1.0 in stage 0.0 (TID 1, ******): java.lang.ClassCastException: cannot assign instance of java.lang.invoke.SerializedLambda to field org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$1$1.f$3 of type org.apache.spark.api.java.function.FlatMapFunction in instance of org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$1$1
</code>```

and the code is the following:

```<code>public class MainTest {
    public static void main( String[] args ) throws {
        String origin = "originPath";

        SparkConf conf = new SparkConf().setAppName("org.sparkexample.WordCount").setMaster("spark://localhost:7077");
        JavaSparkContext context = new JavaSparkContext(conf);
        JavaRDD<String> file = context.textFile(origin);
        JavaRDD<String> words = file.flatMap(s -> Arrays.asList(s.split(" ")));
        JavaPairRDD<String, Integer> pairs = words.mapToPair(word ->new Tuple2<>(word,1));
        JavaPairRDD<String, Integer> counter = pairs.reduceByKey(( valueA,valueB) ->valueA +valueB);
        Map<String,Integer> map = counter.collectAsMap();
        map.forEach((key,value)->System.out.println(key+"="+value));
    }
}
</code>```

My machine has Oracle Java 8 installed and I launch the master and one slave with ./sbin/start-all.sh script

Which one can be the error?

UPDATE:

I'm trying a Java 7 Implementation and I have other problem: The exception is:

```<code>15/01/30 12:47:21 WARN TaskSetManager: Lost task 1.0 in stage 0.0 (TID 1, ***): java.lang.ClassNotFoundException: com.c4om.l3p3.sparkTest.MainTest
</code>```

Maybe this is a configuration problem?

The Java7 Code is the following:

```<code>public static void countWordsJava7(String path,Boolean local, Boolean printResult){
    SparkConf conf = new SparkConf().setAppName("org.sparkexample.WordCount").setMaster("spark://localhost:7077");
    JavaSparkContext context = new JavaSparkContext(conf);
    JavaRDD<String> file = context.textFile(path);
    JavaRDD<String> words = file.flatMap(new FlatMapFunction<String, String>() {
        @Override
        public Iterable<String> call(String s) {
            return Arrays.asList(" ".split(s));
        }
    });
    JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
            return new Tuple2<String, Integer>(s, 1);
        }
    });
    JavaPairRDD<String, Integer> counter = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
            return i1 + i2;
        }
    });
    Map<String, Integer> map = counter.collectAsMap();
}
</code>```

答:
Set jar path on the SparkConf then it works. jar path is the path of jar file after compile by maven or ant.

```<code>String master = "spark://localhost:7077";
    SparkConf conf = new SparkConf()
            .setAppName(WordCountTask.class.getName())
            .setMaster(master)
            .setJars(new String[]{"/home/user/Projects/spark-test/target/first-example-1.0-SNAPSHOT.jar"})
</code>```

Hope it help.

Body:
I'm learning spark and my first program is a words counter and I have had problems executing the program in standalone mode

When I execute the code in local mode, I have no problems (setMaster("local")) but When I try to execute in standalone (with a master-slave) , It doesn't finish (I have run the script ./sbin/start-all.sh). The program runs. but collecting data, a exceptions happens. (in the line counter.collectAsMap() )

The error is the following:

15/01/30 15:23:54 WARN TaskSetManager: Lost task 1.0 in stage 0.0 (TID 1, ******): java.lang.ClassCastException: cannot assign instance of java.lang.invoke.SerializedLambda to field org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$1$1.f$3 of type org.apache.spark.api.java.function.FlatMapFunction in instance of org.apache.spark.api.java.JavaRDDLike$$anonfun$fn$1$1

and the code is the following:

public class MainTest {
    public static void main( String[] args ) throws {
        String origin = "originPath";

        SparkConf conf = new SparkConf().setAppName("org.sparkexample.WordCount").setMaster("spark://localhost:7077");
        JavaSparkContext context = new JavaSparkContext(conf);
        JavaRDD<String> file = context.textFile(origin);
        JavaRDD<String> words = file.flatMap(s -> Arrays.asList(s.split(" ")));
        JavaPairRDD<String, Integer> pairs = words.mapToPair(word ->new Tuple2<>(word,1));
        JavaPairRDD<String, Integer> counter = pairs.reduceByKey(( valueA,valueB) ->valueA +valueB);
        Map<String,Integer> map = counter.collectAsMap();
        map.forEach((key,value)->System.out.println(key+"="+value));
    }
}

My machine has Oracle Java 8 installed and I launch the master and one slave with ./sbin/start-all.sh script

Which one can be the error?

UPDATE:

I'm trying a Java 7 Implementation and I have other problem: The exception is:

15/01/30 12:47:21 WARN TaskSetManager: Lost task 1.0 in stage 0.0 (TID 1, ***): java.lang.ClassNotFoundException: com.c4om.l3p3.sparkTest.MainTest

Maybe this is a configuration problem?

The Java7 Code is the following:

public static void countWordsJava7(String path,Boolean local, Boolean printResult){
    SparkConf conf = new SparkConf().setAppName("org.sparkexample.WordCount").setMaster("spark://localhost:7077");
    JavaSparkContext context = new JavaSparkContext(conf);
    JavaRDD<String> file = context.textFile(path);
    JavaRDD<String> words = file.flatMap(new FlatMapFunction<String, String>() {
        @Override
        public Iterable<String> call(String s) {
            return Arrays.asList(" ".split(s));
        }
    });
    JavaPairRDD<String, Integer> pairs = words.mapToPair(new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
            return new Tuple2<String, Integer>(s, 1);
        }
    });
    JavaPairRDD<String, Integer> counter = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
            return i1 + i2;
        }
    });
    Map<String, Integer> map = counter.collectAsMap();
}

Body:
Set jar path on the SparkConf then it works. jar path is the path of jar file after compile by maven or ant.

String master = "spark://localhost:7077";
    SparkConf conf = new SparkConf()
            .setAppName(WordCountTask.class.getName())
            .setMaster(master)
            .setJars(new String[]{"/home/user/Projects/spark-test/target/first-example-1.0-SNAPSHOT.jar"})

Hope it help.


问:
<MAC> ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I am new to mysql.
So after download the server and workbench from mysql.com, I did run "./mysql -u root -p" and whenever I entered the password I saw the error below:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Also, whenever I typed "mysql -u root" as other people recommended I got another error below:

-bash: mysql: command not found

How should I fix these errors?

Please help.

Thank you

答:
I did run "./mysql -u root -p"

At least command executed successfully.

whenever I typed "mysql -u root"

```<code>-bash: mysql: command not found
</code>```

Command didn't execute, because mysql is not in your $PATH variable in bash.

Try

```<code>./mysql -u root
</code>```

P.S. If it fails with Access denied error, try reinitializing your mysql server.

Body:
I did run "./mysql -u root -p"

At least command executed successfully.

whenever I typed "mysql -u root"

-bash: mysql: command not found

Command didn't execute, because mysql is not in your $PATH variable in bash.

Try

./mysql -u root

P.S. If it fails with Access denied error, try reinitializing your mysql server.


问:
Implementing "begin contact" in box2d
I am working on a game in box2d. I have the following code:

```<code>    for (int contact_num = 0; contact_num<contact_count; ++contact_num)
{
    if (contact->IsTouching())
    {
        // get the colliding bodies
        b2Body* bodyA = contact->GetFixtureA()->GetBody();
        b2Body* bodyB = contact->GetFixtureB()->GetBody();

        // check if one of the colliding objects is a censor
        bool sensorA = contact->GetFixtureA()->IsSensor();
        bool sensorB = contact->GetFixtureB()->IsSensor();

        // do stuff, mainly handling variables

        }
    }
    // Get next contact point
    contact = contact->GetNext();
}
</code>```

All of this is being called in the update function of my main class (which also contains most of the games variables). The problem is that I want the code to only be called when the two objects first collide, because otherwise something like score++ will end up skyrocketing in value as it gets updated for the collisions duration. I am aware of a "contact listener" class in box2d with the function "begin contact", but there is no good documentation that could help a beginer learn how to implement it. For example, if I add a contact listener to my main class, how do I get it to handle my score, for example, if the contact listener doesn't have access to those variables? Or where do I call "begin contact" in the first place? Sorry if these are obvious questions, but i was hoping someone could clarify these. Thank you in advance.

答:
Here's a couple suggestions which hopefully will answer your question:

Take a look at Box2D C++ tutorials - Collision callbacks. Personally, I think it's a great tutorial on using the b2ContactListener class.

Just make your class which contains the score information inherit from b2ContactListener. That way your BeginContact method will have direct access to the score data. Presumably that'll be your "main" class. Be sure to also notify your b2World instance to use this by calling your world instance's SetContactListener method with a pointer to the score containing instance (that you'd subclassed from b2ContactListener).

If you still need more help with this, please add a comment to that effect or update your question to reflect what remains unclear.

Title: Implementing "begin contact" in box2d

Body:
I am working on a game in box2d. I have the following code:

    for (int contact_num = 0; contact_num<contact_count; ++contact_num)
{
    if (contact->IsTouching())
    {
        // get the colliding bodies
        b2Body* bodyA = contact->GetFixtureA()->GetBody();
        b2Body* bodyB = contact->GetFixtureB()->GetBody();

        // check if one of the colliding objects is a censor
        bool sensorA = contact->GetFixtureA()->IsSensor();
        bool sensorB = contact->GetFixtureB()->IsSensor();

        // do stuff, mainly handling variables

        }
    }
    // Get next contact point
    contact = contact->GetNext();
}

All of this is being called in the update function of my main class (which also contains most of the games variables). The problem is that I want the code to only be called when the two objects first collide, because otherwise something like score++ will end up skyrocketing in value as it gets updated for the collisions duration. I am aware of a "contact listener" class in box2d with the function "begin contact", but there is no good documentation that could help a beginer learn how to implement it. For example, if I add a contact listener to my main class, how do I get it to handle my score, for example, if the contact listener doesn't have access to those variables? Or where do I call "begin contact" in the first place? Sorry if these are obvious questions, but i was hoping someone could clarify these. Thank you in advance.


问:
TabbarActivity fragment not called to onActivityResult
im using tabbaractivity and one of the tabs contains listView
i want to update the listView every time that i adding object.
to add object i do it from new activity
what i wants is when this activity will close the listView will update by using
adapter.notifydatachanged

in my activity that contains the tabs

```<code>   if (id == R.id.addButton) {
        Intent intent = new Intent(rootViewTabBarActivity.this, addPictureActivity.class);
        startActivityForResult(intent,101);
        return true;
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}
</code>```

in the fragment (one of the tabs)

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if ((requestCode == 101) && (resultCode == Activity.RESULT_OK))
        adapter.notifyDataSetChanged();
}
</code>```

and the activity that create the object and save him to database

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAM_REQUEST) {
        Bitmap btmp = (Bitmap)data.getExtras().get("data");
        takenPhoto.setImageBitmap(btmp);
    }
}
@Override
protected void onDestroy() {
    super.onDestroy();
    setResult(Activity.RESULT_OK);
}
</code>```

Thanks

答:
fragment not called to onActivityResult

You miss passing the data from Activity to fragment
In Activity, your code should be like this:

```<code>@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            YourFragment fragment = getFragment();
            if (fragment != null) {
                // Pass data to Fragment
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }

    }

public YourFragment getFragment() {
        // You can find your fragment (by tag/ by id) here depends on your layout
    }
</code>```

Body:
im using tabbaractivity and one of the tabs contains listView
i want to update the listView every time that i adding object.
to add object i do it from new activity
what i wants is when this activity will close the listView will update by using
adapter.notifydatachanged

in my activity that contains the tabs

   if (id == R.id.addButton) {
        Intent intent = new Intent(rootViewTabBarActivity.this, addPictureActivity.class);
        startActivityForResult(intent,101);
        return true;
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

in the fragment (one of the tabs)

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if ((requestCode == 101) && (resultCode == Activity.RESULT_OK))
        adapter.notifyDataSetChanged();
}

and the activity that create the object and save him to database

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAM_REQUEST) {
        Bitmap btmp = (Bitmap)data.getExtras().get("data");
        takenPhoto.setImageBitmap(btmp);
    }
}
@Override
protected void onDestroy() {
    super.onDestroy();
    setResult(Activity.RESULT_OK);
}

Thanks

Body:
fragment not called to onActivityResult

You miss passing the data from Activity to fragment
In Activity, your code should be like this:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            YourFragment fragment = getFragment();
            if (fragment != null) {
                // Pass data to Fragment
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }

    }

public YourFragment getFragment() {
        // You can find your fragment (by tag/ by id) here depends on your layout
    }


问:
Tornado request.body
My Tornado application accepts POST data through http body request

In my handler I am able to get the request

```<code>def post(self):
    data = self.request.body
</code>```

The data I am getting is in the from of str(dictionary)

Is there a way to receive this data in the form of a Python dictionary?

I don't want to use eval on the server side to convert this string to a Python dictionary.

答:
If you are using WebApp2, it uses its own json extras. (Decode)
http://webapp2.readthedocs.io/en/latest/_modules/webapp2_extras/json.html

```<code>    data = json.decode(self.request.body)
    v = data.get(key)
    self.response.write(v)
</code>```

For example my post key is 'postvalue'

```<code>    data = json.decode(self.request.body)
    v = data.get('postvalue')
    self.response.write(v)
</code>```

Title: Tornado request.body

Body:
My Tornado application accepts POST data through http body request

In my handler I am able to get the request

def post(self):
    data = self.request.body

The data I am getting is in the from of str(dictionary)

Is there a way to receive this data in the form of a Python dictionary?

I don't want to use eval on the server side to convert this string to a Python dictionary.

Body:
If you are using WebApp2, it uses its own json extras. (Decode)
http://webapp2.readthedocs.io/en/latest/_modules/webapp2_extras/json.html

    data = json.decode(self.request.body)
    v = data.get(key)
    self.response.write(v)

For example my post key is 'postvalue'

    data = json.decode(self.request.body)
    v = data.get('postvalue')
    self.response.write(v)


问:
How to pass data via event from swf1 to swf2 where former is loaded in later
I have a swf(Swf1)that dispatches a CustomEvent

Swf1 :
dispatchEvent( new CustomEvent("eventName", obj)) //Custom event is written in Swf1 that allows to attach data on dispatch. // do tell if there is anyother way to do this using inbuilt AS3 APIs.

Now Swf2: (loads Swf1)
added listener
function onswf1loadComplete(e:Event){
_movie = MovieClip(e.target.content);
_movie.addEventListener("eventName", callrequiredFunction);
 // how to get the obj here?
}

(except that I need to define CustomEvent in Swf2 too)

答:
You could externalize the loading of the SWfs to another class which would handle the communication between the two swfs...</p>

```<code> private var swf1:MovieClip;
 private var swf2:MovieClip;

 private function loadSWF(url:String):void
 {
     //loading swf code
 }

 private function init():void
 {
    loadSWF( swf2URL );
  }

 private function completeHandler (event:Event ):void
 {
     switch( event.currentTarget.name)
     {
         case 'swf1':
           swf1 = new Whatever();
           //swf1.addEventistener( CustomEvent.SWF1 , swfEventListener );
           swf1.addEventistener( Event.COMPLETE , completeEventListener );
           swf1.init();
           break;

        case 'swf2':
           loadSWF( swf1URL );
           break;
     }
 }

 private function completeEventListener( event: Event):void
 {
      //where result is a getter on the Whatever class
      var object:Object = swf1.result;
 }

 private function swfEventListener( event: CustomEvent):void
 {
      if( event.type == CustomEvent.SWF1 )
          var object:Object = event.object;
 }
</code>```

Body:
You could externalize the loading of the SWfs to another class which would handle the communication between the two swfs...

 private var swf1:MovieClip;
 private var swf2:MovieClip;

 private function loadSWF(url:String):void
 {
     //loading swf code
 }

 private function init():void
 {
    loadSWF( swf2URL );
  }

 private function completeHandler (event:Event ):void
 {
     switch( event.currentTarget.name)
     {
         case 'swf1':
           swf1 = new Whatever();
           //swf1.addEventistener( CustomEvent.SWF1 , swfEventListener );
           swf1.addEventistener( Event.COMPLETE , completeEventListener );
           swf1.init();
           break;

        case 'swf2':
           loadSWF( swf1URL );
           break;
     }
 }

 private function completeEventListener( event: Event):void
 {
      //where result is a getter on the Whatever class
      var object:Object = swf1.result;
 }

 private function swfEventListener( event: CustomEvent):void
 {
      if( event.type == CustomEvent.SWF1 )
          var object:Object = event.object;
 }


问:
Test espresso with Travis
I am trying to test integration tests with Travis-CI. I have the yml:

```<code>language: android

jdk: oraclejdk8

sudo: false

android:
  components:
  - platform-tools
  - tools
  - build-tools-25.0.2
  - android-25
  - sys-img-armeabi-v7a-android-22

  #Extras
  - extra-android-m2repository
  - extra-google-m2repository
  - extra-android-m2repository

before_script:
  - android list targets
  - echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a
  - emulator -avd test -no-skin -no-audio -no-window &
  - android-wait-for-emulator
  - adb shell input keyevent 82 &

script:
  - ./gradlew test
  - ./gradlew connectedAndroidTest
script: "./travis-build.sh"
</code>```

This should work, but I am always getting:

Error: Target id is not valid. Use 'android list targets' to get the target ids.

I have no idea how to fix this problem...

Any help is appreciated

答:
Old VM (used with sudo: false) only include platforms up to android-21, please try this

```<code>language: android

jdk: oraclejdk8

sudo: false

android:
  components:
  - platform-tools
  - tools
  - build-tools-25.0.2
  - android-22 # Android platform used by your alternative emulator
  - android-25
  - sys-img-armeabi-v7a-android-22

  #Extras
  - extra-android-m2repository
  - extra-google-m2repository  # Removed duplicated component

before_script:
  - android list targets
  - echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a
  - emulator -avd test -no-skin -no-audio -no-window &
  - android-wait-for-emulator
  - adb shell input keyevent 82 &

script:
  - ./gradlew test
  - ./gradlew connectedAndroidTest
script: "./travis-build.sh"
</code>```

Title: Test espresso with Travis

Body:
I am trying to test integration tests with Travis-CI. I have the yml:

language: android

jdk: oraclejdk8

sudo: false

android:
  components:
  - platform-tools
  - tools
  - build-tools-25.0.2
  - android-25
  - sys-img-armeabi-v7a-android-22

  #Extras
  - extra-android-m2repository
  - extra-google-m2repository
  - extra-android-m2repository

before_script:
  - android list targets
  - echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a
  - emulator -avd test -no-skin -no-audio -no-window &
  - android-wait-for-emulator
  - adb shell input keyevent 82 &

script:
  - ./gradlew test
  - ./gradlew connectedAndroidTest
script: "./travis-build.sh"

This should work, but I am always getting:

Error: Target id is not valid. Use 'android list targets' to get the target ids.

I have no idea how to fix this problem...

Any help is appreciated

Body:
Old VM (used with sudo: false) only include platforms up to android-21, please try this

language: android

jdk: oraclejdk8

sudo: false

android:
  components:
  - platform-tools
  - tools
  - build-tools-25.0.2
  - android-22 # Android platform used by your alternative emulator
  - android-25
  - sys-img-armeabi-v7a-android-22

  #Extras
  - extra-android-m2repository
  - extra-google-m2repository  # Removed duplicated component

before_script:
  - android list targets
  - echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a
  - emulator -avd test -no-skin -no-audio -no-window &
  - android-wait-for-emulator
  - adb shell input keyevent 82 &

script:
  - ./gradlew test
  - ./gradlew connectedAndroidTest
script: "./travis-build.sh"


问:
How can I perfectly center my image?
So I have an image on my website and I want to perfectly center it. I have tried many things but none have worked.

body{
background-color: black;
}

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="images/astronaut.png"></code>```

答:
Setting the left and right margin to auto will center the image horizontally within it's parent if your position isn't set or is set to relative.

So you could use:

```<code>img {
  margin-top: 10%;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  height: 40%;
  z-index: -5
}
</code>```

If your position needs to be set to absolute, you can use CSS3's viewport sizing to center your image. This would place the image in the exact center of the page; so if you want to center the image within a sidebar, for example, don't use this method. You'll need to set a width for your image and then align it using the "left" property. That would look like this:

```<code>img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
  width: 500px;
  left: calc( 50vw - 250px );
}
</code>```

The viewport is always 100vw wide, so setting the left property to 50vw - 1/2 of the image's width will center it on the page.

You can also use jQuery to similarly calculate the proper alignment and position the element.

Title: How can I perfectly center my image?

Body:
Setting the left and right margin to auto will center the image horizontally within it's parent if your position isn't set or is set to relative.

So you could use:

img {
  margin-top: 10%;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  height: 40%;
  z-index: -5
}

If your position needs to be set to absolute, you can use CSS3's viewport sizing to center your image. This would place the image in the exact center of the page; so if you want to center the image within a sidebar, for example, don't use this method. You'll need to set a width for your image and then align it using the "left" property. That would look like this:

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
  width: 500px;
  left: calc( 50vw - 250px );
}

The viewport is always 100vw wide, so setting the left property to 50vw - 1/2 of the image's width will center it on the page.

You can also use jQuery to similarly calculate the proper alignment and position the element.


问:
How do I put focus on a TextBox when a form loads?
I have a TextBox in my C# program. I need focus to be on this TextBox when the program starts.

I tried this on Form_Load:

```<code>MyTextBox.Focus();
</code>```

but it doesn't work.

How do I put focus on this when the form loads?

答:
You cannot set focus to a control if it has not been rendered. Form.Load() occurs before the controls are rendered.

Go to the form's events and double click the "Shown" event. In the form's shown event handler call the control.Focus() method.

```<code>    private void myForm_Shown(object sender, EventArgs e)
    {
        // Call textbox's focus method
        txtMyTextbox.Focus();
    }
</code>```

Body:
I have a TextBox in my C# program. I need focus to be on this TextBox when the program starts.

I tried this on Form_Load:

MyTextBox.Focus();

but it doesn't work.

How do I put focus on this when the form loads?

Body:
You cannot set focus to a control if it has not been rendered. Form.Load() occurs before the controls are rendered.

Go to the form's events and double click the "Shown" event. In the form's shown event handler call the control.Focus() method.

    private void myForm_Shown(object sender, EventArgs e)
    {
        // Call textbox's focus method
        txtMyTextbox.Focus();
    }


问:
How can I get the name of the file to be uploaded by primefaces
I am using the "FileUpload" component of primefaces with "advanced" mode, and I want to get the name of the file once the user makes his choice of the file that he wants to upload and before submitting.

Attributes "Onstart" AND "Oncomplete" are executed after clicking the submit button, so I can not use them.

I tried also getting the name using a validator methode, but It seems to be a primefaces bug, because the method is never invocked.

```<code><p:fileUpload id="fileToUpload" label="Browse"
                            fileUploadListener="#{uploadFile.handleFileUpload}"
                            mode="advanced" dragDropSupport="false" value = "#{uploadFile.file2}"
                            update="growl uploadFile_exposureType"
                            oncomplete="if(PF('ajaxLoaderDialogWidgetImport')) PF('ajaxLoaderDialogWidgetImport').hide();refreshAllRowNumbers();PF('importRisksList').hide();"
                            allowTypes="/(\.|\/)(xlsx|xls|kml)$/"
                            onstart="if(PF('ajaxLoaderDialogWidgetImport')) PF('ajaxLoaderDialogWidgetImport').show();"
                            styleClass="reimport_upload Browse browse_uploadBtn" valueChangeListener="#{uploadFile.handleChange}" >
                            </p:fileUpload>
</code>```

答:
Set fileUploadLisener(fileUploadListener="#{fileUploadView.handleFileUpload}" ). </p>

<p>In bean gets the filename using </p>

```<code>public void handleFileUpload(FileUploadEvent event) {
    fileName = event.getFile().getFileName();
}
</code>```

Body:
I am using the "FileUpload" component of primefaces with "advanced" mode, and I want to get the name of the file once the user makes his choice of the file that he wants to upload and before submitting.

Attributes "Onstart" AND "Oncomplete" are executed after clicking the submit button, so I can not use them.

I tried also getting the name using a validator methode, but It seems to be a primefaces bug, because the method is never invocked.

<p:fileUpload id="fileToUpload" label="Browse"
                            fileUploadListener="#{uploadFile.handleFileUpload}"
                            mode="advanced" dragDropSupport="false" value = "#{uploadFile.file2}"
                            update="growl uploadFile_exposureType"
                            oncomplete="if(PF('ajaxLoaderDialogWidgetImport')) PF('ajaxLoaderDialogWidgetImport').hide();refreshAllRowNumbers();PF('importRisksList').hide();"
                            allowTypes="/(\.|\/)(xlsx|xls|kml)$/"
                            onstart="if(PF('ajaxLoaderDialogWidgetImport')) PF('ajaxLoaderDialogWidgetImport').show();"
                            styleClass="reimport_upload Browse browse_uploadBtn" valueChangeListener="#{uploadFile.handleChange}" >

Body:
Set fileUploadLisener(fileUploadListener="#{fileUploadView.handleFileUpload}" ).

In bean gets the filename using

public void handleFileUpload(FileUploadEvent event) {
    fileName = event.getFile().getFileName();
}


问:
How to use a script in package.json file to make changes to source files
I am using react-scripts in my project. I use some newer syntax that requires my webpack.config use plugins such as

plugins: ['transform-decorators-legacy']

I am trying to avoid ejecting the config files just to add this line to the webpack.config.dev and webpack.config.prod files.

So I am trying to make a script to insert this automatically.

In the dev file, I need to insert it after the cacheDirectory: true.

```<code> // Process JS with Babel.
  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: 'babel',
    query: {
      // @remove-on-eject-begin
      babelrc: false,
      presets: [require.resolve('babel-preset-react-app')],
      // @remove-on-eject-end
      // This is a feature of `babel-loader` for webpack (not Babel itself).
      // It enables caching results in ./node_modules/.cache/babel-loader/
      // directory for faster rebuilds.
      cacheDirectory: true
    }
  }
</code>```

And I have come up with this to insert it

```<code>"fix-react-scripts-dev": "ex -sc '%s/cacheDirectory: true/cacheDirectory: true,plugins: ['transform-decorators-legacy']/g|x' node_modules/react-scripts/config/webpack.config.dev.js"
</code>```

The result is

```<code>  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: 'babel',
    query: {
      // @remove-on-eject-begin
      babelrc: false,
      presets: [require.resolve('babel-preset-react-app')],
      // @remove-on-eject-end
      // This is a feature of `babel-loader` for webpack (not Babel itself).
      // It enables caching results in ./node_modules/.cache/babel-loader/
      // directory for faster rebuilds.
      cacheDirectory: true,
      plugins: [transform-decorators-legacy]
    }
  }
</code>```

the problem is

plugins: [transform-decorators-legacy]

is missing the quotation marks. Is this a character escape issue I am missing from my script?

And for the prod config file. I need to insert it after

```<code>presets: [require.resolve('babel-preset-react-app')]

// Process JS with Babel.
  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: 'babel',
    // @remove-on-eject-begin
    query: {
      babelrc: false,
      presets: [require.resolve('babel-preset-react-app')]
    }
    // @remove-on-eject-end
  }
</code>```

答:
The problem with your script is that you're ending the command string with the single quotes. This isn't an issue to bash since it'll just treat the rest of the string as an unquoted string until the second single quote reopens a single quoted string. However, the preferred method to escape single quotes in bash also interrupts the JSON string! You need an escape sequence that escapes single quotes in a single quoted string with escaped double quotes. That ends up being '\"'\"'. This ends the first string, starts a double quoted string that doesn't end the JSON string, enters a single quote, ends the double quoted string without ending the JSON string, and starts another single quoted string. So, your script becomes:

```<code>"fix-react-scripts-dev": "ex -sc '%s/cacheDirectory: true/cacheDirectory: true,plugins: ['\"'\"'transform-decorators-legacy'\"'\"']/g|x' node_modules/react-scripts/config/webpack.config.dev.js"
</code>```

As for the second part, I'm just going to assume you made a typo by putting presets in there twice since it wouldn't make sense for it to be outside the code block. If this is true then the plugins line needs to go underneath the presets line in the query. If this assumption was wrong please let me know.

This needs a similar super-escape sequence for the single quotes but there's another issue with matching the presets line. This line not only has single quotes but also has square brackets. Those also need to be escaped or else the dashes inside them will be considered part of a range search in the search pattern of %s (think how you can do [a-z] in regex, vim allows this in the search pattern). Your prod script would then be (change the directory if needed):

```<code>"fix-react-scripts-prod": "ex -sc '%s/presets: \\[require.resolve('\"'\"'babel\\-preset\\-react\\-app'\"'\"')\\]/presets: \\[require.resolve('\"'\"'babel\\-preset\\-react\\-app'\"'\"')\\],plugins: \\['\"'\"'transform\\-decorators\\-legacy'\"'\"'\\]/g|x' node_modules/react-scripts/config/webpack.config.prod.js"
</code>```

Body:
I am using react-scripts in my project. I use some newer syntax that requires my webpack.config use plugins such as

plugins: ['transform-decorators-legacy']

I am trying to avoid ejecting the config files just to add this line to the webpack.config.dev and webpack.config.prod files.

So I am trying to make a script to insert this automatically.

In the dev file, I need to insert it after the cacheDirectory: true.

 // Process JS with Babel.
  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: 'babel',
    query: {
      // @remove-on-eject-begin
      babelrc: false,
      presets: [require.resolve('babel-preset-react-app')],
      // @remove-on-eject-end
      // This is a feature of `babel-loader` for webpack (not Babel itself).
      // It enables caching results in ./node_modules/.cache/babel-loader/
      // directory for faster rebuilds.
      cacheDirectory: true
    }
  }

And I have come up with this to insert it

"fix-react-scripts-dev": "ex -sc '%s/cacheDirectory: true/cacheDirectory: true,plugins: ['transform-decorators-legacy']/g|x' node_modules/react-scripts/config/webpack.config.dev.js"

The result is

  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: 'babel',
    query: {
      // @remove-on-eject-begin
      babelrc: false,
      presets: [require.resolve('babel-preset-react-app')],
      // @remove-on-eject-end
      // This is a feature of `babel-loader` for webpack (not Babel itself).
      // It enables caching results in ./node_modules/.cache/babel-loader/
      // directory for faster rebuilds.
      cacheDirectory: true,
      plugins: [transform-decorators-legacy]
    }
  }

the problem is

plugins: [transform-decorators-legacy]

is missing the quotation marks. Is this a character escape issue I am missing from my script?

And for the prod config file. I need to insert it after

presets: [require.resolve('babel-preset-react-app')]

// Process JS with Babel.
  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: 'babel',
    // @remove-on-eject-begin
    query: {
      babelrc: false,
      presets: [require.resolve('babel-preset-react-app')]
    }
    // @remove-on-eject-end
  }

Body:
The problem with your script is that you're ending the command string with the single quotes. This isn't an issue to bash since it'll just treat the rest of the string as an unquoted string until the second single quote reopens a single quoted string. However, the preferred method to escape single quotes in bash also interrupts the JSON string! You need an escape sequence that escapes single quotes in a single quoted string with escaped double quotes. That ends up being '\"'\"'. This ends the first string, starts a double quoted string that doesn't end the JSON string, enters a single quote, ends the double quoted string without ending the JSON string, and starts another single quoted string. So, your script becomes:

"fix-react-scripts-dev": "ex -sc '%s/cacheDirectory: true/cacheDirectory: true,plugins: ['\"'\"'transform-decorators-legacy'\"'\"']/g|x' node_modules/react-scripts/config/webpack.config.dev.js"

As for the second part, I'm just going to assume you made a typo by putting presets in there twice since it wouldn't make sense for it to be outside the code block. If this is true then the plugins line needs to go underneath the presets line in the query. If this assumption was wrong please let me know.

This needs a similar super-escape sequence for the single quotes but there's another issue with matching the presets line. This line not only has single quotes but also has square brackets. Those also need to be escaped or else the dashes inside them will be considered part of a range search in the search pattern of %s (think how you can do [a-z] in regex, vim allows this in the search pattern). Your prod script would then be (change the directory if needed):

"fix-react-scripts-prod": "ex -sc '%s/presets: \\[require.resolve('\"'\"'babel\\-preset\\-react\\-app'\"'\"')\\]/presets: \\[require.resolve('\"'\"'babel\\-preset\\-react\\-app'\"'\"')\\],plugins: \\['\"'\"'transform\\-decorators\\-legacy'\"'\"'\\]/g|x' node_modules/react-scripts/config/webpack.config.prod.js"


答:
You can put the image in a div and make it 100% of the screen in width and height.

Then add text-align:center; to center it horizontally.

Then set the line height to 100% and then add vertical-align: middle; to the image to center it vertically.

body{
background-color: black;
}

   .CenterImage img {

  height: 40%;
  z-index: -5;
vertical-align: middle;

}
.CenterImage{
width:100vw;
height:100vh;
line-height: 100vh;
text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="CenterImage"><img src="images/astronaut.png"></div></code>```

Title: How can I perfectly center my image?

Body:
So I have an image on my website and I want to perfectly center it. I have tried many things but none have worked.

body{
background-color: black;
}

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
}

Body:
You can put the image in a div and make it 100% of the screen in width and height.

Then add text-align:center; to center it horizontally.

Then set the line height to 100% and then add vertical-align: middle; to the image to center it vertically.

body{
background-color: black;
}

   .CenterImage img {

  height: 40%;
  z-index: -5;
vertical-align: middle;

}
.CenterImage{
width:100vw;
height:100vh;
line-height: 100vh;
text-align:center;
}

<div class="CenterImage"><img src="images/astronaut.png"></div>


问:
How to parse json data that provides another url with more data
I'm a little confused how would I parse a json API that gives me 20 objects but then gives me a key of "next" having a url that gives me another 20 objects. I'm using this Pokemon API. It gives me 4 keys: count, previous, results and next. I'm trying to display them all in a collection view but not all at the same time. I would like to load more when the collection view is scrolling down.

I'm just trying to get the name at the moment. This is how my code looks like.

I get it to load the first 20 Pokemon in the collection view. However I don't know how to load the next 20 Pokemon or the 20 after. This is how the json file looks like if the link didn't work.

I would appreciate any help given. :)

答:
You can try using a recursive function reusing the loadPokemonsData function something like this:

```<code>func loadPokemonsData(url: String, quantity: Int?) {
    let request = URLRequest(url: URL(string: url)!)

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print(error!)
        }

        do {
            let jsonResults = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary

            let pokemonArray = jsonResults.value(forKey: "results") as! [[String: Any]]

            var isPokemonsEqualsToQuantity: Bool = false

            for pokemonData in pokemonArray {

                if let quantity = quantity {
                    guard self.pokemons.count < quantity else {
                        isPokemonsEqualsToQuantity = true
                        break
                    }
                }

                guard let name = pokemonData["name"] as? String else {
                    return
                }

                self.pokemon = Pokemon(name: name)
                self.pokemons.append(self.pokemon)
            }

            guard let nextURL = jsonResults.value(forKey: "next") as? String, !isPokemonsEqualsToQuantity else {
                for pokemon in self.pokemons {
                    print(pokemon.name)

                }
                print(self.pokemons.count)
                return
            }

            self.loadPokemonsData(url: nextURL, quantity: quantity)

        } catch let err as NSError {
            print(err.localizedDescription)
        }
    }

    task.resume()
}
</code>```

Attach a screen of algorithm function running... it prints 791 pokemons.

Hope it helps you!

EDITED

Next time you ask put your code please... it will be easier help you!.

I've updated the code to set the quantity you want (nil if you want to get all pokemons), Therefore it will only get the pokemons in the order API returns it, if you want a specific pokemons from ALL pokemons you may do a sort after obtaining all pokemons.

Body:
You can try using a recursive function reusing the loadPokemonsData function something like this:

func loadPokemonsData(url: String, quantity: Int?) {
    let request = URLRequest(url: URL(string: url)!)

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            print(error!)
        }

        do {
            let jsonResults = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary

            let pokemonArray = jsonResults.value(forKey: "results") as! [[String: Any]]

            var isPokemonsEqualsToQuantity: Bool = false

            for pokemonData in pokemonArray {

                if let quantity = quantity {
                    guard self.pokemons.count < quantity else {
                        isPokemonsEqualsToQuantity = true
                        break
                    }
                }

                guard let name = pokemonData["name"] as? String else {
                    return
                }

                self.pokemon = Pokemon(name: name)
                self.pokemons.append(self.pokemon)
            }

            guard let nextURL = jsonResults.value(forKey: "next") as? String, !isPokemonsEqualsToQuantity else {
                for pokemon in self.pokemons {
                    print(pokemon.name)

                }
                print(self.pokemons.count)
                return
            }

            self.loadPokemonsData(url: nextURL, quantity: quantity)

        } catch let err as NSError {
            print(err.localizedDescription)
        }
    }

    task.resume()
}

Attach a screen of algorithm function running... it prints 791 pokemons.

Hope it helps you!

EDITED

Next time you ask put your code please... it will be easier help you!.

I've updated the code to set the quantity you want (nil if you want to get all pokemons), Therefore it will only get the pokemons in the order API returns it, if you want a specific pokemons from ALL pokemons you may do a sort after obtaining all pokemons.


问:
For each value in the array change to the same image in CSS
There is an array which will increase and decrease in size and I was trying to implement something that will allow the code to go through each value in the array and perform the following code: (set the same image for each value)

```<code>if (something) {
myArray[0].css("background-image", "url(pictures/img.png)")
myArray[1].css("background-image", "url(pictures/img.png)")
}
</code>```

The code above works however, it only works for the first two values, what if there is more? or less?

I was thinking of implementing forEach method so it could actually replace the image within every value, however it is not a variable as it modifies the CSS file and I am slightly confused how I could do that since I couldn't find relevant example, so here's the code I thought it might work but it doesn't

```<code>if (something) {
    myArray.forEach(value) {
    myArray.css("background-image", "url(pictures/img.png)")
    }
}
</code>```

Also, it's all inside a function and jQuery has been specified already, that's why you see me using .css without $ sign

Any help appreciated

答:
This loops through your array and updates each of the jQuery elements.</p>

```<code>if (something) {
    for (var i = 0; i < myArray.length; i++) {
        myArray[i].css("background-image", "url(pictures/img.png)");
    }
}
</code>```

Body:
There is an array which will increase and decrease in size and I was trying to implement something that will allow the code to go through each value in the array and perform the following code: (set the same image for each value)

if (something) {
myArray[0].css("background-image", "url(pictures/img.png)")
myArray[1].css("background-image", "url(pictures/img.png)")
}

The code above works however, it only works for the first two values, what if there is more? or less?

I was thinking of implementing forEach method so it could actually replace the image within every value, however it is not a variable as it modifies the CSS file and I am slightly confused how I could do that since I couldn't find relevant example, so here's the code I thought it might work but it doesn't

if (something) {
    myArray.forEach(value) {
    myArray.css("background-image", "url(pictures/img.png)")
    }
}

Also, it's all inside a function and jQuery has been specified already, that's why you see me using .css without $ sign

Any help appreciated

Body:
This loops through your array and updates each of the jQuery elements.

if (something) {
    for (var i = 0; i < myArray.length; i++) {
        myArray[i].css("background-image", "url(pictures/img.png)");
    }
}