问:
Javascript querystring code issue
I am writing some javascript (not jquery, just plain javascript) to manipulate querystrings.

I currently have the following:

```<code>// no viewid in querystring so append as new
if (newUrl.indexOf("viewid") == -1) {
    newUrl += "?viewid=" + viewId;
}
else if (newUrl.indexOf("viewid") > -1) // there is a view id or another key e.g. there is a linkid
{
    newUrl = newUrl.replace(/viewid=\d*/i, "viewid=" + viewId);
}
</code>```

So it appends viewid as a new querystring key otherwise it appends it (&).

What I need to do is check if a querystring value (any, e.g. "blah") is in the URL, and if so, append with &viewid=(number).

If the selection in the dropdown (which calls this javascript) changes, then change the viewid (but don't append a new viewid).

答:
You could use this nifty little package called Query String Manager
and you use it like this:

```<code>var qsm = require('qsm');
newUrl = qsm.add(newUrl, { viewId: 1 });
</code>```

and this will create your viewId=1 if there is not other querystring or append it if there are other querystrings.

Title: Javascript querystring code issue

Body:
I am writing some javascript (not jquery, just plain javascript) to manipulate querystrings.

I currently have the following:

// no viewid in querystring so append as new
if (newUrl.indexOf("viewid") == -1) {
    newUrl += "?viewid=" + viewId;
}
else if (newUrl.indexOf("viewid") > -1) // there is a view id or another key e.g. there is a linkid
{
    newUrl = newUrl.replace(/viewid=\d*/i, "viewid=" + viewId);
}

So it appends viewid as a new querystring key otherwise it appends it (&).

What I need to do is check if a querystring value (any, e.g. "blah") is in the URL, and if so, append with &viewid=(number).

If the selection in the dropdown (which calls this javascript) changes, then change the viewid (but don't append a new viewid).

Body:
You could use this nifty little package called Query String Manager
and you use it like this:

var qsm = require('qsm');
newUrl = qsm.add(newUrl, { viewId: 1 });

and this will create your viewId=1 if there is not other querystring or append it if there are other querystrings.


来源: stackexchange

问:
Need to duplicate the same element in the DOM 4 times using Jquery
Im using jquery to insert html in the dom. Everything is working fine, now i need to duplicate an element 4 times, and i don't know how.

this is how i use Jquery to insert the element into the DOM.

```<code>function Pin(caixaPin){
 var $temp;
  $temp = $("<div></div>");
  $temp.addClass("caixaPin");
  $temp.html(caixaPin);
  $("body").append($temp);
}

Pin('<div></div>');
</code>```

Thanks !!

答:
You can use a for loop to create X amount of Y, like this:

```<code>for (var j = 0; j <= 3; j++)
{
    $('body').append('<div class="caixaPin"></div>')
}
</code>```

what this does is define j as 0, when it gets to 3 and including 3, append

 to the body. Hope this helps

ContentLicense: CC BY-SA 3.0

Body:
Im using jquery to insert html in the dom. Everything is working fine, now i need to duplicate an element 4 times, and i don't know how.

this is how i use Jquery to insert the element into the DOM.

function Pin(caixaPin){
 var $temp;
  $temp = $("

");
  $temp.addClass("caixaPin");
  $temp.html(caixaPin);
  $("body").append($temp);
}

Pin('

');

Thanks !!

Body:
You can use a for loop to create X amount of Y, like this:

for (var j = 0; j <= 3; j++)
{
    $('body').append('<div class="caixaPin"></div>')
}

what this does is define j as 0, when it gets to 3 and including 3, append <div></div> to the body. Hope this helps


问:
Processing python dictionary
I have a variable message is of type dict

```<code>>>> print(message)
{TopicPartition(topic='testing_topic', partition=1): [ConsumerRecord(topic='testing_topic', partition=1, offset=0, timestamp=1499411365748, timestamp_type=0, key=None, value=b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}', checksum=-309359221, serialized_key_size=-1, serialized_value_size=158)]}
</code>```

How to fetch value portion from it.
I tried a lot but I am unable to do it. Please suggest.

I want this.

```<code>value=b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}'
</code>```

答:
this is called named tuple

```<code>for i in message.values():
...     for j in i:
...       print(j.value)
</code>```

full code for some other user want to know

```<code>from collections import namedtuple

R = namedtuple('TopicPartition','topic partition')
index = R(topic='testing_topic', partition=1)

V = namedtuple('ConsumerRecord','topic partition offset timestamp timestamp_
type key value checksum serialized_key_size serialized_value_size')

content = V(topic='testing_topic', partition=1, offset=0, timestamp=14994113
65748, timestamp_type=0, key=None, value=b'{"url":"http://review.travel.rakuten.
co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id"
:"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}', checksum=-309359221, serialized_key_
size=-1, serialized_value_size=158)

D = {index:[content]}

for i in D.values():
...     for j in i:
...       print(j.value)

b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_
cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}
</code>```

Title: Processing python dictionary

Body:
I have a variable message is of type dict

>>> print(message)
{TopicPartition(topic='testing_topic', partition=1): [ConsumerRecord(topic='testing_topic', partition=1, offset=0, timestamp=1499411365748, timestamp_type=0, key=None, value=b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}', checksum=-309359221, serialized_key_size=-1, serialized_value_size=158)]}

How to fetch value portion from it.
I tried a lot but I am unable to do it. Please suggest.

I want this.

value=b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}'

Body:
this is called named tuple

for i in message.values():
...     for j in i:
...       print(j.value)

full code for some other user want to know

from collections import namedtuple

R = namedtuple('TopicPartition','topic partition')
index = R(topic='testing_topic', partition=1)

V = namedtuple('ConsumerRecord','topic partition offset timestamp timestamp_
type key value checksum serialized_key_size serialized_value_size')

content = V(topic='testing_topic', partition=1, offset=0, timestamp=14994113
65748, timestamp_type=0, key=None, value=b'{"url":"http://review.travel.rakuten.
co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id"
:"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}', checksum=-309359221, serialized_key_
size=-1, serialized_value_size=158)

D = {index:[content]}

for i in D.values():
...     for j in i:
...       print(j.value)

b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_
cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}


问:
How to set build path configuration in spring boot webapp
I am in new to spring boot. I have created a web app using spring boot. My application require some properties file to do the processing. In eclipse What I do i set the path on Run configuration like bellow.

  Now When I run the application I gets the require file on path and run smoothly.
Now I want to deploy the war file on some server. How do i provide this path to my application.

Bellow is the project structure of my project. and files are here
highlighted

How do I set this file path using application.properties or any other way so that, I don't have to provide the path from run configuration, and the .war can be deploy on any server.

Update 1 : This what I tried.
Created a customStart.bat
content of the file is

```<code>set CATALINA_OPTS="-engine.home="/src/main/resources/" -Dlog4j.configuration=config/log4j.xml -Dlog4j.debug=true"
call startup.bat %CATALINA_OPTS%
</code>```

But still that argument is not set. How do I do that?

答:
From spring boot official documentation (This is a highlight of the concept of creating custom spring boot variable) bellow you'll find a link to a Q/A that describes the solution.

Spring Boot jars are shipped with meta-data files that provide details
  of all supported configuration properties. The files are designed to
  allow IDE developers to offer contextual help and “code completion” as
  users are working with application.properties or application.yml
  files.

The majority of the meta-data file is generated automatically at
  compile time by processing all items annotated with
  @ConfigurationProperties. However, it is possible to write part of the
  meta-data manually for corner cases or more advanced use cases.

Configuration meta-data files are located inside jars under
  META-INF/spring-configuration-metadata.json They use a simple JSON
  format with items categorized under either “groups” or “properties”
  and additional values hint categorized under "hints":

Here is an example of a meta data config file :

```<code>{"groups": [
    {
        "name": "server",
        "type": "org.springframework.boot.autoconfigure.web.ServerProperties",
        "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
    },
    {
        "name": "spring.jpa.hibernate",
        "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
        "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
        "sourceMethod": "getHibernate()"
    }
    ...
],"properties": [
    {
        "name": "server.port",
        "type": "java.lang.Integer",
        "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
    },
    {
          "name": "spring.jpa.hibernate.ddl-auto",
          "type": "java.lang.String",
          "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.",
          "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
    }
    ...
],"hints": [
    {
        "name": "spring.jpa.hibernate.ddl-auto",
        "values": [
            {
                "value": "none",
                "description": "Disable DDL handling."
            },
            {
                "value": "validate",
                "description": "Validate the schema, make no changes to the database."
            },
            {
                "value": "update",
                "description": "Update the schema if necessary."
            },
            {
                "value": "create",
                "description": "Create the schema and destroy previous data."
            },
            {
                "value": "create-drop",
                "description": "Create and then destroy the schema at the end of the session."
            }
        ]
    }
]}
</code>```

Each “property” is a configuration item that the user specifies with a
  given value. For example server.port and server.servlet-path might be
  specified in application.properties as follows:

server.port=9090 server.servlet-path=/home The “groups” are higher
  level items that don’t themselves specify a value, but instead provide
  a contextual grouping for properties. For example the server.port and
  server.servlet-path properties are part of the server group.

Notes:

The groups section is note required

“hints” are additional information used to assist the user in configuring a given property. When configuring the spring.jpa.hibernate.ddl-auto property, a tool can use it to offer some auto-completion help for the none, validate, update, create and create-drop values.

You can easily generate your own configuration meta-data file from
  items annotated with @ConfigurationProperties by using the
  spring-boot-configuration-processor jar

You can check this Q/A

** for more details check the spring boot apendix section **

Body:
I am in new to spring boot. I have created a web app using spring boot. My application require some properties file to do the processing. In eclipse What I do i set the path on Run configuration like bellow.

  Now When I run the application I gets the require file on path and run smoothly.
Now I want to deploy the war file on some server. How do i provide this path to my application.

Bellow is the project structure of my project. and files are here
highlighted

How do I set this file path using application.properties or any other way so that, I don't have to provide the path from run configuration, and the .war can be deploy on any server.

Update 1 : This what I tried.
Created a customStart.bat
content of the file is

set CATALINA_OPTS="-engine.home="/src/main/resources/" -Dlog4j.configuration=config/log4j.xml -Dlog4j.debug=true"
call startup.bat %CATALINA_OPTS%

But still that argument is not set. How do I do that?

Body:
From spring boot official documentation (This is a highlight of the concept of creating custom spring boot variable) bellow you'll find a link to a Q/A that describes the solution.

Spring Boot jars are shipped with meta-data files that provide details
  of all supported configuration properties. The files are designed to
  allow IDE developers to offer contextual help and “code completion” as
  users are working with application.properties or application.yml
  files.

The majority of the meta-data file is generated automatically at
  compile time by processing all items annotated with
  @ConfigurationProperties. However, it is possible to write part of the
  meta-data manually for corner cases or more advanced use cases.

Configuration meta-data files are located inside jars under
  META-INF/spring-configuration-metadata.json They use a simple JSON
  format with items categorized under either “groups” or “properties”
  and additional values hint categorized under "hints":

Here is an example of a meta data config file :

{"groups": [
    {
        "name": "server",
        "type": "org.springframework.boot.autoconfigure.web.ServerProperties",
        "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
    },
    {
        "name": "spring.jpa.hibernate",
        "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
        "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
        "sourceMethod": "getHibernate()"
    }
    ...
],"properties": [
    {
        "name": "server.port",
        "type": "java.lang.Integer",
        "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
    },
    {
          "name": "spring.jpa.hibernate.ddl-auto",
          "type": "java.lang.String",
          "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.",
          "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
    }
    ...
],"hints": [
    {
        "name": "spring.jpa.hibernate.ddl-auto",
        "values": [
            {
                "value": "none",
                "description": "Disable DDL handling."
            },
            {
                "value": "validate",
                "description": "Validate the schema, make no changes to the database."
            },
            {
                "value": "update",
                "description": "Update the schema if necessary."
            },
            {
                "value": "create",
                "description": "Create the schema and destroy previous data."
            },
            {
                "value": "create-drop",
                "description": "Create and then destroy the schema at the end of the session."
            }
        ]
    }
]}

Each “property” is a configuration item that the user specifies with a
  given value. For example server.port and server.servlet-path might be
  specified in application.properties as follows:

server.port=9090 server.servlet-path=/home The “groups” are higher
  level items that don’t themselves specify a value, but instead provide
  a contextual grouping for properties. For example the server.port and
  server.servlet-path properties are part of the server group.

Notes:

The groups section is note required

“hints” are additional information used to assist the user in configuring a given property. When configuring the spring.jpa.hibernate.ddl-auto property, a tool can use it to offer some auto-completion help for the none, validate, update, create and create-drop values.

You can easily generate your own configuration meta-data file from
  items annotated with @ConfigurationProperties by using the
  spring-boot-configuration-processor jar

You can check this Q/A

** for more details check the spring boot apendix section **


问:
What method is the best to copy files from one server to another using PHP
I need to copy a couple of files over from one server to another using PHP. Now I currently use PHP FTP functionality which is ok but causes issues. Are there better ways to accomplish this?</p>

答: FTP is a good way to do this. It handles the authentication, and there are native PHP functions to use with FTP.</p>

ContentLicense: CC BY-SA 2.5


问:
snippets in vs code version 1.13
In 1.13 (and up) version of vscode update there is some problem or change about the behavior of the snippets in vs code that i don't like.

Whenever you  used a snippet in vs code you would could keep press tab
and vs code would loop over $1 $2 placeholders ... and would never get to the $0 last cursor placeholder.

Now in version 1.13 they have changed something and the $0 is in the last tab hit according to the number of placeholders.

I think it is because thay have added multi-cursor-snippets or strict-snippets
https://code.visualstudio.com/updates/v1_13#_strict-snippets

Example of how it was before

So my question is do somebody knows how to change it back or it is on purpose?

答: This is by design. If you feel the snippet behavior could be improved, please file an issue.</p>

Title: snippets in vs code version 1.13


问:
How to expand to specific TreeNode in JTree
I have a JTree, and I have a node in the JTree, but the node is in like 5 to 6 levels deep. And I have a path for the node. I want to expand the JTree to show the node. Therefore I tried myJTree.expandPath(myJTree.getPath(myNode)); but it didn't work, it only expanded the first level of myJTree. What can I do? I have verified the path is valid.

I have the path to the node, and I tried to expand using myJTree.expandPath(myJTree.getPath(myNode)) but it doesn't actually work.

```<code>private TreePath getPath(TreeNode treeNode) {
    List<Object> nodes = new ArrayList<Object>();
    if (treeNode != null) {
        nodes.add(treeNode);
        treeNode = treeNode.getParent();
        while (treeNode != null) {
            nodes.add(0, treeNode);
            treeNode = treeNode.getParent();
        }
    }
    return nodes.isEmpty() ? null : new TreePath(nodes.toArray());
}
</code>```

答:
What you need is:</p>

```<code>myJTree.expandPath(new TreePath(myNode.getPath()));
</code>```

Body:
I have a JTree, and I have a node in the JTree, but the node is in like 5 to 6 levels deep. And I have a path for the node. I want to expand the JTree to show the node. Therefore I tried myJTree.expandPath(myJTree.getPath(myNode)); but it didn't work, it only expanded the first level of myJTree. What can I do? I have verified the path is valid.

I have the path to the node, and I tried to expand using myJTree.expandPath(myJTree.getPath(myNode)) but it doesn't actually work.

private TreePath getPath(TreeNode treeNode) {
    List<Object> nodes = new ArrayList<Object>();
    if (treeNode != null) {
        nodes.add(treeNode);
        treeNode = treeNode.getParent();
        while (treeNode != null) {
            nodes.add(0, treeNode);
            treeNode = treeNode.getParent();
        }
    }
    return nodes.isEmpty() ? null : new TreePath(nodes.toArray());
}

Body:
What you need is:

myJTree.expandPath(new TreePath(myNode.getPath()));


问:
How to show legends on chart using c3 js with json
I'm using C3 chart to present some data on my project and I want to show up legends (Label in my case) instead of numbers in the AcisX :

Data json format :

```<code>[
    {"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32},
    {"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144},
    {"Label":"DMAI","Aut":1.6999999999999993,"NoAut":0,"CM":0},
    {"Label":"DENG","Aut":0,"NoAut":0,"CM":16}
]
</code>```

My attempt to get the task work :

```<code>       var chart = c3.generate({
         bindto: '.ks-chart-orders-block',
         data: {
          url:  '/Home/AbsencesByDepartementFiltredByReasons',
          mimeType: 'json',
          type:'bar',
          keys:{
            value: ['Aut','NoAut','CM']
          },
         }
       }
     });
</code>```

Getted Result :

Expected Result:

答:
You need to modify the x-axis with a custom category:</p>

```<code>var chart = c3.generate({
     bindto: '.ks-chart-orders-block',

     data: {
      url:  '/Home/AbsencesByDepartementFiltredByReasons',
      mimeType: 'json',
      type:'bar',
      keys:{
        x: 'Label',
        value: ['Aut','NoAut','CM']
      },
     },

     axis: {
       x: {
         type: 'category',
         tick: {
           centered: true
         }
       }
     }
 });
</code>```

Body:
I'm using C3 chart to present some data on my project and I want to show up legends (Label in my case) instead of numbers in the AcisX :

Data json format :

[
    {"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32},
    {"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144},
    {"Label":"DMAI","Aut":1.6999999999999993,"NoAut":0,"CM":0},
    {"Label":"DENG","Aut":0,"NoAut":0,"CM":16}
]

My attempt to get the task work :

       var chart = c3.generate({
         bindto: '.ks-chart-orders-block',
         data: {
          url:  '/Home/AbsencesByDepartementFiltredByReasons',
          mimeType: 'json',
          type:'bar',
          keys:{
            value: ['Aut','NoAut','CM']
          },
         }
       }
     });

Getted Result :

Expected Result:

Body:
You need to modify the x-axis with a custom category:

var chart = c3.generate({
     bindto: '.ks-chart-orders-block',

     data: {
      url:  '/Home/AbsencesByDepartementFiltredByReasons',
      mimeType: 'json',
      type:'bar',
      keys:{
        x: 'Label',
        value: ['Aut','NoAut','CM']
      },
     },

     axis: {
       x: {
         type: 'category',
         tick: {
           centered: true
         }
       }
     }
 });


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
When you write

int *q = 8; it means you declared a pointer q and initialized a pointer with the integer 8. but q being a pointer expects a address value therefore you get error stating incompatibility.

Whereas when you write

*q=8 after declaring, it means you are dereferencing the addresses pointed by q and writing a value to that location. here q points to a int so you are writing 8 a integer value to the location pointed by q. that is right. This can also lead to error at runtime if q is not initialized to point to right location.


问:
MemberInfo.GetCustomAttributes extensions overload
I noticed there are two methods (one class method and one extension method) with the same signature but different return types in package System.Reflection for class MemberInfo:

Class method:

```<code>public abstract object[] GetCustomAttributes(Type attributeType, bool inherit)
</code>```

Extension method (inside CustomAttributeExtensions):

```<code>public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)
</code>```

I know that calling that method with such parameters will always invoke class method, so I am just wondering:

how to call extension method?

and, above all, what's the purpose of defining an extension with same signature as class method?

答:
Having this kind of duplication in a framework is not exactly a feature.  But this was a rock and a hard place, they had to add the extension method in .NET 4.5.  Most readily visible from the bottom of the MSDN articles in the Version Information block.  The extension method is usable in UWP and Phone projects, the legacy method is not.

Underlying reason is the language projection built into the CLR at 4.5.  It makes the rather big difference between WinRT and CLR types highly invisible.  WinRT would be still-born, more than it already was, if programmers had any inkling that it is actually COM under the hood that powers UWP :)  Very well hidden, but the Type class was too heavily married to the CLR, they had to provide the TypeInfo class as an alternative.  And extension methods to bridge the api gap.

If you don't target UWP then you don't have much use for the extension method and should favor the legacy method.  The extension method is about 30% slower.

Body:
I noticed there are two methods (one class method and one extension method) with the same signature but different return types in package System.Reflection for class MemberInfo:

Class method:

public abstract object[] GetCustomAttributes(Type attributeType, bool inherit)

Extension method (inside CustomAttributeExtensions):

public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)

I know that calling that method with such parameters will always invoke class method, so I am just wondering:

how to call extension method?

and, above all, what's the purpose of defining an extension with same signature as class method?


问:
Static Initialization in Java?
I was trying to execute the following code:

```<code>public class StaticTest {

    private static List<String> dat1;
    {
        dat1 = new ArrayList<>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }

    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}
</code>```

I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.

Why am I getting the exception in first case and not in second ?

When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.

答:
Hi @kajal please refer to the correct code below:-

```<code> public class StaticTest {

    private static List<String> dat1;
    static
    {
        dat1 = new ArrayList<String>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }
    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}
</code>```

Instance block is executes when you create a instance of that class.
Question why you are getting the NullPointerException :-
Please find the below flow of the StaticTest class execution :-

First all the import class will load like :-

Object class 2.java.lang Package Class 3.java.util.ArrayList Class.

The compiler goes through the StaticTest Class and allocate the Memory for the all the Static Members in your case it is dat1.

Now the javac compiler searches for the Static block for the execution. in your case their is no Static block.

Now the compiler executes the main method and executes the System.out.println(dat1.contains("a")); is called as null.contains("a"); which trhows the execption but as i said the Instance block is executes when you create a instance of that class. so dat1 is initialized when you create object new StaticTest();

ContentLicense: CC BY-SA 4.0

Title: Static Initialization in Java?

Body:
I was trying to execute the following code:

public class StaticTest {

    private static List<String> dat1;
    {
        dat1 = new ArrayList<>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }

    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}

I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.

Why am I getting the exception in first case and not in second ?

When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.

Body:
Hi @kajal please refer to the correct code below:-

 public class StaticTest {

    private static List<String> dat1;
    static
    {
        dat1 = new ArrayList<String>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }
    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}

Instance block is executes when you create a instance of that class.
Question why you are getting the NullPointerException :-
Please find the below flow of the StaticTest class execution :-

First all the import class will load like :-

Object class 2.java.lang Package Class 3.java.util.ArrayList Class.

The compiler goes through the StaticTest Class and allocate the Memory for the all the Static Members in your case it is dat1.

Now the javac compiler searches for the Static block for the execution. in your case their is no Static block.

Now the compiler executes the main method and executes the System.out.println(dat1.contains("a")); is called as null.contains("a"); which trhows the execption but as i said the Instance block is executes when you create a instance of that class. so dat1 is initialized when you create object new StaticTest();


问:
How to check pushed and popped counts for a redis-queue using reis-cli
I am using redis to send and receive data between different application. However, I found when an application push thousands of data to a queue, the other application implementing pop has incomplete data!

To identify the problem - I added counters at push and pop and found that pop counter to be less than pushed also I don't see any pending message in the same queue when pop has finished executing.

I am trying to dig where is the data getting lost. What are the ways I should try? Is there any command in redis-cli which can show the pushed and pop count for a given queue

答: You can use MONITOR command from redis-cli. Pipe the output to a file and then you should be quite easily to see how many hand landed in Redis. Another advice is use sequential numbers to debug your problem it's easier to see which one is missing. </p>


问:
Pandas transform with sum takes too long
I have a pandas dataframe which has the following columns of integer values:

```<code>user_id, user_agent_id, appearances
</code>```

Number of rows vary but they are more than 4 hundred thousand. I want to create a new row total appearances which is the sum of all appearances for each user. So I do the following:

```<code>dataframe['total_appearances'] = dataframe['appearances'].groupby(dataframe['user_id']).transform('sum')
</code>```

I need that because I want to calculate percentage per of user_agent_id per user that is

```<code>dataframe['percent'] = dataframe['appearances'] / dataframe['total_appearances']
</code>```

I do the same thing to calculate max value of percent

```<code>dataframe['max_percent'] = dataframe['percent'].groupby(dataframe['user_id']).transform('max')
</code>```

etc.

The thing is while the max method in the transform method takes about 5m the sum method takes far to longer that is 2sec. Is this natural? Is there a faster way to obtain the information of the total_appearances?

答:
If I'm understanding the question correctly, you could consolidate the first two lines into one step with something like this:

```<code># sample data
df
   appearances user_id
0            6     abc
1            3     abc
2            5     abc
3            8     def
4            4     gfd
5            2     uio
6            1     def
7            8     poi
8            3     fab

df['percent'] = df.groupby('user_id').appearances.apply(lambda x: x.div(np.sum(x)))

df
   appearances user_id   percent
0            6     abc  0.428571
1            3     abc  0.214286
2            5     abc  0.357143
3            8     def  0.888889
4            4     gfd  1.000000
5            2     uio  1.000000
6            1     def  0.111111
7            8     poi  1.000000
8            3     fab  1.000000
</code>```

Do you see a performance improvement with these changes?

Body:
I have a pandas dataframe which has the following columns of integer values:

user_id, user_agent_id, appearances

Number of rows vary but they are more than 4 hundred thousand. I want to create a new row total appearances which is the sum of all appearances for each user. So I do the following:

dataframe['total_appearances'] = dataframe['appearances'].groupby(dataframe['user_id']).transform('sum')

I need that because I want to calculate percentage per of user_agent_id per user that is

dataframe['percent'] = dataframe['appearances'] / dataframe['total_appearances']

I do the same thing to calculate max value of percent

dataframe['max_percent'] = dataframe['percent'].groupby(dataframe['user_id']).transform('max')

etc.

The thing is while the max method in the transform method takes about 5m the sum method takes far to longer that is 2sec. Is this natural? Is there a faster way to obtain the information of the total_appearances?

Body:
If I'm understanding the question correctly, you could consolidate the first two lines into one step with something like this:

# sample data
df
   appearances user_id
0            6     abc
1            3     abc
2            5     abc
3            8     def
4            4     gfd
5            2     uio
6            1     def
7            8     poi
8            3     fab

df['percent'] = df.groupby('user_id').appearances.apply(lambda x: x.div(np.sum(x)))

df
   appearances user_id   percent
0            6     abc  0.428571
1            3     abc  0.214286
2            5     abc  0.357143
3            8     def  0.888889
4            4     gfd  1.000000
5            2     uio  1.000000
6            1     def  0.111111
7            8     poi  1.000000
8            3     fab  1.000000

Do you see a performance improvement with these changes?


问:
"Cannot convert to IComparer"
I have the following IComparer defined for boxed RegistryItem objects:

```<code>public class BoxedRegistryItemComparer : IComparer<object>
{
    public int Compare(object left, object right)
    {
        RegistryItem leftReg = (RegistryItem)left;
        RegistryItem rightReg = (RegistryItem)right;

        return string.Compare(leftReg.Name, rightReg.Name);
    }
}
</code>```

I want to use this to sort an ArrayList of boxed RegistryItems (It really should be a List<RegistryItem>, but that's out of my control).

```<code>ArrayList regItems = new ArrayList();
// fill up the list ...
BoxedRegistryItemComparer comparer = new BoxedRegistryItemComparer();
ArrayList.sort(comparer);
</code>```

However, the last line gives the compiler error:  "Cannot convert from BoxedRegistryItemComparer to System.Collections.IComparer".  I would appreciate it if someone could point out my mistake.

答:
In case you have a situation where you don't have any control over the Comparer or the Sorter, here are two mini-classes which can convert between the two types (untested):</p>

```<code>private class GenericComparer<T> : IComparer<T>
{
    IComparer _Comparer;
    public GenericComparer(IComparer comparer)
    {
        _Comparer = comparer;
    }
    public int Compare(T a, T b)
    {
        return _Comparer.Compare(a, b);
    }
}

private class NonGenericComparer<T> : IComparer
{
    IComparer<T> _Comparer;
    public NonGenericComparer(IComparer<T> comparer)
    {
        _Comparer = comparer;
    }
    public int Compare(object a, object b)
    {
        return _Comparer.Compare((T)a, (T)b);
    }
}
</code>```

Title: "Cannot convert to IComparer"

Body:
I have the following IComparer defined for boxed RegistryItem objects:

public class BoxedRegistryItemComparer : IComparer<object>
{
    public int Compare(object left, object right)
    {
        RegistryItem leftReg = (RegistryItem)left;
        RegistryItem rightReg = (RegistryItem)right;

        return string.Compare(leftReg.Name, rightReg.Name);
    }
}

I want to use this to sort an ArrayList of boxed RegistryItems (It really should be a List<RegistryItem>, but that's out of my control).

ArrayList regItems = new ArrayList();
// fill up the list ...
BoxedRegistryItemComparer comparer = new BoxedRegistryItemComparer();
ArrayList.sort(comparer);

However, the last line gives the compiler error:  "Cannot convert from BoxedRegistryItemComparer to System.Collections.IComparer".  I would appreciate it if someone could point out my mistake.

Body:
In case you have a situation where you don't have any control over the Comparer or the Sorter, here are two mini-classes which can convert between the two types (untested):

private class GenericComparer<T> : IComparer<T>
{
    IComparer _Comparer;
    public GenericComparer(IComparer comparer)
    {
        _Comparer = comparer;
    }
    public int Compare(T a, T b)
    {
        return _Comparer.Compare(a, b);
    }
}

private class NonGenericComparer<T> : IComparer
{
    IComparer<T> _Comparer;
    public NonGenericComparer(IComparer<T> comparer)
    {
        _Comparer = comparer;
    }
    public int Compare(object a, object b)
    {
        return _Comparer.Compare((T)a, (T)b);
    }
}


问:
Python phantomjs loading webpage not correct
I have an issue where extracting from this link

http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=FA&sub_category=FA1&alphabetical=All&company=5250

brings me data from this link instead which is the main page itself.
http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=all

Any idea why is this occuring ?
I am using PhantomJS selenium and beautiful soup to assit me in this.

```<code># The standard library modules
import os
import sys
import re
import sqlite3
import locale
# The wget module
import wget
import time
import calendar
from datetime import datetime
# The BeautifulSoup module
from bs4 import BeautifulSoup

# The selenium module
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def getURLS(url):
    driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
    driver.get(url) # load the web page
    src = driver.page_source
    #Get text and split it
    soup = BeautifulSoup(src, 'html5lib')

    print soup

link ='http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=FA&sub_category=FA1&alphabetical=All&company=5250'
getURLS(link)
</code>```

Solution from Alex Lucaci

```<code>def getURLS(url):
    driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
    driver.get(url) # load the web page
    src = driver.page_source
    category_select = Select(driver.find_element_by_xpath('//*[@id="bm_announcement_types"]'))
    category_select.select_by_visible_text("Financial Results")
    category_select2 = Select(driver.find_element_by_xpath('//*[@id="bm_sub_announcement_types"]'))
    category_select2.select_by_visible_text("Financial Results")
    category_select3 = Select(driver.find_element_by_xpath('//*[@id="bm_company_list"]'))
    category_select3.select_by_visible_text("7-ELEVEN MALAYSIA HOLDINGS BERHAD (5250)")
    driver.find_element_by_xpath('//*[@id="bm_company_announcements_search_form"]/input[1]').click()
    src = driver.page_source
    soup = BeautifulSoup(src, 'html5lib')
    link="http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=all"
    getURLS(link)
</code>```

答:
When you are saving the source the page is not completely loaded with your submitted post so try to wait for a couple of second before fetching the page source:

```<code>def getURLS(url):
driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
driver.get(url) # load the web page
time.sleep(5)# waiting for 5 seconds before fetching the source
src = driver.page_source
#Get text and split it
soup = BeautifulSoup(src, 'html5lib')

print soup
</code>```

To perform dropdown select you have import the Select class as follow : from selenium.webdriver.support.ui import Select and then you have to select the dropdown element like that:

```<code>category_select = Select(driver.find_element_by_xpath('//*[@id="bm_announcement_types"]'))
category_select.select_by_visible_text('Financial Results')
</code>```

In my example I've done it for the -Category- dropdown, follow the exact steps for every category.
Note that selecting the dropdown by xpath is the best way and you can achieve this by using Google Chrome -> righ click on the element -> Inspect-> right click on the <select> in the right menu that appeared -> Copy -> Copy Xpath

When you`ve selected all the element you have to click the Submit and wait for a couple of seconds to load and after that you will fetch the source code.

Let me know if my answer helped you.

Body:
I have an issue where extracting from this link

http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=FA&sub_category=FA1&alphabetical=All&company=5250

brings me data from this link instead which is the main page itself.
http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=all

Any idea why is this occuring ?
I am using PhantomJS selenium and beautiful soup to assit me in this.

# The standard library modules
import os
import sys
import re
import sqlite3
import locale
# The wget module
import wget
import time
import calendar
from datetime import datetime
# The BeautifulSoup module
from bs4 import BeautifulSoup

# The selenium module
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def getURLS(url):
    driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
    driver.get(url) # load the web page
    src = driver.page_source
    #Get text and split it
    soup = BeautifulSoup(src, 'html5lib')

    print soup

link ='http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=FA&sub_category=FA1&alphabetical=All&company=5250'
getURLS(link)

Solution from Alex Lucaci

def getURLS(url):
    driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
    driver.get(url) # load the web page
    src = driver.page_source
    category_select = Select(driver.find_element_by_xpath('//*[@id="bm_announcement_types"]'))
    category_select.select_by_visible_text("Financial Results")
    category_select2 = Select(driver.find_element_by_xpath('//*[@id="bm_sub_announcement_types"]'))
    category_select2.select_by_visible_text("Financial Results")
    category_select3 = Select(driver.find_element_by_xpath('//*[@id="bm_company_list"]'))
    category_select3.select_by_visible_text("7-ELEVEN MALAYSIA HOLDINGS BERHAD (5250)")
    driver.find_element_by_xpath('//*[@id="bm_company_announcements_search_form"]/input[1]').click()
    src = driver.page_source
    soup = BeautifulSoup(src, 'html5lib')
    link="http://www.bursamalaysia.com/market/listed-companies/company-announcements/#/?category=all"
    getURLS(link)

Body:
When you are saving the source the page is not completely loaded with your submitted post so try to wait for a couple of second before fetching the page source:

def getURLS(url):
driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
driver.get(url) # load the web page
time.sleep(5)# waiting for 5 seconds before fetching the source
src = driver.page_source
#Get text and split it
soup = BeautifulSoup(src, 'html5lib')

print soup

To perform dropdown select you have import the Select class as follow : from selenium.webdriver.support.ui import Select and then you have to select the dropdown element like that:

category_select = Select(driver.find_element_by_xpath('//*[@id="bm_announcement_types"]'))
category_select.select_by_visible_text('Financial Results')

In my example I've done it for the -Category- dropdown, follow the exact steps for every category.
Note that selecting the dropdown by xpath is the best way and you can achieve this by using Google Chrome -> righ click on the element -> Inspect-> right click on the <select> in the right menu that appeared -> Copy -> Copy Xpath

When you`ve selected all the element you have to click the Submit and wait for a couple of seconds to load and after that you will fetch the source code.

Let me know if my answer helped you.


问:
Hackerearth || rhinoJS || Array Input
How read array input in hackerearth or techgig rhinojs editor?
Please help me to read array of inputs in rhinojs. </p>

答:
you didn't mention which programming language you are using.In python programming language it is very easy to get the array input

CODE:

```<code>p=list(map(int,input().split()))
</code>```

Title: Hackerearth || rhinoJS || Array Input

Body:
you didn't mention which programming language you are using.In python programming language it is very easy to get the array input

CODE:

p=list(map(int,input().split()))


问:
Get Active QM Instance from Multi Instance Queue Manager and connect
I have trouble defining multiple hostname for multi-instance queue manager as I am changing a single instance of queue manager to multi-instance queue manager.
The existing host is defined in web.config

```<code><QueueConfigurationSection>
    <QueueConfiguration>
        <add name="SomeQueueHandler" queueManager="QM1" host="99.99.99.01" port="12345" requestQueue="A.B.REQUEST" service="FLATFILE" responseQueue="B.A.RESPONSE" internalResponseQueue="B.A.INTERNAL" channel="A.SVC.SVRCONN" binding="SOAP11TcpBinding" endPoint="net.tcp://localhost:808/Bus/SomeServiceBus.svc/SOAP11" />
    </QueueConfiguration>
  </QueueConfigurationSection>
</code>```

connection is defined in here

```<code>public List<QueueHandler> Queues
{
    get
    {
        if (_queues == null)
            _queues = new List<QueueHandler>();
        if (_queues.Count == 0 && _queueConfiguration != null)
        {
            //create queue handlers from configuration provided
            foreach (QueueConfigurationElement element in _queueConfiguration)
            {
                // Using a different connection factory for each queue
                XMSFactoryFactory factory = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
                IConnectionFactory connectionProperties = factory.CreateConnectionFactory();
                connectionProperties.SetStringProperty(XMSC.WMQ_HOST_NAME, element.Host);
                connectionProperties.SetIntProperty(XMSC.WMQ_PORT, element.Port);
                connectionProperties.SetStringProperty(XMSC.WMQ_CHANNEL, element.Channel);
                connectionProperties.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
                connectionProperties.SetIntProperty(XMSC.WMQ_BROKER_VERSION, XMSC.WMQ_BROKER_V1);
                connectionProperties.SetBooleanProperty(XMSC.WMQ_USE_CONNECTION_POOLING, true);

                var queue = new QueueHandler(element.Name, connectionProperties);
                _queues.Add(queue);
            }
        }
        return new List<QueueHandler>(_queues);
    }
}
</code>```

QueueHandler:

```<code>public QueueHandler(string handlerName, IConnectionFactory mqConnectionFactory)
{
    _connectionProperties = mqConnectionFactory;
    var queueConfigurationSection = ConfigurationManager.GetSection(QueueConfigurationSection.SectionName) as QueueConfigurationSection;
    if (queueConfigurationSection != null)
    {
        if (queueConfigurationSection.QueueConfigurationCollection.Cast<QueueConfigurationElement>().Any(qc => qc.Name == handlerName))
        {
            var element = queueConfigurationSection.QueueConfigurationCollection.Cast<QueueConfigurationElement>().First(qc => qc.Name == handlerName);

            _name = element.Name;
            _serviceType = element.DestinationService;
            _queueManagerName = element.QueueManager;
            _channel = element.Channel;
            _requestQueueName = element.RequestQueue;
            _responseQueueName = element.ResponseQueue;
            _internalResponseQueueName = element.InternalResponseQueue;
            _port = element.Port;
            _host = element.Host;

            //set up binding configuraion
            EndpointType bindingEnum;
            if (System.Enum.TryParse(element.Binding, out bindingEnum))
            {
                _messageType = bindingEnum;

                switch (bindingEnum)
                {
                    case EndpointType.FlatFileTcpBinding:
                        //message received from the request queue is plain text - by configuration
                        _dvsBinding = EndpointHelper.CreateFlatFileTCPBinding();
                        break;
                    // ...
                    default:
                        //unsupported endpoint configuration
                        throw new Exception("Unsupported binding configuration");
                }
            }

            //create endpoint address
            _endPointAddress = new EndpointAddress(element.EndPoint);
        }
    }
}
</code>```

and the hostname and port also defines in the same class in a SendNewMessage method...

```<code>try
        {
            if (port != 0)
                MQEnvironment.Port = port;
            if (host != ".")
                MQEnvironment.Hostname = host;
            if (channel != ".")
                MQEnvironment.Channel = channel;
            hMgr = new MQQueueManager(manager);
        }
</code>```

So how do I set the standby host in MQEnvironment.Hostname?

答:
There are multiple ways to provide MQ with multiple host names and port numbers to connect to.  My suggestions below specify settings similar to how you already specify host and port.

For your QueueHandler which is using XMS you would replace the properties XMSC.WMQ_HOST_NAME and XMSC.WMQ_PORT with the three properties below.  The example below assumes you have defined host1, port1, host2, port2 in your web.config:

```<code>connectionProperties.SetIntProperty(XMSC.WMQ_CLIENT_RECONNECT_OPTIONS, XMSC.WMQ_CLIENT_RECONNECT_Q_MGR);
connectionProperties.SetStringProperty(XMSC.WMQ_CONNECTION_NAME_LIST, String.Format("{0}({1}),{2}({3})", element.Host1, element.Port1, element.Host2, element.Port2));
connectionProperties.SetIntProperty(XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT, XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT_DEFAULT);
</code>```

Links to the IBM MQ Knowledge center pages for those properties:

XMSC_WMQ_CONNECTION_NAME_LIST

XMSC_WMQ_CLIENT_RECONNECT_TIMEOUT

XMSC_WMQ_CLIENT_RECONNECT_OPTIONS

Under the IBM install directory you can review the following XMS sample program:

```<code>tools\dotnet\samples\cs\xms\simple\wmq\SimpleClientAutoReconnect\SimpleClientAutoReconnect.cs
</code>```

For your SendNewMessage method which is written using the IBM MQ C# libraries you would replace your MQEnvironment settings with a Hashtable of the properties and change the way you call MQQueueManager to pass the Hashtable.  This has the added benefit of being thread safe where MQEnvironment is not. The example below assumes you have defined host1, port1, host2, port2 in your web.config:

```<code>properties = new Hashtable();
properties.Add(MQC.CONNECTION_NAME_PROPERTY, String.Format("{0}({1}),{2}({3})", host1, port1, host2, port2));
properties.Add(MQC.CHANNEL_PROPERTY, channel);
properties.Add(MQC.CONNECT_OPTIONS_PROPERTY, MQC.MQCNO_RECONNECT_Q_MGR);
hMgr = new MQQueueManager(manager, properties);
</code>```

The IBM MQ Knowldege center page "MQQueueManager .NET class" has more information on the properties.

Under the IBM install directory you can review the following C# sample program:

```<code>tools\dotnet\samples\cs\base\SimpleClientAutoReconnectPut\SimpleClientAutoReconnectPut.cs
</code>```

Body:
I have trouble defining multiple hostname for multi-instance queue manager as I am changing a single instance of queue manager to multi-instance queue manager.
The existing host is defined in web.config

<QueueConfigurationSection>
    <QueueConfiguration>
        <add name="SomeQueueHandler" queueManager="QM1" host="99.99.99.01" port="12345" requestQueue="A.B.REQUEST" service="FLATFILE" responseQueue="B.A.RESPONSE" internalResponseQueue="B.A.INTERNAL" channel="A.SVC.SVRCONN" binding="SOAP11TcpBinding" endPoint="net.tcp://localhost:808/Bus/SomeServiceBus.svc/SOAP11" />
    </QueueConfiguration>
  </QueueConfigurationSection>

connection is defined in here

public List<QueueHandler> Queues
{
    get
    {
        if (_queues == null)
            _queues = new List<QueueHandler>();
        if (_queues.Count == 0 && _queueConfiguration != null)
        {
            //create queue handlers from configuration provided
            foreach (QueueConfigurationElement element in _queueConfiguration)
            {
                // Using a different connection factory for each queue
                XMSFactoryFactory factory = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
                IConnectionFactory connectionProperties = factory.CreateConnectionFactory();
                connectionProperties.SetStringProperty(XMSC.WMQ_HOST_NAME, element.Host);
                connectionProperties.SetIntProperty(XMSC.WMQ_PORT, element.Port);
                connectionProperties.SetStringProperty(XMSC.WMQ_CHANNEL, element.Channel);
                connectionProperties.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
                connectionProperties.SetIntProperty(XMSC.WMQ_BROKER_VERSION, XMSC.WMQ_BROKER_V1);
                connectionProperties.SetBooleanProperty(XMSC.WMQ_USE_CONNECTION_POOLING, true);

                var queue = new QueueHandler(element.Name, connectionProperties);
                _queues.Add(queue);
            }
        }
        return new List<QueueHandler>(_queues);
    }
}

QueueHandler:

public QueueHandler(string handlerName, IConnectionFactory mqConnectionFactory)
{
    _connectionProperties = mqConnectionFactory;
    var queueConfigurationSection = ConfigurationManager.GetSection(QueueConfigurationSection.SectionName) as QueueConfigurationSection;
    if (queueConfigurationSection != null)
    {
        if (queueConfigurationSection.QueueConfigurationCollection.Cast<QueueConfigurationElement>().Any(qc => qc.Name == handlerName))
        {
            var element = queueConfigurationSection.QueueConfigurationCollection.Cast<QueueConfigurationElement>().First(qc => qc.Name == handlerName);

            _name = element.Name;
            _serviceType = element.DestinationService;
            _queueManagerName = element.QueueManager;
            _channel = element.Channel;
            _requestQueueName = element.RequestQueue;
            _responseQueueName = element.ResponseQueue;
            _internalResponseQueueName = element.InternalResponseQueue;
            _port = element.Port;
            _host = element.Host;

            //set up binding configuraion
            EndpointType bindingEnum;
            if (System.Enum.TryParse(element.Binding, out bindingEnum))
            {
                _messageType = bindingEnum;

                switch (bindingEnum)
                {
                    case EndpointType.FlatFileTcpBinding:
                        //message received from the request queue is plain text - by configuration
                        _dvsBinding = EndpointHelper.CreateFlatFileTCPBinding();
                        break;
                    // ...
                    default:
                        //unsupported endpoint configuration
                        throw new Exception("Unsupported binding configuration");
                }
            }

            //create endpoint address
            _endPointAddress = new EndpointAddress(element.EndPoint);
        }
    }
}

and the hostname and port also defines in the same class in a SendNewMessage method...

try
        {
            if (port != 0)
                MQEnvironment.Port = port;
            if (host != ".")
                MQEnvironment.Hostname = host;
            if (channel != ".")
                MQEnvironment.Channel = channel;
            hMgr = new MQQueueManager(manager);
        }

So how do I set the standby host in MQEnvironment.Hostname?

Body:
There are multiple ways to provide MQ with multiple host names and port numbers to connect to.  My suggestions below specify settings similar to how you already specify host and port.

For your QueueHandler which is using XMS you would replace the properties XMSC.WMQ_HOST_NAME and XMSC.WMQ_PORT with the three properties below.  The example below assumes you have defined host1, port1, host2, port2 in your web.config:

connectionProperties.SetIntProperty(XMSC.WMQ_CLIENT_RECONNECT_OPTIONS, XMSC.WMQ_CLIENT_RECONNECT_Q_MGR);
connectionProperties.SetStringProperty(XMSC.WMQ_CONNECTION_NAME_LIST, String.Format("{0}({1}),{2}({3})", element.Host1, element.Port1, element.Host2, element.Port2));
connectionProperties.SetIntProperty(XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT, XMSC.WMQ_CLIENT_RECONNECT_TIMEOUT_DEFAULT);

Links to the IBM MQ Knowledge center pages for those properties:

XMSC_WMQ_CONNECTION_NAME_LIST

XMSC_WMQ_CLIENT_RECONNECT_TIMEOUT

XMSC_WMQ_CLIENT_RECONNECT_OPTIONS

Under the IBM install directory you can review the following XMS sample program:

tools\dotnet\samples\cs\xms\simple\wmq\SimpleClientAutoReconnect\SimpleClientAutoReconnect.cs

For your SendNewMessage method which is written using the IBM MQ C# libraries you would replace your MQEnvironment settings with a Hashtable of the properties and change the way you call MQQueueManager to pass the Hashtable.  This has the added benefit of being thread safe where MQEnvironment is not. The example below assumes you have defined host1, port1, host2, port2 in your web.config:

properties = new Hashtable();
properties.Add(MQC.CONNECTION_NAME_PROPERTY, String.Format("{0}({1}),{2}({3})", host1, port1, host2, port2));
properties.Add(MQC.CHANNEL_PROPERTY, channel);
properties.Add(MQC.CONNECT_OPTIONS_PROPERTY, MQC.MQCNO_RECONNECT_Q_MGR);
hMgr = new MQQueueManager(manager, properties);

The IBM MQ Knowldege center page "MQQueueManager .NET class" has more information on the properties.

Under the IBM install directory you can review the following C# sample program:

tools\dotnet\samples\cs\base\SimpleClientAutoReconnectPut\SimpleClientAutoReconnectPut.cs


问:
PHP Validation on a text area using preg_match for numbers, letters, and white space
So i have got this almost completely working. The one thing i am stuck on is where to start in preg_match. I have read the manual here http://php.net/manual/en/function.preg-match.php but it doesn't exactly describe to me the syntax for creating my own validation. Example: for a text area, if i wanna only allow white space, letters, numbers and maybe some special characters(unlikely). Here is the code

```<code><?php
    if(isset($_POST['name'])
            && isset($_POST['phone'])
            && isset($_POST['email'])) {

            if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
            }
            else {
                    $name = $_POST["name"];
              // check if name only contains letters and whitespace for name
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                            $nameErr = "Only letters and white space
                                allowed";
                    }
            }

            if (empty($_POST["phone"])) {
                    $phoneErr = "Phone number is required";
            }
            else {
                    $phone = $_POST["phone"];
                     // check if phone only contains numbers for phone
                    if (!preg_match('/^\(?[\d]{3}\)?\s?\-?[\d]{3}\s?\-?[\d]
                        {4}$/', $phone)) {
                            $phoneErr = "Only numbers allowed";
                    }
            }

            if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
            }
            else {
                    $email = $_POST["email"];
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $emailErr = "Invalid email format";
                    }
            }

            if($nameErr or $emailErr or $phoneErr){
                    echo $nameErr;
                    echo $phoneErr;
                    echo $emailErr;
                    die();
            }
            else if($data = $_POST['name'] . "\n" .
                    $_POST['email'] . "\n" .
                    $_POST['phone'] . "\n" .
                    $_POST['county'] . "\n" .
                    $_POST['floor'] . "\n" .
                    $_POST['descr'] . "\n"){

                    echo "Thank you for your inquery!" . "<br/>" .
                            "An estimator will be with you shortly.";

                    mail('theshadowcallsu@gmail.com', 'Estimation Request',
                          $data);
            }
    }

 ?>
</code>```

答:
preg_match will apply a regex pattern to a string to see if the pattern matches the string

For input validation, you will try to match only the character you want in any order, and if the match failed (ie. there is a character not allowed) then the input contains character not declared in the pattern of string to match.

For example :

```<code>if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
   $nameErr = "Only letters and white space allowed";
}
</code>```

It matches strings which contains only letter from a-z and A-Z and white spaces. If the string contains anything else, it won't match it.

For the text area, something like this should do the trick :

```<code>if (!preg_match("/^[a-zA-Z0-9 \(\)\n]*$/",$name)) {
   $nameErr = "not allowed";
}
</code>```

What it does :

^ : Start of the string

$ : End of the string

[a-zA-Z0-9 \(\)\n] : Match letters a-z, A-Z, numbers 0-9, (, ), new lines.

\n : Line return

\( and \) : Literraly the characters ( and ) because parenthesis are used to capture group in matching string

You can add between the [] the characters you want to allow.

See https://regex101.com/r/wmjrkw/1

Body:
So i have got this almost completely working. The one thing i am stuck on is where to start in preg_match. I have read the manual here http://php.net/manual/en/function.preg-match.php but it doesn't exactly describe to me the syntax for creating my own validation. Example: for a text area, if i wanna only allow white space, letters, numbers and maybe some special characters(unlikely). Here is the code

<?php
    if(isset($_POST['name'])
            && isset($_POST['phone'])
            && isset($_POST['email'])) {

            if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
            }
            else {
                    $name = $_POST["name"];
              // check if name only contains letters and whitespace for name
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                            $nameErr = "Only letters and white space
                                allowed";
                    }
            }

            if (empty($_POST["phone"])) {
                    $phoneErr = "Phone number is required";
            }
            else {
                    $phone = $_POST["phone"];
                     // check if phone only contains numbers for phone
                    if (!preg_match('/^\(?[\d]{3}\)?\s?\-?[\d]{3}\s?\-?[\d]
                        {4}$/', $phone)) {
                            $phoneErr = "Only numbers allowed";
                    }
            }

            if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
            }
            else {
                    $email = $_POST["email"];
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $emailErr = "Invalid email format";
                    }
            }

            if($nameErr or $emailErr or $phoneErr){
                    echo $nameErr;
                    echo $phoneErr;
                    echo $emailErr;
                    die();
            }
            else if($data = $_POST['name'] . "\n" .
                    $_POST['email'] . "\n" .
                    $_POST['phone'] . "\n" .
                    $_POST['county'] . "\n" .
                    $_POST['floor'] . "\n" .
                    $_POST['descr'] . "\n"){

                    echo "Thank you for your inquery!" . "
" .
                            "An estimator will be with you shortly.";

                    mail('theshadowcallsu@gmail.com', 'Estimation Request',
                          $data);
            }
    }

 ?>

Body:
preg_match will apply a regex pattern to a string to see if the pattern matches the string

For input validation, you will try to match only the character you want in any order, and if the match failed (ie. there is a character not allowed) then the input contains character not declared in the pattern of string to match.

For example :

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
   $nameErr = "Only letters and white space allowed";
}

It matches strings which contains only letter from a-z and A-Z and white spaces. If the string contains anything else, it won't match it.

For the text area, something like this should do the trick :

if (!preg_match("/^[a-zA-Z0-9 \(\)\n]*$/",$name)) {
   $nameErr = "not allowed";
}

What it does :

^ : Start of the string

$ : End of the string

[a-zA-Z0-9 \(\)\n] : Match letters a-z, A-Z, numbers 0-9, (, ), new lines.

\n : Line return

\( and \) : Literraly the characters ( and ) because parenthesis are used to capture group in matching string

You can add between the [] the characters you want to allow.

See https://regex101.com/r/wmjrkw/1


问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
In your code have 2 problem

when input mathematics must string not Integer

When compare mathematics, must using character " not using '. Because character " have meaning string and ' just meaning character

So, please try this code below

```<code>public static void calculator(){
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();
    System.out.println("Now give me the operation (+,-,*,/): ");
    a.nextLine();
    String b = a.next();
    if (b.equals("+")){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (b.equals("-")){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (b.equals("*")){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
    }
</code>```

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)

Body:
In your code have 2 problem

when input mathematics must string not Integer

When compare mathematics, must using character " not using '. Because character " have meaning string and ' just meaning character

So, please try this code below

public static void calculator(){
    Scanner a = new Scanner(System.in);
    System.out.println("Give me the 2 numbers first: ");
    int x = a.nextInt();
    int y = a.nextInt();
    System.out.println("Now give me the operation (+,-,*,/): ");
    a.nextLine();
    String b = a.next();
    if (b.equals("+")){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (b.equals("-")){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (b.equals("*")){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
    }


问:
Django. How to EXCLUDE one-to-many or many-to-many fields from query?
I have a sample model like this:

```<code>class FooBar(models.Model):
    name = models.CharField ...
    age = models.IntegerField ...
    cats = models.ManyToManyField ...
    dogs = models.ManyToManyField ...
</code>```

As u can see, there is 2 many-to-many fields (cats, dogs)

Then (somewhere else in my code) I have serializer function which converts given model into JSON. Eg.

```<code>make_json(foobar_instance) will produce smth like this:

{
    "id": "9999",
    "name": "John Romero",
    "age": "55",
    "cats": "[421, 5423, 53252]",
    "dogs": "[213, 44124, 321, 753]"
}
</code>```

BUT I don't need that "cats" and "dogs" fields in my result JSON and I don't want to charge database with additional queries for resolving that many-to-many relations.

So, how I can tell Django: Man, exclude that cats and dogs fields from result - I don't need that thing.

Eg.

```<code>FooBar.objects.filter(....).SKIP('cats', 'dogs')...
</code>```

Is that possible?

Thank you!

答:
So... After few hours of thinking, here is what I get:

```<code># Getting list of model fields
# and excluding cats and dogs from this list.
result_fields = [f.name for f in FooBar._meta.get_fields()]
result_fields.remove('cats')
result_fields.remove('dogs')

# Making query.
FooBar.objects.values(*result_fields).filter(....)
</code>```

One bad thing that python dict is returned instead of QuerySet, but maybe this will be enough for many cases.

Body:
I have a sample model like this:

class FooBar(models.Model):
    name = models.CharField ...
    age = models.IntegerField ...
    cats = models.ManyToManyField ...
    dogs = models.ManyToManyField ...

As u can see, there is 2 many-to-many fields (cats, dogs)

Then (somewhere else in my code) I have serializer function which converts given model into JSON. Eg.

make_json(foobar_instance) will produce smth like this:

{
    "id": "9999",
    "name": "John Romero",
    "age": "55",
    "cats": "[421, 5423, 53252]",
    "dogs": "[213, 44124, 321, 753]"
}

BUT I don't need that "cats" and "dogs" fields in my result JSON and I don't want to charge database with additional queries for resolving that many-to-many relations.

So, how I can tell Django: Man, exclude that cats and dogs fields from result - I don't need that thing.

Eg.

FooBar.objects.filter(....).SKIP('cats', 'dogs')...

Is that possible?

Thank you!

Body:
So... After few hours of thinking, here is what I get:

# Getting list of model fields
# and excluding cats and dogs from this list.
result_fields = [f.name for f in FooBar._meta.get_fields()]
result_fields.remove('cats')
result_fields.remove('dogs')

# Making query.
FooBar.objects.values(*result_fields).filter(....)

One bad thing that python dict is returned instead of QuerySet, but maybe this will be enough for many cases.


问:
Wrap each char inside
I'm trying to wrap each char from a given element inside a  tag.
I've tried two methods so far but each one has some issues.

First method:

I replace every char of the .html() of my element by its wrapped
version. The problem is that it also considers tags as chars and wraps them too.

$(function() {
  $(document).click(function(e) {
    var element = e.target;
    if ($(element).text() != '') { //Contains text
      var txt = $(element).contents().filter(function() {
        return this.nodeType === 3;
      }).text();
      if (txt != '') { //Text outside span
        var chars = $(element).html().split('');
        var newChars = '';
        $.each(chars, function(i, el) {
          newChars += "" + el + "";
        });
        $(element).html(newChars);
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  Lorem <span>teeest</span> ipsum dolor sit amet, consectetur adipisicing elit. Dolorem aspernatur ducimus autem eveniet porro vitae ratione illum totam voluptatem alias. Impedit deserunt maiores excepturi ab repellendus atque aperiam quisquam iste! Lorem
  ipsum dolor sit amet, consectetur adipisicing elit. Saepe quasi mollitia perspiciatis explicabo, maxime quae</p></code>```

Second method:

I tried a recursive approach which travels through my element's children and replace the text inside each one. The problem is, my output text somehow doubles and the children are misplaced in the result.

function recursiveReplace(element) {
  if ($(element).children().length > 0) {
    $(element).children().each(function() {
      recursiveReplace($(this)[0]);
    });
  }
  var chars = $(element).contents().filter(function() {
    return this.nodeType === 3;
  }).text().split('');
  var newChars = '';
  $.each(chars, function(i, el) {
    newChars += "" + el + "";
  });
  console.log(newChars);
  $(element).contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(newChars);

}

$(function() {
  $(document).click(function(e) {
    var element = e.target;
    if ($(element).text() != '') { //Contains text
      var txt = $(element).contents().filter(function() {
        return this.nodeType === 3;
      }).text();
      if (txt != '') { //Text outside span
        recursiveReplace(element);
      }
    }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Lorem <span>teeest</span> ipsum dolor sit amet, consectetur adipisicing elit. Dolorem aspernatur ducimus autem eveniet porro vitae ratione illum totam voluptatem alias. Impedit deserunt maiores excepturi ab repellendus atque aperiam quisquam iste! Lorem
  ipsum dolor sit amet, consectetur adipisicing elit. Saepe quasi mollitia perspiciatis expli</p></code>```

Would any of you have any idea on how I could achieve this?

答:
Your recursive approach should work if you process each text node individually instead of concatenating it the way you do (as a result of running text() on the filtered collection)

```<code>function recursiveReplace(element){
  $(element).children().each(function() {
    recursiveReplace(this);
  });

  $(element).contents()
    .filter(function(){ return this.nodeType === 3; })
    .each(function(){
      var wrapped = '<i>' + this.textContent.split('').join('</i><i>') + '</i>';
      console.log(wrapped);
      $(this).replaceWith(wrapped);
    });
}
</code>```

Notice how I also simplified your recursive call, there's no need to check if there are any children when using each() and there's no point in wrapping this just to immediately unwrap it.

Title: Wrap each char inside <i>

Body:
I'm trying to wrap each char from a given element inside a  tag.
I've tried two methods so far but each one has some issues.

First method:

I replace every char of the .html() of my element by its wrapped
version. The problem is that it also considers tags as chars and wraps them too.

$(function() {
  $(document).click(function(e) {
    var element = e.target;
    if ($(element).text() != '') { //Contains text
      var txt = $(element).contents().filter(function() {
        return this.nodeType === 3;
      }).text();
      if (txt != '') { //Text outside span
        var chars = $(element).html().split('');
        var newChars = '';
        $.each(chars, function(i, el) {
          newChars += "" + el + "";
        });
        $(element).html(newChars);
      }
    }
  });
});

  Lorem teeest ipsum dolor sit amet, consectetur adipisicing elit. Dolorem aspernatur ducimus autem eveniet porro vitae ratione illum totam voluptatem alias. Impedit deserunt maiores excepturi ab repellendus atque aperiam quisquam iste! Lorem
  ipsum dolor sit amet, consectetur adipisicing elit. Saepe quasi mollitia perspiciatis explicabo, maxime quae

Second method:

I tried a recursive approach which travels through my element's children and replace the text inside each one. The problem is, my output text somehow doubles and the children are misplaced in the result.

function recursiveReplace(element) {
  if ($(element).children().length > 0) {
    $(element).children().each(function() {
      recursiveReplace($(this)[0]);
    });
  }
  var chars = $(element).contents().filter(function() {
    return this.nodeType === 3;
  }).text().split('');
  var newChars = '';
  $.each(chars, function(i, el) {
    newChars += "" + el + "";
  });
  console.log(newChars);
  $(element).contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(newChars);

}

$(function() {
  $(document).click(function(e) {
    var element = e.target;
    if ($(element).text() != '') { //Contains text
      var txt = $(element).contents().filter(function() {
        return this.nodeType === 3;
      }).text();
      if (txt != '') { //Text outside span
        recursiveReplace(element);
      }
    }
  });

});

  Lorem teeest ipsum dolor sit amet, consectetur adipisicing elit. Dolorem aspernatur ducimus autem eveniet porro vitae ratione illum totam voluptatem alias. Impedit deserunt maiores excepturi ab repellendus atque aperiam quisquam iste! Lorem
  ipsum dolor sit amet, consectetur adipisicing elit. Saepe quasi mollitia perspiciatis expli

Would any of you have any idea on how I could achieve this?

Body:
Your recursive approach should work if you process each text node individually instead of concatenating it the way you do (as a result of running text() on the filtered collection)

function recursiveReplace(element){
  $(element).children().each(function() {
    recursiveReplace(this);
  });

  $(element).contents()
    .filter(function(){ return this.nodeType === 3; })
    .each(function(){
      var wrapped = '<i>' + this.textContent.split('').join('</i><i>') + '</i>';
      console.log(wrapped);
      $(this).replaceWith(wrapped);
    });
}

Notice how I also simplified your recursive call, there's no need to check if there are any children when using each() and there's no point in wrapping this just to immediately unwrap it.


问:
Elastalert in Openshift Origin Container
I would like to implement alerts for EFK stack, which is deployemnt in Openshift origin. To implement alerts, i used Elastalert. I used the krizsan/elastalert-docker docker image for it.

```<code>oc run elastalertcore --image=172.30.1.1:5000/logging/elastalert-core --port=3344 --expose
</code>```

This will succesfully run the elastalert instance, but in the log im getting

```<code>Container timezone set to: Europe/Stockholm
ntpd: can't set priority: Permission denied
reset adjtime failed: Operation not permitted
creating new /var/db/ntpd.drift
adjtimex failed: Operation not permitted
dispatch_imsg in main: pipe closed
Lost child: child exited
Terminating
Waiting for Elasticsearch...
Waiting for Elasticsearch...
Waiting for Elasticsearch...
Waiting for Elasticsearch...
</code>```

I gave environment varialbe

```<code>ELASTICSEARCH_HOST =logging-es
</code>```

Elastalert cannot connect to the elastic search in open shift origin. Any help is appreciated..

答:
Most of the Docker image from Docker hub doesn't work as-is on Openshift often due to Security Context Constraints.

To avoid permission errors, you can add :

```<code>oc adm policy add-scc-to-user anyuid -z default
</code>```

enabling a pod with default service account to run with anyuid SCC. Be aware that it can impact all pod running within the project if you don't specify explicitly an other service account in your pod definition.

Body:
I would like to implement alerts for EFK stack, which is deployemnt in Openshift origin. To implement alerts, i used Elastalert. I used the krizsan/elastalert-docker docker image for it.

oc run elastalertcore --image=172.30.1.1:5000/logging/elastalert-core --port=3344 --expose

This will succesfully run the elastalert instance, but in the log im getting

Container timezone set to: Europe/Stockholm
ntpd: can't set priority: Permission denied
reset adjtime failed: Operation not permitted
creating new /var/db/ntpd.drift
adjtimex failed: Operation not permitted
dispatch_imsg in main: pipe closed
Lost child: child exited
Terminating
Waiting for Elasticsearch...
Waiting for Elasticsearch...
Waiting for Elasticsearch...
Waiting for Elasticsearch...

I gave environment varialbe

ELASTICSEARCH_HOST =logging-es

Elastalert cannot connect to the elastic search in open shift origin. Any help is appreciated..

Body:
Most of the Docker image from Docker hub doesn't work as-is on Openshift often due to Security Context Constraints.

To avoid permission errors, you can add :

oc adm policy add-scc-to-user anyuid -z default

enabling a pod with default service account to run with anyuid SCC. Be aware that it can impact all pod running within the project if you don't specify explicitly an other service account in your pod definition.


问:
Netsuite search filter for list of items
I am trying to add a filter in the search condition.

The problem I am facing is that while I am using the internalid and the int 1111 it works fine. But if i replace with some other column with string it does not work. It throws error in cust search line.
Can anyone suggest ?

```<code>        var custSearch = search.create({
        type : record.Type.CUSTOMER,
        columns : searchColumn,
        filters: [
                 'email', 'ANYOF', ["abanks@acera.com","3m@3m.com"]]
                 //'internalid', 'ANYOF', ["1397","1251"]] // Works fine

        });
        custSearch.run().each(function(result) { // throw errors
            log.debug("Found !",result);
            return true;
        });
</code>```

答:
options.filters that you are using could be:

a single search.Filter object

an array of search.Filter objects

a search filter expression

an array of search filter expressions

In your example, you create 2 Filter Objects (filterscust1 and filterscust2). After that you try to create a search filter expression, combining two Filter Objects with 'or' string inside. But this is not correct:

A search filter expression is a JavaScript string array of zero or more elements. Each element is one of the following:

Operator - either ‘NOT', ‘AND', or ‘OR'

Filter term

Nested search filter expression

So, the equivalent code should be:

filterscust1 = ['email', 'contains', '3m@3m.com'];

filterscust2 = ['email', 'contains', 'abanks@acera.com'];

var filtersExp = [ filterscust1, 'or', filterscust2 ];

var custSearch = search.create({
  type: record.Type.CUSTOMER,
  columns: searchColumn,
  filters: [filtersExp]

});
```

<p>or directly:</p>

<pre class="lang-js prettyprint-override"><code>var custSearch = search.create({
  type: record.Type.CUSTOMER,
  columns: searchColumn,
  filters: [ ['email', 'contains', '3m@3m.com'], 'or',
             ['email', 'contains', 'abanks@acera.com']
           ]

});
</code>```

Body:
I am trying to add a filter in the search condition.

The problem I am facing is that while I am using the internalid and the int 1111 it works fine. But if i replace with some other column with string it does not work. It throws error in cust search line.
Can anyone suggest ?

        var custSearch = search.create({
        type : record.Type.CUSTOMER,
        columns : searchColumn,
        filters: [
                 'email', 'ANYOF', ["abanks@acera.com","3m@3m.com"]]
                 //'internalid', 'ANYOF', ["1397","1251"]] // Works fine

        });
        custSearch.run().each(function(result) { // throw errors
            log.debug("Found !",result);
            return true;
        });

Body:
options.filters that you are using could be:

a single search.Filter object

an array of search.Filter objects

a search filter expression

an array of search filter expressions

In your example, you create 2 Filter Objects (filterscust1 and filterscust2). After that you try to create a search filter expression, combining two Filter Objects with 'or' string inside. But this is not correct:

A search filter expression is a JavaScript string array of zero or more elements. Each element is one of the following:

Operator - either ‘NOT', ‘AND', or ‘OR'

Filter term

Nested search filter expression

So, the equivalent code should be:

filterscust1 = ['email', 'contains', '3m@3m.com'];

filterscust2 = ['email', 'contains', 'abanks@acera.com'];

var filtersExp = [ filterscust1, 'or', filterscust2 ];

var custSearch = search.create({
  type: record.Type.CUSTOMER,
  columns: searchColumn,
  filters: [filtersExp]

});

or directly:

var custSearch = search.create({
  type: record.Type.CUSTOMER,
  columns: searchColumn,
  filters: [ ['email', 'contains', '3m@3m.com'], 'or',
             ['email', 'contains', 'abanks@acera.com']
           ]

});


问:
Issue with bindings on attached properties in Xamarin.Forms
EDIT: Please, do not post answers on how to implement gestures in Xamarin.Forms - read the entire post first.

I'm creating a swipe gesture handlers as effects using the attached properties (as described in Xamarin guides). Skipping the approach discussion I have a strange issue with attached properties implementation.

Long story short (code below) - XAML bindings to attached properties are not working. The Set\Get...Command methods in my static class are not executed at all. I don't see any Debug.WriteLine() result in app output. The debugger doesn't hit the breakpoints set there as well. The same with ...CommandPropertyChanged() handler.

This is my class for the properties handling:

```<code>namespace Core.Effects
{
    public static class Gesture
    {
        public static readonly BindableProperty SwipeLeftCommandProperty =
            BindableProperty.CreateAttached("SwipeLeftCommand", typeof(ICommand), typeof(Gesture), null, propertyChanged: SwipeLeftCommandPropertyChanged);

        public static readonly BindableProperty SwipeRightCommandProperty =
            BindableProperty.CreateAttached("SwipeRightCommand", typeof(ICommand), typeof(Gesture), null, propertyChanged: SwipeRightCommandPropertyChanged);

        public static ICommand GetSwipeLeftCommand(BindableObject view)
        {
            Debug.WriteLine("GetSwipeLeftCommand");
            return (ICommand) view.GetValue(SwipeLeftCommandProperty);
        }

        public static void SetSwipeLeftCommand(BindableObject view, ICommand value)
        {
            Debug.WriteLine("SetSwipeLeftCommand");
            view.SetValue(SwipeLeftCommandProperty, value);
        }

        public static ICommand GetSwipeRightCommand(BindableObject view)
        {
            Debug.WriteLine("GetSwipeRightCommand");
            return (ICommand) view.GetValue(SwipeRightCommandProperty);
        }

        public static void SetSwipeRightCommand(BindableObject view, ICommand value)
        {
            Debug.WriteLine("SetSwipeRightCommand");
            view.SetValue(SwipeRightCommandProperty, value);
        }

        private static void SwipeLeftCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            Debug.WriteLine("SwipeLeftCommandPropertyChanged");
            // ...
        }

        private static void SwipeRightCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            Debug.WriteLine("SwipeRightCommandPropertyChanged");
            // ...
        }

        // ...
    }
}
</code>```

and here is how I use it in XAML:

```<code><?xml version="1.0" encoding="UTF-8"?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:effects="clr-namespace:Core.Effects"
             x:Class="Core.Pages.RequestDetailsPage">
    <ContentPage.Content>
        <StackLayout Spacing="0"
                     Padding="0"
                     VerticalOptions="FillAndExpand"
                     effects:Gesture.SwipeLeftCommand="{Binding NavigateToPreviousRequestCommand}"
                     effects:Gesture.SwipeRightCommand="{Binding NavigateToNextRequestCommand}">
</code>```

I have corresponding commands in my view model (MVVM implemented with FreshMvvm framework):

```<code>namespace Core.PageModels
{
    public class RequestDetailsPageModel : FreshBasePageModel
    {
        public IRelayCommand NavigateToNextRequestCommand;
        public IRelayCommand NavigateToPreviousRequestCommand;
</code>```

IRelayCommand is my type deriving from ICommand. The BindingContext is properly set by FreshMvvm (works well in other places on this view).

Any clue what might be wrong?

答:
I have done sample repo on GitHub, Check Below Link.

https://github.com/softlion/XamarinFormsGesture

https://github.com/tkowalczyk/SimpleCustomGestureFrame

http://arteksoftware.com/gesture-recognizers-with-xamarin-forms/

Body:
EDIT: Please, do not post answers on how to implement gestures in Xamarin.Forms - read the entire post first.

I'm creating a swipe gesture handlers as effects using the attached properties (as described in Xamarin guides). Skipping the approach discussion I have a strange issue with attached properties implementation.

Long story short (code below) - XAML bindings to attached properties are not working. The Set\Get...Command methods in my static class are not executed at all. I don't see any Debug.WriteLine() result in app output. The debugger doesn't hit the breakpoints set there as well. The same with ...CommandPropertyChanged() handler.

This is my class for the properties handling:

namespace Core.Effects
{
    public static class Gesture
    {
        public static readonly BindableProperty SwipeLeftCommandProperty =
            BindableProperty.CreateAttached("SwipeLeftCommand", typeof(ICommand), typeof(Gesture), null, propertyChanged: SwipeLeftCommandPropertyChanged);

        public static readonly BindableProperty SwipeRightCommandProperty =
            BindableProperty.CreateAttached("SwipeRightCommand", typeof(ICommand), typeof(Gesture), null, propertyChanged: SwipeRightCommandPropertyChanged);

        public static ICommand GetSwipeLeftCommand(BindableObject view)
        {
            Debug.WriteLine("GetSwipeLeftCommand");
            return (ICommand) view.GetValue(SwipeLeftCommandProperty);
        }

        public static void SetSwipeLeftCommand(BindableObject view, ICommand value)
        {
            Debug.WriteLine("SetSwipeLeftCommand");
            view.SetValue(SwipeLeftCommandProperty, value);
        }

        public static ICommand GetSwipeRightCommand(BindableObject view)
        {
            Debug.WriteLine("GetSwipeRightCommand");
            return (ICommand) view.GetValue(SwipeRightCommandProperty);
        }

        public static void SetSwipeRightCommand(BindableObject view, ICommand value)
        {
            Debug.WriteLine("SetSwipeRightCommand");
            view.SetValue(SwipeRightCommandProperty, value);
        }

        private static void SwipeLeftCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            Debug.WriteLine("SwipeLeftCommandPropertyChanged");
            // ...
        }

        private static void SwipeRightCommandPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            Debug.WriteLine("SwipeRightCommandPropertyChanged");
            // ...
        }

        // ...
    }
}

and here is how I use it in XAML:

<?xml version="1.0" encoding="UTF-8"?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:effects="clr-namespace:Core.Effects"
             x:Class="Core.Pages.RequestDetailsPage">
    <ContentPage.Content>
        <StackLayout Spacing="0"
                     Padding="0"
                     VerticalOptions="FillAndExpand"
                     effects:Gesture.SwipeLeftCommand="{Binding NavigateToPreviousRequestCommand}"
                     effects:Gesture.SwipeRightCommand="{Binding NavigateToNextRequestCommand}">

I have corresponding commands in my view model (MVVM implemented with FreshMvvm framework):

namespace Core.PageModels
{
    public class RequestDetailsPageModel : FreshBasePageModel
    {
        public IRelayCommand NavigateToNextRequestCommand;
        public IRelayCommand NavigateToPreviousRequestCommand;

IRelayCommand is my type deriving from ICommand. The BindingContext is properly set by FreshMvvm (works well in other places on this view).

Any clue what might be wrong?


问:
What method is the best to copy files from one server to another using PHP
I need to copy a couple of files over from one server to another using PHP. Now I currently use PHP FTP functionality which is ok but causes issues. Are there better ways to accomplish this?</p>

答:
I would suggest rsync, or sftp

However, if restricted to PHP only, try ssh2_sftp

required - pecl ssh2 package

with the proper configured ssh public key, you don't even require to supply password


问:
How to install both .net framework 4.6.1 and 4.6.2 on a server?
Ho do i install both the versions 4.6.1 and 4.6.2 on a server and target applications specifically to a specific version of .net framework?

答:
When you install 4.6.2, it replaces among others 4.6.1. Applications targeting 4.6.1 still will work.

See the installer notes:

The Microsoft .NET Framework 4.6.2 is a highly compatible, in-place update to the Microsoft .NET Framework 4, 4.5, 4.5.1, 4.5.2, 4.6, and 4.6.1.

https://support.microsoft.com/en-us/help/3151802/the-.net-framework-4.6.2-web-installer-for-windows