问:
How do i use nth-child to the icons while hovering?
How do I use nth-child technique so that each time use hover a particular icon, it should change color and pop-up without disturbing the others. I tried and the effects are working for every icons not on a particular one.

.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  color: crimson;
  padding: 10px;
}

.icon ul li a i {
  font-size: 20px;
}

.icon ul li a:nth-child(1):hover {
  color: blue;
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<label><strong>Or follow Us -</strong></label>
<div class="icon">
  <ul>
    <li><i class="fa fa-facebook"></i></li>
    <li><i class="fa fa-twitter"></i></li>
    <li><i class="fa fa-linkedin"></i></li>
    <li><i class="fa fa-youtube"></i></li>
    <li><i class="fa fa-instagram"></i></li>
  </ul>
</div></code>```

答:
Assign font-size to only one element either a or i. And use li:nth-child(1)

To make font larger on hover, instead of increasing font-size,
Try Css scale().

```<code>-ms-transform: scale(1.2); /* IE 9 */
    -webkit-transform: scale(1.2); /* Safari */
    transform: scale(1.2)
</code>```

Body:
How do I use nth-child technique so that each time use hover a particular icon, it should change color and pop-up without disturbing the others. I tried and the effects are working for every icons not on a particular one.

.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  color: crimson;
  padding: 10px;
}

.icon ul li a i {
  font-size: 20px;
}

.icon ul li a:nth-child(1):hover {
  color: blue;
  font-size: 25px;
}

<link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

Or follow Us -

Body:
Assign font-size to only one element either a or i. And use li:nth-child(1)

To make font larger on hover, instead of increasing font-size,
Try Css scale().

-ms-transform: scale(1.2); /* IE 9 */
    -webkit-transform: scale(1.2); /* Safari */
    transform: scale(1.2)


来源: stackexchange

答:
You want to use :nth-child(1) on the li and not on the a element. Like this:

```<code>.icon ul li:nth-child(1) a:hover
</code>```

This selects the first li element among a collection of sibling li's. What you were trying to do was to select the first a element in a collection of sibling a's, but there is only one sibling a in each li.

Full demo:

.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  color: crimson;
  padding: 10px;
}

.icon ul li a i {
  font-size: 20px;
}

.icon ul li:nth-child(1) a:hover {
  color: blue;
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<label><strong>Or follow Us -</strong></label>
<div class="icon">
  <ul>
    <li><i class="fa fa-facebook"></i></li>
    <li><i class="fa fa-twitter"></i></li>
    <li><i class="fa fa-linkedin"></i></li>
    <li><i class="fa fa-youtube"></i></li>
    <li><i class="fa fa-instagram"></i></li>
  </ul>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: How do i use nth-child to the icons while hovering?

Body:
You want to use :nth-child(1) on the li and not on the a element. Like this:

.icon ul li:nth-child(1) a:hover

This selects the first li element among a collection of sibling li's. What you were trying to do was to select the first a element in a collection of sibling a's, but there is only one sibling a in each li.

Full demo:

.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  color: crimson;
  padding: 10px;
}

.icon ul li a i {
  font-size: 20px;
}

.icon ul li:nth-child(1) a:hover {
  color: blue;
  font-size: 25px;
}

<link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<label><strong>Or follow Us -</strong></label>
<div class="icon">
  <ul>
    <li><a href="https://facebook.com"><i class="fa fa-facebook"></i></a></li>
    <li><a href="https://twitter.com"><i class="fa fa-twitter"></i></a></li>
    <li><a href="https://linkedin.com"><i class="fa fa-linkedin"></i></a></li>
    <li><a href="https://Youtube.com"><i class="fa fa-youtube"></i></a></li>
    <li><a href="https://instagram.com"><i class="fa fa-instagram"></i></a></li>
  </ul>
</div>


问:
convert newline to br textarea java servlet
I'm trying to convert below message to represent in the text Area which i got from the The JAVA Rest API call (Thirdpaty)and the message  is this

```<code>String x =   "-----BEGIN PGP MESSAGE-----\nVersion: BCPG v1.58\n\nhIwDmCS94uDDx9kBA/4jkqEOWjbe03C1Dgd2A9eDBdk6cYczsOu6Typm0kjT15uQ\nT+Qc4Koz/yIq4gQpwccxRQ9NGl3Bi1cmPYvwxHIe+4bmqd31Izdkaj1VJCEVqZl2\nrLZvogFOo1oHUmdL2uIdUQJGJgslEOh91wp7CfxGhlxKSg0PvY3gyyWyofUwx9JU\nAUu+NY6YYrfd2l95C7EmMJXUDPysCitl/TGy04DbMuMNAyjZPPfkXqvjcG4A10nk\nPujs6RjnRYyCk+3ZJxvkhsjvGXKIQi7gTgWz7AV8vkBhSM2M\n\u003dRtkb\n-----END PGP MESSAGE-----\n"
</code>```

When the message displays in the HTML text Area after applying regex patterns

```<code>x.replaceAll("(\r\n|\n)", "<br />");
x.replaceAll("(\r\n|\n)", "<br />");

<textarea rows="10" cols="50" id="test" name="test"><%=pKey%> </textarea>
</code>```

still appearing like this

The Expected Output I'm not getting is this

答:
Use this, x=x.replace("\\n", "
"); it will work

```<code>PrintWriter pw=res.getWriter();

    pw.println("<textarea name='suggest_list' rows='10' id='word_suggest'>");
    pw.println(x);
    pw.println("</textarea>");
    pw.println("</body></html>");
</code>```

Output

Body:
I'm trying to convert below message to represent in the text Area which i got from the The JAVA Rest API call (Thirdpaty)and the message  is this

String x =   "-----BEGIN PGP MESSAGE-----\nVersion: BCPG v1.58\n\nhIwDmCS94uDDx9kBA/4jkqEOWjbe03C1Dgd2A9eDBdk6cYczsOu6Typm0kjT15uQ\nT+Qc4Koz/yIq4gQpwccxRQ9NGl3Bi1cmPYvwxHIe+4bmqd31Izdkaj1VJCEVqZl2\nrLZvogFOo1oHUmdL2uIdUQJGJgslEOh91wp7CfxGhlxKSg0PvY3gyyWyofUwx9JU\nAUu+NY6YYrfd2l95C7EmMJXUDPysCitl/TGy04DbMuMNAyjZPPfkXqvjcG4A10nk\nPujs6RjnRYyCk+3ZJxvkhsjvGXKIQi7gTgWz7AV8vkBhSM2M\n\u003dRtkb\n-----END PGP MESSAGE-----\n"

When the message displays in the HTML text Area after applying regex patterns

x.replaceAll("(\r\n|\n)", "
");
x.replaceAll("(\r\n|\n)", "
");

<textarea rows="10" cols="50" id="test" name="test"><%=pKey%> </textarea>

still appearing like this

The Expected Output I'm not getting is this

Body:
Use this, x=x.replace("\\n", "<br />"); it will work

PrintWriter pw=res.getWriter();

    pw.println("<textarea name='suggest_list' rows='10' id='word_suggest'>");
    pw.println(x);
    pw.println("</textarea>");
    pw.println("</body></html>");

Output


问:
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function?

```<code>bool returnValue = true;
// Code that does something
return(returnValue);
</code>```

and this?

```<code>bool returnValue = true;
// Code
return returnValue;
</code>```

The former has parentheses around returnValue.

答: Nope there's no difference between the two, although you can include parenthesis if it makes the expression easy to read and clear.</p>

ContentLicense: CC BY-SA 4.0

Body:
Is there a difference between these two statements inside a function?

bool returnValue = true;
// Code that does something
return(returnValue);

and this?

bool returnValue = true;
// Code
return returnValue;

The former has parentheses around returnValue.

ContentLicense: CC BY-SA 2.5


答:
The nth-child declaration should be based on li. In your code, you put it for the anchor tag. Here is the correct code.

.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  color: crimson;
  padding: 10px;
}

.icon ul li a i {
  font-size: 20px;
}

.icon ul li:nth-child(1) a:hover {
  color: blue;
  font-size: 25px;
}
.icon ul li:nth-child(2) a:hover {
  color: green;
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<label><strong>Or follow Us -</strong></label>
<div class="icon">
  <ul>
    <li><i class="fa fa-facebook"></i></li>
    <li><i class="fa fa-twitter"></i></li>
    <li><i class="fa fa-linkedin"></i></li>
    <li><i class="fa fa-youtube"></i></li>
    <li><i class="fa fa-instagram"></i></li>
  </ul>
</div></code>```

Body:
The nth-child declaration should be based on li. In your code, you put it for the anchor tag. Here is the correct code.

.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  color: crimson;
  padding: 10px;
}

.icon ul li a i {
  font-size: 20px;
}

.icon ul li:nth-child(1) a:hover {
  color: blue;
  font-size: 25px;
}
.icon ul li:nth-child(2) a:hover {
  color: green;
  font-size: 25px;
}

<link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<label><strong>Or follow Us -</strong></label>
<div class="icon">
  <ul>
    <li><a href="https://facebook.com"><i class="fa fa-facebook"></i></a></li>
    <li><a href="https://twitter.com"><i class="fa fa-twitter"></i></a></li>
    <li><a href="https://linkedin.com"><i class="fa fa-linkedin"></i></a></li>
    <li><a href="https://Youtube.com"><i class="fa fa-youtube"></i></a></li>
    <li><a href="https://instagram.com"><i class="fa fa-instagram"></i></a></li>
  </ul>
</div>


答:
.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  padding: 10px;
  display:inline-block;
}

.icon ul li a i {
  font-size: 20px;
  color: crimson;
  -webkit-transition:transform .3s;
}

.icon ul li a i:hover {
  color: blue;
  -webkit-transform:scale(1.2);
  -webkit-transition:transform .3s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<label><strong>Or follow Us -</strong></label>
<div class="icon">
  <ul>
    <li><i class="fa fa-facebook"></i></li>
    <li><i class="fa fa-twitter"></i></li>
    <li><i class="fa fa-linkedin"></i></li>
    <li><i class="fa fa-youtube"></i></li>
    <li><i class="fa fa-instagram"></i></li>
  </ul>
</div></code>```

no need nth-child

Body:
.icon ul li {
  list-style: none;
  display: inline;
  margin: 30px;
}

.icon {
  background: #000;
}

.icon ul li a {
  text-decoration: none;
  padding: 10px;
  display:inline-block;
}

.icon ul li a i {
  font-size: 20px;
  color: crimson;
  -webkit-transition:transform .3s;
}

.icon ul li a i:hover {
  color: blue;
  -webkit-transform:scale(1.2);
  -webkit-transition:transform .3s;
}

<link href="https://fonts.googleapis.com/css?
family=Berkshire+Swash|Boogaloo|Lobster+Two|Raleway|Amaranth"
rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet">

<label><strong>Or follow Us -</strong></label>
<div class="icon">
  <ul>
    <li><a href="https://facebook.com"><i class="fa fa-facebook"></i></a></li>
    <li><a href="https://twitter.com"><i class="fa fa-twitter"></i></a></li>
    <li><a href="https://linkedin.com"><i class="fa fa-linkedin"></i></a></li>
    <li><a href="https://Youtube.com"><i class="fa fa-youtube"></i></a></li>
    <li><a href="https://instagram.com"><i class="fa fa-instagram"></i></a></li>
  </ul>
</div>

no need nth-child


问:
Select timer continues running after the process has been stopped with SIGSTOP?
I have tried to stop a process through sending SIGSTOP and then after the timeout value of select (4min) then send a SIGCONT. The select call immediately then fails with a timeout, is there a way to prevent having select's timer running while the process is frozen?

答: Select seems to check the OS time and based on it decides if the timeout has been elapsed. So even if the process is suspended, Select will still timeout (if the process was suspended during a select call of course)</p>


问:
(ILC0005 Error) i couldn't compile UWP x64/x86 Release project
I'm creating a UWP Project for windows 10.

I have googled about this problem, cleaned obj and bin folder by myself.

Then, my project folder, there is only ascii characters.

My changes had no effect.

1>C:\Program Files
  (x86)\MSBuild\Microsoft.NetNative\x64\ilc\IlcInternals.targets(1192,5):
  error : 内部コンパイラ エラー (Internal Compile Error)
  1>C:\Program Files
  (x86)\MSBuild\Microsoft.NetNative\x64\ilc\IlcInternals.targets(1192,5):
  error : ILT0005: 'C:\Program Files
  (x86)\MSBuild\Microsoft.NetNative\x64\ilc\Tools\nutc_driver.exe
  @"(Project
  Folder)obj\x64\Release\ilc\intermediate\MDIL\ECToolControl.rsp"'
  は終了コード 1 を戻しました (was returned exit code 1)

答:
1>C:\Program Files (x86)\MSBuild\Microsoft.NetNative\x64\ilc\IlcInternals.targets(1192,5): error : 内部コンパイラ エラー (Internal Compile Error) 1>C:\Program Files (x86)\MSBuild\Microsoft.NetNative\x64\ilc\IlcInternals.targets(1192,5): error : ILT0005: 'C:\Program Files (x86)\MSBuild\Microsoft.NetNative\x64\ilc\Tools\nutc_driver.exe @"(Project Folder)obj\x64\Release\ilc\intermediate\MDIL\ECToolControl.rsp"' は終了コード 1 を戻しました (was returned exit code 1)

Please try to uncheck Compile with .Net Native tool chain option in project property. It will work.


问:
Elasticsearch: Data Encryption at Rest
I am trying to encrypt the Elasticsearch data. Are there any native methods to encrypt the data?
I studied about Elasticsearch supporting dm-crypt, but there are no proper supporting documents on how it is being implemented.
Also, my clients need free/opensource alternatives to Shield/X-Pack.

TIA.

答:
What is the supposed behaviour for encryption? Be able to search against encrypted data or just store some sensitive fields (e.g. PII) encrypted?

First of all, consider removing your sensitive data from ELK stack, as it isn't a reliable place to store it there. Detach it (just remove and store somewhere else or tokenize, if you want to have a link to it) or obfuscate before pushing to ELK.

As an alternative to performing encryption by means of Elasticsearch or its plugins, you can encrypt your data in the application that pushes data to ES in advance and just keep a couple of index fields (which are going to be used to search by) in plain text. E.g.

```<code>{
    "index_field" : "John Doe", // plain text to search by
    "address" : "s3_34$af78...", // encrypted
    "passport" : "3%75O9gfjdg4%...", // encrypted
    ...
}
</code>```

That depends on your specific application, however in some cases solving encryption & key management questions would be much easier than looking for a particular solution e.g. for ES.

Title: Elasticsearch: Data Encryption at Rest

Body:
What is the supposed behaviour for encryption? Be able to search against encrypted data or just store some sensitive fields (e.g. PII) encrypted?

First of all, consider removing your sensitive data from ELK stack, as it isn't a reliable place to store it there. Detach it (just remove and store somewhere else or tokenize, if you want to have a link to it) or obfuscate before pushing to ELK.

As an alternative to performing encryption by means of Elasticsearch or its plugins, you can encrypt your data in the application that pushes data to ES in advance and just keep a couple of index fields (which are going to be used to search by) in plain text. E.g.

{
    "index_field" : "John Doe", // plain text to search by
    "address" : "s3_34$af78...", // encrypted
    "passport" : "3%75O9gfjdg4%...", // encrypted
    ...
}

That depends on your specific application, however in some cases solving encryption & key management questions would be much easier than looking for a particular solution e.g. for ES.


问:
Can I have toolbar for each fragment separately. How to handle navigation drawer
In my app some pages have custom view in toolbar. Some fragment have transparent toolbar and some have coordinate layout scroll.

So I have decided to have toolbar separate for each fragment I want to know is it a good practice or not.

If someone has already done this please share code or example.

答:
You can use custom toolbars in your fragments. and you have to implement them separately for each fragment. First of all declare your toolbar in your fragment layout :

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            >
<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:gravity="start"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    >

    <RelativeLayout
       // your custom toolbar layout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </RelativeLayout>

</android.support.v7.widget.Toolbar>
</code>```

Then implement it in your fragment:

find it in fragment:

```<code> @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
    savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);

        //set toolbar appearance
        toolbar.setBackground(your background);

        //for create home button
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

  return view;
}
</code>```

And yes you can implement click listeners and whatever you want to do with your toolbar. For more take a look at the second answer:
How to get custom toolbar

Body:
You can use custom toolbars in your fragments. and you have to implement them separately for each fragment. First of all declare your toolbar in your fragment layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white"
            >
<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:gravity="start"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    >

    <RelativeLayout
       // your custom toolbar layout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </RelativeLayout>

</android.support.v7.widget.Toolbar>

Then implement it in your fragment:

find it in fragment:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
    savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);

        //set toolbar appearance
        toolbar.setBackground(your background);

        //for create home button
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

  return view;
}

And yes you can implement click listeners and whatever you want to do with your toolbar. For more take a look at the second answer:
How to get custom toolbar


问:
Installing outlook add-in every time user logs off
I have an Outlook add-in that is working fine for every client. They get the installation (ClickOnce) from the web, install it and run it without any problem. However, I just got this client that it's complaining about seeing that "Microsoft Office Customization Installer" window (and of course, downloading and installing the add-in again) every time he logs off and logs back (he can close outlook and re-open it without any issues). BTW, He is using a Terminal Services environment.

Does anyone have any idea why this is happening and/or how to solve it?

答: It is probably a policy or login script that removes any installed applications. You'd best talk to his system administrator.</p>


问:
libuv fs read file print one more time
Recently I am writing some c code to simply read file and print out content using libuv.

But I don't know why my code would print first buffer twice.

```<code>void open_cb(uv_fs_t* open_req){
    int r = 0;
    if(open_req -> result < 0 ) printf("open_req");

    context_t* context = open_req -> data;

    size_t buf_len = sizeof(char) * BUF_SIZE;
    char *buf = malloc(buf_len);
    context->iov = uv_buf_init(buf, buf_len);
    context->times = 0;

    uv_fs_t *read_req = malloc(sizeof(uv_fs_t));
    context->read_req = read_req;
    read_req->data = context;
    r = uv_fs_read(uv_default_loop(), read_req, open_req->result, &context->iov, 1, 0, read_cb);
}
void read_cb(uv_fs_t* read_req){
    int r = 0;

    //uv_fs_t* close_req = mollac(sizeof(uv_fs_t));
    if(read_req->result < 0){
        printf("read_req");
        return;
    }else if(read_req->result == 0){
        printf("read finish\n");
        return;
    }

    context_t* context = read_req->data;

    printf("%zu %zu", read_req->result, context->read_open_req->result);
    printf("%i :", context->times);
    printf("%s\n", context->iov.base);

    size_t buf_len = sizeof(char) * BUF_SIZE;
    char *buf = malloc(buf_len);
    context->iov = uv_buf_init(buf, buf_len);
    context->times++;
    read_req->data = context;

    r = uv_fs_read(uv_default_loop(), read_req, context->read_open_req->result, &context->iov, 1, -1, read_cb);
    if(r<0) printf("read_req");
}
</code>```

I am reading this file with only one line text: "hello1234567\n",
the buffer size is 5 so it would print 5 characters per time.

However the result is

```<code>read result:5, open result:10
time: 0 :hello
read result:5, open result:10
time: 1 :hello
read result:5, open result:10
time: 2 :12345
read result:3, open result:10
time: 3 :67

read finish
</code>```

first number is read_req->result, second number is context->read_open_req->result.

Other codes are similar to the official tutorial

Thanks.

答:
Finally found out my stupid mistake.

r = uv_fs_read(uv_default_loop(), read_req, open_req->result, &context->iov, 1, 0, read_cb);

The params offset should be -1 instead of 0 to read from prev offset.

Title: libuv fs read file print one more time

Body:
Recently I am writing some c code to simply read file and print out content using libuv.

But I don't know why my code would print first buffer twice.

void open_cb(uv_fs_t* open_req){
    int r = 0;
    if(open_req -> result < 0 ) printf("open_req");

    context_t* context = open_req -> data;

    size_t buf_len = sizeof(char) * BUF_SIZE;
    char *buf = malloc(buf_len);
    context->iov = uv_buf_init(buf, buf_len);
    context->times = 0;

    uv_fs_t *read_req = malloc(sizeof(uv_fs_t));
    context->read_req = read_req;
    read_req->data = context;
    r = uv_fs_read(uv_default_loop(), read_req, open_req->result, &context->iov, 1, 0, read_cb);
}
void read_cb(uv_fs_t* read_req){
    int r = 0;

    //uv_fs_t* close_req = mollac(sizeof(uv_fs_t));
    if(read_req->result < 0){
        printf("read_req");
        return;
    }else if(read_req->result == 0){
        printf("read finish\n");
        return;
    }

    context_t* context = read_req->data;

    printf("%zu %zu", read_req->result, context->read_open_req->result);
    printf("%i :", context->times);
    printf("%s\n", context->iov.base);

    size_t buf_len = sizeof(char) * BUF_SIZE;
    char *buf = malloc(buf_len);
    context->iov = uv_buf_init(buf, buf_len);
    context->times++;
    read_req->data = context;

    r = uv_fs_read(uv_default_loop(), read_req, context->read_open_req->result, &context->iov, 1, -1, read_cb);
    if(r<0) printf("read_req");
}

I am reading this file with only one line text: "hello1234567\n",
the buffer size is 5 so it would print 5 characters per time.

However the result is

read result:5, open result:10
time: 0 :hello
read result:5, open result:10
time: 1 :hello
read result:5, open result:10
time: 2 :12345
read result:3, open result:10
time: 3 :67

read finish

first number is read_req->result, second number is context->read_open_req->result.

Other codes are similar to the official tutorial

Thanks.


问:
Basic Auth + oAuth Implementation in Spring Boot
I am trying to implement Basic Auth + oAuth2 in springboot,
means some url should work like traditional way after login to system, and some should work on AOuth2.

Like I want to allow access to SuperAdmin for admin panel, with url starts from

/superAdmin/****

I just want to access all the these url after general login into the system.

and Rest service should work on AOuth2 with url starts form

/api/vi/****

these urls are use to give access to the applicants.

Separately both are working fine, but together both are not working.

here is my configurations.

```<code>import in.kpis.tracking.configuration.CustomAuthenticationSuccessHandler;
import in.kpis.tracking.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
public class OAuth2ServerConfiguration {

    protected static final String RESOURCE_ID = "restservice";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            // @formatter:off
            resources.resourceId(RESOURCE_ID);
            // @formatter:on
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/api/v1/*").hasRole("ADMIN")
                    .antMatchers("/greeting").authenticated();
        }
    }

    @Configuration
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private AdminUserService adminUserService;

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(adminUserService);
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

    }

    @Configuration
    @Order(1)
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {

            String[] permitAll = new String[]{"/error"};
            String[] permitToSuperAdmin = new String[]{
                    "/superAdmin/*",
            };

            http.authorizeRequests()
                    .antMatchers(permitToSuperAdmin).access("hasRole('SUPER_ADMIN')")
                    .antMatchers("/login").permitAll()
                    .and().formLogin().loginPage("/userLogin.html")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginProcessingUrl("/login")
                    .successHandler(new CustomAuthenticationSuccessHandler())
                    .and()
                    .logout().logoutSuccessUrl("/userLogin.html?logout")
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true);
            http.csrf().disable();
        }
    }
}
</code>```

答:
If you need different security setups for different parts of your application, you need to create separate Spring Security @Configuration-s, where each one will configure just one authentication mechanism. Each configuration should specify the URIs it covers and the configurations need to be @Order-ed. The configuration without the @Order annotation is considered the last - the fallback. It's described in the Spring Security reference manual.

So you will need three configurations:

One for the http.antMatcher("/superAdmin/**")... with @Order(1).

One for the API http.antMatcher("/api/vi/**")... with @Order(2).

A fallback config without authentication for other resources, without the @Order annotation specified.

Body:
I am trying to implement Basic Auth + oAuth2 in springboot,
means some url should work like traditional way after login to system, and some should work on AOuth2.

Like I want to allow access to SuperAdmin for admin panel, with url starts from

/superAdmin/****

I just want to access all the these url after general login into the system.

and Rest service should work on AOuth2 with url starts form

/api/vi/****

these urls are use to give access to the applicants.

Separately both are working fine, but together both are not working.

here is my configurations.

import in.kpis.tracking.configuration.CustomAuthenticationSuccessHandler;
import in.kpis.tracking.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
public class OAuth2ServerConfiguration {

    protected static final String RESOURCE_ID = "restservice";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            // @formatter:off
            resources.resourceId(RESOURCE_ID);
            // @formatter:on
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/api/v1/*").hasRole("ADMIN")
                    .antMatchers("/greeting").authenticated();
        }
    }

    @Configuration
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private AdminUserService adminUserService;

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(adminUserService);
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

    }

    @Configuration
    @Order(1)
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {

            String[] permitAll = new String[]{"/error"};
            String[] permitToSuperAdmin = new String[]{
                    "/superAdmin/*",
            };

            http.authorizeRequests()
                    .antMatchers(permitToSuperAdmin).access("hasRole('SUPER_ADMIN')")
                    .antMatchers("/login").permitAll()
                    .and().formLogin().loginPage("/userLogin.html")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginProcessingUrl("/login")
                    .successHandler(new CustomAuthenticationSuccessHandler())
                    .and()
                    .logout().logoutSuccessUrl("/userLogin.html?logout")
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true);
            http.csrf().disable();
        }
    }
}


问:
Workaround to Hero Card as attachment markdown formatting?
I know that markdown is supported on the HeroCard "text" field value, even though I couldn't make it work(Tested on MSTeams):

Code

```<code>this.bot.dialog("sendCard", (session, args, next) => {
    session.sendTyping();
    const card = new builder.HeroCard(session);

    card.title("Title");
    card.subtitle("Subtitle");
    card.text("This is some *mardown* text! \n\n - one \n\n - two");

    const msg = new builder.Message(session);

    msg.textFormat("markdown");
    msg.attachments([
        card,
    ]);
    session.endDialog(msg);
});
</code>```

I am wondering how can I achieve this formatting(From mailclark bot in MSTeams):

As you can see, it is a carousel of what I think it might be HeroCards, but they are formatted with bold, code and unordered lists on new paragraphs.

It seems to be a known issue that message attachments do not receive formatting, but how could the mailclark guys achieve it?

Edit:
Unordered list example:

Bold and code example:

答:
As Hero Cards eventually will be convert to Rich Card send to user from bot, and from MS Teams documents at https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-conversations#formatting-text-content:

Microsoft Teams supports a subset of Markdown and XML (HTML) formatting tags.

Rich cards do not support Markdown or table formatting

So in MS Teams channel, markdown formatting is only supported in text only message, however, we can leverage HTML tags in Rich Card.

Please consider following code snippet:

```<code>bot.dialog('/', function (session) {
    const card = new builder.HeroCard(session);
    card.title("Type your question to our support team here");
    card.subtitle("Or, click the ◀▶ arrows for a series of how-tos");
    card.images([builder.CardImage.create(session,"<image url>")])
    card.text("<p>This is some <i>mardown</i> <b>text</b>!</p> <ul><li><b>one</b></li><li><code>two</code></li></ul>")
    const msg = new builder.Message(session);
    msg.attachmentLayout(builder.AttachmentLayout.carousel);
    msg.attachments([
        card,card,card
    ]).toMessage();
    session.send(msg);
    session.endDialog("This is some *mardown* **text**! \n\n - **one** \n\n - `two`");
});
</code>```

This shows in MS Teams as following:

Body:
I know that markdown is supported on the HeroCard "text" field value, even though I couldn't make it work(Tested on MSTeams):

Code

this.bot.dialog("sendCard", (session, args, next) => {
    session.sendTyping();
    const card = new builder.HeroCard(session);

    card.title("Title");
    card.subtitle("Subtitle");
    card.text("This is some *mardown* text! \n\n - one \n\n - two");

    const msg = new builder.Message(session);

    msg.textFormat("markdown");
    msg.attachments([
        card,
    ]);
    session.endDialog(msg);
});

I am wondering how can I achieve this formatting(From mailclark bot in MSTeams):

As you can see, it is a carousel of what I think it might be HeroCards, but they are formatted with bold, code and unordered lists on new paragraphs.

It seems to be a known issue that message attachments do not receive formatting, but how could the mailclark guys achieve it?

Edit:
Unordered list example:

Bold and code example:

Body:
As Hero Cards eventually will be convert to Rich Card send to user from bot, and from MS Teams documents at https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-conversations#formatting-text-content:

Microsoft Teams supports a subset of Markdown and XML (HTML) formatting tags.

Rich cards do not support Markdown or table formatting

So in MS Teams channel, markdown formatting is only supported in text only message, however, we can leverage HTML tags in Rich Card.

Please consider following code snippet:

bot.dialog('/', function (session) {
    const card = new builder.HeroCard(session);
    card.title("Type your question to our support team here");
    card.subtitle("Or, click the ◀▶ arrows for a series of how-tos");
    card.images([builder.CardImage.create(session,"<image url>")])
    card.text("<p>This is some <i>mardown</i> <b>text</b>!</p> <ul><li><b>one</b></li><li><code>two</code></li></ul>")
    const msg = new builder.Message(session);
    msg.attachmentLayout(builder.AttachmentLayout.carousel);
    msg.attachments([
        card,card,card
    ]).toMessage();
    session.send(msg);
    session.endDialog("This is some *mardown* **text**! \n\n - **one** \n\n - `two`");
});

This shows in MS Teams as following:


问:
Android View.getDrawingCache returns null, only null
Would anyone please try to explain to me why

```<code>public void addView(View child) {
  child.setDrawingCacheEnabled(true);
  child.setWillNotCacheDrawing(false);
  child.setWillNotDraw(false);
  child.buildDrawingCache();
  if(child.getDrawingCache() == null) { //TODO Make this work!
    Log.w("View", "View child's drawing cache is null");
  }
  setImageBitmap(child.getDrawingCache()); //TODO MAKE THIS WORK!!!
}
</code>```

ALWAYS logs that the drawing cache is null, and sets the bitmap to null?

Do I have to actually draw the view before the cache is set?

Thanks!

答:
This the simple and efficient way to get bitmap</p>

```<code>public void addView(View v) {
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();

        Bitmap bitmap = v.getDrawingCache();

        if(bitmap == null) {
            // bitmap is null
            // do whatever you want
        } else {
            setImageBitmap(bitmap);
        }
        v.setDrawingCacheEnabled(false);
        v.destroyDrawingCache();
    }
</code>```

Body:
Would anyone please try to explain to me why

public void addView(View child) {
  child.setDrawingCacheEnabled(true);
  child.setWillNotCacheDrawing(false);
  child.setWillNotDraw(false);
  child.buildDrawingCache();
  if(child.getDrawingCache() == null) { //TODO Make this work!
    Log.w("View", "View child's drawing cache is null");
  }
  setImageBitmap(child.getDrawingCache()); //TODO MAKE THIS WORK!!!
}

ALWAYS logs that the drawing cache is null, and sets the bitmap to null?

Do I have to actually draw the view before the cache is set?

Thanks!

Body:
This the simple and efficient way to get bitmap

public void addView(View v) {
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();

        Bitmap bitmap = v.getDrawingCache();

        if(bitmap == null) {
            // bitmap is null
            // do whatever you want
        } else {
            setImageBitmap(bitmap);
        }
        v.setDrawingCacheEnabled(false);
        v.destroyDrawingCache();
    }


问:
About the non-nullable types debate
I keep hearing people talk about how non-nullable reference types would solve so many bugs and make programming so much easier. Even the creator of null calls it his billion dollar mistake, and Spec# has introduced non-nullable types to combat this problem.

EDIT: Ignore my comment about  Spec#. I misunderstood how it works.

EDIT 2: I must be talking to the wrong people, I was really hoping for somebody to argue with :-)

So I would guess, being in the minority, that I'm wrong, but I can't understand why this debate has any merit. I see null as a bug-finding tool. Consider the following:

```<code>class Class { ... }

void main() {
    Class c = nullptr;
    // ... ... ... code ...
    for(int i = 0; i < c.count; ++i) { ... }
}
</code>```

BAM! Access violation. Someone forgot to initialize c.

Now consider this:

```<code>class Class { ... }

void main() {
    Class c = new Class(); // set to new Class() by default
    // ... ... ... code ...
    for(int i = 0; i < c.count; ++i) { ... }
}
</code>```

Whoops. The loop gets silently skipped. It could take a while to track down the problem.

If your class is empty, the code is going to fail anyway. Why not have the system tell you (albeit slightly rudely) instead of having to figure it out yourself?

答:
Non-nullable types make more sense to me when we are dealing with domain objects. When you are mapping database tables to objects and you have non-nullable columns. Say you have a table called User and it has column userid varchar(20) not nullable;

That would be so convenient to have a User class with UserId string field which is not nullable. You cab reduce some bugs at compile time.

Title: About the non-nullable types debate

Body:
I keep hearing people talk about how non-nullable reference types would solve so many bugs and make programming so much easier. Even the creator of null calls it his billion dollar mistake, and Spec# has introduced non-nullable types to combat this problem.

EDIT: Ignore my comment about  Spec#. I misunderstood how it works.

EDIT 2: I must be talking to the wrong people, I was really hoping for somebody to argue with :-)

So I would guess, being in the minority, that I'm wrong, but I can't understand why this debate has any merit. I see null as a bug-finding tool. Consider the following:

class Class { ... }

void main() {
    Class c = nullptr;
    // ... ... ... code ...
    for(int i = 0; i < c.count; ++i) { ... }
}

BAM! Access violation. Someone forgot to initialize c.

Now consider this:

class Class { ... }

void main() {
    Class c = new Class(); // set to new Class() by default
    // ... ... ... code ...
    for(int i = 0; i < c.count; ++i) { ... }
}

Whoops. The loop gets silently skipped. It could take a while to track down the problem.

If your class is empty, the code is going to fail anyway. Why not have the system tell you (albeit slightly rudely) instead of having to figure it out yourself?


问:
AttributeError: 'function' object has no attribute 'universe'
I get the following error, when I run the program. I have attached my error and program as follow. What's wrong with my program?

```<code>        error_x= x - x_old
        error_y= y - y_old
        reglage.input['position'] = int(x)
        reglage.input['vitesse'] = int(error_x - error_precedent_x)
        reglage.compute()
        x_angle=reglage.output['angle']
        print x_angle
        reglage.input['position'] = int(y)
        reglage.input['vitesse'] = int(error_y - error_precedent_y)  #dy/dt
        reglage.compute()
        y_angle=reglage.output['angle']
        print y_angle
</code>```

value = np.fmax(value, np.var.universe.min())
AttributeError: 'function' object has no attribute 'universe'

答:
```<code>reglage.input['position'] = int(x)
reglage.input['vitesse'] = int(error_x - error_precedent_x)
</code>```

inputs should be in the marge of the declared universe:

```<code>position = ctrl.Antecedent(np.arange(0, 400, 1), 'position')
vitesse = ctrl.Antecedent(np.arange(-200, 200, 1), 'vitesse')
</code>```

for this example :
x in [0 400]  AND
error_x - error_precedent_x in [-200 200]

Body:
I get the following error, when I run the program. I have attached my error and program as follow. What's wrong with my program?

        error_x= x - x_old
        error_y= y - y_old
        reglage.input['position'] = int(x)
        reglage.input['vitesse'] = int(error_x - error_precedent_x)
        reglage.compute()
        x_angle=reglage.output['angle']
        print x_angle
        reglage.input['position'] = int(y)
        reglage.input['vitesse'] = int(error_y - error_precedent_y)  #dy/dt
        reglage.compute()
        y_angle=reglage.output['angle']
        print y_angle

value = np.fmax(value, np.var.universe.min())
AttributeError: 'function' object has no attribute 'universe'

Body:
reglage.input['position'] = int(x)
reglage.input['vitesse'] = int(error_x - error_precedent_x)

inputs should be in the marge of the declared universe:

position = ctrl.Antecedent(np.arange(0, 400, 1), 'position')
vitesse = ctrl.Antecedent(np.arange(-200, 200, 1), 'vitesse')

for this example :
x in [0 400]  AND
error_x - error_precedent_x in [-200 200]


问:
ExtJs 6 always show ext/modern/modern/src/layout/container/Column.js net::ERR_FILE_NOT_FOUND
I want to try the hello world sample using Extjs 6.5.2.
When i try to run the following code

```<code>    var containerPanel = Ext.create('Ext.panel.Panel', {
        renderTo: 'app-div1',
        width: 400,
        height: 200,
        title: 'Container Panel',
        layout: 'column',
        suspendLayout: true // Suspend automatic layouts while we do several different things that could trigger a layout on their own
    });

    containerPanel.add({
        xtype: 'panel',
        title: 'Child Panel 1',
        height: 100,
        columnWidth: 0.5
    });

    containerPanel.add({
        xtype: 'panel',
        title: 'Child Panel 2',
        height: 100,
        columnWidth: 0.5
    });
    containerPanel.suspendLayout = false;
    containerPanel.updateLayout();
</code>```

the browser console is thrown error about

```<code>ext/modern/modern/src/layout/container/Column.js net::ERR_FILE_NOT_FOUND
</code>```

even if i try to import the package in app.js

```<code>Ext.application({
    name: 'MyApp',
    extend: 'MyApp.Application',

    requires: [
        'MyApp.*',
        'Ext.panel.Panel',
        'Ext.layout.container.Column'
    ]
});
</code>```

I found that the ext-6.5.2-trial.zip have not included container folder in \ext\modern\modern\src\layout.

May i know if i miss any steps before i use Ext.panel.Panel component?
Thank you.

答:
For classic you need to remove this 2 lines in your app.js Ext.panel.Panel and Ext.layout.container.Column. If you need you can requires in you classic views.

In modern toolkit there is no column layout but in classic there is present column layout Ext.layout.container.Column.

Please refer this FIDDLE this is working with layout:column property on Ext.panel.Panel.

```<code>var containerPanel = Ext.create('Ext.panel.Panel', {
    renderTo: Ext.getBody(),
    width: 400,
    height: 200,
    title: 'Container Panel',
    layout: 'column'
});

// Suspend automatic layouts while we do several different things that could trigger a layout on their own
containerPanel.suspendLayouts(true); //you can also use like this.
containerPanel.add({
    xtype: 'panel',
    title: 'Child Panel 1',
    height: 100,
    columnWidth: 0.5
},{
    xtype: 'panel',
    title: 'Child Panel 2',
    height: 100,
    columnWidth: 0.5
});
containerPanel.resumeLayouts(true);
</code>```

Body:
I want to try the hello world sample using Extjs 6.5.2.
When i try to run the following code

    var containerPanel = Ext.create('Ext.panel.Panel', {
        renderTo: 'app-div1',
        width: 400,
        height: 200,
        title: 'Container Panel',
        layout: 'column',
        suspendLayout: true // Suspend automatic layouts while we do several different things that could trigger a layout on their own
    });

    containerPanel.add({
        xtype: 'panel',
        title: 'Child Panel 1',
        height: 100,
        columnWidth: 0.5
    });

    containerPanel.add({
        xtype: 'panel',
        title: 'Child Panel 2',
        height: 100,
        columnWidth: 0.5
    });
    containerPanel.suspendLayout = false;
    containerPanel.updateLayout();

the browser console is thrown error about

ext/modern/modern/src/layout/container/Column.js net::ERR_FILE_NOT_FOUND

even if i try to import the package in app.js

Ext.application({
    name: 'MyApp',
    extend: 'MyApp.Application',

    requires: [
        'MyApp.*',
        'Ext.panel.Panel',
        'Ext.layout.container.Column'
    ]
});

I found that the ext-6.5.2-trial.zip have not included container folder in \ext\modern\modern\src\layout.

May i know if i miss any steps before i use Ext.panel.Panel component?
Thank you.

Body:
For classic you need to remove this 2 lines in your app.js Ext.panel.Panel and Ext.layout.container.Column. If you need you can requires in you classic views.

In modern toolkit there is no column layout but in classic there is present column layout Ext.layout.container.Column.

Please refer this FIDDLE this is working with layout:column property on Ext.panel.Panel.

var containerPanel = Ext.create('Ext.panel.Panel', {
    renderTo: Ext.getBody(),
    width: 400,
    height: 200,
    title: 'Container Panel',
    layout: 'column'
});

// Suspend automatic layouts while we do several different things that could trigger a layout on their own
containerPanel.suspendLayouts(true); //you can also use like this.
containerPanel.add({
    xtype: 'panel',
    title: 'Child Panel 1',
    height: 100,
    columnWidth: 0.5
},{
    xtype: 'panel',
    title: 'Child Panel 2',
    height: 100,
    columnWidth: 0.5
});
containerPanel.resumeLayouts(true);


问:
Determine if relation is in BCNF form?
How do I determine if the following relation is in BCNF form?

```<code>R(U,V,W,X,Y,Z)

UVW ->X
VW -> YU
VWY ->Z
</code>```

I understand that for a functional dependency A->B A must be a superkey. And the relation must be in 3NF form. But I am unsure how to apply the concepts.

答:
To determine if a relation is in BCNF, for the definition you should check that for each non-trivial dependency in F+, that is, for all the dependencies specified (F) and those derived from them, the determinant should be a superkey. Fortunately, there is a theorem that says that it is sufficient perform this check only for the specified dependencies.

In your case this means that you must check if UVW, VW and VWY are superkeys.

And to see if in a dependency X -> Y the set attributes X is a superkey you can compute the closure of the attributes (X+) and check if it contains the right hand part Y.

So you have to compute UVW+ and see if it contains {U,V,W,X,Y,Z} and similarly for the other two dependencies. I leave to you this simple exercise.

Title: Determine if relation is in BCNF form?

Body:
How do I determine if the following relation is in BCNF form?

R(U,V,W,X,Y,Z)

UVW ->X
VW -> YU
VWY ->Z

I understand that for a functional dependency A->B A must be a superkey. And the relation must be in 3NF form. But I am unsure how to apply the concepts.


问:
Radix sort not sorting "some" numbers?
I'm trying to implement Radix sort, from all i learnt is that it first compares the one's digit , places in the right order, the it goes for ten's so on and so fourth.

i tried to implement it but didn't got satisfactory results, what i'm doing wrong here?
Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>

struct heap {
    int data;
};

int main()
{
    int arr[18] = {545, 934, 829, 883, 842, 957, 241, 856, 878, 101, 555, 20, 964, 529, 156, 161, 566, 820};
    int i;

    struct heap *heaparr = malloc(sizeof(struct heap) * 18);

    for(i=0; i<18; i++) {
        heaparr[i].data = arr[i];
    }

    int k = 0, temp, div = 1;
    int ind = 0;

    while(div<=100 ){
        k=0;
        ind = 0;
        while(k<10) {
            for(i=0; i<18; i++) {
                if ((heaparr[i].data/div)% 10 == k) {
                    temp = heaparr[ind].data;
                    heaparr[ind].data = heaparr[i].data;
                    heaparr[i].data = temp;
                    ind++;
                }
            }
            k = k+1;
        }
        div = div*10;
    }

    printf("\n");
    free(heaparr);
    return 0;
}
</code>```

it is giving me result

```<code>20 101 156 161 241 545 555 566 529 842 856 820 829 878 883 957 934 964
</code>```

ans it should be.

```<code>20 101 156 161 241 529 545 555 566 820 829 842 856 878 883 934 964 957
</code>```

答:
Radix sort requires the the intermediate sorts to be stable, as you can read in Wikipedia. Here is a nice picture, explaining what stability is:

"An example of stable sort on playing cards. When the cards are sorted by rank with a stable sort, the two 5s must remain in the same order in the sorted output that they were originally in. When they are sorted with a non-stable sort, the 5s may end up in the opposite order in the sorted output."

So, in your code, when you are swapping two elements, you do not make sure that the stability is preserved for the element you take from the begining and are pushing back towards the end, which breaks the requirement of radix sort, thus producing undesired effects.

Inspired by GeeksforGeeks, I transformed your code to use Counting sort (which is stable for the intermediate sorting steps):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>       /* pow */

struct heap {
    int data;
};

void print(struct heap* heaparr)
{
    for(int i = 0; i < 18; i++)
        printf("%d ", heaparr[i].data);
    printf("\n");

}

// A function to do counting sort of arr[] according to
// the digit represented by exp.
struct heap* countSort(struct heap* heaparr, int n, int exp)
{
    int output[n]; // output array
    int i, count[10] = {0};

    // Store count of occurrences in count[]
    for (i = 0; i < n; i++)
        count[ (heaparr[i].data/exp)%10 ]++;

    // Change count[i] so that count[i] now contains actual
    //  position of this digit in output[]
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];

    // Build the output array
    for (i = n - 1; i >= 0; i--)
    {
        output[count[ (heaparr[i].data/exp)%10 ] - 1] = heaparr[i].data;
        count[ (heaparr[i].data/exp)%10 ]--;
    }

    // Copy the output array to arr[], so that arr[] now
    // contains sorted numbers according to current digit
    for (i = 0; i < n; i++)
        heaparr[i].data = output[i];
    return heaparr;
}

int main()
{
    int arr[18] = {545, 934, 829, 883, 842, 957, 241, 856, 878, 101, 555, 20, 964, 529, 156, 161, 566, 820};
    int i;

    struct heap *heaparr = malloc(sizeof(struct heap) * 18);

    for(i=0; i<18; i++) {
        heaparr[i].data = arr[i];
    }

    int k = 0, div = 1;

    while(div<=100 ){
        k=0;
        while(k<10) {
            for(i=0; i<18; i++) {
                countSort(heaparr, 18, (int)pow(10, heaparr[i].data/div% 10));
            }
            k = k+1;
        }
        div = div*10;
    }
    print(heaparr);
    free(heaparr);
    return 0;
}
</code>```

which gives:

20 101 156 161 241 529 545 555 566 820 829 842 856 878 883 934 957 964

However, this should be just an example to get you started.

Title: Radix sort not sorting "some" numbers?

Body:
I'm trying to implement Radix sort, from all i learnt is that it first compares the one's digit , places in the right order, the it goes for ten's so on and so fourth.

i tried to implement it but didn't got satisfactory results, what i'm doing wrong here?
Here is my code:

#include <stdio.h>
#include <stdlib.h>

struct heap {
    int data;
};

int main()
{
    int arr[18] = {545, 934, 829, 883, 842, 957, 241, 856, 878, 101, 555, 20, 964, 529, 156, 161, 566, 820};
    int i;

    struct heap *heaparr = malloc(sizeof(struct heap) * 18);

    for(i=0; i<18; i++) {
        heaparr[i].data = arr[i];
    }

    int k = 0, temp, div = 1;
    int ind = 0;

    while(div<=100 ){
        k=0;
        ind = 0;
        while(k<10) {
            for(i=0; i<18; i++) {
                if ((heaparr[i].data/div)% 10 == k) {
                    temp = heaparr[ind].data;
                    heaparr[ind].data = heaparr[i].data;
                    heaparr[i].data = temp;
                    ind++;
                }
            }
            k = k+1;
        }
        div = div*10;
    }

    printf("\n");
    free(heaparr);
    return 0;
}

it is giving me result

20 101 156 161 241 545 555 566 529 842 856 820 829 878 883 957 934 964

ans it should be.

20 101 156 161 241 529 545 555 566 820 829 842 856 878 883 934 964 957

Body:
Radix sort requires the the intermediate sorts to be stable, as you can read in Wikipedia. Here is a nice picture, explaining what stability is:

"An example of stable sort on playing cards. When the cards are sorted by rank with a stable sort, the two 5s must remain in the same order in the sorted output that they were originally in. When they are sorted with a non-stable sort, the 5s may end up in the opposite order in the sorted output."

So, in your code, when you are swapping two elements, you do not make sure that the stability is preserved for the element you take from the begining and are pushing back towards the end, which breaks the requirement of radix sort, thus producing undesired effects.

Inspired by GeeksforGeeks, I transformed your code to use Counting sort (which is stable for the intermediate sorting steps):

#include <stdio.h>
#include <stdlib.h>
#include <math.h>       /* pow */

struct heap {
    int data;
};

void print(struct heap* heaparr)
{
    for(int i = 0; i < 18; i++)
        printf("%d ", heaparr[i].data);
    printf("\n");

}

// A function to do counting sort of arr[] according to
// the digit represented by exp.
struct heap* countSort(struct heap* heaparr, int n, int exp)
{
    int output[n]; // output array
    int i, count[10] = {0};

    // Store count of occurrences in count[]
    for (i = 0; i < n; i++)
        count[ (heaparr[i].data/exp)%10 ]++;

    // Change count[i] so that count[i] now contains actual
    //  position of this digit in output[]
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];

    // Build the output array
    for (i = n - 1; i >= 0; i--)
    {
        output[count[ (heaparr[i].data/exp)%10 ] - 1] = heaparr[i].data;
        count[ (heaparr[i].data/exp)%10 ]--;
    }

    // Copy the output array to arr[], so that arr[] now
    // contains sorted numbers according to current digit
    for (i = 0; i < n; i++)
        heaparr[i].data = output[i];
    return heaparr;
}

int main()
{
    int arr[18] = {545, 934, 829, 883, 842, 957, 241, 856, 878, 101, 555, 20, 964, 529, 156, 161, 566, 820};
    int i;

    struct heap *heaparr = malloc(sizeof(struct heap) * 18);

    for(i=0; i<18; i++) {
        heaparr[i].data = arr[i];
    }

    int k = 0, div = 1;

    while(div<=100 ){
        k=0;
        while(k<10) {
            for(i=0; i<18; i++) {
                countSort(heaparr, 18, (int)pow(10, heaparr[i].data/div% 10));
            }
            k = k+1;
        }
        div = div*10;
    }
    print(heaparr);
    free(heaparr);
    return 0;
}

which gives:

20 101 156 161 241 529 545 555 566 820 829 842 856 878 883 934 957 964

However, this should be just an example to get you started.


问:
Is it possible to load List of values in excel using VSTO web add-ins using office.js
I am developing a excel add-in using office.js, that populates table data in excel sheet. Add-in allows user to update table column details, but I want to display list of reference values rather than free text.
Example for scenario is given below.

Table displayed in excel will have two columns Column 1 And Column 2, I will have reference data as shown in reference table, When user want to update column 2 I want user to select only allowed values, but I don't see any options available in office.js library. Please guide me If any of you have any suggestions to achieve my need.

I am loading table using offfice.js objects as given below

```<code>var data = serverTableObjectAsArray;
var officeTable = new Office.TableData();
officeTable.addHeaders(data[0]);
officeTable.addRange(data);
</code>```

答: Data validation was just introduced in 'beta' version. It is not available in the production version. You can check out the details in range.validation API here</p>

Body:
I am developing a excel add-in using office.js, that populates table data in excel sheet. Add-in allows user to update table column details, but I want to display list of reference values rather than free text.
Example for scenario is given below.

Table displayed in excel will have two columns Column 1 And Column 2, I will have reference data as shown in reference table, When user want to update column 2 I want user to select only allowed values, but I don't see any options available in office.js library. Please guide me If any of you have any suggestions to achieve my need.

I am loading table using offfice.js objects as given below

var data = serverTableObjectAsArray;
var officeTable = new Office.TableData();
officeTable.addHeaders(data[0]);
officeTable.addRange(data);


问:
Entropy in classification
I am just few doubts in entropy. The entropy formula is given as
-summation(p(i|j) log2 p(i|j)
This is the formula for target attribute which has only 2 values. What if the target has more than 2 class values (say high,medium and low) ? How will the formula gets affected ?
Will it be,
-summation(p(i|j) log3 p(i|j)) ?

Another question:
How to calculate the accuracy of random baseline classifier without any bias ?
Say my question says:

```<code> 1)class1=50% and class2=50%
 2)class1=40% and class2=60%
 3)class1=10%,class2=20% and class3=70%
</code>```

Could you please help me in these two questions?

答:
No, the usual choice for the logarithm remains base 2, "bits".

But in fact, the base of the log is just a constant, that in most cases cancels out or is a global scaling constant that does not matter.

Title: Entropy in classification

Body:
I am just few doubts in entropy. The entropy formula is given as
-summation(p(i|j) log2 p(i|j)
This is the formula for target attribute which has only 2 values. What if the target has more than 2 class values (say high,medium and low) ? How will the formula gets affected ?
Will it be,
-summation(p(i|j) log3 p(i|j)) ?

Another question:
How to calculate the accuracy of random baseline classifier without any bias ?
Say my question says:

 1)class1=50% and class2=50%
 2)class1=40% and class2=60%
 3)class1=10%,class2=20% and class3=70%

Could you please help me in these two questions?


问:
escape hidden character that is causing JSON validation to fail
I have a hidden character that is causing JSON parsing to fail. What is the best way to escape a string properly just that hidden characters like these done crash my json?

Here is the code, the invisible character is between the n and the s in "brains" until you remove that invisible character JSON.parse() will fail... question is, how to strip the invisible character?

```<code>var mystring='{"invis":"their brains process differently"}';
console.log("cool" + mystring);
console.log(JSON.parse(mystring));
</code>```

Note I found that in the above code actually removed the invisible character, but it is here on pastie, if you want to copy and paste to see the issue:
See the code on pastie

答:
Somehow a cancel character (0x18) got into your string. You can simply replace it out with a regular expression.</p>

```<code>var mystring='{"invis":"their brains process differently"}';
mystring = mystring.replace( /\x18/g, "" );
console.log("cool" + mystring);
console.log(JSON.parse(mystring));
</code>```

Body:
I have a hidden character that is causing JSON parsing to fail. What is the best way to escape a string properly just that hidden characters like these done crash my json?

Here is the code, the invisible character is between the n and the s in "brains" until you remove that invisible character JSON.parse() will fail... question is, how to strip the invisible character?

var mystring='{"invis":"their brains process differently"}';
console.log("cool" + mystring);
console.log(JSON.parse(mystring));

Note I found that in the above code actually removed the invisible character, but it is here on pastie, if you want to copy and paste to see the issue:
See the code on pastie

Body:
Somehow a cancel character (0x18) got into your string. You can simply replace it out with a regular expression.

var mystring='{"invis":"their brains process differently"}';
mystring = mystring.replace( /\x18/g, "" );
console.log("cool" + mystring);
console.log(JSON.parse(mystring));


问:
ValueError: math domain error in python2
when I run this code:

```<code>max(MIN_LEARNING_RATE, min(0.5, 1.0 - math.log10((t+1)/25)))
</code>```

with t = 0

I've this error:

```<code>ValueError: math domain error
</code>```

but if i run the same code with python 3.6 the error disappeared

答:
It's because in Python 2, the division returns a floor of the float, and in the case where it's 1/25, it returns 0.

And math.log(0) gives a domain error.

So in your Python 2 code, add this at the start of the script:

```<code>from __future__ import division
</code>```

By default in Python 2:

```<code>$ python2
Python 2.7.13 (default, Dec 18 2016, 07:03:39)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.log(1/25)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> 1/25
0
</code>```

In Python 3:

```<code>$ python3
Python 3.6.1 (default, Apr  4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.log(1/25)
-3.2188758248682006
>>> 1/25
0.04
</code>```

In Python 2 with __future__.division:

```<code>$ python2
Python 2.7.13 (default, Dec 18 2016, 07:03:39)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import division
>>> import math
>>> math.log(1/25)
-3.2188758248682006
>>> 1/25
0.04
</code>```

Body:
when I run this code:

max(MIN_LEARNING_RATE, min(0.5, 1.0 - math.log10((t+1)/25)))

with t = 0

I've this error:

ValueError: math domain error

but if i run the same code with python 3.6 the error disappeared

Body:
It's because in Python 2, the division returns a floor of the float, and in the case where it's 1/25, it returns 0.

And math.log(0) gives a domain error.

So in your Python 2 code, add this at the start of the script:

from __future__ import division

By default in Python 2:

$ python2
Python 2.7.13 (default, Dec 18 2016, 07:03:39)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.log(1/25)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> 1/25
0

In Python 3:

$ python3
Python 3.6.1 (default, Apr  4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.log(1/25)
-3.2188758248682006
>>> 1/25
0.04

In Python 2 with __future__.division:

$ python2
Python 2.7.13 (default, Dec 18 2016, 07:03:39)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import division
>>> import math
>>> math.log(1/25)
-3.2188758248682006
>>> 1/25
0.04


问:
How to put an excel formula to a dynamic range of cells using VBA?
I am new to VBA and am using the following snippet to populate a range of cells with a vlookup function:

```<code>With wbk1.Sheets("classes")
       .Range("AA2:AA" & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup
</code>```

In order to make this dynamic, I want to replace the .Range("AA2:AA" & .Range("C" & .Rows.Count) part with a dynamic reference (in my case the first empty column in the same sheet).

First, I find the first empty column with this one-liner:

```<code>first_empty_column = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
</code>```

However, when I do

```<code>With wbk1.Sheets("classes")
   .Range(ws.Cells(1, first_empty_column) & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup
</code>```

I get "Runtime Error '1004': Application-defined an object-defined error.

What is the syntax to define hard-coded ranges dynamically in this context?

答:
You need to use the following Range reference logic:

```<code>'PSEUDO-CODE
.Range(LeftTopCell, RightBottomCell)
</code>```

where both LeftTopCell and RightBottomCell can be set with any valid range reference.
Moreover, you can not combine reference to range from two different sheets. You are referencing both ws and Sheets("classes") in single range reference.

Try with this:

```<code>With wbk1.Sheets("classes")

   .Range(.Cells(1, first_empty_column), _
          .Cells(.Range("C" & .Rows.Count).End(xlUp).Row, first_empty_column)).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup

End With
</code>```

Body:
I am new to VBA and am using the following snippet to populate a range of cells with a vlookup function:

With wbk1.Sheets("classes")
       .Range("AA2:AA" & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup

In order to make this dynamic, I want to replace the .Range("AA2:AA" & .Range("C" & .Rows.Count) part with a dynamic reference (in my case the first empty column in the same sheet).

First, I find the first empty column with this one-liner:

first_empty_column = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

However, when I do

With wbk1.Sheets("classes")
   .Range(ws.Cells(1, first_empty_column) & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup

I get "Runtime Error '1004': Application-defined an object-defined error.

What is the syntax to define hard-coded ranges dynamically in this context?

Body:
You need to use the following Range reference logic:

'PSEUDO-CODE
.Range(LeftTopCell, RightBottomCell)

where both LeftTopCell and RightBottomCell can be set with any valid range reference.
Moreover, you can not combine reference to range from two different sheets. You are referencing both ws and Sheets("classes") in single range reference.

Try with this:

With wbk1.Sheets("classes")

   .Range(.Cells(1, first_empty_column), _
          .Cells(.Range("C" & .Rows.Count).End(xlUp).Row, first_empty_column)).Formula = "=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'Actual vlookup

End With


问:
How to use LDAP in ASP.NET Boilerplate (Free Startup Template)
I would like to integrate authentication via Active Directory in my .net Core app using Free Startup Template version of the Boilerplate. I followed the instruction in the documentation such as installing Abp.Zero.Ldap package, creating LdapAuthenticationSource class, and injecting dependency like:

```<code>[DependsOn(typeof(AbpZeroLdapModule))]
public class MyApplicationCoreModule : AbpModule
{
    public override void PreInitialize()
    {
        Configuration.Modules.ZeroLdap().Enable(typeof (MyLdapAuthenticationSource));
    }

    ...
}
</code>```

Do I need to define any custom settings by using a class implementing ILdapSettings interface? Or create any class or files referencing to this folder?

答:
.NET Core 2.0

The instructions may not work, as LDAP / AD auth extension for .NET Core isn't implemented yet.

Track this feature: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2755

.NET Framework 4.6.1

By installing Abp.Zero.Ldap package, you're already referencing that module (moved here).

As mentioned in LDAP/Active Directory > Settings:

LdapAuthenticationSource expects ILdapSettings as a constructor argument. This interface is used to get LDAP settings like domain, user name and password to connect to Active Directory. Default implementation (LdapSettings class) gets these settings from the setting manager.

If you work with Setting manager, then no problem. You can change LDAP settings using setting manager API. If you want, you can add an initial/seed data to database to enable LDAP auth by default.

So, you don't need to create a class that implements ILdapSettings. The benefit of using the Setting Manager is that it stores the settings in your database. A custom class is for getting it from elsewhere or hardcoding it (useful if you just want to try, but a big no-no in production / git commit).

For a start, you can add seed data for your Host in DefaultSettingsCreator with LdapSettingNames:

```<code>public void Create()
{
    // ...

    // LDAP
    AddSettingIfNotExists(LdapSettingNames.IsEnabled, "false");
    // AddSettingIfNotExists(LdapSettingNames...
}
</code>```

Body:
I would like to integrate authentication via Active Directory in my .net Core app using Free Startup Template version of the Boilerplate. I followed the instruction in the documentation such as installing Abp.Zero.Ldap package, creating LdapAuthenticationSource class, and injecting dependency like:

[DependsOn(typeof(AbpZeroLdapModule))]
public class MyApplicationCoreModule : AbpModule
{
    public override void PreInitialize()
    {
        Configuration.Modules.ZeroLdap().Enable(typeof (MyLdapAuthenticationSource));
    }

    ...
}

Do I need to define any custom settings by using a class implementing ILdapSettings interface? Or create any class or files referencing to this folder?

Body:
.NET Core 2.0

The instructions may not work, as LDAP / AD auth extension for .NET Core isn't implemented yet.

Track this feature: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2755

.NET Framework 4.6.1

By installing Abp.Zero.Ldap package, you're already referencing that module (moved here).

As mentioned in LDAP/Active Directory > Settings:

LdapAuthenticationSource expects ILdapSettings as a constructor argument. This interface is used to get LDAP settings like domain, user name and password to connect to Active Directory. Default implementation (LdapSettings class) gets these settings from the setting manager.

If you work with Setting manager, then no problem. You can change LDAP settings using setting manager API. If you want, you can add an initial/seed data to database to enable LDAP auth by default.

So, you don't need to create a class that implements ILdapSettings. The benefit of using the Setting Manager is that it stores the settings in your database. A custom class is for getting it from elsewhere or hardcoding it (useful if you just want to try, but a big no-no in production / git commit).

For a start, you can add seed data for your Host in DefaultSettingsCreator with LdapSettingNames:

public void Create()
{
    // ...

    // LDAP
    AddSettingIfNotExists(LdapSettingNames.IsEnabled, "false");
    // AddSettingIfNotExists(LdapSettingNames...
}


问:
How to make the Text item always display fractional parts of numbers?
I have a Text item that display a real number:

```<code>Text { id: txt; ... }

...

txt.text: Math.round(sensor.value*10)/10

...
</code>```

But if sensor.value is the integer number, it's displayed without a fractional part (35 instead 35.0). How to explicitly force txt always display a fractional part of number?

答:
Use toPrecision method to specify the number of decimals you want to show. The method will return a string with the number formatted in the desired format

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision

Body:
I have a Text item that display a real number:

Text { id: txt; ... }

...

txt.text: Math.round(sensor.value*10)/10

...

But if sensor.value is the integer number, it's displayed without a fractional part (35 instead 35.0). How to explicitly force txt always display a fractional part of number?


问:
What is the quickest way to compile and run any single C file
I'd like to compile and run a single c source file on a keypress such as <F5>, now I've looked at several ways of accomplishing this and most involve using a Makefile. However, every example I've found on a generic Makefile require editing the TARGET or compiling all source files in the working directory. This led me to the question if I could run a regexp and replace the first line of the Makefile from any source file I'm working on.

Press <F5>

Update Makefile in root projectdir with current <file>.c working on.

Run make ONLY on <file>

There may be a simpler way of accomplishing this without editing the Makefile, but I've exhausted myself with trying to make a generic enough makefile to do it.

The regexp I have that would select the correct line:

```<code>^TARGET\s[=]\s.*
</code>```

答:
I use multi-compile.  Here's my config:

```<code>(use-package multi-compile
  :config
  (defun locate-repo-dir (&optional file-or-dir)
    "Find the root of the version control repository."
    (let* ((file-or-dir (or file-or-dir (buffer-file-name) default-directory))
           (file-dir (if (file-directory-p file-or-dir)
                         file-or-dir
                       (file-name-directory file-or-dir)))
           (root-dir (vc-call-backend (vc-deduce-backend) 'root file-dir)))
      root-dir))

  (dolist (e '(("%cflags" . (or (getenv "CFLAGS") "-Wall -g3 -std=c11"))
               ("%cxxflags" . (or (getenv "CXXFLAGS") "-Wall -g3"))
               ("%repo-dir" . (locate-repo-dir))))
    (add-to-list 'multi-compile-template e))

  (setq multi-compile-alist
        '((".*" . (("make-simple" .
                    "make -k")
                   ("make-repo" .
                    "make -k --no-print-directory -C '%repo-dir'")
                   ("make-top" .
                    "make -k --no-print-directory -C '%make-dir'")))
          (c-mode . (("c-simple" .
                      "gcc -o '%file-sans' %cflags '%file-name'")
                     ("c-simple32" .
                      "gcc -o '%file-sans' %cflags -m32 '%file-name'")))
          (c++-mode . (("c++-simple" .
                        "g++ -o '%file-sans' %cxxflags '%file-name'")))))

  :bind (("C-c b" . multi-compile-run))
  )
</code>```

The c-simple option is exactly what I use for single-file C programs.

Body:
I'd like to compile and run a single c source file on a keypress such as <F5>, now I've looked at several ways of accomplishing this and most involve using a Makefile. However, every example I've found on a generic Makefile require editing the TARGET or compiling all source files in the working directory. This led me to the question if I could run a regexp and replace the first line of the Makefile from any source file I'm working on.

Press <F5>

Update Makefile in root projectdir with current <file>.c working on.

Run make ONLY on <file>

There may be a simpler way of accomplishing this without editing the Makefile, but I've exhausted myself with trying to make a generic enough makefile to do it.

The regexp I have that would select the correct line:

^TARGET\s[=]\s.*

Body:
I use multi-compile.  Here's my config:

(use-package multi-compile
  :config
  (defun locate-repo-dir (&optional file-or-dir)
    "Find the root of the version control repository."
    (let* ((file-or-dir (or file-or-dir (buffer-file-name) default-directory))
           (file-dir (if (file-directory-p file-or-dir)
                         file-or-dir
                       (file-name-directory file-or-dir)))
           (root-dir (vc-call-backend (vc-deduce-backend) 'root file-dir)))
      root-dir))

  (dolist (e '(("%cflags" . (or (getenv "CFLAGS") "-Wall -g3 -std=c11"))
               ("%cxxflags" . (or (getenv "CXXFLAGS") "-Wall -g3"))
               ("%repo-dir" . (locate-repo-dir))))
    (add-to-list 'multi-compile-template e))

  (setq multi-compile-alist
        '((".*" . (("make-simple" .
                    "make -k")
                   ("make-repo" .
                    "make -k --no-print-directory -C '%repo-dir'")
                   ("make-top" .
                    "make -k --no-print-directory -C '%make-dir'")))
          (c-mode . (("c-simple" .
                      "gcc -o '%file-sans' %cflags '%file-name'")
                     ("c-simple32" .
                      "gcc -o '%file-sans' %cflags -m32 '%file-name'")))
          (c++-mode . (("c++-simple" .
                        "g++ -o '%file-sans' %cxxflags '%file-name'")))))

  :bind (("C-c b" . multi-compile-run))
  )

The c-simple option is exactly what I use for single-file C programs.


问:
Change language from dynamically content using Javascript
My project should support different languages for the GUI (spanish, english, german, etc). I'm using CodeIgniter, so I haven't got any problem with PHP views using Language Class. I can load some previously defined vars on PHP to create views in different languages.

The problem comes here:

Some features (a lot of them actually) use Javascript: personalized context menu for some items, differents DIVs created dynamically, etc. The most of this features are created dynamically, so I can't know the language selected (I can create a lot of duplicated code, one for each language, but this is too redundant).

I need to find a way to translate this content into the new language previously selected by user.

For example:

The user right-click and the context menu have the following options (created dynamically using Javascript):

Hi

Goodbye

When the user change the page language to 'Spanish', the context menu should show:

Hola

Adios

Is there any way to save some variables with all the names in different languages, and then load to create the menus?

Sorry for the big post. I hope everyone can help me or bring me a little tip.

答:
there are several systems to use when you want i18n (short for "internationalization") to work in a server side language as well as in client side Javascript.

this is an example I found for PHP and JavaScript: http://doc.silverstripe.org/sapphire/en/topics/i18n

I've done this in PHP, Ruby and Python. In general there is one way this is done. You create a library of text. this library has pointers to specific pieces of that text. In your code you use that pointer to refer to that piece of text. What the example above does provide you a way to create a library in PHP that can be compiled to a JavaScript equivalent that you can call in JavaScript. Basically it completely separates copywriting and other text from the code.

I hope this helps you on your way.


问:
Kdb - string to double or float
I am trying to convert a string into a double or a float in KDB - the string contains a number with "accounting" format of the like of 2,228,25 (amount) - is I use something like "j"$amount I get 50 44 50 50 56 46 50 53 as a return value. How do I convert that string into a proper number? Thanks

答:
As the other example stated you can use except to exclude "," before converting. However, if you have many characters in the string that you need to remove, and those vary, you can use inter and a list of accepted characters rather than have exceptions:

```<code>q)amt:"2/228,25.0"
q)"F"$amt inter "0123456789."
222825f
</code>```

Title: Kdb - string to double or float

Body:
As the other example stated you can use except to exclude "," before converting. However, if you have many characters in the string that you need to remove, and those vary, you can use inter and a list of accepted characters rather than have exceptions:

q)amt:"2/228,25.0"
q)"F"$amt inter "0123456789."
222825f


问:
Display data from combobox to a datagridview
I am trying to get data  from a combo Box into a datagrindview but when I run the program it shows the datagrindview blank! any suggestions ?
Thank you

private void fillCombo()
         {
                 string query = "select DISTINCT FirstName,LastName from ActivityDataView";
                 myConnection.Open();
                 myCommand = new SqlCommand(query, myConnection);
                 myDataAdapter = new SqlDataAdapter(myCommand);

                 SqlDataReader dr = myCommand.ExecuteReader();

            while (dr.Read())
                 {
                     string name = String.Format("{0} {1} ",  dr["LastName"], dr["FirstName"]);
                     comboBox1.Items.Add(name);
                }
            dr.Close();

            myConnection.Close();

        }
        ```
</div>
</div>

here is the funcion for the combobox
</p>

```         private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            string query = "select * from ActivityDataView where LastName='" + comboBox1.SelectedValue + "'";

            myConnection.Open();
                 myCommand = new SqlCommand(query, myConnection);

               myDataAdapter = new SqlDataAdapter(myCommand);
            DataSet myDataSet = new DataSet();

            myDataAdapter.Fill(myDataSet);
           dataGridView1.DataSource = myDataSet.Tables[0];

             myConnection.Close();

        }
```

答:
Your format clearly states that you are selecting the lastname as well as the first name into your combobox:

```<code>string name = String.Format("{0} {1} ",  dr["LastName"], dr["FirstName"]);
</code>```

but when you fetch data for your DataGridView you try to compare this entire string with the LastName row.

To solve this you could split the combobox string and get only the last name

```<code>string lastName = comboBox1.SelectedItem.ToString()
                .Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries).First();
</code>```

Body:
I am trying to get data  from a combo Box into a datagrindview but when I run the program it shows the datagrindview blank! any suggestions ?
Thank you

private void fillCombo()
         {
                 string query = "select DISTINCT FirstName,LastName from ActivityDataView";
                 myConnection.Open();
                 myCommand = new SqlCommand(query, myConnection);
                 myDataAdapter = new SqlDataAdapter(myCommand);

                 SqlDataReader dr = myCommand.ExecuteReader();

            while (dr.Read())
                 {
                     string name = String.Format("{0} {1} ",  dr["LastName"], dr["FirstName"]);
                     comboBox1.Items.Add(name);
                }
            dr.Close();

            myConnection.Close();

        }

here is the funcion for the combobox

         private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            string query = "select * from ActivityDataView where LastName='" + comboBox1.SelectedValue + "'";

            myConnection.Open();
                 myCommand = new SqlCommand(query, myConnection);

               myDataAdapter = new SqlDataAdapter(myCommand);
            DataSet myDataSet = new DataSet();

            myDataAdapter.Fill(myDataSet);
           dataGridView1.DataSource = myDataSet.Tables[0];

             myConnection.Close();

        }

Body:
Your format clearly states that you are selecting the lastname as well as the first name into your combobox:

string name = String.Format("{0} {1} ",  dr["LastName"], dr["FirstName"]);

but when you fetch data for your DataGridView you try to compare this entire string with the LastName row.

To solve this you could split the combobox string and get only the last name

string lastName = comboBox1.SelectedItem.ToString()
                .Split(new string[] { " "}, StringSplitOptions.RemoveEmptyEntries).First();


问:
how to rename pyramind of numbers file
I have 1000+ files on my Linux machine:

```<code>somefiletest001.DAT_999
somefiletest001.DAT_1000
somefiletest001.DAT_1000_1001
somefiletest001.DAT_1000_1001_1002
somefiletest001.DAT_1000_1001_1002_1003
</code>```

I would like to know how to rename them to:

```<code>somefiletest001.DAT_999
somefiletest001.DAT_1000
somefiletest001.DAT_1001
somefiletest001.DAT_1002
somefiletest001.DAT_1003
</code>```

I can do mv command one by one at the time. Can someone show me how to do a simple bash script to rename this kind of files? Thank you for the help.

答:
With prename (Perl rename) command:

```<code>prename 's/\.DAT(_.*)?(_[0-9]{4})$/.DAT$2/' *.DAT_*
</code>```

Title: how to rename pyramind of numbers file

Body:
I have 1000+ files on my Linux machine:

somefiletest001.DAT_999
somefiletest001.DAT_1000
somefiletest001.DAT_1000_1001
somefiletest001.DAT_1000_1001_1002
somefiletest001.DAT_1000_1001_1002_1003

I would like to know how to rename them to:

somefiletest001.DAT_999
somefiletest001.DAT_1000
somefiletest001.DAT_1001
somefiletest001.DAT_1002
somefiletest001.DAT_1003

I can do mv command one by one at the time. Can someone show me how to do a simple bash script to rename this kind of files? Thank you for the help.

Body:
With prename (Perl rename) command:

prename 's/\.DAT(_.*)?(_[0-9]{4})$/.DAT$2/' *.DAT_*


问:
Angular's `@Host` decorator not reaching the top?
In my main app.ts I've declared a global provider :

```<code>providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}]
</code>```

(Where createDependency is just a function that returns a class which has a getName() method.)

I also have a components :

```<code>    <my-app-component-3>Hello from 3</my-app-component-3>
</code>```

Code :

```<code>@Component({
    selector: 'my-app-component-3',
    template: `
        <div>Component3:
            <ng-content></ng-content>
            : <span [innerHTML]="dependency?.getName()"></span>
        </div>
    `,

})
export class Component3 {
    constructor(@Host() @Optional() public dependency: Dependency) {}
}
</code>```

The result is:

Component3: Hello from 3 :

But I expect the result to be :

Component3: Hello from 3 :AppModule provider

Because basically the app structure is :

```<code><my-app>
  <my-app-component-3>
  </my-app-component-3>
</my-app>
</code>```

Question:

Why doesn't @Host()  match the parent provider ?

(which is   : providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}])

To my knowledge - the injector should seek for a Dependency in this manner :

So why doesn't it find it ?

PLUNKER

Notice

I already know that if I remove @host - it does reach the top. My question is why adding @host - is not reaching the top - despite the fact thatmy-component3 is under my-app !!

答:
just remove @Host() decorator from your Component 3 constructor:

```<code>Component({
    selector: 'my-app-component-3',
    template: `
        <div>Component3:
            <ng-content></ng-content>
            : <span [innerHTML]="dependency?.getName()"></span></div>
    `,

})
export class Component3 {
    constructor(@Optional() public dependency: Dependency) {}
}
</code>```

Angular will take the provider from the AppModule.

Body:
In my main app.ts I've declared a global provider :

providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}]

(Where createDependency is just a function that returns a class which has a getName() method.)

I also have a components :

    <my-app-component-3>Hello from 3</my-app-component-3>

Code :

@Component({
    selector: 'my-app-component-3',
    template: `

Component3:
            <ng-content></ng-content>
            :

    `,

})
export class Component3 {
    constructor(@Host() @Optional() public dependency: Dependency) {}
}

The result is:

Component3: Hello from 3 :

But I expect the result to be :

Component3: Hello from 3 :AppModule provider

Because basically the app structure is :

<my-app>
  <my-app-component-3>
  </my-app-component-3>
</my-app>

Question:

Why doesn't @Host()  match the parent provider ?

(which is   : providers: [{provide: Dependency, useValue: createDependency('AppModule provider')}])

To my knowledge - the injector should seek for a Dependency in this manner :

So why doesn't it find it ?

PLUNKER

Notice

I already know that if I remove @host - it does reach the top. My question is why adding @host - is not reaching the top - despite the fact thatmy-component3 is under my-app !!

Body:
just remove @Host() decorator from your Component 3 constructor:

Component({
    selector: 'my-app-component-3',
    template: `
        <div>Component3:
            <ng-content></ng-content>
            : <span [innerHTML]="dependency?.getName()"></span></div>
    `,

})
export class Component3 {
    constructor(@Optional() public dependency: Dependency) {}
}

Angular will take the provider from the AppModule.


问:
Map json Object with randomise array creation
I have JSON object and array

```<code>sampleJson={"id":1,"option1":"","option2":"","option3":""}
sampleArray=["car","","Animals"]
</code>```

i want to add sampleArray to sampleJson in following format

```<code>sampleJson={"id":1,"option1"="car","option2":"Animals","option3":""}
</code>```

sample array will be randomise like ["","car",""] Or ["","animal","Car"]?

答:
Thanks for your help, I found the solution

var i=1;
    sampleData.forEach(element => {
      if(element.length != 0){
        sampleJson['option'+i]=element;
        i++;
      }
    });```

Body:
I have JSON object and array

sampleJson={"id":1,"option1":"","option2":"","option3":""}
sampleArray=["car","","Animals"]

i want to add sampleArray to sampleJson in following format

sampleJson={"id":1,"option1"="car","option2":"Animals","option3":""}

sample array will be randomise like ["","car",""] Or ["","animal","Car"]?


问:
How many times does the script used in spark pipes gets executed.?
I tried the below spark scala code and got the output as mentioned below.
I have tried to pass the inputs to script, but it didn't receive and when i used collect the print statement i used in the script appeared twice.

My simple and very basic perl script first:

```<code>#!/usr/bin/perl
print("arguments $ARGV[0] \n"); // Just print the arguments.
</code>```

My Spark code:

```<code>object PipesExample {
  def main(args:Array[String]){
    val conf = new SparkConf();

    val sc = new SparkContext(conf);

    val distScript = "/home/srinivas/test.pl"
    sc.addFile(distScript)

    val rdd = sc.parallelize(Array("srini"))

    val piped = rdd.pipe(Seq(SparkFiles.get("test.pl")))

    println(" output " + piped.collect().mkString(" "));

  }
}
</code>```

Output looked like this..

```<code> output arguments arguments
</code>```

1) What mistake i have done to make it fail receiving the arguments.?
2) Why it executed twice.?

If it looks too basic, please apologize me. I was trying to understand to the best and want to clear my doubts.

答:
The reason your application couldn't pick test.pl file is, the file is in some node's location. But the application master is created in one of the nodes in cluster. So prolly if the file isn't in that node, it can't pick the file.

You should always save the file in HDFS or S3 to access the external files. Or else pass the HDFS file location through spark command options.

Body:
I tried the below spark scala code and got the output as mentioned below.
I have tried to pass the inputs to script, but it didn't receive and when i used collect the print statement i used in the script appeared twice.

My simple and very basic perl script first:

#!/usr/bin/perl
print("arguments $ARGV[0] \n"); // Just print the arguments.

My Spark code:

object PipesExample {
  def main(args:Array[String]){
    val conf = new SparkConf();

    val sc = new SparkContext(conf);

    val distScript = "/home/srinivas/test.pl"
    sc.addFile(distScript)

    val rdd = sc.parallelize(Array("srini"))

    val piped = rdd.pipe(Seq(SparkFiles.get("test.pl")))

    println(" output " + piped.collect().mkString(" "));

  }
}

Output looked like this..

 output arguments arguments

1) What mistake i have done to make it fail receiving the arguments.?
2) Why it executed twice.?

If it looks too basic, please apologize me. I was trying to understand to the best and want to clear my doubts.


问:
How do I get the Publish information to show up in the output window?
I'm trying to get the publishing information to show up in my output window when I use the publish wizard from the context menu.

Right now when I go through the publish it only generates two lines:

------ Publish started: Project: NerdDinner, Configuration: Release Any CPU ------

Project "NerdDinner.csproj" (MSDeployPublish target(s)):

Done building project "NerdDinner.csproj".

Does anyone have any idea why it's not showing the details of the publish?

答:
Make sure your in your Options->Project and Solutions->Build and Run->MsBuild Project build output vebosity is at least set to Normal.

This should so you all the files that are being copied etc when you Publish.