问:
Represent Classes in JSON
I try to implement Transaction Classes into a JSON file. For an Example...

```<code>Holidays [Flights, Hotels, etc.]
Groceries [Drinks, Food]
Transportation [Car Taxes, Car Insurance, rental car, petrol]
</code>```

How would i manage to do so?

Could i define two classes and link them with IDs?

```<code>   categoryList: [
        {
            name: 'Holidays',
            id: 1000
        },  {
            name: 'Groceries',
            id: 1001
        },  {
            name: 'Transportation',
            id: 1002
        }
    ],
    subCategoryList: [
        {
            name: 'Flights',
            categoryId: 1000
        },  {
            name: 'Hotels',
            categoryId: 1000
        },  {
            name: 'Drinks',
            categoryId: 1001
        }, {
            name: 'Food',
            categoryId: 1001
        }, {
            name: 'Car Taxes',
            categoryId: 1002
        }, {
            name: 'Car Insurance',
            categoryId: 1002
        }, {
            name: 'Rental Car',
            categoryId: 1002
        }
    ]
</code>```

I've bank transactions and would like to classify them by category's within my app.

答:
I am supposing that you think in JavaScript, and...
Yes! you can!

I think the best way is create an array in each object with subelements:

```<code>   categoryList: [
        {
            name: 'Holidays',
            subelements: ['Flights', 'Hotels']
        },  {
            name: 'Groceries',
            subelements: ['Drinks', 'Foods']
        },  {
            name: 'Transportation',
            subelements: ['Car Taxes', 'Rent a Car']
        }
    ],
</code>```

Also, if you want detailed subelement you could create a object array instead a string array:

```<code>   categoryList: [
        {
            name: 'Holidays',
            subelements:  [{
                name: 'Flights',
                optional: false
            },  {
                name: 'Hotels',
                optional: true
            }]
        }, ... ]
</code>```

But if you will have sub a lot of sub-elements repeated take only one property to identify, like name or ID and search details in an array for detailed sub-element.

I am supposing that you think in JavaScript, and...
Yes! you can!

I think the best way is create an array in each object with subelements:

```<code>categoryList: [
    {
        name: 'Holidays',
        subelements: ['Flights', 'Hotels']
    },  {
        name: 'Groceries',
        subelements: ['Drinks', 'Foods']
    },  {
        name: 'Transportation',
        subelements: ['Car Taxes', 'Rent a Car']
    }
 ],
</code>```

Also, if you want detailed subelement you could create a object array instead a string array:

```<code>categoryList: [
        {
            name: 'Holidays',
            subelements:  [{
                name: 'Flights',
                optional: false
            },  {
                name: 'Hotels',
                optional: true
            }]
        }, ... ]
</code>```

But if you will have sub a lot of sub-elements repeated take only one property to identify, like name or ID and search details in an array for detailed sub-element.

Alternative solution

And, I think the most simple way is changing categoryList array:

```<code>categoryList: [ 'Holidays', 'Groceries', 'Transportation' ]
</code>```

Now you got a auto-numbered array, so: 0 -> Holidays 1 -> Groceries 2 -> Transportation

Then, you have to change the subCategoryList:

```<code>subCategoryList: [
    {
        categoryId: 0, name: 'Flights' }, {
        categoryId: 0, name: 'Hotels' }, {
        categoryId: 1, name: 'Drinks' }, {
        categoryId: 1, name: 'Food' }, {
        categoryId: 2, name: 'Car Taxes' }, {
        categoryId: 2, name: 'Car Insurance' }, {
        categoryId: 2, name: 'Rental Car' }
]
</code>```

Now, every time you need the name of a category go to the array, for example:

```<code>for(var i=0 ; i < subCategoryList; i++){
    console.log('for ' + subCategoryList[i].name + ', category is: '
    + categoryList[ subCategoryList[i].categoryId ] );
}
</code>```

Title: Represent Classes in JSON

Body:
I try to implement Transaction Classes into a JSON file. For an Example...

Holidays [Flights, Hotels, etc.]
Groceries [Drinks, Food]
Transportation [Car Taxes, Car Insurance, rental car, petrol]

How would i manage to do so?

Could i define two classes and link them with IDs?

   categoryList: [
        {
            name: 'Holidays',
            id: 1000
        },  {
            name: 'Groceries',
            id: 1001
        },  {
            name: 'Transportation',
            id: 1002
        }
    ],
    subCategoryList: [
        {
            name: 'Flights',
            categoryId: 1000
        },  {
            name: 'Hotels',
            categoryId: 1000
        },  {
            name: 'Drinks',
            categoryId: 1001
        }, {
            name: 'Food',
            categoryId: 1001
        }, {
            name: 'Car Taxes',
            categoryId: 1002
        }, {
            name: 'Car Insurance',
            categoryId: 1002
        }, {
            name: 'Rental Car',
            categoryId: 1002
        }
    ]

I've bank transactions and would like to classify them by category's within my app.

Body:
I am supposing that you think in JavaScript, and...
Yes! you can!

I think the best way is create an array in each object with subelements:

   categoryList: [
        {
            name: 'Holidays',
            subelements: ['Flights', 'Hotels']
        },  {
            name: 'Groceries',
            subelements: ['Drinks', 'Foods']
        },  {
            name: 'Transportation',
            subelements: ['Car Taxes', 'Rent a Car']
        }
    ],

Also, if you want detailed subelement you could create a object array instead a string array:

   categoryList: [
        {
            name: 'Holidays',
            subelements:  [{
                name: 'Flights',
                optional: false
            },  {
                name: 'Hotels',
                optional: true
            }]
        }, ... ]

But if you will have sub a lot of sub-elements repeated take only one property to identify, like name or ID and search details in an array for detailed sub-element.

I am supposing that you think in JavaScript, and...
Yes! you can!

I think the best way is create an array in each object with subelements:

categoryList: [
    {
        name: 'Holidays',
        subelements: ['Flights', 'Hotels']
    },  {
        name: 'Groceries',
        subelements: ['Drinks', 'Foods']
    },  {
        name: 'Transportation',
        subelements: ['Car Taxes', 'Rent a Car']
    }
 ],

Also, if you want detailed subelement you could create a object array instead a string array:

categoryList: [
        {
            name: 'Holidays',
            subelements:  [{
                name: 'Flights',
                optional: false
            },  {
                name: 'Hotels',
                optional: true
            }]
        }, ... ]

But if you will have sub a lot of sub-elements repeated take only one property to identify, like name or ID and search details in an array for detailed sub-element.

Alternative solution

And, I think the most simple way is changing categoryList array:

categoryList: [ 'Holidays', 'Groceries', 'Transportation' ]

Now you got a auto-numbered array, so: 0 -> Holidays 1 -> Groceries 2 -> Transportation

Then, you have to change the subCategoryList:

subCategoryList: [
    {
        categoryId: 0, name: 'Flights' }, {
        categoryId: 0, name: 'Hotels' }, {
        categoryId: 1, name: 'Drinks' }, {
        categoryId: 1, name: 'Food' }, {
        categoryId: 2, name: 'Car Taxes' }, {
        categoryId: 2, name: 'Car Insurance' }, {
        categoryId: 2, name: 'Rental Car' }
]

Now, every time you need the name of a category go to the array, for example:

for(var i=0 ; i < subCategoryList; i++){
    console.log('for ' + subCategoryList[i].name + ', category is: '
    + categoryList[ subCategoryList[i].categoryId ] );
}


来源: stackexchange

问:
create Advanced and Custom Dynamics CRM online report
I know how to create the report using ADVANCED FIND but I want to create a Custom Report in CRM online using fetchxml. </p>

答:
A good way to get up and running with FetchXML is to use the FetchXML Builder tool in XrmToolBox.

XrmToolBox can be downloaded from www.xrmtoolbox.com and the FetchXML Builder is installed from the Plugins Store inside XrmToolBox.

More information on FetchXML Builder can be found on fxb.xrmtoolbox.com and a tutorial on how to create advanced views with it in this article on MSDynamicsWorld.com.

ContentLicense: CC BY-SA 3.0


问:
java web page reader
I want to retrieve all the links in web page ,but the web page use javascript and each page contain number of links

how can i go to the next page and read its contain in java program

答: What you are looking for is called Web Spider engine. There are plenty of open source web spider engine's are available. Check http://j-spider.sourceforge.net/ for example

ContentLicense: CC BY-SA 2.5

Title: java web page reader


问:
Div click not working using phantomjsdriver / selenium-support
I am new to PhantomJSDriver and was trying to enter my email and proceed to the next screen by clicking "NEXT" button in https://www.youtube.com/content_id.

I am able to enter my email but, click event does not work.

My code:

```<code>DesiredCapabilities caps = DesiredCapabilities.firefox();
caps.setBrowserName("firefox");
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", true);
caps.setCapability("handlesAlerts", true);
caps.setCapability("elementScrollBehavior", 1);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.out.println(caps);
WebDriver driver = new PhantomJSDriver(caps);
driver.manage().window().setSize(new Dimension(1920, 1080));
driver.get("https://www.youtube.com/content_id");
System.out.println(driver.getTitle());

WebElement elementEmail = driver.findElement(By.id("identifierId"));
System.out.println(elementEmail);
elementEmail.sendKeys("test@gmail.com");

WebElement elementNext = driver.findElement(By.id("identifierNext"));
System.out.println(elementNext + " :: " + elementNext.getText() + " :: " + elementNext.getAttribute("role"));
elementNext.click();
</code>```

I also tried submitting the form using below code but it didn't work:

```<code>WebElement elementForm = driver.findElement(By.tagName("form"));
System.out.println(elementForm + " :: " + elementForm.getText() + " :: " + elementForm.getAttribute("class"));
elementForm.submit();
</code>```

I also tried doing it using JavascriptExecutor -

```<code>JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", elementNext);
</code>```

Even, tried doing it using selenium driver -

```<code>Actions action = new Actions(driver);
action.moveToElement(elementNext).click().perform();
</code>```

I tried taking the screenshot after waiting for few seconds for password field to be displayed on the next screen but, the screenshot captured is of the initial page.

```<code>try {
  (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver d) {
      return d.findElement(By.cssSelector("#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input")).isDisplayed();
    }
  });
  System.out.println("We are on password screen.");
} catch (Exception e) {
  System.out.println(e.getMessage());
}
takeScreenshot(driver, "final.png"); // private method which captures screenshot to a file
</code>```

It works fine when I run it in PhantomJS - Javascript code but, need to run it java.

Any help will be greatly appreciated.

答:
I was able to resolve it by setting user agent as mentioned below (just positing the answer as it might help someone):</p>

```<code>String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36";
DesiredCapabilities caps = DesiredCapabilities.firefox();
caps.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX + "userAgent", userAgent);
</code>```

Body:
I am new to PhantomJSDriver and was trying to enter my email and proceed to the next screen by clicking "NEXT" button in https://www.youtube.com/content_id.

I am able to enter my email but, click event does not work.

My code:

DesiredCapabilities caps = DesiredCapabilities.firefox();
caps.setBrowserName("firefox");
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", true);
caps.setCapability("handlesAlerts", true);
caps.setCapability("elementScrollBehavior", 1);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
System.out.println(caps);
WebDriver driver = new PhantomJSDriver(caps);
driver.manage().window().setSize(new Dimension(1920, 1080));
driver.get("https://www.youtube.com/content_id");
System.out.println(driver.getTitle());

WebElement elementEmail = driver.findElement(By.id("identifierId"));
System.out.println(elementEmail);
elementEmail.sendKeys("test@gmail.com");

WebElement elementNext = driver.findElement(By.id("identifierNext"));
System.out.println(elementNext + " :: " + elementNext.getText() + " :: " + elementNext.getAttribute("role"));
elementNext.click();

I also tried submitting the form using below code but it didn't work:

WebElement elementForm = driver.findElement(By.tagName("form"));
System.out.println(elementForm + " :: " + elementForm.getText() + " :: " + elementForm.getAttribute("class"));
elementForm.submit();

I also tried doing it using JavascriptExecutor -

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", elementNext);

Even, tried doing it using selenium driver -

Actions action = new Actions(driver);
action.moveToElement(elementNext).click().perform();

I tried taking the screenshot after waiting for few seconds for password field to be displayed on the next screen but, the screenshot captured is of the initial page.

try {
  (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver d) {
      return d.findElement(By.cssSelector("#password > div.aCsJod.oJeWuf > div > div.Xb9hP > input")).isDisplayed();
    }
  });
  System.out.println("We are on password screen.");
} catch (Exception e) {
  System.out.println(e.getMessage());
}
takeScreenshot(driver, "final.png"); // private method which captures screenshot to a file

It works fine when I run it in PhantomJS - Javascript code but, need to run it java.

Any help will be greatly appreciated.

Body:
I was able to resolve it by setting user agent as mentioned below (just positing the answer as it might help someone):

String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36";
DesiredCapabilities caps = DesiredCapabilities.firefox();
caps.setCapability(PhantomJSDriverService.PHANTOMJS_PAGE_SETTINGS_PREFIX + "userAgent", userAgent);


问:
Sort List with two parameters but in different lines of code
I have a method which sorts a List of Clients.

There are two parameters I want to sort by.
I am well aware of the

```<code>List.OrderBy(x => x. [...]).ThenBy...
</code>```

Method but my situation is a bit different:

```<code>switch(mySortType)
{
     case SortType.mostVisits:
         clients = clients.OrderBy(x => x. and so on...)
     break;
     More cases with different sortTypes
}
</code>```

And after that I would like to sort after a Boolean parameter, but only if the settings tell the method to do so via another bool.
Ist there a way to say something like

```<code>clients = clients.OrderBy(Current).ThenBy(x => x.param).ToList()?
</code>```

I could of course have an if() in every case

```<code>case SortType.MostVisits:
  if(settingsTellsMeToDoSo)
     clients = clients.OrderBy(x=>x.numberOfVisits).ThenBy(x => x.param).ToList();
  else clients = clients.OrderBy(x => x.numberOfVisits).ToList();
</code>```

and then use the simple ThenBy Method but I thaught that there has to be an easier way to do it.

I hope you got my question right. I am not sure whether or not I was able to explain well enough...

regards,
Eric

答:
Since the problem is to decide which lambda to put into OrderBy (as opposed to the rest of the lambdas, which go into ThenBy) you can use a little trick, and put all your lambdas (or no lambdas if no sorting is to be performed) into ThenBy. Since ThenBy is an extension method on IOrderedEnumerable<T>, you need a way to make a regular enumerable into an ordered enumerable without disturbing the original order.

You can make an IOrderedEnumerable<T> from your IEnumerable<T> (or IOrderedQueryable<T> from IQueryable<T>, depending on your situation) by applying a dummy sort on a constant, like this:

```<code>IOrderedEnumerable<Client> orderdClients = list.OrderBy(c => 1);
</code>```

Now you can apply ThenBy repeatedly as needed. This approach is similar in nature to making a dummy search condition when dealing with a chain of AND operations which may contain zero elements.

Body:
I have a method which sorts a List of Clients.

There are two parameters I want to sort by.
I am well aware of the

List.OrderBy(x => x. [...]).ThenBy...

Method but my situation is a bit different:

switch(mySortType)
{
     case SortType.mostVisits:
         clients = clients.OrderBy(x => x. and so on...)
     break;
     More cases with different sortTypes
}

And after that I would like to sort after a Boolean parameter, but only if the settings tell the method to do so via another bool.
Ist there a way to say something like

clients = clients.OrderBy(Current).ThenBy(x => x.param).ToList()?

I could of course have an if() in every case

case SortType.MostVisits:
  if(settingsTellsMeToDoSo)
     clients = clients.OrderBy(x=>x.numberOfVisits).ThenBy(x => x.param).ToList();
  else clients = clients.OrderBy(x => x.numberOfVisits).ToList();

and then use the simple ThenBy Method but I thaught that there has to be an easier way to do it.

I hope you got my question right. I am not sure whether or not I was able to explain well enough...

regards,
Eric

Body:
Since the problem is to decide which lambda to put into OrderBy (as opposed to the rest of the lambdas, which go into ThenBy) you can use a little trick, and put all your lambdas (or no lambdas if no sorting is to be performed) into ThenBy. Since ThenBy is an extension method on IOrderedEnumerable<T>, you need a way to make a regular enumerable into an ordered enumerable without disturbing the original order.

You can make an IOrderedEnumerable<T> from your IEnumerable<T> (or IOrderedQueryable<T> from IQueryable<T>, depending on your situation) by applying a dummy sort on a constant, like this:

IOrderedEnumerable<Client> orderdClients = list.OrderBy(c => 1);

Now you can apply ThenBy repeatedly as needed. This approach is similar in nature to making a dummy search condition when dealing with a chain of AND operations which may contain zero elements.


问:
C++ 'wrapper class' for XML library
So I've been attempting to create some classes around the xerces XML library so I can 'hide' it from the rest of my project the underlying xml library stays independent from the rest of my project.

This was supposed to be a fairly easy task, however it seems entirely impossible to hide a library from the rest of a project by writing some classes around it.

Have I got the wrong approach or is my 'wrapper' idea completely silly?

I end up with something like this:

```<code>DOMElement* root();  //in my 'wrapper' class, however this DOMElement is part of the xerces library, at this point my 'wrapper' is broken.  Now I have to use the xerces library everywhere I want to use this function.
</code>```

Where is my thinking gone wrong?

答:
Writing your own abstract interface for a library is not a silly idea IF you have plan to change or to have the possibility to change the library you are using.

You should not rely on your library object to implement your wrapper interface. Implement your own structure and your own function interface. It will ease a lot of work when you will want to change how xml is implemented (eg: change library).

One example of implementation:

```<code>class XmlElement
{
    private:
    DOMElement element; // point to the element of your library

    public:
    // Here you define how its public interface.
    // There should be enough method/parameter to interact
    // with any xml interface you will use in the future
    XmlElement getSubElement(param)
    {
        // Create the Xmlelement
        // Set the DOMElement wanted
        // return it
    }
}
</code>```

In your program you will see:

```<code>void function()
{
    XmlElement root();
    root.getSubElement("value"); // for example
}
</code>```

Like that no DOMElement or their function appear in the project.

Title: C++ 'wrapper class' for XML library

Body:
So I've been attempting to create some classes around the xerces XML library so I can 'hide' it from the rest of my project the underlying xml library stays independent from the rest of my project.

This was supposed to be a fairly easy task, however it seems entirely impossible to hide a library from the rest of a project by writing some classes around it.

Have I got the wrong approach or is my 'wrapper' idea completely silly?

I end up with something like this:

DOMElement* root();  //in my 'wrapper' class, however this DOMElement is part of the xerces library, at this point my 'wrapper' is broken.  Now I have to use the xerces library everywhere I want to use this function.

Where is my thinking gone wrong?

Body:
Writing your own abstract interface for a library is not a silly idea IF you have plan to change or to have the possibility to change the library you are using.

You should not rely on your library object to implement your wrapper interface. Implement your own structure and your own function interface. It will ease a lot of work when you will want to change how xml is implemented (eg: change library).

One example of implementation:

class XmlElement
{
    private:
    DOMElement element; // point to the element of your library

    public:
    // Here you define how its public interface.
    // There should be enough method/parameter to interact
    // with any xml interface you will use in the future
    XmlElement getSubElement(param)
    {
        // Create the Xmlelement
        // Set the DOMElement wanted
        // return it
    }
}

In your program you will see:

void function()
{
    XmlElement root();
    root.getSubElement("value"); // for example
}

Like that no DOMElement or their function appear in the project.


问:
Resize a matrix in matlab and keep the same values
I have a 2 dimentional matrix [n,m] containing indices of segmented regions. I need to reshape or resize the matrix in matlab to any size [n',m'] without losing the original values. In other words, I need to extend the segmented regions. I tried to use reshpae, but it did not work since the scale must be similar for both the height and the width. imresize did not work as well because it changes the orignal values.

答:
I tried to solve it without using loops as follows:</p>

```<code>function m1=reshapez(m,sz)

 sa = sz(1) / size(m,1);      % height scale between original matrix and desired one
 sb = sz(2) / size(m,2);      % width scale between original matrix and desired one
 a2 = ceil([1:sz(1)]./sa);    % corresponding indices (x) of the desired matrix in the original one
 b2 = ceil([1:sz(2)]./sb);    % corresponding indices (y) of the desired matrix in the original one
 m1 = m(a2,b2);               % desired matrix
</code>```

Body:
I tried to solve it without using loops as follows:

function m1=reshapez(m,sz)

 sa = sz(1) / size(m,1);      % height scale between original matrix and desired one
 sb = sz(2) / size(m,2);      % width scale between original matrix and desired one
 a2 = ceil([1:sz(1)]./sa);    % corresponding indices (x) of the desired matrix in the original one
 b2 = ceil([1:sz(2)]./sb);    % corresponding indices (y) of the desired matrix in the original one
 m1 = m(a2,b2);               % desired matrix


问:
AWS ELB -> nginx -> socket.io node.js sticky load balancing
I am having an issue with this configuration. My AWS ELB accepts TCP connections on port 80 and forwards them using proxy protocol to an nginx instance listening on port 8080. This nginx node is supposed to use ip_hash module to stick the user to a specific node.

This is working perfectly fine, but only 2 out of the 4 nodes are being used instead of being load balanced among all of them, here is my nginx config

```<code>upstream socket_nodes {
    ip_hash;
    server a.server.com:2000;
    server a.server.com:2001;
    server a.server.com:2002;
    server a.server.com:2003;
}

# Accept connections via the load balancer
server {
  listen 8080 proxy_protocol;
  set_real_ip_from 0.0.0.0/32;
  real_ip_header proxy_protocol;
  charset utf-8;
  location / {
      proxy_pass http://socket_nodes;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
  }
}
</code>```

答: Unlike "round robin" loading balancing, ip_hash means that for any given IP address, NGINX will always forward to the same application instance.</p>

Body:
I am having an issue with this configuration. My AWS ELB accepts TCP connections on port 80 and forwards them using proxy protocol to an nginx instance listening on port 8080. This nginx node is supposed to use ip_hash module to stick the user to a specific node.

This is working perfectly fine, but only 2 out of the 4 nodes are being used instead of being load balanced among all of them, here is my nginx config

upstream socket_nodes {
    ip_hash;
    server a.server.com:2000;
    server a.server.com:2001;
    server a.server.com:2002;
    server a.server.com:2003;
}

# Accept connections via the load balancer
server {
  listen 8080 proxy_protocol;
  set_real_ip_from 0.0.0.0/32;
  real_ip_header proxy_protocol;
  charset utf-8;
  location / {
      proxy_pass http://socket_nodes;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
  }
}


问:
How to get height of Popup after it is set to wrap_content?
Helo,

I've got this popup:

```<code>    // Inflate the popup_layout.xml
    LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View layout = layoutInflater.inflate(R.layout.day_popup_date, viewGroup);

    layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

    int popupWidth = width;
    final int popupHeight = height;

    // Creating the PopupWindow
    final PopupWindow popup = new PopupWindow(context);

    popup.setContentView(layout);
    popup.setWidth(popupWidth);
    popup.setHeight(ListPopupWindow.WRAP_CONTENT);
    popup.setFocusable(false);
</code>```

As you see, popup.setHeight(ListPopupWindow.WRAP_CONTENT); is set to wrap content.

But I want enlarge the popup to 600px if the size is smaller than 100px.

How can I do that?

Thanks :-)

答:
Finally got it:</p>

```<code>    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            if(layout.getMeasuredHeight()> 0){

                layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int heightmeasured = layout.getMeasuredHeight();

                if(heightmeasured < popupHeight) {
                    popup.update(popupWidth, popupHeight);
                }
            }
        }
    });
</code>```

Body:
Helo,

I've got this popup:

    // Inflate the popup_layout.xml
    LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View layout = layoutInflater.inflate(R.layout.day_popup_date, viewGroup);

    layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

    int popupWidth = width;
    final int popupHeight = height;

    // Creating the PopupWindow
    final PopupWindow popup = new PopupWindow(context);

    popup.setContentView(layout);
    popup.setWidth(popupWidth);
    popup.setHeight(ListPopupWindow.WRAP_CONTENT);
    popup.setFocusable(false);

As you see, popup.setHeight(ListPopupWindow.WRAP_CONTENT); is set to wrap content.

But I want enlarge the popup to 600px if the size is smaller than 100px.

How can I do that?

Thanks :-)

Body:
Finally got it:

    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            if(layout.getMeasuredHeight()> 0){

                layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int heightmeasured = layout.getMeasuredHeight();

                if(heightmeasured < popupHeight) {
                    popup.update(popupWidth, popupHeight);
                }
            }
        }
    });


问:
How to use HikariCP in Spring Boot with two datasources in conjunction with Flyway
I want to use HikariCP as JDBC connection pool in my Spring boot application. I have two datasources (MySQL database as the primary database and accessing those data through Hibernate and additionally an Oracle database for reading some other data through JDBCTemplate).

I set the MySQL datasource as primary bean:

```<code>@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties mySQLDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSource mySQLDataSource() {
    return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("oracle.datasource")
public DataSourceProperties oracleDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean(name = "oracleDatabase")
@ConfigurationProperties("oracle.datasource")
public DataSource oracleDataSource() {
    return oracleDataSourceProperties().initializeDataSourceBuilder().build();
}

 @Bean
 public JdbcTemplate oracleJdbcTemplate(@Qualifier("oracleDatabase") DataSource oracleDb) {
     return new JdbcTemplate(oracleDb);
 }
</code>```

and I put the following configurations in my application.properties :

```<code>spring.datasource.type=com.zaxxer.hikari.HikariDataSource

spring.datasource.hikari.minimum-idle=7
spring.datasource.hikari.pool-name=Test-1

spring.datasource.hikari.data-source-properties.prepStmtCacheSize=250
spring.datasource.hikari.data-source-properties.prepStmtCacheSqlLimit=2048
spring.datasource.hikari.data-source-properties.cachePrepStmts=true
spring.datasource.hikari.data-source-properties.useServerPrepStmts=true
</code>```

Unforuntately, these HikariCP configurations are not being read :

```<code> HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - maximumPoolSize.................10
 HikariConfig - metricRegistry..................none
 HikariConfig - metricsTrackerFactory...........none
 HikariConfig - minimumIdle.....................10
 HikariConfig - password........................<masked>
 HikariConfig - poolName........................"HikariPool-1"
</code>```

Creating the HikariCP beans and deactivating the DataSource autoconfiguration and removing  "spring.datasource" :

```<code>@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@SpringBootApplication
@ComponentScan
public class SpringApplication {

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public HikariConfig hikariConfig() {
    return new HikariConfig();
}

@Bean
public DataSource dataSource() {
    return new HikariDataSource(hikariConfig());
}
</code>```

solves my problem :

```<code> HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>, prepStmtCacheSqlLimit=2048, cachePrepStmts=true, useServerPrepStmts=true, prepStmtCacheSize=250}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB?autoReconnect=true"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - poolName........................"Test-1"
</code>```

But then the Flyway showing some weird warnings which were not shown before and I have to create the database Schema manually before running the Spring application, that is : the create schema does not work anymore.

```<code>[WARN ] JdbcTemplate - DB: Can't create database 'test'; database exists (SQL State: HY000 - Error Code: 1007)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.tenant' (SQL State: 42S02 - Error Code: 1051)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.user' (SQL State: 42S02 - Error Code: 1051)
</code>```

My Flyway SQL scripts are plain DDL scripts :

```<code>CREATE SCHEMA IF NOT EXISTS `testSchema` DEFAULT CHARACTER SET utf8 ;

DROP TABLE IF EXISTS `testSchema`.`tenant`;

CREATE TABLE `testSchema`.`tenant` (
  `id` int NOT NULL AUTO_INCREMENT,
</code>```

I think that disabling the Auto-Datasource configuration is not the best solution since Flyway stops creating the schema and showing warnings.  Is there any other way to solve this ?

答:
Declaring your own DataSource will already have implicity disabled Spring Boot's auto-configuration of a data source. In other words this won't be having any effect:

```<code>@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
</code>```

I think the problem lies in the fact that you aren't binding Hikari-specific configuration to your MySQL DataSource. You need to do something like this:

```<code>@Bean
@Primary
@ConfigurationProperties("spring.datasource.hikari")
public DataSource mySQLDataSource() {
    return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
}
</code>```

This will mean that your mySQLDataSourceProperties are configured with general-purpose data source configuration. They then create a HikariDataSource which is further configured with the Hikari-specific configuration.

Body:
I want to use HikariCP as JDBC connection pool in my Spring boot application. I have two datasources (MySQL database as the primary database and accessing those data through Hibernate and additionally an Oracle database for reading some other data through JDBCTemplate).

I set the MySQL datasource as primary bean:

@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties mySQLDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSource mySQLDataSource() {
    return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("oracle.datasource")
public DataSourceProperties oracleDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean(name = "oracleDatabase")
@ConfigurationProperties("oracle.datasource")
public DataSource oracleDataSource() {
    return oracleDataSourceProperties().initializeDataSourceBuilder().build();
}

 @Bean
 public JdbcTemplate oracleJdbcTemplate(@Qualifier("oracleDatabase") DataSource oracleDb) {
     return new JdbcTemplate(oracleDb);
 }

and I put the following configurations in my application.properties :

spring.datasource.type=com.zaxxer.hikari.HikariDataSource

spring.datasource.hikari.minimum-idle=7
spring.datasource.hikari.pool-name=Test-1

spring.datasource.hikari.data-source-properties.prepStmtCacheSize=250
spring.datasource.hikari.data-source-properties.prepStmtCacheSqlLimit=2048
spring.datasource.hikari.data-source-properties.cachePrepStmts=true
spring.datasource.hikari.data-source-properties.useServerPrepStmts=true

Unforuntately, these HikariCP configurations are not being read :

 HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - maximumPoolSize.................10
 HikariConfig - metricRegistry..................none
 HikariConfig - metricsTrackerFactory...........none
 HikariConfig - minimumIdle.....................10
 HikariConfig - password........................<masked>
 HikariConfig - poolName........................"HikariPool-1"

Creating the HikariCP beans and deactivating the DataSource autoconfiguration and removing  "spring.datasource" :

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
@SpringBootApplication
@ComponentScan
public class SpringApplication {

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public HikariConfig hikariConfig() {
    return new HikariConfig();
}

@Bean
public DataSource dataSource() {
    return new HikariDataSource(hikariConfig());
}

solves my problem :

 HikariConfig - dataSourceJNDI..................none
 HikariConfig - dataSourceProperties............{password=<masked>, prepStmtCacheSqlLimit=2048, cachePrepStmts=true, useServerPrepStmts=true, prepStmtCacheSize=250}
 HikariConfig - driverClassName................."com.mysql.jdbc.Driver"
 HikariConfig - healthCheckProperties...........{}
 HikariConfig - healthCheckRegistry.............none
 HikariConfig - idleTimeout.....................600000
 HikariConfig - initializationFailFast..........true
 HikariConfig - initializationFailTimeout.......1
 HikariConfig - isolateInternalQueries..........false
 HikariConfig - jdbc4ConnectionTest.............false
 HikariConfig - jdbcUrl........................."jdbc:mysql://localhost:3306/testDB?autoReconnect=true"
 HikariConfig - leakDetectionThreshold..........0
 HikariConfig - maxLifetime.....................1800000
 HikariConfig - poolName........................"Test-1"

But then the Flyway showing some weird warnings which were not shown before and I have to create the database Schema manually before running the Spring application, that is : the create schema does not work anymore.

[WARN ] JdbcTemplate - DB: Can't create database 'test'; database exists (SQL State: HY000 - Error Code: 1007)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.tenant' (SQL State: 42S02 - Error Code: 1051)
[WARN ] JdbcTemplate - DB: Unknown table 'testSchema.user' (SQL State: 42S02 - Error Code: 1051)

My Flyway SQL scripts are plain DDL scripts :

CREATE SCHEMA IF NOT EXISTS `testSchema` DEFAULT CHARACTER SET utf8 ;

DROP TABLE IF EXISTS `testSchema`.`tenant`;

CREATE TABLE `testSchema`.`tenant` (
  `id` int NOT NULL AUTO_INCREMENT,

I think that disabling the Auto-Datasource configuration is not the best solution since Flyway stops creating the schema and showing warnings.  Is there any other way to solve this ?

Body:
Declaring your own DataSource will already have implicity disabled Spring Boot's auto-configuration of a data source. In other words this won't be having any effect:

@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})

I think the problem lies in the fact that you aren't binding Hikari-specific configuration to your MySQL DataSource. You need to do something like this:

@Bean
@Primary
@ConfigurationProperties("spring.datasource.hikari")
public DataSource mySQLDataSource() {
    return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
}

This will mean that your mySQLDataSourceProperties are configured with general-purpose data source configuration. They then create a HikariDataSource which is further configured with the Hikari-specific configuration.


问:
SELECT STATMENT IN OR LIKE OR REGEXP
I have a table new_table

```<code>ID            DESCRIPTION
1             abdad jadjnd kandkadn 01/19-P-154-37
2             jscbsjc jscnscj 01/19-H-443-38 sbjcj sjcnjscn
3             scjbcs sc, scnsc 01/19-P-16-39 sjcbnjcs
4             scbcsjc 01/19-K-139-40 hcbchsb
</code>```

AND LISTS

```<code>01/19-P-154-37
01/19-H-443-38
01/19-K-139-40
</code>```

I want to

```<code>select * from new_table where descriptin in (
01/19-P-154-37
01/19-H-443-38
01/19-P-16-39
01/19-K-139-40
)
</code>```

OR LIKE I don't now please help

答:
I guess you want something like this (join with like operator):</p>

```<code>with new_table (ID,            DESCRIPTION) as (
    select 1 ,'abdad jadjnd kandkadn 01/19-P-154-37' from dual union all
    select 2 ,'jscbsjc jscnscj 01/19-H-443-38 sbjcj sjcnjscn' from dual union all
    select 3 ,'scjbcs sc, scnsc 01/19-P-16-39 sjcbnjcs' from dual union all
    select 4 ,'scbcsjc 01/19-K-139-40 hcbchsb' from dual
) ,
LISTS(val) as(
    select '01/19-P-154-37' from dual union all
    select '01/19-H-443-38' from dual union all
    select '01/19-K-139-40' from dual
)

-- Below is actual query:

select new_table.* from new_table
inner join LISTS
on new_table.DESCRIPTION   like '%'||LISTS.val||'%'
</code>```

Title: SELECT STATMENT IN OR LIKE OR REGEXP

Body:
I have a table new_table

ID            DESCRIPTION
1             abdad jadjnd kandkadn 01/19-P-154-37
2             jscbsjc jscnscj 01/19-H-443-38 sbjcj sjcnjscn
3             scjbcs sc, scnsc 01/19-P-16-39 sjcbnjcs
4             scbcsjc 01/19-K-139-40 hcbchsb

AND LISTS

01/19-P-154-37
01/19-H-443-38
01/19-K-139-40

I want to

select * from new_table where descriptin in (
01/19-P-154-37
01/19-H-443-38
01/19-P-16-39
01/19-K-139-40
)

OR LIKE I don't now please help

Body:
I guess you want something like this (join with like operator):

with new_table (ID,            DESCRIPTION) as (
    select 1 ,'abdad jadjnd kandkadn 01/19-P-154-37' from dual union all
    select 2 ,'jscbsjc jscnscj 01/19-H-443-38 sbjcj sjcnjscn' from dual union all
    select 3 ,'scjbcs sc, scnsc 01/19-P-16-39 sjcbnjcs' from dual union all
    select 4 ,'scbcsjc 01/19-K-139-40 hcbchsb' from dual
) ,
LISTS(val) as(
    select '01/19-P-154-37' from dual union all
    select '01/19-H-443-38' from dual union all
    select '01/19-K-139-40' from dual
)

-- Below is actual query:

select new_table.* from new_table
inner join LISTS
on new_table.DESCRIPTION   like '%'||LISTS.val||'%'


问:
preventDefault() stops form validation
having a problem with browser form validation using .preventDefault()

Is there a way to let browser check validation of required inputs, but stops submit?

Is there any flags I can use to get if form is valid?

Thanks

update:
using both backbone and jquery

```<code>events: {
    "click #commentFormSubmit": "commentFormSubmit",
},
commentFormSubmit: function(el){
    el.preventDefault();
    var $el = $(el.target).parent();

    // this.$el.find('button').prop('disabled', true).addClass('disabled');
    var commentData = {};
    commentData.name = this.$el.find('input[name=comment_name]').val();
    commentData.country = this.$el.find('input[name=comment_country]').val();
    commentData.email = this.$el.find('input[name=comment_email]').val();
    commentData.comment = this.$el.find('textarea[name=comment_text]').val();
    commentData.grade = this.$el.find('.commnt_grade:checked').val();
    console.log('dd')
    this.model.onSubmitComment(commentData);
},
</code>```

and the form:

```<code>    <form action="" class="" method="post">
        <span>
            <input type="text" name="comment_name" class="comment_input" placeholder="{{ 'your name'|_ }}" required>
            <input type="text" name="comment_country" class="comment_input" placeholder="{{ 'country'|_ }}">
            <input type="text" name="comment_email" class="comment_input" placeholder="{{ 'your email'|_ }}" required>
        </span>

        <textarea name="comment_text" id="comment_text" cols="30" rows="10" placeholder="{{ 'your comment'|_ }}" required></textarea>
        <span class="grades">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_1" value="1">
            <label for="grade_1" class="selectGrades" data-eq="1"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_2" value="2">
            <label for="grade_2" class="selectGrades" data-eq="2"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_3" value="3">
            <label for="grade_3" class="selectGrades" data-eq="3"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_4" value="4">
            <label for="grade_4" class="selectGrades" data-eq="4"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_5" value="5">
            <label for="grade_5" class="selectGrades" data-eq="5"></label>
        </span>
        <button type="submit" id="commentFormSubmit">{{ 'submit'|_ }}</button>

    </form>
</code>```

答:
Thanks for @T.J. Crowder for the direction.
as for me it's a fix, not a solution.

```<code>commentFormSubmit: function(el){
    var $el = $(el.target).parent();
    if ($el[0].checkValidity()){
        el.preventDefault();
        // this.$el.find('button').prop('disabled', true).addClass('disabled');
        var commentData = {};
        commentData.name = this.$el.find('input[name=comment_name]').val();
        commentData.country = this.$el.find('input[name=comment_country]').val();
        commentData.email = this.$el.find('input[name=comment_email]').val();
        commentData.comment = this.$el.find('textarea[name=comment_text]').val();
        commentData.grade = this.$el.find('.commnt_grade:checked').val();
        // this.model.onSubmitComment(commentData);
    }
    else $el[0].reportValidity();
},
</code>```

Again, thanks!

Title: preventDefault() stops form validation

Body:
having a problem with browser form validation using .preventDefault()

Is there a way to let browser check validation of required inputs, but stops submit?

Is there any flags I can use to get if form is valid?

Thanks

update:
using both backbone and jquery

events: {
    "click #commentFormSubmit": "commentFormSubmit",
},
commentFormSubmit: function(el){
    el.preventDefault();
    var $el = $(el.target).parent();

    // this.$el.find('button').prop('disabled', true).addClass('disabled');
    var commentData = {};
    commentData.name = this.$el.find('input[name=comment_name]').val();
    commentData.country = this.$el.find('input[name=comment_country]').val();
    commentData.email = this.$el.find('input[name=comment_email]').val();
    commentData.comment = this.$el.find('textarea[name=comment_text]').val();
    commentData.grade = this.$el.find('.commnt_grade:checked').val();
    console.log('dd')
    this.model.onSubmitComment(commentData);
},

and the form:

    <form action="" class="" method="post">

            <input type="text" name="comment_name" class="comment_input" placeholder="{{ 'your name'|_ }}" required>
            <input type="text" name="comment_country" class="comment_input" placeholder="{{ 'country'|_ }}">
            <input type="text" name="comment_email" class="comment_input" placeholder="{{ 'your email'|_ }}" required>

        <textarea name="comment_text" id="comment_text" cols="30" rows="10" placeholder="{{ 'your comment'|_ }}" required></textarea>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_1" value="1">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_2" value="2">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_3" value="3">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_4" value="4">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_5" value="5">

        <button type="submit" id="commentFormSubmit">{{ 'submit'|_ }}</button>

    </form>

Body:
Thanks for @T.J. Crowder for the direction.
as for me it's a fix, not a solution.

commentFormSubmit: function(el){
    var $el = $(el.target).parent();
    if ($el[0].checkValidity()){
        el.preventDefault();
        // this.$el.find('button').prop('disabled', true).addClass('disabled');
        var commentData = {};
        commentData.name = this.$el.find('input[name=comment_name]').val();
        commentData.country = this.$el.find('input[name=comment_country]').val();
        commentData.email = this.$el.find('input[name=comment_email]').val();
        commentData.comment = this.$el.find('textarea[name=comment_text]').val();
        commentData.grade = this.$el.find('.commnt_grade:checked').val();
        // this.model.onSubmitComment(commentData);
    }
    else $el[0].reportValidity();
},

Again, thanks!


问:
Accept Privacy Policy Contact Form-7 in two lines
I have an acceptance button with my contact form 7 plugin, but it is separating the button from the linked text in two different lines. How can I fix this?

```<code>> <div class="align-center"> [acceptance acceptance-564 ]<a
> href="http://www.jornadasdeldeportelarobla.com/aviso-legal/">Acepto la
> Política de Privacidad</a> </div>
</code>```

That´s the code I am using to create the contact form and this is a picture of how it looks:

enter image description here

Thank you!

答:
I've got same problem. I solved with these:

HTML (Edit Contact Form)

 [acceptance acceptance-443] Acconsento al trattamento dei dati personali D.Lgs. 196/2003 (link di approfondimento)

then I put in CSS these code

.wpcf7-form-control-wrap { display: inline!important; }

enter image description here

Body:
I have an acceptance button with my contact form 7 plugin, but it is separating the button from the linked text in two different lines. How can I fix this?

>
 [acceptance acceptance-564 ] href="http://www.jornadasdeldeportelarobla.com/aviso-legal/">Acepto la
> Política de Privacidad

That´s the code I am using to create the contact form and this is a picture of how it looks:

enter image description here

Thank you!

Body:
I've got same problem. I solved with these:

HTML (Edit Contact Form)

<div class="acceptance-container"> [acceptance acceptance-443] Acconsento al trattamento dei dati personali D.Lgs. 196/2003 (<a href="#">link</a> di approfondimento) <br /></div>

then I put in CSS these code

.wpcf7-form-control-wrap { display: inline!important; }

enter image description here


问:
Value contains many text in Conditional Format Rules Google Sheet
I want to set conditional format rules in my Google spreadsheet. For the format cell, I select "Text contains", then I type values "PA, MA, CT, NY", formatting style I choose red. When I click DONE, the columns containing these words didn't show the color. I don't want to create rules "PA', "MA", "CT"and "NY" one by one. How can I fix them? Thanks for helping.</p>

答:
Select the relevant range (I am assuming starts at A1) and clear any existing CF rules from it. Format, Conditional formatting..., Format cells if... Custom formula is and:

```<code>=regexmatch(A1,"PA|MA|CT|NY")
</code>```

with red fill and Done.

This should format any cells that contain any of the four state abbreviations (that is, both as part of the content of a cell and as all the content of the cell). It should format PACT but being case sensitive not many.

Body:
Select the relevant range (I am assuming starts at A1) and clear any existing CF rules from it. Format, Conditional formatting..., Format cells if... Custom formula is and:

=regexmatch(A1,"PA|MA|CT|NY")

with red fill and Done.

This should format any cells that contain any of the four state abbreviations (that is, both as part of the content of a cell and as all the content of the cell). It should format PACT but being case sensitive not many.


问:
Targetting server control in ASP.NET and jQuery
I am not able to find the answer in already created threads. Is

$(<%=txtRating.ClientID%>).val("Set the value");

equivalent to

```<code>$("#<%=txtRating.ClientID%>").val("Set the value");
</code>```

? Both are working just fine, so is there any difference? Thank you.

答:
Both work because the browser is automatically creating a variable for each tag id in order to follow HTML5 standard. See http://2ality.com/2012/08/ids-are-global.html

Your code:

```<code>$(<%=txtRating.ClientID%>).val("Set the value");
$("#<%=txtRating.ClientID%>").val("Set the value2");
</code>```

Renders this Javascript on the resulting HTML page:

```<code>$(txtRating).val("Set the value");
$("#txtRating").val("Set the value2");
</code>```

The first one works because:

The HTML5 standard specifies that the window object must have a property key whose value is elem if there is exactly one DOM element elem whose property id has the value key.

For example, given this HTML:

```<code><div id="foo"></div>
</code>```

You can get the HTML tag by using the id as a variable. Hence $(foo) returns jQuery object for that tag. Same as $('#foo') that also returns jQuery object for same tag.

```<code>> "foo" in window
true

> foo
<div id="foo"></div>

> $(foo)
Object [ <div#foo> ]

> $('#foo')
Object [ <div#foo> ]
</code>```

Body:
I am not able to find the answer in already created threads. Is

$(<%=txtRating.ClientID%>).val("Set the value");

equivalent to

$("#<%=txtRating.ClientID%>").val("Set the value");

? Both are working just fine, so is there any difference? Thank you.

Body:
Both work because the browser is automatically creating a variable for each tag id in order to follow HTML5 standard. See http://2ality.com/2012/08/ids-are-global.html

Your code:

$(<%=txtRating.ClientID%>).val("Set the value");
$("#<%=txtRating.ClientID%>").val("Set the value2");

Renders this Javascript on the resulting HTML page:

$(txtRating).val("Set the value");
$("#txtRating").val("Set the value2");

The first one works because:

The HTML5 standard specifies that the window object must have a property key whose value is elem if there is exactly one DOM element elem whose property id has the value key.

For example, given this HTML:

<div id="foo"></div>

You can get the HTML tag by using the id as a variable. Hence $(foo) returns jQuery object for that tag. Same as $('#foo') that also returns jQuery object for same tag.

> "foo" in window
true

> foo
<div id="foo"></div>

> $(foo)
Object [ <div#foo> ]

> $('#foo')
Object [ <div#foo> ]


问:
Angular - Disable next button when at end of array
I'm trying to have my previous button be disabled whenever you're at the beginning of an array and my next button be disabled whenever you've reached the end of the array. The user will select an employee from a combo box which will get the index of the selected employee into a variable named selectedEmployee. I have gotten the previous button to work but not the next button for some reason.

Here's my tracker.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[];
    ptoData: PTOData[];
    isHidden: boolean = false;

    public selectedEmployee: number = 0;
    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
            );
    }

    getPTOData(): void {
        this.ptoDataService.getPTODatas().then(
            ptoData => this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee+1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee-1;
    }

    isPreviousValid() {
        if (this.selectedEmployee > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    isNextValid() {
        if (this.selectedEmployee < EmpInfo.length) {
            return true;
        }
        else {
            return false;
        }
    }
}```
</div>
</div>
</p>

<p>and here's a snippet of my html where i'm trying to implement it:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <button [disabled]="isNextValid()"class="form-control" style="width: 150px;" (click)="nextEmployee()">Next</button>
    <button [disabled]="!isPreviousValid()" class="form-control" style="width: 150px;" (click)="previousEmployee()">Previous</button></code>```

答:
You have to use variable name empInfo instead of class name. Please check below code

```<code>isNextValid() {
    if (this.selectedEmployee < this.empInfo.length) {
        return true;
    }
    else {
        return false;
    }
}
</code>```

Body:
I'm trying to have my previous button be disabled whenever you're at the beginning of an array and my next button be disabled whenever you've reached the end of the array. The user will select an employee from a combo box which will get the index of the selected employee into a variable named selectedEmployee. I have gotten the previous button to work but not the next button for some reason.

Here's my tracker.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[];
    ptoData: PTOData[];
    isHidden: boolean = false;

    public selectedEmployee: number = 0;
    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
            );
    }

    getPTOData(): void {
        this.ptoDataService.getPTODatas().then(
            ptoData => this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }

    nextEmployee(): void {
        this.selectedEmployee = this.selectedEmployee+1;
    }

    previousEmployee(): void {
        this.selectedEmployee = this.selectedEmployee-1;
    }

    isPreviousValid() {
        if (this.selectedEmployee > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    isNextValid() {
        if (this.selectedEmployee < EmpInfo.length) {
            return true;
        }
        else {
            return false;
        }
    }
}

and here's a snippet of my html where i'm trying to implement it:

    <button [disabled]="isNextValid()"class="form-control" style="width: 150px;" (click)="nextEmployee()">Next</button>
    <button [disabled]="!isPreviousValid()" class="form-control" style="width: 150px;" (click)="previousEmployee()">Previous</button>

Body:
You have to use variable name empInfo instead of class name. Please check below code

isNextValid() {
    if (this.selectedEmployee < this.empInfo.length) {
        return true;
    }
    else {
        return false;
    }
}


问:
How to write a switch statement with do-syntax?
Syntactically, how can I write a switch statement using do expressions?

e.g. this:

```<code><div>
{do{
    switch(foo) {
      case 'a':
          <Bar/>
        case 'b':
          <Baz/>
    }
}}
</div>
</code>```

comes out as

```<code>'use strict';

React.createElement(
  'div',
  null,
  function () {
    switch (foo) {
      case 'a':
        React.createElement(Bar, null);
      case 'b':
        React.createElement(Baz, null);
    }
  }()
);
</code>```

REPL

Note the lack of returns in the output -- i.e., it's useless. Babel won't let me add returns to the source though. Is it even possible to use switches inside of a do exppression?

答:
This doesn't work probably because switch is not an expression (but neither is if, so I don't know, it might be just a bug in Babel). A workaround for this is to assign the value to some variable and place it at the and of the do block (remember to add breaks too):

```<code><div>
{do{
    let r;
    switch(foo) {
      case 'a':
          r = <Bar/>
          break;
        case 'b':
          r = <Baz/>
          break;
    }
    r;
}}
</div>
</code>```

Body:
Syntactically, how can I write a switch statement using do expressions?

e.g. this:

{do{
    switch(foo) {
      case 'a':
          <Bar/>
        case 'b':
          <Baz/>
    }
}}

comes out as

'use strict';

React.createElement(
  'div',
  null,
  function () {
    switch (foo) {
      case 'a':
        React.createElement(Bar, null);
      case 'b':
        React.createElement(Baz, null);
    }
  }()
);

<a href="https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=env%2Creact%2Cstage-0&targets=Node-8&browsers=&builtIns=false&debug=false&experimental=true&loose=true&spec=false&code=%3Cdiv%3E%0A%7Bdo%7B%0A%20%20%20%20switch(foo)%20%7B%0A%20%20%20%20%20%20case%20'a'%3A%0A%20%20%20%20%20%20%20%20%20%20%3CBar%2F%3E%0A%20%20%20%20%20%20%20%20case%20'b'%3A%0A%20%20%20%20%20%20%20%20%20%20%3CBaz%2F%3E%0A%20%20%20%20%7D%0A%7D%7D%0A%3C%2Fdiv%3E" rel="nofollow noreferrer">REPL

Note the lack of returns in the output -- i.e., it's useless. Babel won't let me add returns to the source though. Is it even possible to use switches inside of a do exppression?

Body:
This doesn't work probably because switch is not an expression (but neither is if, so I don't know, it might be just a bug in Babel). A workaround for this is to assign the value to some variable and place it at the and of the do block (remember to add breaks too):

<div>
{do{
    let r;
    switch(foo) {
      case 'a':
          r = <Bar/>
          break;
        case 'b':
          r = <Baz/>
          break;
    }
    r;
}}
</div>


问:
Can a private channel communication happen between two Pusher Apps
I have two iOS apps, lets call it Agent app and Customer App.
I have a chat feature between these two apps, but the chats need to be recorded on the server.

I have created two Pusher Apps, one for each of the iOS apps. They both subscribe to their respective private-{id}-channel.

Now every time a message is generated from say Agent app (via HTTP request to server), I want server to create a pusher event with Agent's message on Customer's private channel.

Is it possible to achieve the above using Pusher Private channels?

答:
One way you could achieve this is by having both users join the same channel.

Let's say you have two users: user-a and user-b. Both users subscribe to a common private channel private-chat-user-a-user-b.

```<code>let myChannel = pusher.subscribe("private-chat-user-a-user-b")
</code>```

Then triggering client events on the channel

```<code>myChannel.trigger(eventName: "client-my-event", data: ["your": "data"])
</code>```

Client events are a way of sending messages just between clients, without a server relaying them.

Disclosure: I work at pusher.

Body:
One way you could achieve this is by having both users join the same channel.

Let's say you have two users: user-a and user-b. Both users subscribe to a common private channel private-chat-user-a-user-b.

let myChannel = pusher.subscribe("private-chat-user-a-user-b")

Then triggering client events on the channel

myChannel.trigger(eventName: "client-my-event", data: ["your": "data"])

Client events are a way of sending messages just between clients, without a server relaying them.

Disclosure: I work at pusher.


问:
How can I make /etc/hosts writable by root in a Docker Container?
I'm new to using docker and am configuring a container.

I am unable to edit /etc/hosts (but need to for some software I'm developing). Auto-edit (via sudo or root) of the file says its on a read only file system.  Manual (vim) edit of the file says its read-only and I'm unable to save changes as root (file permissions are rw for owner (root)).

I can however modify other files and add files in /etc.

Is there some reason for this?

Can I change the Docker configuration to allow edit of /etc/hosts?

thanks

答:
I have recently stumbled upon a need to add an entry into /etc/hosts file as well (in order to make sendmail working).

I ended up making it part of the Dockerfile's CMD declaration like this:

```<code>CMD echo "127.0.0.1 noreply.example.com $(hostname)" >> /etc/hosts \
    && sendmailconfig \
    && cron -f
</code>```

So it effectively is not a part of the image, but it is always available after creating a container from the image.

Body:
I have recently stumbled upon a need to add an entry into /etc/hosts file as well (in order to make sendmail working).

I ended up making it part of the Dockerfile's CMD declaration like this:

CMD echo "127.0.0.1 noreply.example.com $(hostname)" >> /etc/hosts \
    && sendmailconfig \
    && cron -f

So it effectively is not a part of the image, but it is always available after creating a container from the image.


问:
Handle udefined or null in child component in reactjs
I have a parent and a child component. Say

```<code>Parent{
    render(){
       return(
          <Child1 />
          <Child2 list={this.state.value}/>
       )
    }
}
</code>```

Now my problem is my when my control reaches Child2,props.list will always come null and when my i will click my selectbox from Child1 then state will get populated and hence list in child2.

The problem that i am facing is when the control first reaches child2 the console in browser shows list is not defined and it breaks and nothing is being rendered in my child1.How to handle this scenerio?

Also

is there a way that i can put some condition on child2 that if state is loaded only then it should be rendered?

答:
If it is throwing the error that props.list is null then you need to handle this case inside Child2 component by putting the check on the value of this.props.list. Like this:

```<code>class Child2 extends React.Component{

   render(){
       console.log(this.props.list)
       if(this.props.list)
           return <div>
                {this.props.list}
                /*other code*/
           </div>
       return null;
   }

}
</code>```

If Child2 contains proper list value then only render the complete component.

Or if you want to render something instead of null then replace the null part by some other component:

```<code>class Child2 extends React.Component{

   render(){
       console.log(this.props.list)
       if(this.props.list)
           return <div>
                {this.props.list}
                /*other code*/
           </div>
       return <div>No content</div>
   }

}
</code>```

Body:
I have a parent and a child component. Say

Parent{
    render(){
       return(
          <Child1 />
          <Child2 list={this.state.value}/>
       )
    }
}

Now my problem is my when my control reaches Child2,props.list will always come null and when my i will click my selectbox from Child1 then state will get populated and hence list in child2.

The problem that i am facing is when the control first reaches child2 the console in browser shows list is not defined and it breaks and nothing is being rendered in my child1.How to handle this scenerio?

Also

is there a way that i can put some condition on child2 that if state is loaded only then it should be rendered?

Body:
If it is throwing the error that props.list is null then you need to handle this case inside Child2 component by putting the check on the value of this.props.list. Like this:

class Child2 extends React.Component{

   render(){
       console.log(this.props.list)
       if(this.props.list)
           return <div>
                {this.props.list}
                /*other code*/
           </div>
       return null;
   }

}

If Child2 contains proper list value then only render the complete component.

Or if you want to render something instead of null then replace the null part by some other component:

class Child2 extends React.Component{

   render(){
       console.log(this.props.list)
       if(this.props.list)
           return <div>
                {this.props.list}
                /*other code*/
           </div>
       return <div>No content</div>
   }

}


问:
IndexedDb - fetching the last-added item from an ObjectStore
Given an object store, how can I go about fetching the latest item from that store without introducing an additional index?  I'm using a guid as a keypath so leveraging auto-incrementing keys is not possible.

答:
There is nothing in the IndexedDB API that will provide this directly. You'll need to build it yourself, either by using an index or manually tracking the most recent insertion.

There are several approaches:

Add an insertion timestamp property to the record, and index on it.

Change the primary key for the object store to be autoincremented, and use an index on the guid instead for lookups.

Have another store (or just a different part of the key space) record the primary key of the last inserted item.


问:
Loading table from Cloud Storage to BigQuery using Python
Could someone share an example of a job config for uploading json newline_delimited file to a new Bigquery table, please?

Trying to do this based on google docs with no success so far.

答:
This example from GCP repository is a good one for loading data from GCS.

The only thing you will have to adapt in your code is setting the job.source_format to be the new delimited json file, like so:

```<code>def load_data_from_gcs(dataset_name, table_name, source):
    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset_name)
    table = dataset.table(table_name)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, source)

    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()

    wait_for_job(job)

    print('Loaded {} rows into {}:{}.'.format(
        job.output_rows, dataset_name, table_name))
</code>```

(The correct thing would be to receive this parameter as input in your function but this works as an example).

Also, the table should already exist when you run this code (I looked for schema auto-detection in the Python API but it seems there isn't one yet).

Body:
This example from GCP repository is a good one for loading data from GCS.

The only thing you will have to adapt in your code is setting the job.source_format to be the new delimited json file, like so:

def load_data_from_gcs(dataset_name, table_name, source):
    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset_name)
    table = dataset.table(table_name)
    job_name = str(uuid.uuid4())

    job = bigquery_client.load_table_from_storage(
        job_name, table, source)

    job.source_format = 'NEWLINE_DELIMITED_JSON'
    job.begin()

    wait_for_job(job)

    print('Loaded {} rows into {}:{}.'.format(
        job.output_rows, dataset_name, table_name))

(The correct thing would be to receive this parameter as input in your function but this works as an example).

Also, the table should already exist when you run this code (I looked for schema auto-detection in the Python API but it seems there isn't one yet).


问:
How do I create a public default constructor and an overloaded constructor?
I am extremely new to Java and coding in general. I am working on a project where I have created two interfaces and am now creating a concrete class named VehicleChassis that implements my Chassis interface. First, I created a String named chassisName instance variable. Now, I need to create a default constructor and overloaded constructor with the following value - A String with a parameter value of chassisName. I have searched the Internet on how to do both, but I am so confused. Help!

Below is the code I have so far.

```<code>public abstract class VehicleChassis implements Chassis{
public String chassisName;
}
</code>```

答: A class which is labelled as abstract could not be instantiate directly. so we don't need to create constructor and overloaded constructor.</p>

Body:
I am extremely new to Java and coding in general. I am working on a project where I have created two interfaces and am now creating a concrete class named VehicleChassis that implements my Chassis interface. First, I created a String named chassisName instance variable. Now, I need to create a default constructor and overloaded constructor with the following value - A String with a parameter value of chassisName. I have searched the Internet on how to do both, but I am so confused. Help!

Below is the code I have so far.

public abstract class VehicleChassis implements Chassis{
public String chassisName;
}


问:
Microsoft Word VBA multiple addresses - text box
Apologies in advance if this is already a question.

I've developed a user form to auto populate some of the letters we send to stakeholders. I currently have an address section in the userform  - textboxstreet textboxsuburb etc.
User form

in certain circumstances I need to have:

```<code>Address A - the address we are sending the letter to
and
Address B - the address we sent the letter to previously
</code>```

For example:

```<code>John Smith
15 Madeup Street
Faketown Australia
</code>```

this is a follow up letter to advise we have sent your previous letter to 33 Fake Place Nowhere Australia.

My conclusion is that I obviously need an Address A section and an Address B section to break the addresses up. Is there a way though - if address a and address b are the same, that address a populates at the bookmarks set for Address B?

eg:

If address' are different:

```<code>(bookmarkaddressA) = textboxaddressA
(bookmarkaddressB) = textboxaddressB
</code>```

If address' are the same:

```<code>(bookmarkaddressA) = textboxaddressA
(bookmarkaddressB) = textboxaddressA
</code>```

Ideally I would like it to function like the
"is the postal address the same as the residential address?" checkbox - and just grey out/lock textboxaddressb and fill the info from textboxaddressa

Any suggestions welcome.

full code:

```<code>    Option Explicit

Private Sub CheckBox1_Click()
If (CheckBox1.Value = True) Then TextBoxStreet2 = TextBoxStreet
If (CheckBox1.Value = True) Then TextBoxSuburb2 = TextBoxSuburb
If (CheckBox1.Value = True) Then TextBoxPostcode2 = TextBoxpostcode
If (CheckBox1.Value = True) Then ComboBoxState2 = ComboBoxState
If (CheckBox1.Value = False) Then TextBoxStreet2 = Null
If (CheckBox1.Value = False) Then TextBoxSuburb2 = Null
If (CheckBox1.Value = False) Then TextBoxPostcode2 = Null
If (CheckBox1.Value = False) Then ComboBoxState2 = Null
End Sub

Private Sub ComboBoxTitle_Change()

End Sub

Private Sub CommandButtonCancel_Click()
    Unload Me
End Sub

Private Sub CommandButtonClear_Click()
TextBoxFN.Value = Null
TextBoxGN.Value = Null
ComboBoxState.Value = Null
ComboBoxTitle.Value = Null
TextBoxStreet.Value = Null
TextBoxSuburb.Value = Null
TextBoxpostcode.Value = Null
TextBoxCD.Value = Null
TextboxMPN.Value = Null
TextBoxMPDD.Value = Null
TextBoxNPN.Value = Null
TextBoxNPDD.Value = Null
ComboBoxState2.Value = Null
TextBoxStreet2.Value = Null
TextBoxSuburb2.Value = Null
TextBoxPostcode2.Value = Null
CheckBox1.Value = False
End Sub

Private Sub CommandButtonOk_Click()
    Application.ScreenUpdating = False
    With ActiveDocument
        .Bookmarks("Title").Range.Text = ComboBoxTitle.Value
        .Bookmarks("GN").Range.Text = TextBoxGN.Value
        .Bookmarks("FN").Range.Text = TextBoxFN.Value
        .Bookmarks("FN2").Range.Text = TextBoxFN.Value
        .Bookmarks("Street").Range.Text = TextBoxStreet.Value
        .Bookmarks("Suburb").Range.Text = TextBoxSuburb.Value
        .Bookmarks("State").Range.Text = ComboBoxState.Value
        .Bookmarks("PostCode").Range.Text = TextBoxpostcode.Value
        .Bookmarks("Street2").Range.Text = TextBoxStreet2.Value
        .Bookmarks("Suburb2").Range.Text = TextBoxSuburb2.Value
        .Bookmarks("State2").Range.Text = ComboBoxState2.Value
        .Bookmarks("PostCode2").Range.Text = TextBoxPostcode2.Value
        .Bookmarks("CD").Range.Text = TextBoxCD.Value
        .Bookmarks("MPN").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN2").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN3").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN4").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN5").Range.Text = TextboxMPN.Value
        .Bookmarks("MPDD").Range.Text = TextBoxMPDD.Value
        .Bookmarks("NPN").Range.Text = TextBoxNPN.Value
        .Bookmarks("NPDD").Range.Text = TextBoxNPDD.Value
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    With ComboBoxState
        .AddItem "QLD"
        .AddItem "NSW"
        .AddItem "ACT"
        .AddItem "VIC"
        .AddItem "TAS"
        .AddItem "SA"
        .AddItem "WA"
        .AddItem "NT"
    End With
    With ComboBoxTitle
        .AddItem "Mr"
        .AddItem "Mrs"
        .AddItem "Miss"
        .AddItem "Ms"
    End With
lbl_Exit:
    Exit Sub
End Sub

Private Sub TextBoxMPN_Change()
    TextboxMPN = UCase(TextboxMPN)
End Sub

Private Sub TextBoxNPN_Change()
    TextBoxNPN = UCase(TextBoxNPN)
End Sub

Private Sub TextBoxFN_Change()
    TextBoxFN = UCase(TextBoxFN)
End Sub
</code>```

答:
Since you asked, this is what i might have done (some code not included for clarity):</p>

```<code>'disable "address B" controls is user selects to use same address for both
Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(TextBoxStreet2, TextBoxSuburb2, _
                          ComboBoxState2, TextBoxPostcode2), en
End Sub

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub

Private Sub CommandButtonOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        '....
        .Bookmarks("Street").Range.Text = TextBoxStreet.Value
        .Bookmarks("Suburb").Range.Text = TextBoxSuburb.Value
        .Bookmarks("State").Range.Text = ComboBoxState.Value
        .Bookmarks("PostCode").Range.Text = TextBoxpostcode.Value

        .Bookmarks("Street2").Range.Text = IIf(useAforB, _
                                     TextBoxStreet.Value, TextBoxStreet2.Value)
        .Bookmarks("Suburb2").Range.Text = IIf(useAforB, _
                                     TextBoxSuburb.Value, TextBoxSuburb2.Value)
        .Bookmarks("State2").Range.Text = IIf(useAforB, _
                                     ComboBoxState.Value, ComboBoxState2.Value)
        .Bookmarks("PostCode2").Range.Text = IIf(useAforB, _
                                     TextBoxpostcode.Value, TextBoxPostcode2.Value)
        '...
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub
</code>```

Body:
Apologies in advance if this is already a question.

I've developed a user form to auto populate some of the letters we send to stakeholders. I currently have an address section in the userform  - textboxstreet textboxsuburb etc.
User form

in certain circumstances I need to have:

Address A - the address we are sending the letter to
and
Address B - the address we sent the letter to previously

For example:

John Smith
15 Madeup Street
Faketown Australia

this is a follow up letter to advise we have sent your previous letter to 33 Fake Place Nowhere Australia.

My conclusion is that I obviously need an Address A section and an Address B section to break the addresses up. Is there a way though - if address a and address b are the same, that address a populates at the bookmarks set for Address B?

eg:

If address' are different:

(bookmarkaddressA) = textboxaddressA
(bookmarkaddressB) = textboxaddressB

If address' are the same:

(bookmarkaddressA) = textboxaddressA
(bookmarkaddressB) = textboxaddressA

Ideally I would like it to function like the
"is the postal address the same as the residential address?" checkbox - and just grey out/lock textboxaddressb and fill the info from textboxaddressa

Any suggestions welcome.

full code:

    Option Explicit

Private Sub CheckBox1_Click()
If (CheckBox1.Value = True) Then TextBoxStreet2 = TextBoxStreet
If (CheckBox1.Value = True) Then TextBoxSuburb2 = TextBoxSuburb
If (CheckBox1.Value = True) Then TextBoxPostcode2 = TextBoxpostcode
If (CheckBox1.Value = True) Then ComboBoxState2 = ComboBoxState
If (CheckBox1.Value = False) Then TextBoxStreet2 = Null
If (CheckBox1.Value = False) Then TextBoxSuburb2 = Null
If (CheckBox1.Value = False) Then TextBoxPostcode2 = Null
If (CheckBox1.Value = False) Then ComboBoxState2 = Null
End Sub

Private Sub ComboBoxTitle_Change()

End Sub

Private Sub CommandButtonCancel_Click()
    Unload Me
End Sub

Private Sub CommandButtonClear_Click()
TextBoxFN.Value = Null
TextBoxGN.Value = Null
ComboBoxState.Value = Null
ComboBoxTitle.Value = Null
TextBoxStreet.Value = Null
TextBoxSuburb.Value = Null
TextBoxpostcode.Value = Null
TextBoxCD.Value = Null
TextboxMPN.Value = Null
TextBoxMPDD.Value = Null
TextBoxNPN.Value = Null
TextBoxNPDD.Value = Null
ComboBoxState2.Value = Null
TextBoxStreet2.Value = Null
TextBoxSuburb2.Value = Null
TextBoxPostcode2.Value = Null
CheckBox1.Value = False
End Sub

Private Sub CommandButtonOk_Click()
    Application.ScreenUpdating = False
    With ActiveDocument
        .Bookmarks("Title").Range.Text = ComboBoxTitle.Value
        .Bookmarks("GN").Range.Text = TextBoxGN.Value
        .Bookmarks("FN").Range.Text = TextBoxFN.Value
        .Bookmarks("FN2").Range.Text = TextBoxFN.Value
        .Bookmarks("Street").Range.Text = TextBoxStreet.Value
        .Bookmarks("Suburb").Range.Text = TextBoxSuburb.Value
        .Bookmarks("State").Range.Text = ComboBoxState.Value
        .Bookmarks("PostCode").Range.Text = TextBoxpostcode.Value
        .Bookmarks("Street2").Range.Text = TextBoxStreet2.Value
        .Bookmarks("Suburb2").Range.Text = TextBoxSuburb2.Value
        .Bookmarks("State2").Range.Text = ComboBoxState2.Value
        .Bookmarks("PostCode2").Range.Text = TextBoxPostcode2.Value
        .Bookmarks("CD").Range.Text = TextBoxCD.Value
        .Bookmarks("MPN").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN2").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN3").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN4").Range.Text = TextboxMPN.Value
        .Bookmarks("MPN5").Range.Text = TextboxMPN.Value
        .Bookmarks("MPDD").Range.Text = TextBoxMPDD.Value
        .Bookmarks("NPN").Range.Text = TextBoxNPN.Value
        .Bookmarks("NPDD").Range.Text = TextBoxNPDD.Value
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    With ComboBoxState
        .AddItem "QLD"
        .AddItem "NSW"
        .AddItem "ACT"
        .AddItem "VIC"
        .AddItem "TAS"
        .AddItem "SA"
        .AddItem "WA"
        .AddItem "NT"
    End With
    With ComboBoxTitle
        .AddItem "Mr"
        .AddItem "Mrs"
        .AddItem "Miss"
        .AddItem "Ms"
    End With
lbl_Exit:
    Exit Sub
End Sub

Private Sub TextBoxMPN_Change()
    TextboxMPN = UCase(TextboxMPN)
End Sub

Private Sub TextBoxNPN_Change()
    TextBoxNPN = UCase(TextBoxNPN)
End Sub

Private Sub TextBoxFN_Change()
    TextBoxFN = UCase(TextBoxFN)
End Sub

Body:
Since you asked, this is what i might have done (some code not included for clarity):

'disable "address B" controls is user selects to use same address for both
Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(TextBoxStreet2, TextBoxSuburb2, _
                          ComboBoxState2, TextBoxPostcode2), en
End Sub

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub

Private Sub CommandButtonOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        '....
        .Bookmarks("Street").Range.Text = TextBoxStreet.Value
        .Bookmarks("Suburb").Range.Text = TextBoxSuburb.Value
        .Bookmarks("State").Range.Text = ComboBoxState.Value
        .Bookmarks("PostCode").Range.Text = TextBoxpostcode.Value

        .Bookmarks("Street2").Range.Text = IIf(useAforB, _
                                     TextBoxStreet.Value, TextBoxStreet2.Value)
        .Bookmarks("Suburb2").Range.Text = IIf(useAforB, _
                                     TextBoxSuburb.Value, TextBoxSuburb2.Value)
        .Bookmarks("State2").Range.Text = IIf(useAforB, _
                                     ComboBoxState.Value, ComboBoxState2.Value)
        .Bookmarks("PostCode2").Range.Text = IIf(useAforB, _
                                     TextBoxpostcode.Value, TextBoxPostcode2.Value)
        '...
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub


问:
Checking Input to a Custom Directive in AngularJS
I have a very large form, which was getting difficult to read and follow when editing the HTML. I decided that I would try and make the most of AngularJS and use custom directives to compress the amount of repeated text. Here is the original directive I wrote:

```<code>app.directive("formField", function () {
    return {
        restrict: 'E',
        scope: {
            fieldData: '=field',
            fieldName: '=name',
            fieldType: '=type'
        },
        template: <SOME HTML>
    }
});
</code>```

And I would use this directive to add form fields to my page as follows:

```<code><form-field field="some_data" type="text" name="other_data"></form-field>
</code>```

I was using the type variable to differentiate between dateTime input, text input, numbers, etc, as they were distinguished in my code by only one keyword (by the input's type attribute.)

However now I have encountered a need to include checkboxes, which, thanks to my layout, require significantly different code to be structured properly. Based on this, when the type "checkbox" is passed into the directive I would like to return a different template value. I have tried variations of this kind of thing:

```<code>app.directive("formField", function () {
    return {
        restrict: 'E',
        scope: {
            fieldData: '=field',
            fieldName: '=name',
            fieldType: '=type'
        },
        template: function () {
            if(fieldType == 'checkbox') {
                return <CHECKBOX HTML>;
            } else {
                return <REGULAR FIELD HTML>;
        }
    }
});
</code>```

This doesn't work. Can anybody tell me how to check the value coming in for the type field so that I can compare it in the directive's returned object? Thanks.

答:
In the template, you can check for the element's attributes.

Your template should look like:

```<code>template: function (element, attrs) {
        if(attrs.type == 'checkbox') {
            return <CHECKBOX HTML>;
        } else {
            return <REGULAR FIELD HTML>;
        }
    }
</code>```

The isolate scope attribute definitions for fieldData, fieldName, and fieldType are available in the template return string (using expressions), but they are not available in the template's logic. Ex:

```<code>template: '<p>{{ fieldData }}</p>'
</code>```

Body:
I have a very large form, which was getting difficult to read and follow when editing the HTML. I decided that I would try and make the most of AngularJS and use custom directives to compress the amount of repeated text. Here is the original directive I wrote:

app.directive("formField", function () {
    return {
        restrict: 'E',
        scope: {
            fieldData: '=field',
            fieldName: '=name',
            fieldType: '=type'
        },
        template: <SOME HTML>
    }
});

And I would use this directive to add form fields to my page as follows:

<form-field field="some_data" type="text" name="other_data"></form-field>

I was using the type variable to differentiate between dateTime input, text input, numbers, etc, as they were distinguished in my code by only one keyword (by the input's type attribute.)

However now I have encountered a need to include checkboxes, which, thanks to my layout, require significantly different code to be structured properly. Based on this, when the type "checkbox" is passed into the directive I would like to return a different template value. I have tried variations of this kind of thing:

app.directive("formField", function () {
    return {
        restrict: 'E',
        scope: {
            fieldData: '=field',
            fieldName: '=name',
            fieldType: '=type'
        },
        template: function () {
            if(fieldType == 'checkbox') {
                return <CHECKBOX HTML>;
            } else {
                return <REGULAR FIELD HTML>;
        }
    }
});

This doesn't work. Can anybody tell me how to check the value coming in for the type field so that I can compare it in the directive's returned object? Thanks.

Body:
In the template, you can check for the element's attributes.

Your template should look like:

template: function (element, attrs) {
        if(attrs.type == 'checkbox') {
            return <CHECKBOX HTML>;
        } else {
            return <REGULAR FIELD HTML>;
        }
    }

The isolate scope attribute definitions for fieldData, fieldName, and fieldType are available in the template return string (using expressions), but they are not available in the template's logic. Ex:

template: '<p>{{ fieldData }}</p>'


问:
Reading an xml / incorporating it in to a project - C#
if i want to add a file to a project in c#, i just right click the project, add a new xml file and then always set to copy to the output directory. That way when the user runs it there will always be a copy of it.

Now i want to logically group 4 xml files with a folder. I added the folder, added the xml files to the folder, and set to copy. Thats great in the sense that it copies the folder to the output directory. But now however, instead of being able to open the xml file like this

```<code>XmlDocument doc = new XmlDocument();
doc.Load(filename);
</code>```

i need a new way of doing it as it doesnt locate the xml file as its within the folder in the output directory, opposed to directly in the output directory if that makes sense?

what can i do?

Thanks

答:
You could set it as an embedded resource and access it that way.  Have a look at this link

http://support.microsoft.com/kb/319292

Body:
if i want to add a file to a project in c#, i just right click the project, add a new xml file and then always set to copy to the output directory. That way when the user runs it there will always be a copy of it.

Now i want to logically group 4 xml files with a folder. I added the folder, added the xml files to the folder, and set to copy. Thats great in the sense that it copies the folder to the output directory. But now however, instead of being able to open the xml file like this

XmlDocument doc = new XmlDocument();
doc.Load(filename);

i need a new way of doing it as it doesnt locate the xml file as its within the folder in the output directory, opposed to directly in the output directory if that makes sense?

what can i do?

Thanks


问:
Local storage to change background colour
I am trying to change the background colour of my website with local storage. I am using onchange() within the HTML for the colours() function, and the rest is the JavaScript below

```<code>var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

function colours(){
    localStorage.bgcolour = document.getElementById("party").value;

    if (localStorage.bgcolour == '1'){
        document.body.style.backgroundColor = "red";
    }
}
</code>```

It does nothing. It doesn't even change, let alone store it as local storage.

I keep missing vital, small parts of code and it feels like I have done it again with this one.

Any help is greatly appreciated!

HTML:

```<code> <select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>
</code>```

答:
You seem to have some issues with setting and getting values from local-storage. Below is how it is done.

// Store

localStorage.setItem("lastname", "Smith");

// Retrieve

document.getElementById("result").innerHTML = localStorage.getItem("lastname");

Body:
I am trying to change the background colour of my website with local storage. I am using onchange() within the HTML for the colours() function, and the rest is the JavaScript below

var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

function colours(){
    localStorage.bgcolour = document.getElementById("party").value;

    if (localStorage.bgcolour == '1'){
        document.body.style.backgroundColor = "red";
    }
}

It does nothing. It doesn't even change, let alone store it as local storage.

I keep missing vital, small parts of code and it feels like I have done it again with this one.

Any help is greatly appreciated!

HTML:

 <select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>


问:
Sending users to different sections of survey
So I just created a google forms survey and wondered if its possible to send the users to different sections.

I am looking for at way to direct half of the users directly to section 2 and have the other half only see section 1.

User 1: Sees only section 1

User 2: Sees only section 2

User 3: Sees only section 1

and so on

Is there a way to keep a counter in google scripts that that sends the users directly to a section depending on whenever its odd or even without having them answer any questions first?

答:
On the form you can specify that after each of those sections, the form should be submitted instead of continuing on to the next section.

Then, you can get a pre-filled URL for each of the different users by:

Go to the form editor, and on the first page of the form, add a multiple choice question that has each different user as the options.

Then, check the box that says Go to page based on answer.

Next to the multiple choice options for each user, choose Go to page X, depending on which users should go to which sections.

In the menu, go to Responses > Get pre-filled URL.

For each user, select that user from the first multiple choice question and then click Submit.

In the new URL to share the pre-filled form, change viewform? to formResponse? and add &continue=continue to the end of the URL.

Repeat this for each of the different users and then give the users these new URLs for them to fill out the form.