问:
Java Junit Mock fails for MongoDB because of Null pointer
I am doing unit test case for mongoDB read operation. When I try to mock find operation, I am getting a NullPointerException

```<code>   public class MongoQueriertest {

        HelperUtil testhelper = new HelperUtil();

        DBCollection feedCollection;
        DBCursor curr;

        @Test(expected=NullPointerException.class)
        public void test_MongoQuerier ()throws Exception {

            MongoQuerier query = new MongoQuerier();
            FindIterable iterable = mock(FindIterable.class);
            curr =  mock(DBCursor.class);
            BasicDBObject obj = mock(BasicDBObject.class);
            when(feedCollection.find(obj)).thenReturn((DBCursor) iterable);
            query.getMaxId("String");
        }

    }

Method to test
 public String getMaxId(String dataVersion) throws Exception{
    String  maxJobId = "1";

    try {

    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("instance", dataVersion);

      DBCursor curr = feedCollection.find(whereQuery);  //.sort(new BasicDBObject(mongoDBSetting.maxIdField.replace("$", ""), -1)).limit(1);

      //AggregationOutput cursor = feedCollection.find().sort(""); //.aggregate(Arrays.asList(query));
      while (curr.hasNext()) {
//      String mid = curr.next().get(mongoDBSetting.maxIdField.replace("$", "")).toString();
//
//      mid = mid.replace("", "");

        maxJobId =  curr.next().get(mongoDBSetting.maxIdField.replace("$", "")).toString(); //Integer.parseInt(mid);
       }

     /* for (DBObject result : curr.results()) {
        maxJobId = Integer.parseInt(result.get(mongoDBSetting.maxIdField.replace("$", "")).toString());
            break;
      }*/
    }
    catch (Exception ex) {
      AppLogger.EventLogger.error("Exception occured selecting maxid in mongoDB. Exception -" + ex.getMessage().toString());
      throw new Exception(ex.getMessage().toString());
    }
    return maxJobId;
  }
</code>```

Please let me know where I am missing. I have added method that needs test case.

答:
You record a mock behavior on feedCollection that is not actually mocked

```<code>when(feedCollection.find(obj)).thenReturn((DBCursor) iterable);
</code>```

The object is null.

So feedCollection.find(obj) throws a nullPointerException.

Actually you have mocked these two objects :

```<code> curr =  mock(DBCursor.class);
 BasicDBObject obj = mock(BasicDBObject.class);
</code>```

Besides mocking an object is the first step to mock a method but to get it working, the mock object should be associated to the object under test.

And it is not the case. You create the MongoQuerier object you want to test but you don't set mocks object to it.

```<code>MongoQuerier query = new MongoQuerier();
</code>```

You should rather create an instance of the object to test with mocked object.

For example in this way to associate to it the mocked object(s).

```<code>MongoQuerier query = new MongoQuerier(mockObject, mockObject2, ...);
</code>```

Body:
I am doing unit test case for mongoDB read operation. When I try to mock find operation, I am getting a NullPointerException

   public class MongoQueriertest {

        HelperUtil testhelper = new HelperUtil();

        DBCollection feedCollection;
        DBCursor curr;

        @Test(expected=NullPointerException.class)
        public void test_MongoQuerier ()throws Exception {

            MongoQuerier query = new MongoQuerier();
            FindIterable iterable = mock(FindIterable.class);
            curr =  mock(DBCursor.class);
            BasicDBObject obj = mock(BasicDBObject.class);
            when(feedCollection.find(obj)).thenReturn((DBCursor) iterable);
            query.getMaxId("String");
        }

    }

Method to test
 public String getMaxId(String dataVersion) throws Exception{
    String  maxJobId = "1";

    try {

    BasicDBObject whereQuery = new BasicDBObject();
    whereQuery.put("instance", dataVersion);

      DBCursor curr = feedCollection.find(whereQuery);  //.sort(new BasicDBObject(mongoDBSetting.maxIdField.replace("$", ""), -1)).limit(1);

      //AggregationOutput cursor = feedCollection.find().sort(""); //.aggregate(Arrays.asList(query));
      while (curr.hasNext()) {
//      String mid = curr.next().get(mongoDBSetting.maxIdField.replace("$", "")).toString();
//
//      mid = mid.replace("", "");

        maxJobId =  curr.next().get(mongoDBSetting.maxIdField.replace("$", "")).toString(); //Integer.parseInt(mid);
       }

     /* for (DBObject result : curr.results()) {
        maxJobId = Integer.parseInt(result.get(mongoDBSetting.maxIdField.replace("$", "")).toString());
            break;
      }*/
    }
    catch (Exception ex) {
      AppLogger.EventLogger.error("Exception occured selecting maxid in mongoDB. Exception -" + ex.getMessage().toString());
      throw new Exception(ex.getMessage().toString());
    }
    return maxJobId;
  }

Please let me know where I am missing. I have added method that needs test case.

Body:
You record a mock behavior on feedCollection that is not actually mocked

when(feedCollection.find(obj)).thenReturn((DBCursor) iterable);

The object is null.

So feedCollection.find(obj) throws a nullPointerException.

Actually you have mocked these two objects :

 curr =  mock(DBCursor.class);
 BasicDBObject obj = mock(BasicDBObject.class);

Besides mocking an object is the first step to mock a method but to get it working, the mock object should be associated to the object under test.

And it is not the case. You create the MongoQuerier object you want to test but you don't set mocks object to it.

MongoQuerier query = new MongoQuerier();

You should rather create an instance of the object to test with mocked object.

For example in this way to associate to it the mocked object(s).

MongoQuerier query = new MongoQuerier(mockObject, mockObject2, ...);


来源: stackexchange

问:
C++ Partial Template Specialization: Member Functions
I have a template

```<code>template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething();
};
</code>```

which i would like to partially specialize for two special cases of b:

```<code>template<int a>
void MyTemplateClass<a, 2> :: computeSomething()
{
    // Special case for b=2 here
}

template<int a>
void MyTemplateClass<a, 3> :: computeSomething()
{
    // Special case for b=3 here
}
</code>```

However, as far as i know, partial specialization is invalid for member functions. How can i achieve what i want? Is there any other solution? Thank you!

答:
A possible way is estract compute(), create a base class only for it and specialize this base class.

I mean... if you create a generic version and two specializations for fooSub

```<code>template <int a, int b>
struct fooSub
 {
   void compute ()
    { std::cout << "- foo generic compute()" << std::endl; }
 };

template <int a>
struct fooSub<a, 2>
 {
   void compute ()
    { std::cout << "- foo compute() for 2" << std::endl; }
 };

template <int a>
struct fooSub<a, 3>
 {
   void compute ()
    { std::cout << "- foo compute() for 3" << std::endl; }
 };
</code>```

you can "specialize" compute in foo through inheritance simply as follows

```<code>template <int a, int b>
struct foo : public fooSub<a, b>
 { };
</code>```

Another possible solution, if you can use at least C++11, is activate/deactivate different version of compute() using SFINAE (std::enable_if) as in the following bar class

```<code>template <int a, int b>
struct bar
 {
   template <int bb = b>
   typename std::enable_if<(b == bb) && (b != 2) && (b != 3)>::type
         compute ()
    { std::cout << "- bar generic compute()" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 2)>::type compute ()
    { std::cout << "- bar compute() for 2" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 3)>::type compute ()
    { std::cout << "- bar compute() for 3" << std::endl; }
 };
</code>```

Follows a full compilable example for both ways

```<code>#include <iostream>
#include <type_traits>

template <int a, int b>
struct fooSub
 {
   void compute ()
    { std::cout << "- foo generic compute()" << std::endl; }
 };

template <int a>
struct fooSub<a, 2>
 {
   void compute ()
    { std::cout << "- foo compute() for 2" << std::endl; }
 };

template <int a>
struct fooSub<a, 3>
 {
   void compute ()
    { std::cout << "- foo compute() for 3" << std::endl; }
 };

template <int a, int b>
struct foo : public fooSub<a, b>
 { };

template <int a, int b>
struct bar
 {
   template <int bb = b>
   typename std::enable_if<(b == bb) && (b != 2) && (b != 3)>::type
         compute ()
    { std::cout << "- bar generic compute()" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 2)>::type compute ()
    { std::cout << "- bar compute() for 2" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 3)>::type compute ()
    { std::cout << "- bar compute() for 3" << std::endl; }
 };

int main()
 {
   foo<0, 1>{}.compute(); // print - foo generic compute()
   foo<1, 2>{}.compute(); // print - foo compute() for 2
   foo<2, 3>{}.compute(); // print - foo compute() for 3

   bar<2, 1>{}.compute(); // print - bar generic compute()
   bar<3, 2>{}.compute(); // print - bar compute() for 2
   bar<4, 3>{}.compute(); // print - bar compute() for 3
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a template

template <int a, int b>
class MyTemplateClass
{
    // ....
    void computeSomething();
};

which i would like to partially specialize for two special cases of b:

template<int a>
void MyTemplateClass :: computeSomething()
{
    // Special case for b=2 here
}

template<int a>
void MyTemplateClass :: computeSomething()
{
    // Special case for b=3 here
}

However, as far as i know, partial specialization is invalid for member functions. How can i achieve what i want? Is there any other solution? Thank you!

Body:
A possible way is estract compute(), create a base class only for it and specialize this base class.

I mean... if you create a generic version and two specializations for fooSub

template <int a, int b>
struct fooSub
 {
   void compute ()
    { std::cout << "- foo generic compute()" << std::endl; }
 };

template <int a>
struct fooSub<a, 2>
 {
   void compute ()
    { std::cout << "- foo compute() for 2" << std::endl; }
 };

template <int a>
struct fooSub<a, 3>
 {
   void compute ()
    { std::cout << "- foo compute() for 3" << std::endl; }
 };

you can "specialize" compute in foo through inheritance simply as follows

template <int a, int b>
struct foo : public fooSub<a, b>
 { };

Another possible solution, if you can use at least C++11, is activate/deactivate different version of compute() using SFINAE (std::enable_if) as in the following bar class

template <int a, int b>
struct bar
 {
   template <int bb = b>
   typename std::enable_if<(b == bb) && (b != 2) && (b != 3)>::type
         compute ()
    { std::cout << "- bar generic compute()" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 2)>::type compute ()
    { std::cout << "- bar compute() for 2" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 3)>::type compute ()
    { std::cout << "- bar compute() for 3" << std::endl; }
 };

Follows a full compilable example for both ways

#include <iostream>
#include <type_traits>

template <int a, int b>
struct fooSub
 {
   void compute ()
    { std::cout << "- foo generic compute()" << std::endl; }
 };

template <int a>
struct fooSub<a, 2>
 {
   void compute ()
    { std::cout << "- foo compute() for 2" << std::endl; }
 };

template <int a>
struct fooSub<a, 3>
 {
   void compute ()
    { std::cout << "- foo compute() for 3" << std::endl; }
 };

template <int a, int b>
struct foo : public fooSub<a, b>
 { };

template <int a, int b>
struct bar
 {
   template <int bb = b>
   typename std::enable_if<(b == bb) && (b != 2) && (b != 3)>::type
         compute ()
    { std::cout << "- bar generic compute()" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 2)>::type compute ()
    { std::cout << "- bar compute() for 2" << std::endl; }

   template <int bb = b>
   typename std::enable_if<(b == bb) && (b == 3)>::type compute ()
    { std::cout << "- bar compute() for 3" << std::endl; }
 };

int main()
 {
   foo<0, 1>{}.compute(); // print - foo generic compute()
   foo<1, 2>{}.compute(); // print - foo compute() for 2
   foo<2, 3>{}.compute(); // print - foo compute() for 3

   bar<2, 1>{}.compute(); // print - bar generic compute()
   bar<3, 2>{}.compute(); // print - bar compute() for 2
   bar<4, 3>{}.compute(); // print - bar compute() for 3
 }


问:
add new editable field for tfs work item
I am editing an existing work item type which we have called "Requirement".  To this I wish to add an additional string field that we can edit the value, search and sort on.

Using the TFS Process Editor I am able to edit the Requirement work item type in a GUI environment.  With this open, I created a field modeled after an existing field.  I then open the Layout tab and add this new field to the layout.

When I open an existing Requirement work item, the label for the new field is there, but no control appears to edit the value.

I can't figure out what I am missing.  Can someone direct me what the missing step is please?

Thanks!

答:
On the Fields tab, have you set the Type of the new field to String?
On the Layout tab, have you set the Type property of the control to FieldControl?</p>

ContentLicense: CC BY-SA 2.5


问:
Newly created xamarin solution getting errors on xamarin.forms and application inherited type
Every time I create a new solution in vs2017, I get errors on the using Xamarin.Forms directive and also on the app.axml.cs class definition when Application is inherited (which causes errors on the On methods), see image.

Is there a way of modifying the way vs configures solutions upon creation.

![Xamarin Errors](https://drive.google.com/drive/my-drive/xamarin errors.jpg)

答: I did a repair on the IDE, and everything is working now. I wish this version of studio was more stable. All I did was create a new cross platform solution and the errors were present. I could open a solution I had already worked on and it works fine. Go figure!</p>


问:
Regex: If/Else Condition in HTML Form Validation
I'm struggling with creating an If/Else statement in regex to a) validate a phone number format, then b) invalidate a certain set of phone numbers.

I currently have:

```<code><input type="tel" name="mobilePhone" pattern="^(?:\+?61|0)4 ?(?:(?:[01] ?[0-9]|2 ?[0-57-9]|3 ?[1-9]|4 ?[7-9]|5 ?[018]) ?[0-9]|3 ?0 ?[0-5])(?: ?[0-9]){5}$">
</code>```

as a way of targeting the following phone number formats (mobile numbers in Australia):

0414570776
0414 570 776

However we have a lot of 0411 111 111 or 0400000000 user entries that I would like to try and wash out before submission, but I can't seem to get it right.

I want to invalidate a series of numbers, but for this example, these two would suffice: 0411 111 111 or 0400000000.

Any help would be greatly appreciated.

Thank you

答:
Solution

var re = /^\s*\+?04(\d)(?!\1\s*\1{3}\s*\1{3})\d\s*\d{3}\s*\d{3}\s*$/;

console.log(re.test('0411111111') ? 'pass' : 'fail', '"0411111111"');
console.log(re.test('0411 111 111') ? 'pass' : 'fail', '"0411 111 111"');
console.log(re.test('0400 000 000') ? 'pass' : 'fail', '"0400 000 000"');
console.log(re.test('0412345678') ? 'pass' : 'fail', '"0412345678"');
console.log(re.test('0412 345 678') ? 'pass' : 'fail', '0412 345 678');
console.log(re.test('+0412345678') ? 'pass' : 'fail', '"+0412345678"');
console.log(re.test('+0412 345 678') ? 'pass' : 'fail', '"+0412 345 678"');
console.log(re.test('0412   345   678') ? 'pass' : 'fail', '"0412   345   678"');
console.log(re.test('+0412   345   678') ? 'pass' : 'fail', '"+0412   345   678"');
console.log(re.test('       +0412       345      678        ') ? 'pass' : 'fail', '"       +0412       345      678        "');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE>
<html>
  <head></head>
  <body>
    <form>
      <input type='tel' name='mobilePhone' pattern='^\s*\+?04(\d)(?!\1\s*\1{3}\s*\1{3})\d\s*\d{3}\s*\d{3}\s*$' placeholder='enter phone number'>
      <input type='submit'>
    </form>
  </body>
</html></code>```

Explanation

^\s* - starting with zero or more whitespace characters

\+? - followed by an optional +

04 - followed by a literal 04

(\d) - followed by a single digit (group 1)

(?!...) - NOT FOLLOWED BY

\1 - the value of group 1

\s* - followed by zero or more whitespace characters

\1{3} - followed by 3 occurrences of the value of group 1

\s* - followed by zero or more whitespace characters

\1{3} - followed by 3 occurrences of the value of group 1

\d - followed by a single digit

\s* - followed by zero or more whitespace characters

\d{3} - followed by 3 occurrences of the value of group 1

\s* - followed by zero or more whitespace characters

\d{3} - followed by 3 occurrences of the value of group 1

\s*$ - ending with zero or more whitespace characters

Body:
I'm struggling with creating an If/Else statement in regex to a) validate a phone number format, then b) invalidate a certain set of phone numbers.

I currently have:

<input type="tel" name="mobilePhone" pattern="^(?:\+?61|0)4 ?(?:(?:[01] ?[0-9]|2 ?[0-57-9]|3 ?[1-9]|4 ?[7-9]|5 ?[018]) ?[0-9]|3 ?0 ?[0-5])(?: ?[0-9]){5}$">

as a way of targeting the following phone number formats (mobile numbers in Australia):

0414570776
0414 570 776

However we have a lot of 0411 111 111 or 0400000000 user entries that I would like to try and wash out before submission, but I can't seem to get it right.

I want to invalidate a series of numbers, but for this example, these two would suffice: 0411 111 111 or 0400000000.

Any help would be greatly appreciated.

Thank you

Body:
Solution

var re = /^\s*\+?04(\d)(?!\1\s*\1{3}\s*\1{3})\d\s*\d{3}\s*\d{3}\s*$/;

console.log(re.test('0411111111') ? 'pass' : 'fail', '"0411111111"');
console.log(re.test('0411 111 111') ? 'pass' : 'fail', '"0411 111 111"');
console.log(re.test('0400 000 000') ? 'pass' : 'fail', '"0400 000 000"');
console.log(re.test('0412345678') ? 'pass' : 'fail', '"0412345678"');
console.log(re.test('0412 345 678') ? 'pass' : 'fail', '0412 345 678');
console.log(re.test('+0412345678') ? 'pass' : 'fail', '"+0412345678"');
console.log(re.test('+0412 345 678') ? 'pass' : 'fail', '"+0412 345 678"');
console.log(re.test('0412   345   678') ? 'pass' : 'fail', '"0412   345   678"');
console.log(re.test('+0412   345   678') ? 'pass' : 'fail', '"+0412   345   678"');
console.log(re.test('       +0412       345      678        ') ? 'pass' : 'fail', '"       +0412       345      678        "');

<!DOCTYPE>
<html>
  <head></head>
  <body>
    <form>
      <input type='tel' name='mobilePhone' pattern='^\s*\+?04(\d)(?!\1\s*\1{3}\s*\1{3})\d\s*\d{3}\s*\d{3}\s*$' placeholder='enter phone number'>
      <input type='submit'>
    </form>
  </body>
</html>

Explanation

^\s* - starting with zero or more whitespace characters

\+? - followed by an optional +

04 - followed by a literal 04

(\d) - followed by a single digit (group 1)

(?!...) - NOT FOLLOWED BY

\1 - the value of group 1

\s* - followed by zero or more whitespace characters

\1{3} - followed by 3 occurrences of the value of group 1

\s* - followed by zero or more whitespace characters

\1{3} - followed by 3 occurrences of the value of group 1

\d - followed by a single digit

\s* - followed by zero or more whitespace characters

\d{3} - followed by 3 occurrences of the value of group 1

\s* - followed by zero or more whitespace characters

\d{3} - followed by 3 occurrences of the value of group 1

\s*$ - ending with zero or more whitespace characters


问:
SQL Server: select the first character that is not a digit 0-9 or /
I have a table called Person, and a NVarChar column called Notes.

The Notes column has a lot of text in it, but always begins with a number of some kind, with /'s inserted throughout.

For example:

```<code>1/23 some text
45/678/9%*&^%$#@
02/468/ some other text
</code>```

I need to select the first character position that isn't a digit or /.

I don't care whether the position is 0-based or 1-based; I can accommodate that after the fact.

In this example, if I'm using 1-based character positions, the selection should produce the following:

```<code>5
9
8
</code>```

答:
So you're looking for an index that matches some sort of pattern, say a pattern index. If we're whimsical, we might abbreviate it to PATINDEX.

```<code>SELECT PATINDEX('%[^0-9/]%', Notes)
FROM Person
</code>```

Body:
I have a table called Person, and a NVarChar column called Notes.

The Notes column has a lot of text in it, but always begins with a number of some kind, with /'s inserted throughout.

For example:

1/23 some text
45/678/9%*&^%$#@
02/468/ some other text

I need to select the first character position that isn't a digit or /.

I don't care whether the position is 0-based or 1-based; I can accommodate that after the fact.

In this example, if I'm using 1-based character positions, the selection should produce the following:

5
9
8

Body:
So you're looking for an index that matches some sort of pattern, say a pattern index. If we're whimsical, we might abbreviate it to PATINDEX.

SELECT PATINDEX('%[^0-9/]%', Notes)
FROM Person


问:
Multiple data for the IF function
How can I simplify this formula for huge number of lookup value?

I have two Columns:

```<code>Column A = Team Name
Column B = Agent Name
</code>```

I want Column A to auto-populate based on the data from Column B. For now, we only have 6 agents, but come August we will have around 300 agents.

So what I need to see is if B2 = "david", a2 should show "Team D", if b2 = "cruz", a2 should show "Team A", if b2 = "dela", a2 should show "team B",etc.

The crucial aspect of this is by August, we will have many agents already so it will be a huge formula. Currently, I'm using the IF function for A2:

```<code>= IF(B2="David","Team D", IF(B2="Cruz", "Team A", if(B2="Dela", "Team B", "Team C")))
</code>```

答:
When you have all the 300 agents, you need to prepare a lookup table with all the agents along with the Team names like below,

Enter the formula in cell A2 and drag it down,

```<code>=VLOOKUP(B2,F:G,2,FALSE)
</code>```

Title: Multiple data for the IF function

Body:
How can I simplify this formula for huge number of lookup value?

I have two Columns:

Column A = Team Name
Column B = Agent Name

I want Column A to auto-populate based on the data from Column B. For now, we only have 6 agents, but come August we will have around 300 agents.

So what I need to see is if B2 = "david", a2 should show "Team D", if b2 = "cruz", a2 should show "Team A", if b2 = "dela", a2 should show "team B",etc.

The crucial aspect of this is by August, we will have many agents already so it will be a huge formula. Currently, I'm using the IF function for A2:

= IF(B2="David","Team D", IF(B2="Cruz", "Team A", if(B2="Dela", "Team B", "Team C")))

Body:
When you have all the 300 agents, you need to prepare a lookup table with all the agents along with the Team names like below,

Enter the formula in cell A2 and drag it down,

=VLOOKUP(B2,F:G,2,FALSE)


问:
Add a Progress Bar in WebView
I am trying to add a progress/loading bar to my application that uses WebView. I am confused on how to implement a progress bar that appears every time a link is clicked.

Current code:

```<code>public class CULearnBrowser extends Activity {

    WebView webview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("https://culearn.colorado.edu/webct/entryPageIns.dowebct");
    }

    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
</code>```

Activity layout:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>
</code>```

答:
Put a progress bar and the webview inside a relativelayout and set the properties for the progress bar as follows,

Make its visibility as GONE.

CENTRE it in the Relativelayout.

and then in onPageStarted() of the webclient make the progress bar visible so that it shows the progressbar when you have clicked on a link. In onPageFinished()  make the progress bar visiblility as GONE so that it disappears when the page has finished loading... This will work fine for your scenario. Hope this helps...

Title: Add a Progress Bar in WebView

Body:
I am trying to add a progress/loading bar to my application that uses WebView. I am confused on how to implement a progress bar that appears every time a link is clicked.

Current code:

public class CULearnBrowser extends Activity {

    WebView webview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("https://culearn.colorado.edu/webct/entryPageIns.dowebct");
    }

    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

Activity layout:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>


问:
Puppet file resource need to check source is available and target is R/W
I have the following puppet class.

```<code>class vintela_monitor::keytab {
  file { '/etc/vasinst.key':
    ensure => 'present',
    source => '/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab',
  }
}
</code>```

I need to make sure the source is accessible (cd to that directory) and that the target file system is in read write mode before executing this. How can I achieve this?

答:
You can use the attribute mode of the resource file

```<code> file { '/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab':
    ensure  => 'present',
    mode => '777',
 }

  file { '/etc/vasinst.key':
    ensure  => 'present',
    source  => '/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab',
    require => File["/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab"],
  }
</code>```

You can see more about mode and permessions here

Body:
I have the following puppet class.

class vintela_monitor::keytab {
  file { '/etc/vasinst.key':
    ensure => 'present',
    source => '/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab',
  }
}

I need to make sure the source is accessible (cd to that directory) and that the target file system is in read write mode before executing this. How can I achieve this?

Body:
You can use the attribute mode of the resource file

 file { '/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab':
    ensure  => 'present',
    mode => '777',
 }

  file { '/etc/vasinst.key':
    ensure  => 'present',
    source  => '/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab',
    require => File["/auto/hosting-hard/QAS/creds/keytabs/vas_engit.keytab"],
  }

You can see more about mode and permessions here


问:
2 Elements fill remaining height
I have a div in the middle with content inside.

I wish to have the top and bottom divs fill the remaining space.

Something like this

```<code><div class="container">
    <div class="top">

    </div>
    <div class="middle">
        Content
    </div>
    <div class="bottom">

    </div>
</div>
</code>```

If possible I would like the set a min height for the top and bottom containers.

答:
Here is a table solution for all you purists.

html, body {
  margin: 0;
  height:100%;
}
.container {
  display: table;
  height: 100%;
  width: 100%;
}
.container > div {
  display: table-row;
}
.table-cell {
  display: table-cell;
}
.top, .bottom {
  background: #ADD8E6;
}
.middle {
  background: #90EE90;
  height:1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="top">
    <div class="table-cell">

    </div>
  </div>
  <div class="middle">
    <div class="table-cell">
      Content
    </div>
  </div>
  <div class="bottom">
    <div class="table-cell">

    </div>
  </div>
</div></code>```

Title: 2 Elements fill remaining height

Body:
I have a div in the middle with content inside.

I wish to have the top and bottom divs fill the remaining space.

Something like this

        Content

If possible I would like the set a min height for the top and bottom containers.

Body:
Here is a table solution for all you purists.

html, body {
  margin: 0;
  height:100%;
}
.container {
  display: table;
  height: 100%;
  width: 100%;
}
.container > div {
  display: table-row;
}
.table-cell {
  display: table-cell;
}
.top, .bottom {
  background: #ADD8E6;
}
.middle {
  background: #90EE90;
  height:1px;
}

<div class="container">
  <div class="top">
    <div class="table-cell">

    </div>
  </div>
  <div class="middle">
    <div class="table-cell">
      Content
    </div>
  </div>
  <div class="bottom">
    <div class="table-cell">

    </div>
  </div>
</div>


问:
logstash index not assigned with json pattern
I am new to ELK stack and trying to configure fields in kibana dashboard. my logstash.conf

```<code>input {
tcp {
    port => 5000
}
}

filter{
json{
    source => "message"
    add_field => {
        "newfiled" => "static"
    }
}

}}

output {
elasticsearch {
    hosts => "elasticsearch:9200"
    index => "test"
}
}
</code>```

But index test is not present when i use curl to elastic server. Iam using python-logstash.I have installed json plugin. someone can help me how to send the json to elastic search so that I could view it on kibana dashboard?

答: Found the issue. There are two libraries json and jsonencode. If you are sending dictionary in text format(or using python logstash) make sure you use json encode</p>

Body:
I am new to ELK stack and trying to configure fields in kibana dashboard. my logstash.conf

input {
tcp {
    port => 5000
}
}

filter{
json{
    source => "message"
    add_field => {
        "newfiled" => "static"
    }
}

}}

output {
elasticsearch {
    hosts => "elasticsearch:9200"
    index => "test"
}
}

But index test is not present when i use curl to elastic server. Iam using python-logstash.I have installed json plugin. someone can help me how to send the json to elastic search so that I could view it on kibana dashboard?


问:
Writing to render texture in Unity using Compute Shaders is slow?
I am just learning Compute Shaders and experimenting with Unity ( i am not familiar with shaders too much), and i am trying to do something like a simple raycast and write to a render texture from a Compute Shader. Everything works just perfect, i get the wanted result. The ray-triangle intersections happens really fast - just less than a half of a second. However at the moment i try to apply a new color to the render texture, performance breaks down. The time needed jumps to 5 seconds. I couldn't break out of a loop without worsening the performance even more. I couldn't even use a bool flag in the loop which i could use outside the loop to update the texture colors if it is set to true in the loop.

The performance gets really bad. How would i update the render texture colors?

Here is the shader code: Any help is appreciated.

```<code>//--------------------------------------------------------------------
#pragma kernel MainCS

//--------------------------------------------------------------------
struct Triangle
{
    float3 v0;
    float3 v1;
    float3 v2;
    float3 n;
};

// Precomputed and set from C# script
struct Pixel
{
    float3   position;
    float3   direction;
    int      index;
    float    pixelColor;
};

//-----------------------------------------------------------------------------
#define blocksize 8

// variables
int imageSize;

// buffers
RWStructuredBuffer<Pixel>        pixels    : register(u0); // UAV
RWTexture2D<float4>              rendTex   : register(u1); // UAV
const StructuredBuffer<Triangle> tris      : register(t0); // SRV

// This kernel writes some color in the current pixel if there is ray intersection with some of the triangles from the tris buffer.  In general works well but slow. The intersection part without writing to the render texture is SUPER FAST. When i attempt to write to the texture - gets SUPER SLOW. Render Texture random write is enabled from the C# script

[numthreads(blocksize,blocksize,1)]
void MainCS (uint3 id : SV_DispatchThreadID, uint3 Gid : SV_GroupID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex )
{
    // Get the current pixel ID - pixels is 1D array
    int pixelID = (int)(id.y * imageSize + id.x);

    // Ray
    float3 rayO = pixels[pixelID].position;
    float3 rayD = pixels[pixelID].direction;

    // Intersection variables
    float3 pt0, pt1, pt2, edge0, edge1, edge2, cross1, cross2, cross3, n;
    float angle1, angle2, angle3;
    float r, _a, b;
    float3 w0, I;

    bool bIntersect = false;

    [loop][allow_uav_condition]
    for (uint tr = 0; tr < tris.Length; tr++)
    {
        // Somecalculations
        pt0 = tris[tr].v0; pt1 = tris[tr].v1; pt2 = tris[tr].v2;
        edge0 = rayO - pt0; edge1 = rayO - pt1; edge2 = rayO - pt2;

        // First check - is the ray intersecting the triangle
        if (dot(rayD, cross(edge0, edge1)) >= 0.0 ||
            dot(rayD, cross(edge1, edge2)) >= 0.0 ||
            dot(rayD, cross(edge2, edge0)) >= 0.0) continue;

        // Fiding the intersection point
        n = normalize(cross(pt0 - pt1, pt0 - pt2));
        w0 = rayO - pt0;
        _a = -dot(n, w0);
        b  =  dot(n, rayD);
        r  = _a / b;
        I = rayO + rayD * r;

        // Second check - before validate the hitpoint
        if (_a < 0.0)
        {
            // Here i would want to update texture colors

            // ==============================================
            // Variant 1 =======================================
            // Only update the texture without break;
            // Gives proper result but is SLOW - 3 seconds
            rendTex[id.xy] = float4(1.0, 0.0, 0.0, 1.0);
            // if add break; - MUCH SLOWER
            break;

            // ===============================================
            // Variant 2 - Part 1 ==================================
            // rising flag to true - fast
            if(!bIntersect)
            {
                bIntersect = true;
            }
        }
    }

// Variant 2 - Part 2 - When using the flag - updating Render texture colror is SUPER SLOW but acurate
    if(bIntersect)
        rendTex[id.xy] = float4(1.0, 0.0, 0.0, 1.0);
}
</code>```

答:
Dynamic branching is very expensive when programming on the GPU.

This is because of the way GPUs are designed.  A simplified view of how a CPU works: fetch an instruction, decode it, and then execute it on an ALU.  A GPU fetches an instruction, decodes it, and then executes it on a bunch of ALUs at the same time.  It steps through each line on each one of its threads at the same time, and it will need to run the program again for all of those pixels even if only one of those threads has to execute a different instruction.

Basically, avoid dynamic branching (if statements) where possible.  When you do a for loop with a conditional break, you're creating a lot of branches, which is the GPU's Achille's heel.  The flag is faster because the GPU is able to execute all those instructions on each thread no matter what.  Try to get as many of your threads to execute the same lines of code as possible.

Body:
I am just learning Compute Shaders and experimenting with Unity ( i am not familiar with shaders too much), and i am trying to do something like a simple raycast and write to a render texture from a Compute Shader. Everything works just perfect, i get the wanted result. The ray-triangle intersections happens really fast - just less than a half of a second. However at the moment i try to apply a new color to the render texture, performance breaks down. The time needed jumps to 5 seconds. I couldn't break out of a loop without worsening the performance even more. I couldn't even use a bool flag in the loop which i could use outside the loop to update the texture colors if it is set to true in the loop.

The performance gets really bad. How would i update the render texture colors?

Here is the shader code: Any help is appreciated.

//--------------------------------------------------------------------
#pragma kernel MainCS

//--------------------------------------------------------------------
struct Triangle
{
    float3 v0;
    float3 v1;
    float3 v2;
    float3 n;
};

// Precomputed and set from C# script
struct Pixel
{
    float3   position;
    float3   direction;
    int      index;
    float    pixelColor;
};

//-----------------------------------------------------------------------------
#define blocksize 8

// variables
int imageSize;

// buffers
RWStructuredBuffer<Pixel>        pixels    : register(u0); // UAV
RWTexture2D<float4>              rendTex   : register(u1); // UAV
const StructuredBuffer<Triangle> tris      : register(t0); // SRV

// This kernel writes some color in the current pixel if there is ray intersection with some of the triangles from the tris buffer.  In general works well but slow. The intersection part without writing to the render texture is SUPER FAST. When i attempt to write to the texture - gets SUPER SLOW. Render Texture random write is enabled from the C# script

[numthreads(blocksize,blocksize,1)]
void MainCS (uint3 id : SV_DispatchThreadID, uint3 Gid : SV_GroupID, uint3 GTid : SV_GroupThreadID, uint GI : SV_GroupIndex )
{
    // Get the current pixel ID - pixels is 1D array
    int pixelID = (int)(id.y * imageSize + id.x);

    // Ray
    float3 rayO = pixels[pixelID].position;
    float3 rayD = pixels[pixelID].direction;

    // Intersection variables
    float3 pt0, pt1, pt2, edge0, edge1, edge2, cross1, cross2, cross3, n;
    float angle1, angle2, angle3;
    float r, _a, b;
    float3 w0, I;

    bool bIntersect = false;

    [loop][allow_uav_condition]
    for (uint tr = 0; tr < tris.Length; tr++)
    {
        // Somecalculations
        pt0 = tris[tr].v0; pt1 = tris[tr].v1; pt2 = tris[tr].v2;
        edge0 = rayO - pt0; edge1 = rayO - pt1; edge2 = rayO - pt2;

        // First check - is the ray intersecting the triangle
        if (dot(rayD, cross(edge0, edge1)) >= 0.0 ||
            dot(rayD, cross(edge1, edge2)) >= 0.0 ||
            dot(rayD, cross(edge2, edge0)) >= 0.0) continue;

        // Fiding the intersection point
        n = normalize(cross(pt0 - pt1, pt0 - pt2));
        w0 = rayO - pt0;
        _a = -dot(n, w0);
        b  =  dot(n, rayD);
        r  = _a / b;
        I = rayO + rayD * r;

        // Second check - before validate the hitpoint
        if (_a < 0.0)
        {
            // Here i would want to update texture colors

            // ==============================================
            // Variant 1 =======================================
            // Only update the texture without break;
            // Gives proper result but is SLOW - 3 seconds
            rendTex[id.xy] = float4(1.0, 0.0, 0.0, 1.0);
            // if add break; - MUCH SLOWER
            break;

            // ===============================================
            // Variant 2 - Part 1 ==================================
            // rising flag to true - fast
            if(!bIntersect)
            {
                bIntersect = true;
            }
        }
    }

// Variant 2 - Part 2 - When using the flag - updating Render texture colror is SUPER SLOW but acurate
    if(bIntersect)
        rendTex[id.xy] = float4(1.0, 0.0, 0.0, 1.0);
}


问:
Specify web brower in href tag
Is there a way to specify the web browser to be used in a href tag ? For instance, I have the following URL and I need it to be opened with Firefox only :

```<code><a href="http://vienne.lpo.fr">LPO Vienne</a>
</code>```

Thanks for your advices !

答: Actually it is possible these days - at least in the case of Microsoft Edge.  Check this out. Although agree with ProWebMonkey that usability issues still apply.</p>

Title: Specify web brower in href tag

Body:
Is there a way to specify the web browser to be used in a href tag ? For instance, I have the following URL and I need it to be opened with Firefox only :

LPO Vienne

Thanks for your advices !


问:
How to set tinymce content dynamically
I am trying to change content of tinymce editor dynamically.
even this steps is not working. Actually i want to put contents on ajax success, But since it is not working i cant continue.

I am getting Type error tinemce.get() is null and tinymce.activeEditor is null erros

```<code><textarea style="height:700px" name="proposal" id="proposal" >
                        hi
</textarea>
<script>
    $(document).ready(function () {
                        tinymce.init({
                          selector: "#proposal",
                          height: 250,
                          theme: "modern",
                          plugins: [
                            "autoresize advlist autolink lists link image charmap print preview hr anchor pagebreak",
                            "searchreplace wordcount visualblocks visualchars code fullscreen",
                            "insertdatetime media nonbreaking save table contextmenu directionality",
                            "emoticons template paste textcolor colorpicker textpattern imagetools codesample toc"
                          ],
                          toolbar1: "undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media | forecolor backcolor emoticons | codesample",
                          image_advtab: true,
                          content_css: [
                            "https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css",
                          ],

                        });
                        var content = "<p>Hello World </p>";
                        tinyMCE.get("proposal").setContent(content);//not working
                        tinyMCE.activeEditor.setContent(content);//not working

                    });

<script>
</code>```

答:
Your calls to tinyMCE.get("proposal") and tinyMCE.activeEditor are likely happening before the editor is actually instantiated.  The TinyMCE init() method takes time to complete but you are calling these two methods directly after the init() so the editor is probably not yet initialized.

The editor has an init event you can use to know when the editor is fully initialized and then you can use the editor APIs.  You can put something like this in your TinyMCE configuration:

```<code>tinymce.init({
    selector: "#proposal",
    ...
    setup: function (editor) {
        editor.on('init', function () {
            var content = "<p>Hello World </p>";
            editor.setContent(content);
        });
    }
});
</code>```

Title: How to set tinymce content dynamically

Body:
I am trying to change content of tinymce editor dynamically.
even this steps is not working. Actually i want to put contents on ajax success, But since it is not working i cant continue.

I am getting Type error tinemce.get() is null and tinymce.activeEditor is null erros

<textarea style="height:700px" name="proposal" id="proposal" >
                        hi
</textarea>

Body:
Your calls to tinyMCE.get("proposal") and tinyMCE.activeEditor are likely happening before the editor is actually instantiated.  The TinyMCE init() method takes time to complete but you are calling these two methods directly after the init() so the editor is probably not yet initialized.

The editor has an init event you can use to know when the editor is fully initialized and then you can use the editor APIs.  You can put something like this in your TinyMCE configuration:

tinymce.init({
    selector: "#proposal",
    ...
    setup: function (editor) {
        editor.on('init', function () {
            var content = "<p>Hello World </p>";
            editor.setContent(content);
        });
    }
});


问:
Rolling Update with Kubernetes Deployment without increasing the cluster size
I have a cluster that can only run one Pod per node due to our configuration (sometimes Kubernetes will randomly run two on one pod but w/e). Any time I have to update my Deployment which causes a Rolling Update, Kubernetes will simply never finish the update.

The reason for this appears to be that there isn't enough room in the nodes to deploy the new pods from the rolling update.

Now, some of you may say that I may simple increase the cluster size every time I want to perform an update. The problem with that approach is that I have enabled autoscaling on the cluster and the Deployment replicas is set high so that Kubernetes automatically scales with the cluster. This means I can't change the cluster size to accomodate the Rolling Update.

How can I perform a Rolling Update with this configuration?

答: Can you set maxSurge to 0 and maxUnavailable to some positive value?</p>


问:
Deep Learning Multi-Input CNN
I am trying to create a multi-view convolutional neural network that starts off separately applying convolutional and pooling layers to each of the inputs. The structure would look something like this.

CNN Multi View Structure

Just as an example, I would want to have the top, bottom, left, and right view of a cat, apply convolutional and pooling layers to each separately, and then combine this info later.

I have been mostly using Keras on this project, however I cannot seem to figure this out with what Keras has to offer. Is there any way to do this with Keras, and if not, how can I create the first step of this multi-view CNN?

答: Take a look at the Keras multi-input multi-output model example. Just follow it and make minor changes. You should be able to adapt it to your usage.</p>

Title: Deep Learning Multi-Input CNN


问:
Cast Anyobject to dictionary
I receive a json object with this format

```<code>"type":[{"id":"926"}]
</code>```

I bind it with an Anyobject type

```<code>@NSManaged var type: AnyObject?
</code>```

and I want to cast it to a dictionary

```<code>if let t = type as? Dictionary<String, AnyObject>  {
     print(t["id"])
    }
</code>```

but the cast dose not success and the t still always nil

答:
The value of "type" in your json response is an array of dictionaries, so you should parse it accordingly.</p>

```<code>if let t = type as? [[String:AnyObject]] {
   if let id = t.first?["id"] as? String {
      print(id)
   }
}
</code>```

Title: Cast Anyobject to dictionary

Body:
I receive a json object with this format

"type":[{"id":"926"}]

I bind it with an Anyobject type

@NSManaged var type: AnyObject?

and I want to cast it to a dictionary

if let t = type as? Dictionary<String, AnyObject>  {
     print(t["id"])
    }

but the cast dose not success and the t still always nil

Body:
The value of "type" in your json response is an array of dictionaries, so you should parse it accordingly.

if let t = type as? [[String:AnyObject]] {
   if let id = t.first?["id"] as? String {
      print(id)
   }
}


问:
React + Redux : reducer won't reload component
I wrote a generic Table component, instancied twice with two differents datasets. I use a Redux store to hydrate props and I try to delete a row when I click on it.

Components are well displayed and onClick function is fired and reducer is called. The new returned state returns the previous state without the element clicked.

My problem is that the components are not re-rendered.
According to the troubleshouting page (http://redux.js.org/docs/Troubleshooting.html), it seems that I don't mutate the previous state (maybe I just don't understand how to do), I'm calling the dispatch() function and my mapStateToProps seems to be right as datas are well displayed on the page load.

I tried to define initial state in reducer.js > table function instead of doing it with createStore function, I tried to split 'tables' reducer into 'domains' and 'hosts' reducers (duplicate code), I tried to not use combineReducers() as I have only one (but I will have more in the future), and I tried so many things so I can't remember.

I bet it's not a big deal but I just not able to figure out what's going on. Can you help me please ? Thank you very much.

reducer.js

```<code>import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = Object.assign({}, state)

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    switch (action.type) {
        case DELETE_HOST:
            return Object.assign({}, state, {
                hosts: deleteItem(state.hosts, action.host)
            })

        case DELETE_DOMAIN:
            return Object.assign({}, state, {
                domains: deleteItem(state.domains, action.domain)
            })

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers
</code>```

actions.js

```<code>export const DELETE_DOMAIN = 'DELETE_DOMAIN'
export const DELETE_HOST = 'DELETE_HOST'

export function deleteDomain(domain) {
    return { type: DELETE_DOMAIN, domain }
}

export function deleteHost(host) {
    return { type: DELETE_HOST, host }
}
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './reducers'

const initialState = {
    tables: {
        domains: {
            headers: {
                id: 'Id',
                domain: 'Domain',
                host: 'Hoster',
            },
            items: [
                {
                    id: 1,
                    domain: 'dev.example.com',
                    host: 'dev',
                },
                {
                    id: 2,
                    domain: 'prod.example.com',
                    host: 'prod',
                }
            ]
        },
        hosts: {
            headers: {
                id: 'Id',
                label: 'Label',
                type: 'Type',
                hoster: 'Corporation',
            },
            items: [
                {
                    id: 1,
                    label: 'Server 1',
                    type: 'Server type',
                    hoster: 'Gandi',
                },
                {
                    id: 2,
                    label: 'Server 2',
                    type: 'Server type',
                    hoster: 'OVH',
                }
            ]
        }
    }
}

let store = createStore(reducers, initialState)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);
</code>```

app.js

```<code>import React from 'react';
import Domains from './modules/domains.js';
import Hosts from './modules/hosts.js';
import Nav from './modules/nav.js';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom'

export default class App extends React.Component {
    render() {
        return (
            <Router>
                <div className="container-fluid col-md-6">
                    <Nav />
                    <Route path="/domains" component={Domains}/>
                    <Route path="/hosts" component={Hosts}/>
                </div>
            </Router>
        );
    }
}
</code>```

domain.js

```<code>import React from 'react';
import Table from './../components/table.js';
import { connect } from 'react-redux'
import { deleteDomain } from './../actions'

const mapStateToProps = (state) => {
    return state.tables.domains
}

const mapDispatchToProps = (dispatch) => {
    return {
            onRowClick: (id) => {
                dispatch(deleteDomain(id))
            }
        }
}

class DomainsView extends React.Component {
    render() {
        return (
            <Table headers={this.props.headers} items={this.props.items} onRowClick={this.props.onRowClick} />
        )
    }
}

const Domains = connect(
    mapStateToProps,
    mapDispatchToProps,
)(DomainsView)

export default Domains
</code>```

hosts.js
Same as domains.js with differents const / class names and props

答:
Since your redux state is deeply nested, Object.assign does not make an actual duplicate. Although the state itself is a duplicate, its values are references to the same objects as before. As a result, your deeply nested objects are not duplicated. My advice is to use the merge method from lodash instead of Object.assign in your reducer. Install lodash via npm and then:</p>

```<code>import { combineReducers } from 'redux'
import { merge } from 'lodash'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = merge({}, state);

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    let newState;
    switch (action.type) {
        case DELETE_HOST:
            newState = merge({}, state);
            newState.hosts = deleteItem(state.hosts, action.host)
            return newState;
        case DELETE_DOMAIN:
            newState = merge({}, state);
            newState.domains = deleteItem(state.domains, action.domain)
            return newState;
        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers
</code>```

Body:
I wrote a generic Table component, instancied twice with two differents datasets. I use a Redux store to hydrate props and I try to delete a row when I click on it.

Components are well displayed and onClick function is fired and reducer is called. The new returned state returns the previous state without the element clicked.

My problem is that the components are not re-rendered.
According to the troubleshouting page (http://redux.js.org/docs/Troubleshooting.html), it seems that I don't mutate the previous state (maybe I just don't understand how to do), I'm calling the dispatch() function and my mapStateToProps seems to be right as datas are well displayed on the page load.

I tried to define initial state in reducer.js > table function instead of doing it with createStore function, I tried to split 'tables' reducer into 'domains' and 'hosts' reducers (duplicate code), I tried to not use combineReducers() as I have only one (but I will have more in the future), and I tried so many things so I can't remember.

I bet it's not a big deal but I just not able to figure out what's going on. Can you help me please ? Thank you very much.

reducer.js

import { combineReducers } from 'redux'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = Object.assign({}, state)

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    switch (action.type) {
        case DELETE_HOST:
            return Object.assign({}, state, {
                hosts: deleteItem(state.hosts, action.host)
            })

        case DELETE_DOMAIN:
            return Object.assign({}, state, {
                domains: deleteItem(state.domains, action.domain)
            })

        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers

actions.js

export const DELETE_DOMAIN = 'DELETE_DOMAIN'
export const DELETE_HOST = 'DELETE_HOST'

export function deleteDomain(domain) {
    return { type: DELETE_DOMAIN, domain }
}

export function deleteHost(host) {
    return { type: DELETE_HOST, host }
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './reducers'

const initialState = {
    tables: {
        domains: {
            headers: {
                id: 'Id',
                domain: 'Domain',
                host: 'Hoster',
            },
            items: [
                {
                    id: 1,
                    domain: 'dev.example.com',
                    host: 'dev',
                },
                {
                    id: 2,
                    domain: 'prod.example.com',
                    host: 'prod',
                }
            ]
        },
        hosts: {
            headers: {
                id: 'Id',
                label: 'Label',
                type: 'Type',
                hoster: 'Corporation',
            },
            items: [
                {
                    id: 1,
                    label: 'Server 1',
                    type: 'Server type',
                    hoster: 'Gandi',
                },
                {
                    id: 2,
                    label: 'Server 2',
                    type: 'Server type',
                    hoster: 'OVH',
                }
            ]
        }
    }
}

let store = createStore(reducers, initialState)

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

app.js

import React from 'react';
import Domains from './modules/domains.js';
import Hosts from './modules/hosts.js';
import Nav from './modules/nav.js';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom'

export default class App extends React.Component {
    render() {
        return (
            <Router>

                    <Route path="/domains" component={Domains}/>
                    <Route path="/hosts" component={Hosts}/>

            </Router>
        );
    }
}

domain.js

import React from 'react';
import Table from './../components/table.js';
import { connect } from 'react-redux'
import { deleteDomain } from './../actions'

const mapStateToProps = (state) => {
    return state.tables.domains
}

const mapDispatchToProps = (dispatch) => {
    return {
            onRowClick: (id) => {
                dispatch(deleteDomain(id))
            }
        }
}

class DomainsView extends React.Component {
    render() {
        return (

        )
    }
}

const Domains = connect(
    mapStateToProps,
    mapDispatchToProps,
)(DomainsView)

export default Domains

hosts.js
Same as domains.js with differents const / class names and props

Body:
Since your redux state is deeply nested, Object.assign does not make an actual duplicate. Although the state itself is a duplicate, its values are references to the same objects as before. As a result, your deeply nested objects are not duplicated. My advice is to use the merge method from lodash instead of Object.assign in your reducer. Install lodash via npm and then:

import { combineReducers } from 'redux'
import { merge } from 'lodash'
import { DELETE_DOMAIN, DELETE_HOST } from './actions'

function deleteItem(state, index) {
    let newState = merge({}, state);

    newState.items.splice(index, 1)

    return newState
}

function tables(state = {}, action) {
    let newState;
    switch (action.type) {
        case DELETE_HOST:
            newState = merge({}, state);
            newState.hosts = deleteItem(state.hosts, action.host)
            return newState;
        case DELETE_DOMAIN:
            newState = merge({}, state);
            newState.domains = deleteItem(state.domains, action.domain)
            return newState;
        default:
            return state
    }
}

const reducers = combineReducers({
    tables,
})

export default reducers


问:
Getting local time creates error
The following code returns the error Invalid qualifier:

```<code>Set Nav_Selected = TL.ActiveBook.FindDataWatch("Navigator_SelectedOIDs")
Set Nav_Items = Nav_Selected.Data
Set block_path = Nav_Items.AttributeMap(0)
Set block_watch = TL.FindDataWatch(block_path)

Dim creationTime As Date
Dim localTime As String

'Get CreationTime
Set myWF = block_watch.Data
creationTime = myWF.Properties.Item("Created")
Set localTime = creationTime.ToLocalTime
</code>```

I'm trying to get the localTime property from the creationTime object, just not sure how to do it. Thanks for the help.

答:
To solve this issue, I made changes following this article describing GMT and DLST corrections:

First, I added these functions to parse the string into a date object and then adjust for day light savings time (DLST) and Greenwich Median Time (GMT)

```<code>Function GetLocalTimeFromGMT(Optional GMTTime As Date) As Date
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GetLocalTimeFromGMT
' This returns the Local Time from a GMT time. If GMTTime is present and
' greater than 0, it is assumed to be the GMT from which we will calculate
' Local Time. If GMTTime is 0 or omitted, it is assumed to be the GMT
' time.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim GMT As Date
Dim TZI As TIME_ZONE_INFORMATION
Dim DST As TIME_ZONE
Dim localTime As Date

DST = GetTimeZoneInformation(TZI)
localTime = GMTTime - TimeSerial(0, TZI.Bias, 0) + IIf(DST =
TIME_ZONE_DAYLIGHT, TimeSerial(1, 0, 0), 0)
GetLocalTimeFromGMT = localTime

End Function
----------------------------------------------------------------------------
Function ParseDateTime(dt As String) As Date
  ParseDateTime = CDate(dt)
End Function
</code>```

Next, I modified the the main function to call on the time adjustment functions:

```<code>'Get CreationTime
Set myWF = block_watch.Data
creationTime = myWF.Properties.Item("Created")
localTime = ParseDateTime(creationTime)
</code>```

I now have time being fed into my function that is corrected for any time keeping methods and is accurate to within a few seconds.

Title: Getting local time creates error

Body:
The following code returns the error Invalid qualifier:

Set Nav_Selected = TL.ActiveBook.FindDataWatch("Navigator_SelectedOIDs")
Set Nav_Items = Nav_Selected.Data
Set block_path = Nav_Items.AttributeMap(0)
Set block_watch = TL.FindDataWatch(block_path)

Dim creationTime As Date
Dim localTime As String

'Get CreationTime
Set myWF = block_watch.Data
creationTime = myWF.Properties.Item("Created")
Set localTime = creationTime.ToLocalTime

I'm trying to get the localTime property from the creationTime object, just not sure how to do it. Thanks for the help.

Body:
To solve this issue, I made changes following this article describing GMT and DLST corrections:

First, I added these functions to parse the string into a date object and then adjust for day light savings time (DLST) and Greenwich Median Time (GMT)

Function GetLocalTimeFromGMT(Optional GMTTime As Date) As Date
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GetLocalTimeFromGMT
' This returns the Local Time from a GMT time. If GMTTime is present and
' greater than 0, it is assumed to be the GMT from which we will calculate
' Local Time. If GMTTime is 0 or omitted, it is assumed to be the GMT
' time.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim GMT As Date
Dim TZI As TIME_ZONE_INFORMATION
Dim DST As TIME_ZONE
Dim localTime As Date

DST = GetTimeZoneInformation(TZI)
localTime = GMTTime - TimeSerial(0, TZI.Bias, 0) + IIf(DST =
TIME_ZONE_DAYLIGHT, TimeSerial(1, 0, 0), 0)
GetLocalTimeFromGMT = localTime

End Function
----------------------------------------------------------------------------
Function ParseDateTime(dt As String) As Date
  ParseDateTime = CDate(dt)
End Function

Next, I modified the the main function to call on the time adjustment functions:

'Get CreationTime
Set myWF = block_watch.Data
creationTime = myWF.Properties.Item("Created")
localTime = ParseDateTime(creationTime)

I now have time being fed into my function that is corrected for any time keeping methods and is accurate to within a few seconds.


问:
UPDATE mysql with array without foreach
I insert array into mysql without any loop and make query for each array:

```<code>$albumid = $_GET['id'];
$gettrack = $_POST["songtrack"];
$gename = $_POST["songname"];
$getlength = $_POST["songlength"];
$getprice = $_POST["songprice"];

$data = array();
$size = count($_POST["songname"]);

for($i = 0 ; $i < $size ; $i++){
  $data[$i] = array(
     "albumid"     => $albumid,
     "track"     => $gettrack[$i],
     "name"    => $gename[$i],
     "length"    => $getlength[$i],
     "price"       => $getprice[$i]
  );
}

$values = array();
foreach($data as $datas){
  $values[] = "('{$datas['albumid']}','{$datas['track']}', '{$datas['name']}', '{$datas['length']}', '{$datas['price']}')";
}

$values = implode(", ", $values);

$sql = "INSERT INTO `song` (albumid, track, name, length, price) VALUES {$values};";

if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
</code>```

Now i want update mysql with something like this, but i have no idea, googled and found similar topics but all of theme update mysql with array with foreach loop, i don't want to make query with every array, any solution?

can i change above code to update mysql?

答:
You are using mysqli extension.
So one of the possible options is use multi_query function, generate to string all update statements separatelly and run it during one transaction:

START TRANSACTION;
UPDATE....
UPDATE....
UPDATE....
COMMIT;

It should be faster that run updates one by once.

Another solution could be build complexity UPDATE statement. For example:

UPDATE song
SET
    Field = CASE value1 WHEN condition1 THEN value1
WHEN condition2 THEN value2 ...

Or complex IF ELSE statement.

Last possibility is using custom procedure or function to evaluate correct value.

I thins there's no other way.

Title: UPDATE mysql with array without foreach

Body:
I insert array into mysql without any loop and make query for each array:

$albumid = $_GET['id'];
$gettrack = $_POST["songtrack"];
$gename = $_POST["songname"];
$getlength = $_POST["songlength"];
$getprice = $_POST["songprice"];

$data = array();
$size = count($_POST["songname"]);

for($i = 0 ; $i < $size ; $i++){
  $data[$i] = array(
     "albumid"     => $albumid,
     "track"     => $gettrack[$i],
     "name"    => $gename[$i],
     "length"    => $getlength[$i],
     "price"       => $getprice[$i]
  );
}

$values = array();
foreach($data as $datas){
  $values[] = "('{$datas['albumid']}','{$datas['track']}', '{$datas['name']}', '{$datas['length']}', '{$datas['price']}')";
}

$values = implode(", ", $values);

$sql = "INSERT INTO `song` (albumid, track, name, length, price) VALUES {$values};";

if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "
" . mysqli_error($connection);
}

Now i want update mysql with something like this, but i have no idea, googled and found similar topics but all of theme update mysql with array with foreach loop, i don't want to make query with every array, any solution?

can i change above code to update mysql?


问:
trying to manage the value of 2 inputs
I'm not really good for speaking english, but this problem could kill me.. I'm on since 3 days..

I have 2 inputs, each input can be 1 to 100.
But i need that the addition of the both is never below 100.
Exemple : 40 & 60, 30 & 70, ...

I tried to change the second input with a focusout (rly that i need), to add to the second input the value that i needed.
Exemple :
Input 1 : value 40
Input 2 : Value 20 (In this case i need that this input change to 60 whenever i focusout it)

Sorry for this poor english, but instead of reading a solution this time i need to post (Never posted before because i always find what i needed ).

This is my code :

```<code>if($("#coemp_pret1").val() == "1"){
    $(this).val(function(index, value) {
        var tempValue = $(this).val($(this).val() + $("#QuotDecAdh_s3p1").val());

        if( tempValue < "100" ){
            return value
                .replace(/\d{1,2}(?!\d)|100/, "");

            $(this).val(100 - $("#QuotDecAdh_s3p1").val());
        }
    });
}
</code>```

Thanks i hope you can help me, byebye !

答:
I have added a new event, to handle first input changes. So, everytime you change the value from it, the value from the second will reset to ''.

Also added .on('blur') event for the second field, so you can check if the sum of both is below 100. If it is, then the difference from 100 and the sum will be extracted to be displayed as the second input value.

Code below:

$(function() {
  $('#inp1').on('change', function() {
    $('#inp2').val('');
  });

  $('#inp2').on('blur', function() {
    var val1 = $('#inp1').val();

    if (val1 > 0) {
      var val2 = $(this).val();
      var sum = (val1 + val2);

      if (sum < 100) {
        var diff = (100 - sum);
        $(this).val(diff);
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Value 1</span>
<input id="inp1" type="text" />
<br />
<br />
<span>Value 2</span>
<input id="inp2" type="text" /></code>```

Title: trying to manage the value of 2 inputs

Body:
I'm not really good for speaking english, but this problem could kill me.. I'm on since 3 days..

I have 2 inputs, each input can be 1 to 100.
But i need that the addition of the both is never below 100.
Exemple : 40 & 60, 30 & 70, ...

I tried to change the second input with a focusout (rly that i need), to add to the second input the value that i needed.
Exemple :
Input 1 : value 40
Input 2 : Value 20 (In this case i need that this input change to 60 whenever i focusout it)

Sorry for this poor english, but instead of reading a solution this time i need to post (Never posted before because i always find what i needed ).

This is my code :

if($("#coemp_pret1").val() == "1"){
    $(this).val(function(index, value) {
        var tempValue = $(this).val($(this).val() + $("#QuotDecAdh_s3p1").val());

        if( tempValue < "100" ){
            return value
                .replace(/\d{1,2}(?!\d)|100/, "");

            $(this).val(100 - $("#QuotDecAdh_s3p1").val());
        }
    });
}

Thanks i hope you can help me, byebye !

Body:
I have added a new event, to handle first input changes. So, everytime you change the value from it, the value from the second will reset to ''.

Also added .on('blur') event for the second field, so you can check if the sum of both is below 100. If it is, then the difference from 100 and the sum will be extracted to be displayed as the second input value.

Code below:

$(function() {
  $('#inp1').on('change', function() {
    $('#inp2').val('');
  });

  $('#inp2').on('blur', function() {
    var val1 = $('#inp1').val();

    if (val1 > 0) {
      var val2 = $(this).val();
      var sum = (val1 + val2);

      if (sum < 100) {
        var diff = (100 - sum);
        $(this).val(diff);
      }
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Value 1</span>
<input id="inp1" type="text" />
<br />
<br />
<span>Value 2</span>
<input id="inp2" type="text" />


问:
How to list all files added to the first commit of a GIT repository?
Current status:
I am using git diff-tree -r HASH to list all added, modified and deleted files in a specific commit. This worked until today.

The problem:
I want to list all added files in my first commit, however passing the first HASH as a parameter doesn't work. Why?

Main question:
How can I get the list of all files added in my first commit?

答:
For the first commit, if you insist on git diff-tree -r HASH, one more parameter is needed, 4b825dc642cb6eb9a060e54bf8d69288fbee4904.

4b825dc642cb6eb9a060e54bf8d69288fbee4904 is an empty tree. In order to make this special tree object:

```<code>#inside your repo
git rm -r *
git write-tree
git reset HEAD --hard
</code>```

Or a more reliable way:

```<code>#inside your repo
git init temp
cd temp
git commit --allow-empty -m 'empty tree'
cd ..
git fetch temp/ master
rm -rf temp
</code>```

Now git diff-tree -r HASH 4b825dc642cb6eb9a060e54bf8d69288fbee4904 works.

You can tag this tree object for easy use in the future, and push it to other repos.

```<code>git tag void 4b825dc642cb6eb9a060e54bf8d69288fbee4904
git diff-tree -r HASH void
git push <remote> void
</code>```

Body:
For the first commit, if you insist on git diff-tree -r HASH, one more parameter is needed, 4b825dc642cb6eb9a060e54bf8d69288fbee4904.

4b825dc642cb6eb9a060e54bf8d69288fbee4904 is an empty tree. In order to make this special tree object:

#inside your repo
git rm -r *
git write-tree
git reset HEAD --hard

Or a more reliable way:

#inside your repo
git init temp
cd temp
git commit --allow-empty -m 'empty tree'
cd ..
git fetch temp/ master
rm -rf temp

Now git diff-tree -r HASH 4b825dc642cb6eb9a060e54bf8d69288fbee4904 works.

You can tag this tree object for easy use in the future, and push it to other repos.

git tag void 4b825dc642cb6eb9a060e54bf8d69288fbee4904
git diff-tree -r HASH void
git push <remote> void


问:
Calling WCF service using VBA code in Excel 2010
I'm trying to call an ASP.Net WCF service in XML from VBA in Excel 2010.

I read this question:
calling web service using VBA code in excel 2010
but I can't use a third party library, XML or JSON.

Is there a way to do it natively with VBA working with web services?

EDIT
I've installed SOAP Toolkit 3.0 and SOAP Toolkit 3.0 Software Update.

I've added these libraries to my workbook:

Microsoft XML, v3.0

Microsoft Soap Type Library v3.0

WinHttp Soap Connector Type Library

WinInet Soap Connector Type Library

Microsoft Soap WSDL File Generator v3.0

I think I have to add a web reference to my service into my workbook by "Tools->Add a web reference" menu, but this option doesn't appear. What should I do to see it ?

答:
I found a useful post dealing with the subject.

Web Service Software Factory 2010 is not maintained and seems to be obsolete.


问:
Python crawler does not work properly
I'd just written a Python crawler to download midi files from freemidi.org. Looking at the request headers in Chrome, I found that the "Referer" attribute had to be https://freemidi.org/download-20225 (referred to as "download-20225" later) if the download page was https://freemidi.org/getter-20225 (referred to as "getter-20225" later) in order to download the midi file properly. I did so in Python, setting the header like this:

```<code>headers = {
    'Referer': 'https://freemidi.org/download-20225',
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}
</code>```

which was exactly the same as the request header I had viewed in Chrome, and I tried to download the file using this line of code.

```<code>midi = requests.get(url, headers=headers).content
</code>```

However, it did not work properly. Instead of downloading the midi file, it downloaded a html file of the site "download-20225". I later found that if I tried to access the site "getter-20225" directly, it takes me to "download-20225" as well. I think it probably indicates that the header was wrong, so it took me to the other website instead of starting the download.

I'm quite new to writing Python crawlers, so could someone help me find what went wrong with the program?

答:
It looks like the problem here is that the page with the midi file (e.g. "getter-20225") wants to redirect you back to the song page (e.g. "download-20225") after downloading the song. However, requests is only returning the content from the final page in the redirect.

You can set the allow_redirects parameter to False to have requests return the content from the "getter" page (i.e. the midi file):

```<code>midi = requests.get(url, headers=headers, allow_redirects=False)
</code>```

Note that if you want to write the midi file to disk, you will need to open your target file in binary mode (since the midi file is written in bytes).

```<code>with open('example.mid', 'wb') as ex:
    ex.write(midi.content)
</code>```

Title: Python crawler does not work properly

Body:
I'd just written a Python crawler to download midi files from freemidi.org. Looking at the request headers in Chrome, I found that the "Referer" attribute had to be https://freemidi.org/download-20225 (referred to as "download-20225" later) if the download page was https://freemidi.org/getter-20225 (referred to as "getter-20225" later) in order to download the midi file properly. I did so in Python, setting the header like this:

headers = {
    'Referer': 'https://freemidi.org/download-20225',
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}

which was exactly the same as the request header I had viewed in Chrome, and I tried to download the file using this line of code.

midi = requests.get(url, headers=headers).content

However, it did not work properly. Instead of downloading the midi file, it downloaded a html file of the site "download-20225". I later found that if I tried to access the site "getter-20225" directly, it takes me to "download-20225" as well. I think it probably indicates that the header was wrong, so it took me to the other website instead of starting the download.

I'm quite new to writing Python crawlers, so could someone help me find what went wrong with the program?

Body:
It looks like the problem here is that the page with the midi file (e.g. "getter-20225") wants to redirect you back to the song page (e.g. "download-20225") after downloading the song. However, requests is only returning the content from the final page in the redirect.

You can set the allow_redirects parameter to False to have requests return the content from the "getter" page (i.e. the midi file):

midi = requests.get(url, headers=headers, allow_redirects=False)

Note that if you want to write the midi file to disk, you will need to open your target file in binary mode (since the midi file is written in bytes).

with open('example.mid', 'wb') as ex:
    ex.write(midi.content)


问:
Wildfly 9 - Want to expose 1 app to internet and another to intranet
Im working on Wildfly 9 and want to expose 1 app to intranet 10.x.x.x and another to Internet on 200.x.x.x

The question is how you do this in standalone.xml?

Thanks.

答:
You will need two standalone instances.

It's not possible separate aplications by IP.

This will bind all your apps for the configured IP:

```<code><interfaces>
    <interface name="public">
        <inet-address value="${jboss.bind.address:10.x.x.x}"/>
    </interface>
</interfaces>
</code>```

You can add other interface, but you can't apply that for only one app.

Body:
You will need two standalone instances.

It's not possible separate aplications by IP.

This will bind all your apps for the configured IP:

<interfaces>
    <interface name="public">
        <inet-address value="${jboss.bind.address:10.x.x.x}"/>
    </interface>
</interfaces>

You can add other interface, but you can't apply that for only one app.


问:
Openfire Android PubSub Subscription request aproval
I am new to Openfire and smack, therefore I have questions regarding pubsub feature. Actually, I have created a node with setAccessModel as authorize, shown below.

```<code>PubSubManager mgr = new PubSubManager(xmpp.getConnection());
try {
    LeafNode leaf = mgr.createNode("testNode");
    ConfigureForm form = new ConfigureForm(DataForm.Type.submit);
    form.setAccessModel(AccessModel.authorize);
    form.setDeliverPayloads(true);
    form.setNotifyRetract(true);
    form.setPersistentItems(true);
    form.setPublishModel(PublishModel.open);
    leaf.sendConfigurationForm(form);
} catch (SmackException.NoResponseException e) {
        e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
        e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
        e.printStackTrace();
}
</code>```

My question is that when somebody wants to subscribe to above node, how the owner of this node can handle the subscription request? Subscription part is as follows:

```<code>PubSubManager mgr = new PubSubManager(xmpp.getConnection());

// Get the node
LeafNode node = null;
try {
     node = mgr.getNode("testNode");
     node.addItemEventListener(new ItemEventCoordinator());
     node.subscribe(senderUser+"@desi.loc");
    } catch (SmackException.NoResponseException e) {
        e.printStackTrace();
    } catch (XMPPException.XMPPErrorException e) {
        e.printStackTrace();
    } catch (SmackException.NotConnectedException e) {
        e.printStackTrace();
    }

class ItemEventCoordinator  implements ItemEventListener {
    @Override
    public void handlePublishedItems(ItemPublishEvent items) {
        final ItemPublishEvent itemstemp=items;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //stuff that updates ui
                    dspySub.setText("Item: " + itemstemp.getItems());
            }
        });
    }
}
</code>```

When I set form.setAccessModel(AccessModel.open) every thing works fine. Users can publish and subscribe easily but when its AccessModel is authorize, owner don't listen, or might be I don't know how to handle subscription request at owner side with above piece of code. Kindly guide me.

答:
Jawad, I've just replied another guy' question about listening subscription requests. Please take a look:

How can i listen incoming subscription request in smack openfire android

I really hope that it can help you.

Good luck!

PS.: Sorry, but I haven't enough reputation to do a comment :(

Body:
I am new to Openfire and smack, therefore I have questions regarding pubsub feature. Actually, I have created a node with setAccessModel as authorize, shown below.

PubSubManager mgr = new PubSubManager(xmpp.getConnection());
try {
    LeafNode leaf = mgr.createNode("testNode");
    ConfigureForm form = new ConfigureForm(DataForm.Type.submit);
    form.setAccessModel(AccessModel.authorize);
    form.setDeliverPayloads(true);
    form.setNotifyRetract(true);
    form.setPersistentItems(true);
    form.setPublishModel(PublishModel.open);
    leaf.sendConfigurationForm(form);
} catch (SmackException.NoResponseException e) {
        e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
        e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
        e.printStackTrace();
}

My question is that when somebody wants to subscribe to above node, how the owner of this node can handle the subscription request? Subscription part is as follows:

PubSubManager mgr = new PubSubManager(xmpp.getConnection());

// Get the node
LeafNode node = null;
try {
     node = mgr.getNode("testNode");
     node.addItemEventListener(new ItemEventCoordinator());
     node.subscribe(senderUser+"@desi.loc");
    } catch (SmackException.NoResponseException e) {
        e.printStackTrace();
    } catch (XMPPException.XMPPErrorException e) {
        e.printStackTrace();
    } catch (SmackException.NotConnectedException e) {
        e.printStackTrace();
    }

class ItemEventCoordinator  implements ItemEventListener {
    @Override
    public void handlePublishedItems(ItemPublishEvent items) {
        final ItemPublishEvent itemstemp=items;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //stuff that updates ui
                    dspySub.setText("Item: " + itemstemp.getItems());
            }
        });
    }
}

When I set form.setAccessModel(AccessModel.open) every thing works fine. Users can publish and subscribe easily but when its AccessModel is authorize, owner don't listen, or might be I don't know how to handle subscription request at owner side with above piece of code. Kindly guide me.


问:
c++ create object with an array as member
i'm new to c++ (coming from java) and i'm actually struggeling with the
following:
Let foo be a class

```<code>int bar[10] = {};

Foo::Foo()
{
    bar[1] = 42;

}
</code>```

and doSmth() a method in the main class:

```<code>Foo doSmth(){
Foo f;
f.bar[0] = 10;
return f;
}
</code>```

the main will be something like:

```<code>int main(int argc, char *argv[])
{
Foo f = doSmth();

cout << f.bar[1] << endl;
cout << f.bar[0] << endl;
return 0;
}
</code>```

Is this the right way to return the foo-object in doSmth()?
I want to create the object on stack, but I'm worried about the array (bar) from the foo object, when will it be deleted from stack?

答:
If bar is a non-static data member of your class Foo, then the bar-content of a foo-object will be part of the foo-object; it will reside where foo resides (on the stack, on the heap, ...) and it will be created and destroyed once foo gets created or destroyed.

If bar is a static data member, then it will exist once in your complete program and will "live" until the program finishes.

Body:
i'm new to c++ (coming from java) and i'm actually struggeling with the
following:
Let foo be a class

int bar[10] = {};

Foo::Foo()
{
    bar[1] = 42;

}

and doSmth() a method in the main class:

Foo doSmth(){
Foo f;
f.bar[0] = 10;
return f;
}

the main will be something like:

int main(int argc, char *argv[])
{
Foo f = doSmth();

cout << f.bar[1] << endl;
cout << f.bar[0] << endl;
return 0;
}

Is this the right way to return the foo-object in doSmth()?
I want to create the object on stack, but I'm worried about the array (bar) from the foo object, when will it be deleted from stack?


问:
disable touch interaction in UITableView
I have a UITableView that draws a subView when the user touches a cell.

The problem is that the subView drawing is animated and if the user is fast enough they can tap a cell multiple times which I want to disable during the animation and afterwards.

I've tried using this:

```<code>- (void) tableView: (UITableView*) tableView didSelectRowAtIndexPath: (NSIndexPath*) indexPath {

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
</code>```

and also a bool variable:

```<code>if (isAnimating == NO) {
</code>```

but neither seem to work. In each case rapid touches screws up everything.

Any help would be great thanks!

答:
I know this is an old question however it lacked the swift version so,
in Swift 3 it is:

```<code>tableView.isUserInteractionEnabled = false;
</code>```

and to turn it back on is:

```<code>tableView.isUserInteractionEnabled = true;
</code>```

Just thought this might help someone if they were looking for the answer in swift 3 as I was, and ends up here.

Body:
I have a UITableView that draws a subView when the user touches a cell.

The problem is that the subView drawing is animated and if the user is fast enough they can tap a cell multiple times which I want to disable during the animation and afterwards.

I've tried using this:

- (void) tableView: (UITableView*) tableView didSelectRowAtIndexPath: (NSIndexPath*) indexPath {

    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];

and also a bool variable:

if (isAnimating == NO) {

but neither seem to work. In each case rapid touches screws up everything.

Any help would be great thanks!

Body:
I know this is an old question however it lacked the swift version so,
in Swift 3 it is:

tableView.isUserInteractionEnabled = false;

and to turn it back on is:

tableView.isUserInteractionEnabled = true;

Just thought this might help someone if they were looking for the answer in swift 3 as I was, and ends up here.


问:
Get the first ocurrence of a string in a variable REGEX
I have the following variable in a database: PSC-CAMPO-GRANDE-I08-V00-C09-H09-IPRMKT and I want to split it into two variables, the first will be PSC-CAMPO-GRANDE-I08 and the second V00-C09-H09-IPRMKT.

I'm trying the regex .*(\-I).*(\-V), this doesn't work. Then I tried .*(\-I), but it gets the last -IPRMKT string.

Then my question is: There a way of split the string PSC-CAMPO-GRANDE-I08-V00-C09-H09-IPRMKT considering the first occurrence of -I?

答:
You may use

```<code>^(.*?-I[^-]*)-(.*)
</code>```

See the regex demo

Details:

^ - start of a string

(.*?-I[^-]*) - Group 1:

.*? - any 0+ 0+ chars other than line break chars up to the first (because *? is a lazy quantifier that matches up to the first occurrence)

-I - a literal substring -I

[^-]* - any 0+ chars other than a hyphen (your pattern was missing it)

- -  a hyphen

(.*) - Group 2: any 0+ chars other than line break chars up to the end of a line.

Body:
You may use

^(.*?-I[^-]*)-(.*)

See the regex demo

Details:

^ - start of a string

(.*?-I[^-]*) - Group 1:

.*? - any 0+ 0+ chars other than line break chars up to the first (because *? is a lazy quantifier that matches up to the first occurrence)

-I - a literal substring -I

[^-]* - any 0+ chars other than a hyphen (your pattern was missing it)

- -  a hyphen

(.*) - Group 2: any 0+ chars other than line break chars up to the end of a line.


问:
Proper use of generics with collection instance factory
I'm trying to do the following thing using Apache Commons Collections v4:

```<code>Map<Integer, List<String>> namesPerNumber =
        MapUtils.lazyMap(
            new HashMap<Integer, List<String>>(),
            FactoryUtils.instantiateFactory(ArrayList.class));

namesPerNumber.get(1).add("Mickey");
</code>```

But I get the following compiler error at the lazyMap call:

The method lazyMap(Map<K,V>, Factory<? extends V>) in the type MapUtils is not applicable for the arguments (HashMap<Integer,List<String&t;>, Factory<ArrayList>)

Is there any proper way to use the factory for generating lists in a map? I tried also this:

```<code>Map<Integer, List<String>> namesPerNumber =
            MapUtils.lazyMap(
                new HashMap<Integer, List<String>>(),
                FactoryUtils.<List<String>instantiateFactory(ArrayList.class));
</code>```

But then I get this error at the instantiateFactory call:

The parameterized method <List<String>>instantiateFactory(Class<List<String>>) of type FactoryUtils is not applicable for the arguments (Class<ArrayList>)

The only working solution I found is the following, but I find it ugly:

```<code>Map<Integer, List<String>> namesPerNumber3 =
            MapUtils.lazyMap(
                new HashMap<Integer, List<String>>(),
                new Factory<List<String>>() {
                    @Override
                    public List<String> create() {
                        return new ArrayList<String>();
                    }
                });
</code>```

Any help appreciated.

Signed,

lostingenerics

答:
Due to type erasure, class literals support only reifiable types or raw types, so ArrayList.class represents the raw type ArrayList, not the intended ArrayList<String>.

One way to solve this, is by using one unchecked operation:

```<code>@SuppressWarnings("unchecked") Class<ArrayList<String>> type = (Class)ArrayList.class;

Map<Integer, List<String>> namesPerNumber =
    MapUtils.lazyMap(
        new HashMap<Integer, List<String>>(),
        FactoryUtils.instantiateFactory(type));
</code>```

Note that the effect of @SuppressWarnings("unchecked") is intentionally limited to the single unchecked operation here.

Or you use

```<code>Map<Integer, List<String>> namesPerNumber =
    MapUtils.lazyMap(
        new HashMap<Integer, List<String>>(),
        FactoryUtils.prototypeFactory(new ArrayList<String>()));
</code>```

instead.

If you are using Java 8, the best option is

```<code>Map<Integer, List<String>> namesPerNumber =
    MapUtils.lazyMap(new HashMap<>(), () -> new ArrayList<>());
</code>```

Body:
I'm trying to do the following thing using Apache Commons Collections v4:

Map<Integer, List<String>> namesPerNumber =
        MapUtils.lazyMap(
            new HashMap<Integer, List<String>>(),
            FactoryUtils.instantiateFactory(ArrayList.class));

namesPerNumber.get(1).add("Mickey");

But I get the following compiler error at the lazyMap call:

The method lazyMap(Map<K,V>, Factory<? extends V>) in the type MapUtils is not applicable for the arguments (HashMap<Integer,List<String&t;>, Factory<ArrayList>)

Is there any proper way to use the factory for generating lists in a map? I tried also this:

Map<Integer, List<String>> namesPerNumber =
            MapUtils.lazyMap(
                new HashMap<Integer, List<String>>(),
                FactoryUtils.<List<String>instantiateFactory(ArrayList.class));

But then I get this error at the instantiateFactory call:

The parameterized method <List<String>>instantiateFactory(Class<List<String>>) of type FactoryUtils is not applicable for the arguments (Class<ArrayList>)

The only working solution I found is the following, but I find it ugly:

Map<Integer, List<String>> namesPerNumber3 =
            MapUtils.lazyMap(
                new HashMap<Integer, List<String>>(),
                new Factory<List<String>>() {
                    @Override
                    public List<String> create() {
                        return new ArrayList<String>();
                    }
                });

Any help appreciated.

Signed,

lostingenerics

Body:
Due to type erasure, class literals support only reifiable types or raw types, so ArrayList.class represents the raw type ArrayList, not the intended ArrayList<String>.

One way to solve this, is by using one unchecked operation:

@SuppressWarnings("unchecked") Class<ArrayList<String>> type = (Class)ArrayList.class;

Map<Integer, List<String>> namesPerNumber =
    MapUtils.lazyMap(
        new HashMap<Integer, List<String>>(),
        FactoryUtils.instantiateFactory(type));

Note that the effect of @SuppressWarnings("unchecked") is intentionally limited to the single unchecked operation here.

Or you use

Map<Integer, List<String>> namesPerNumber =
    MapUtils.lazyMap(
        new HashMap<Integer, List<String>>(),
        FactoryUtils.prototypeFactory(new ArrayList<String>()));

instead.

If you are using Java 8, the best option is

Map<Integer, List<String>> namesPerNumber =
    MapUtils.lazyMap(new HashMap<>(), () -> new ArrayList<>());


答:
Is this the right way to return the foo object in doSmth()?

It sure is.

I want to create the object on stack

You have.

but i'm worried about the array (bar) from the foo object

bar is not "from foo". bar is a global static object.

```<code>f.bar[1]
</code>```

This is ill formed, since bar is not a member of Foo. To declare a member, it has to be inside the definition of the class:

```<code>struct Foo {
    int bar[10] = {};
};
</code>```

when will it be deleted from stack?

If bar has static storage, such as in your code, then it is destroyed at the end of the program. If it is a (non static) member, then it is destroyed when its complete object is destroyed i.e. the instance of Foo that contains it.

Title: c++ create object with an array as member

Body:
Is this the right way to return the foo object in doSmth()?

It sure is.

I want to create the object on stack

You have.

but i'm worried about the array (bar) from the foo object

bar is not "from foo". bar is a global static object.

f.bar[1]

This is ill formed, since bar is not a member of Foo. To declare a member, it has to be inside the definition of the class:

struct Foo {
    int bar[10] = {};
};

when will it be deleted from stack?

If bar has static storage, such as in your code, then it is destroyed at the end of the program. If it is a (non static) member, then it is destroyed when its complete object is destroyed i.e. the instance of Foo that contains it.