问:
A typical bracket balanced problem in ocaml
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

```<code>false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"
</code>```
```<code>let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;
</code>```

But I got the following results:

```<code>is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false
</code>```

答:
When learning to program, it's important not only to learn programming techniques (such as algorithms) and programming languages, but also tools.

You're confronted with a problem: you've written some code that takes some input and returns the wrong input, but you don't understand why. There are two main approaches to this kind of problem:

Break down the code into smaller pieces, and test them separately, until you find one (or more) that doesn't return the outputs you wanted.

Use debugging tools to look at what's happening inside the program.

Here you can test list_car independently and see that it's not the source of the problem. There's not much you can do to break down is_balanced, but you can take out left and make it a top-level function.

```<code>let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
;;
let is_balanced klm =
  let brk = list_car klm in
  left (brk, 0) ;;
</code>```

That's not going to help directly, because the problem is inside left and it's all one thing that can't really be broken down into smaller pieces. However, making left a toplevel function allows you to use a simple debugging tool: tracing in the toplevel. (A function doesn't have to be at the top level to debug it, but it does to use the toplevel's simple tracing function.)

```<code># #trace left;;
left is now traced.
# is_balanced "()";;
left <-- (['('; ')'], 0)
left <-- ([')'], 0)
left --> false
left --> false
</code>```

Now you can see where the code is going wrong: the second call to left is made with the level 0, but it should be 1 since the previous call opened a parenthesis. So the problem is that left (['('; ')'], 0) is passing the wrong level value when it makes its recursive call.

```<code>    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
                     ^
</code>```

Now that you've located the problem, the correction should be obvious: in the recursive call, you need to remember the number of opening parentheses somehow — that's what level is for. So level here should be 1, not 0.

```<code>let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 1)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
;;
let is_balanced klm =
  let brk = list_car klm in
  left (brk, 0) ;;
</code>```

(Remember that in the toplevel, after redefining left, you need to redefine is_balanced as well, even if its textual definition hasn't changed: the old definition refers to the old definition of left.)

I think is_balanced is now correct for inputs that consists solely of parentheses. It doesn't properly ignore other characters, but I'll let you debug that on your own. It may help to write the code in a simpler way, taking advantage of the fact that you can match on the first element of the list, on the level, or both. For example, the incorrect case above was actually unnecessary: you could have made the first case

```<code>    | ')'::xs, 0 -> false
</code>```

and the second case already handles lists starting with ( correctly: when the first character is (, the logic is the same regardless of the value of the level.

Body:
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"

let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;

But I got the following results:

is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false

Body:
When learning to program, it's important not only to learn programming techniques (such as algorithms) and programming languages, but also tools.

You're confronted with a problem: you've written some code that takes some input and returns the wrong input, but you don't understand why. There are two main approaches to this kind of problem:

Break down the code into smaller pieces, and test them separately, until you find one (or more) that doesn't return the outputs you wanted.

Use debugging tools to look at what's happening inside the program.

Here you can test list_car independently and see that it's not the source of the problem. There's not much you can do to break down is_balanced, but you can take out left and make it a top-level function.

let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
;;
let is_balanced klm =
  let brk = list_car klm in
  left (brk, 0) ;;

That's not going to help directly, because the problem is inside left and it's all one thing that can't really be broken down into smaller pieces. However, making left a toplevel function allows you to use a simple debugging tool: tracing in the toplevel. (A function doesn't have to be at the top level to debug it, but it does to use the toplevel's simple tracing function.)

# #trace left;;
left is now traced.
# is_balanced "()";;
left <-- (['('; ')'], 0)
left <-- ([')'], 0)
left --> false
left --> false

Now you can see where the code is going wrong: the second call to left is made with the level 0, but it should be 1 since the previous call opened a parenthesis. So the problem is that left (['('; ')'], 0) is passing the wrong level value when it makes its recursive call.

    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
                     ^

Now that you've located the problem, the correction should be obvious: in the recursive call, you need to remember the number of opening parentheses somehow — that's what level is for. So level here should be 1, not 0.

let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 1)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
;;
let is_balanced klm =
  let brk = list_car klm in
  left (brk, 0) ;;

(Remember that in the toplevel, after redefining left, you need to redefine is_balanced as well, even if its textual definition hasn't changed: the old definition refers to the old definition of left.)

I think is_balanced is now correct for inputs that consists solely of parentheses. It doesn't properly ignore other characters, but I'll let you debug that on your own. It may help to write the code in a simpler way, taking advantage of the fact that you can match on the first element of the list, on the level, or both. For example, the incorrect case above was actually unnecessary: you could have made the first case

    | ')'::xs, 0 -> false

and the second case already handles lists starting with ( correctly: when the first character is (, the logic is the same regardless of the value of the level.


来源: stackexchange

问:
Outlook Interop Folder.CopyTo method work offline without server connection
I'm trying to copy outlook inbox mail to new pst file with outlook interop. I can do with folder.CopyTo(destination) method and it works i can copy from ost to pst. But the problem is currenlty exchange server is not available and when i run the command without internet connection (or exchange server is unavailable to client ) i get exception saying "network problems are preventing connection to microsoft exchange."

If i try to read each item in outlook (.ost) one by one  and create copy of item and move it to new pst i can do it offline. But it's slower and mostly outlook is gets into not responding state.

Is it possbile to use  folder.CopyTo() method in outlook interop offline without server connection ?

答:
Open Outlook in cached mode, and then copy the Inbox folder to the target folder. There is a chance that not all content of the folder is cached on the client side, so it is not possible to copy the full content available on the server side only without a connection available.

Also you may check out the DisableCrossAccountCopy value in the window registry:

```<code>HKCU\Software\Microsoft\Office\16.0\Outlook
</code>```

where 16.0 stands for the Outlook version. It has the side effect of disabling this method.

ContentLicense: CC BY-SA 4.0

Body:
Open Outlook in cached mode, and then copy the Inbox folder to the target folder. There is a chance that not all content of the folder is cached on the client side, so it is not possible to copy the full content available on the server side only without a connection available.

Also you may check out the DisableCrossAccountCopy value in the window registry:

HKCU\Software\Microsoft\Office\16.0\Outlook

where 16.0 stands for the Outlook version. It has the side effect of disabling this method.


问:
Multiple errors in ServiceStack Angular client
We just started getting these errors when building our Angular project

```<code> Error: node_modules/@servicestack/client/dist/index.d.ts:484:20 - error TS1005: ';' expected.

484     get completed(): boolean;
                       ~

Error: node_modules/@servicestack/client/dist/index.d.ts:484:22 - error TS2693: 'boolean' only refers to a type, but is being used as a value here.

484     get completed(): boolean;
                         ~~~~~~~

Error: node_modules/@servicestack/client/dist/index.d.ts:484:5 - error TS1131: Property or signature expected.

484     get completed(): boolean;
</code>```

using "@servicestack/client": "^1.1.17"

答: We fixed by using "@servicestack/client": "1.0.59"</p>

Body:
We just started getting these errors when building our Angular project

 Error: node_modules/@servicestack/client/dist/index.d.ts:484:20 - error TS1005: ';' expected.

484     get completed(): boolean;
                       ~

Error: node_modules/@servicestack/client/dist/index.d.ts:484:22 - error TS2693: 'boolean' only refers to a type, but is being used as a value here.

484     get completed(): boolean;
                         ~~~~~~~

Error: node_modules/@servicestack/client/dist/index.d.ts:484:5 - error TS1131: Property or signature expected.

484     get completed(): boolean;

using "@servicestack/client": "^1.1.17"


问:
Why is use effect rendering the page twice?
I have data I'm trying to fetch and use with the code below, however when I am logging the value of records I get an empty array first and my fetched object second. Because of this, I'm unable to access the object's information in my app.</p>
```<code>
  const [records, setRecords] = useState([]);

 useEffect(() => {
    async function getRecords() {
      const response = await fetch(`http://localhost:5000/record`);

      if (!response.ok) {
        const message = `An error occurred: ${response.statusText}`;
        window.alert(message);
        return;
      }

      const records = await response.json();
      setRecords(records);
    }

    getRecords();

    return;
  }, []);

  console.log(records);
</code>```

答:
The first render triggers the effect.

The effect calls setRecords which triggers the second render.

You need to write your display logic so it can account for records defaulting to an empty array.

Body:
I have data I'm trying to fetch and use with the code below, however when I am logging the value of records I get an empty array first and my fetched object second. Because of this, I'm unable to access the object's information in my app.

  const [records, setRecords] = useState([]);

 useEffect(() => {
    async function getRecords() {
      const response = await fetch(`http://localhost:5000/record`);

      if (!response.ok) {
        const message = `An error occurred: ${response.statusText}`;
        window.alert(message);
        return;
      }

      const records = await response.json();
      setRecords(records);
    }

    getRecords();

    return;
  }, []);

  console.log(records);


问:
Printing a multidimensional array in C
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

```<code>#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}
</code>```

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

答:
In

```<code>    for ( p = arr; p <= arr+6; p++)
</code>```

the expression arr, as an rvalue, is a pointer to the first element of the array (which is of type int [3], so each time you increment that pointer, it moves three int positions forward ---a whole row---, and so, arr + 6 points just after the sixth row of the array (if the array should ever had six rows)  You can do it (with the proper explicit pointer conversions, as you are mixing pointers to int with pointers to int [3]) with the expression arr + 2 which is the addres of the first array element after the second row (and the number of rows of the array).

You can do it also declaring

```<code>    int (*aux)[2][3] = &arr;  /* aux is a pointer to the whole 3x2 array,
                        * so aux + 1 will be the position of the second
                        * 2D array after this one */
</code>```

and then

```<code>    int *end = (int *)(aux + 1);
</code>```

or simply

```<code>    int *end = (int *)(&arr + 1); /* see below */
</code>```

(Beware that arr and &arr are both pointers and point to the same place, but they are not the same type (arr is of type int (*)[3] and &arr is of type int(*)[2][3])

So let's rewrite your code as

```<code>    for (p = (int *)arr; p < end; p++)
</code>```

or

```<code>    for (p = (int *)arr; p < (int *)&arr + 1; p++)
</code>```

would work, which seems more natural to do the calculus in complete array units than in rows or single cells (and you can change freely the dimensions of the array)

Your code would be:

```<code>#include <stdio.h>
int main()
{
    int arr[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
    int *end = (int *)(&arr + 1); /* try to avoid evaluating this expression in the loop
                                   * despite that it can be optimized to comparing
                                   * with a constant value */
    char *sep = "";
    for (int *p = (int *)arr; p < end; p++)
    {
        printf("%s%d", sep, *p);
        sep = ", ";
    }
    putchar('\n');
    return 0;
}
</code>```

(Beware that you have to use < operator and not <= as you don't want to print the value pointed by end, because it lies one place outside of the array)

Finally a note: this will work with true arrays, but not with function parameters declared as arrays, because they decay to pointers and then &arr is not a pointer to data the size of the array, but it is the address of the parameter itself, which points to the array somewhere else.

Title: Printing a multidimensional array in C

Body:
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

Body:
In

    for ( p = arr; p <= arr+6; p++)

the expression arr, as an rvalue, is a pointer to the first element of the array (which is of type int [3], so each time you increment that pointer, it moves three int positions forward ---a whole row---, and so, arr + 6 points just after the sixth row of the array (if the array should ever had six rows)  You can do it (with the proper explicit pointer conversions, as you are mixing pointers to int with pointers to int [3]) with the expression arr + 2 which is the addres of the first array element after the second row (and the number of rows of the array).

You can do it also declaring

    int (*aux)[2][3] = &arr;  /* aux is a pointer to the whole 3x2 array,
                        * so aux + 1 will be the position of the second
                        * 2D array after this one */

and then

    int *end = (int *)(aux + 1);

or simply

    int *end = (int *)(&arr + 1); /* see below */

(Beware that arr and &arr are both pointers and point to the same place, but they are not the same type (arr is of type int (*)[3] and &arr is of type int(*)[2][3])

So let's rewrite your code as

    for (p = (int *)arr; p < end; p++)

or

    for (p = (int *)arr; p < (int *)&arr + 1; p++)

would work, which seems more natural to do the calculus in complete array units than in rows or single cells (and you can change freely the dimensions of the array)

Your code would be:

#include <stdio.h>
int main()
{
    int arr[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
    int *end = (int *)(&arr + 1); /* try to avoid evaluating this expression in the loop
                                   * despite that it can be optimized to comparing
                                   * with a constant value */
    char *sep = "";
    for (int *p = (int *)arr; p < end; p++)
    {
        printf("%s%d", sep, *p);
        sep = ", ";
    }
    putchar('\n');
    return 0;
}

(Beware that you have to use < operator and not <= as you don't want to print the value pointed by end, because it lies one place outside of the array)

Finally a note: this will work with true arrays, but not with function parameters declared as arrays, because they decay to pointers and then &arr is not a pointer to data the size of the array, but it is the address of the parameter itself, which points to the array somewhere else.


问:
How to output logs in a containerized application?
Normally, in docker/k8s, it's recommended that directly ouput the logs to the stdout.

Then we can use kubectl logs or docker logs to see the logs.

like: time=123 action=write msg=hello world , as a tty, it might be colorized for human friendliness.

However, if we want to export the logs to a log processing center, like EFK (elasticsearch-fluentd-kibana), we need a json-format log file.

like: {"time"=123,"action"="write","msg"="hello world"}

What I want?

Is there a log method that can take into account both human friendliness and json format?

I'm looking for a way that if I use docker logs, then I can get human-readable logs, and at the same time, the log collector can still get the logs in json-format

Conclusion

Thanks for the answer below. I have got 2 methods:

different log format in different env:

1.1 use text-format in developing: docker logs will print colorized and human readable logs.

1.2 use json-format in production: EFK can process json-format well.

log collector's format convertion
2.1 we use text-format, but in log collector like fluentd we can define some scripts to translate text-format kv pair to json-format kv pair.

答:
yes you can do that with Flunetd, below are the basic action items that you need to take to finalize this setup

Configure docker container to log to stdout (you can use any format you like)

Configure FluentD to tail docker files from /var/lib/docker/containers/*/*-json.log

parse logs with Flunetd and change the format to JSON logs

output the logs to Elasticsearch.

This article shows exactly how to do this setup also this one explain how to parse Key-Value logs


问:
Selenium: Open browsers one at a time from Array of IWebDriver
We are doing a Proof of Concept with Selenium and MS Test at our company. We are supporting only three browsers for the POC; Chrome, Firefox, and Edge.

I have created an array of IWebDriver and added the browsers to it in this way:

```<code>    private IWebDriver[] drivers = { new ChromeDriver(), new FirefoxDriver(), new EdgeDriver() };

    [TestMethod]
    [TestCategory("SmokeTest")]
    public void LoadHomePageWhenInitiated()
    {

        foreach (var driver in drivers)
        {
            using (driver)
            {
                // arrange (do prep work here, if needed)
                var searchPage = new SearchPage(driver);

                // act  (perform the actual test)
                driver.Manage().Window.Maximize();
                searchPage.NavigateTo();

                // assert (determine pass/fail outcome)

                // doesn't seem to be closing the browser like it should
                driver.Close();
            }

        }
    }
</code>```

What I'd hoped for is that each browser would initialize in succession (at the foreach or the using), each run the tests, and the close. At that point the next browser would initialize and run the same tests.

What's happening is that all three browsers are opening at the time the array is created.

I'm thinking there must be a way to do this with [ClassInitialize()] or [TestInitialize()] but at the moment cannot determine how to accomplish what I'm looking for.

I appreciate any insights on a better way to accomplish this with Selenium and MS Test.

答:
This seems to have solved the problem. The browsers now open one at a time.</p>
```<code>    private Func<IWebDriver>[] driverBuilders = { () => new ChromeDriver(), () => new FirefoxDriver(), () => new EdgeDriver() };

    [TestMethod]
    [TestCategory("SmokeTest")]
    public void LoadHomePageWhenInitiated()
    {
        foreach (var driverBuilder in driverBuilders)
        {
            using (var driver = driverBuilder.Invoke())
            {
                // arrange (do prep work here, if needed)
                var searchPage = new SearchPage(driver);

                // act  (perform the actual test)
                driver.Manage().Window.Maximize();
                searchPage.NavigateTo();

                // assert (determine pass/fail outcome)
                // We don't need an assert here because the NavigateTo verifies we are on the
                // correct page.

                // doesn't seem to be closing the browser like it should
                driver.Close();
            }

        }
    }
</code>```

Body:
We are doing a Proof of Concept with Selenium and MS Test at our company. We are supporting only three browsers for the POC; Chrome, Firefox, and Edge.

I have created an array of IWebDriver and added the browsers to it in this way:

    private IWebDriver[] drivers = { new ChromeDriver(), new FirefoxDriver(), new EdgeDriver() };

    [TestMethod]
    [TestCategory("SmokeTest")]
    public void LoadHomePageWhenInitiated()
    {

        foreach (var driver in drivers)
        {
            using (driver)
            {
                // arrange (do prep work here, if needed)
                var searchPage = new SearchPage(driver);

                // act  (perform the actual test)
                driver.Manage().Window.Maximize();
                searchPage.NavigateTo();

                // assert (determine pass/fail outcome)

                // doesn't seem to be closing the browser like it should
                driver.Close();
            }

        }
    }

What I'd hoped for is that each browser would initialize in succession (at the foreach or the using), each run the tests, and the close. At that point the next browser would initialize and run the same tests.

What's happening is that all three browsers are opening at the time the array is created.

I'm thinking there must be a way to do this with [ClassInitialize()] or [TestInitialize()] but at the moment cannot determine how to accomplish what I'm looking for.

I appreciate any insights on a better way to accomplish this with Selenium and MS Test.

Body:
This seems to have solved the problem. The browsers now open one at a time.

    private Func<IWebDriver>[] driverBuilders = { () => new ChromeDriver(), () => new FirefoxDriver(), () => new EdgeDriver() };

    [TestMethod]
    [TestCategory("SmokeTest")]
    public void LoadHomePageWhenInitiated()
    {
        foreach (var driverBuilder in driverBuilders)
        {
            using (var driver = driverBuilder.Invoke())
            {
                // arrange (do prep work here, if needed)
                var searchPage = new SearchPage(driver);

                // act  (perform the actual test)
                driver.Manage().Window.Maximize();
                searchPage.NavigateTo();

                // assert (determine pass/fail outcome)
                // We don't need an assert here because the NavigateTo verifies we are on the
                // correct page.

                // doesn't seem to be closing the browser like it should
                driver.Close();
            }

        }
    }


问:
Visual Studio 2022 Git context menu does not appear anymore
All,

In the previous version of VS (19) was a lovely source files context menu that could provide basic git operations like "blame", "compare with unmodified", "commit", etc. But in new VS 22 version git context menu completely disappeared.

I have feeling it was deleted.
Does anyone know the good replacement of this feature? Any extension that provides a git hub context menu?

答: Not sure what's going on in your v Visual Studio 2022. Mine has a Git context menu at the bottom of the context menu.</p>


问:
How would I paginate multiples of 20 correctly based on query params?
When the user inputs an offSet value in the query param in the URL, oddly enough, when $take = 20; and $page = 1; - this is when it displays the relevant data, but I'm not sure why numbers like 2, 4, 5, 10 won't work. So what's wrong with my code?

```<code>$results = $response->json()['results'];

collect($results);
$page = $request->get('offSet');
$take = 20;
$skip = ($page - 1) * $take;
$paginationResults = collect($results)->skip($skip)->take($take)->all();

dd(paginationResults);
</code>```

答:
you can use the chunk methods of collection</p>
```<code>$results = collect($result);
$outputs = $results->chunck(20)[$request->input('offset')];
</code>```

Body:
When the user inputs an offSet value in the query param in the URL, oddly enough, when $take = 20; and $page = 1; - this is when it displays the relevant data, but I'm not sure why numbers like 2, 4, 5, 10 won't work. So what's wrong with my code?

$results = $response->json()['results'];

collect($results);
$page = $request->get('offSet');
$take = 20;
$skip = ($page - 1) * $take;
$paginationResults = collect($results)->skip($skip)->take($take)->all();

dd(paginationResults);

Body:
you can use the chunk methods of collection

$results = collect($result);
$outputs = $results->chunck(20)[$request->input('offset')];


问:
websocket server and client using WebsocketSharp on localhost
I am trying to write a simple client-server application using WebsocketSharp on the same device (localhost) but I keep getting a "Not a Websocket handshake response.

the client is set up like so:

```<code>private const int _port = 555;
 private static WebSocket _ws = new WebSocket("ws://" + IPAddress.Loopback.ToString() + $":{_port}/websocket" );
</code>```

also tried with / WebSocket

the server is set up like so

```<code>private const int _port = 555;
        private static  WebSocketServer _ws = new WebSocketServer(IPAddress.Loopback, _port);
</code>```

thankyou

答: It doesn't look like you add the service ... this is 8 months old BUT Im not sure if you figured this out or not.</p>

Body:
I am trying to write a simple client-server application using WebsocketSharp on the same device (localhost) but I keep getting a "Not a Websocket handshake response.

the client is set up like so:

private const int _port = 555;
 private static WebSocket _ws = new WebSocket("ws://" + IPAddress.Loopback.ToString() + $":{_port}/websocket" );

also tried with / WebSocket

the server is set up like so

private const int _port = 555;
        private static  WebSocketServer _ws = new WebSocketServer(IPAddress.Loopback, _port);

thankyou


问:
text-align right and padding right
I've seen this posted everywhere, with no real help, or it being closed for no reason other then moderators feeling it would be 'unhelpful' in the future even though google whips up a nice result summing some 55,000+ relevant results.

So, why won't padding-right work with a parent, and text-align right child?

```<code>.rightcbar {
    display: block;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 20px #dbd69d;
    padding-right: 50px;
    height: 152px;
    width: 592px;
    line-height: 152px;
    background: url(rightcbar.png) no-repeat;
}

.rightcbar .rightctext {
    display: inline-block;
    width: 100%;
    text-align: right;
    font-size: 25px;
    color: #f3f1de;
    font-size: 25px;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 10px #aaa;
    -webkit-font-smoothing: subpixel-antialiased;
}
</code>```

The HTML

```<code><div id="rightc">
    <div class="rightcbar">
        <div class="rightctext">Test</div>
    </div>
    <div class="rightcbar">
        <div class="rightctext">Test</div>
    </div>
    <div class="rightcbar">
        <div class="rightctext">Test</div>
    </div>
</div>
</code>```

Smeegs helped explain exactly why things were not working as I was intending below; if you are interested. Here is the revised, and working code.

```<code>.rightcbar {
    display: block;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 20px #dbd69d;
    padding-right: 50px;
    height: 152px;
    width: 592px;
    line-height: 152px;
    background: url(rightcbar.png) no-repeat;
    background-position: center right;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;
}

.rightcbar .rightctext {
    display: inline-block;
    width: 100%;
    text-align: right;
    font-size: 25px;
    color: #f3f1de;
    font-size: 25px;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 10px #aaa;
    -webkit-font-smoothing: subpixel-antialiased;
    cursor: pointer;
}
</code>```

Live example

答:
Try this, on the container holding your text

```<code>.rightctext{ box-sizing: border-box; padding-right:10px;}
</code>```

The box-sizing property will force the container object to take the padding on the right into account.

Hopefully that's what you're looking to achieve. *Note, adjust the px accordingly.

ContentLicense: CC BY-SA 3.0

Title: text-align right and padding right

Body:
I've seen this posted everywhere, with no real help, or it being closed for no reason other then moderators feeling it would be 'unhelpful' in the future even though google whips up a nice result summing some 55,000+ relevant results.

So, why won't padding-right work with a parent, and text-align right child?

.rightcbar {
    display: block;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 20px #dbd69d;
    padding-right: 50px;
    height: 152px;
    width: 592px;
    line-height: 152px;
    background: url(rightcbar.png) no-repeat;
}

.rightcbar .rightctext {
    display: inline-block;
    width: 100%;
    text-align: right;
    font-size: 25px;
    color: #f3f1de;
    font-size: 25px;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 10px #aaa;
    -webkit-font-smoothing: subpixel-antialiased;
}

The HTML

Test

Test

Test

Smeegs helped explain exactly why things were not working as I was intending below; if you are interested. Here is the revised, and working code.

.rightcbar {
    display: block;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 20px #dbd69d;
    padding-right: 50px;
    height: 152px;
    width: 592px;
    line-height: 152px;
    background: url(rightcbar.png) no-repeat;
    background-position: center right;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;
}

.rightcbar .rightctext {
    display: inline-block;
    width: 100%;
    text-align: right;
    font-size: 25px;
    color: #f3f1de;
    font-size: 25px;
    font-family: 'Roboto', sans-serif;
    text-shadow: 0px 0px 10px #aaa;
    -webkit-font-smoothing: subpixel-antialiased;
    cursor: pointer;
}

Live example

Body:
Try this, on the container holding your text

.rightctext{ box-sizing: border-box; padding-right:10px;}

The box-sizing property will force the container object to take the padding on the right into account.

Hopefully that's what you're looking to achieve. *Note, adjust the px accordingly.


问:
How to get the child code list from the given parent code in database Using MySql or Jpa repository
I have a business requirement to write a service that returns the list of child agent codes from the given agent code. this agent_details table as below.

This table agent_code is unique, but reporter_code can be duplicated. every agent has a reporter.
Also, the reporter is an agent. According to this table agent and reporter are linked as follows.

I need a service to get the list of child agents by giving agent code.
As example when giving 1011 that should returns [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010]

when giving 1005 that should returns [ 1002, 1003].

I am using Jpa repository for this project. my entity class and repository class as follows. How to solve this problem sql query or jpa repository?

```<code>@Data
@Entity
@Table(name = "agent_details")
public class AgentDetails  {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @Column(name = "agent_code", nullable = false, length = 16)
    private String agentCode;

    @Column(name = "reporter_code", nullable = false, length = 16)
    private String reporterCode;

    @Column(name = "branch", nullable = false, length = 32)
    private String branch;
}

public interface AgentDetailsRepository extends JpaRepository<AgentDetails, Long>
{
    AgentDetails findByAgentCode(String agentCode);

    List<AgentDetails> findByReporterCode(String reporterCode);

}
</code>```

答:
You could try this (Common Table Expression):
ex.: '1011' as your dynamic parent node.

```<code>
    with recursive
    cte
      (childs)
    as
      ( select agent_code as childs
        from agent_details where agent_code = '1011'
      union all
        select  g.agent_code as childs
        from cte  a
        join agent_details g
        on a.childs = g.reporter_code
      )

    select childs as parent_and_childs from cte;

</code>```

and then create a method in your repository that recieve a List<String>.

Body:
I have a business requirement to write a service that returns the list of child agent codes from the given agent code. this agent_details table as below.

This table agent_code is unique, but reporter_code can be duplicated. every agent has a reporter.
Also, the reporter is an agent. According to this table agent and reporter are linked as follows.

I need a service to get the list of child agents by giving agent code.
As example when giving 1011 that should returns [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010]

when giving 1005 that should returns [ 1002, 1003].

I am using Jpa repository for this project. my entity class and repository class as follows. How to solve this problem sql query or jpa repository?

@Data
@Entity
@Table(name = "agent_details")
public class AgentDetails  {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @Column(name = "agent_code", nullable = false, length = 16)
    private String agentCode;

    @Column(name = "reporter_code", nullable = false, length = 16)
    private String reporterCode;

    @Column(name = "branch", nullable = false, length = 32)
    private String branch;
}

public interface AgentDetailsRepository extends JpaRepository<AgentDetails, Long>
{
    AgentDetails findByAgentCode(String agentCode);

    List<AgentDetails> findByReporterCode(String reporterCode);

}

Body:
You could try this (Common Table Expression):
ex.: '1011' as your dynamic parent node.

    with recursive
    cte
      (childs)
    as
      ( select agent_code as childs
        from agent_details where agent_code = '1011'
      union all
        select  g.agent_code as childs
        from cte  a
        join agent_details g
        on a.childs = g.reporter_code
      )

    select childs as parent_and_childs from cte;

and then create a method in your repository that recieve a List<String>.


问:
Is there any way to optimise this code?
I have a piece of code which will invert all the checkboxes on my form. I have multiple elements (not just checkboxes but also  <input type='text'>'s) in it. The reason I need it to be optimised is because it takes about two to three seconds to select all the checkboxes (275 right now).

Here's my code:

```<code>function FormInverse() {
    var iCheckbox = 1; // Because there are multiple input elements, we need to distinquish the input element ID and the row id
    var FormLength = document.FormFacturen.elements.length;
    for (i=0; i < FormLength; i++) {
        var FormElementType = document.FormFacturen.elements[i].type;
        if (FormElementType == "checkbox") {
            var Elements = document.getElementsByClassName('row' + iCheckbox); // Alle elementen in de array zetten
            var iNumElements = Elements.length;
            for (iElement=0; iElement < iNumElements; iElement++) {
                if (document.FormFacturen[i].checked == true) {
                    Elements[iElement].className = "invoice-tr-standard row" + iCheckbox;
                } else {
                    Elements[iElement].className = "invoice-tr-clicked row" + iCheckbox;
                }
            }
            iCheckbox++;
            document.FormFacturen[i].checked = !document.FormFacturen[i].checked;
        }
    }
}
</code>```

And here is the document.getElementsByClassName function:

```<code>document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = document.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};
</code>```

答:
I am pretty much sure the bottleneck here is the getElementsByClassName function, the browser needs to re-scan the whole html each time to find your element. I suggest you give your elements a unique id id="row1", id="row2", ... instead of a unique class name and use getElementById which is much faster.

```<code> var Elements = document.getElementsById('row' + iCheckbox);
</code>```

Title: Is there any way to optimise this code?

Body:
I have a piece of code which will invert all the checkboxes on my form. I have multiple elements (not just checkboxes but also  <input type='text'>'s) in it. The reason I need it to be optimised is because it takes about two to three seconds to select all the checkboxes (275 right now).

Here's my code:

function FormInverse() {
    var iCheckbox = 1; // Because there are multiple input elements, we need to distinquish the input element ID and the row id
    var FormLength = document.FormFacturen.elements.length;
    for (i=0; i < FormLength; i++) {
        var FormElementType = document.FormFacturen.elements[i].type;
        if (FormElementType == "checkbox") {
            var Elements = document.getElementsByClassName('row' + iCheckbox); // Alle elementen in de array zetten
            var iNumElements = Elements.length;
            for (iElement=0; iElement < iNumElements; iElement++) {
                if (document.FormFacturen[i].checked == true) {
                    Elements[iElement].className = "invoice-tr-standard row" + iCheckbox;
                } else {
                    Elements[iElement].className = "invoice-tr-clicked row" + iCheckbox;
                }
            }
            iCheckbox++;
            document.FormFacturen[i].checked = !document.FormFacturen[i].checked;
        }
    }
}

And here is the document.getElementsByClassName function:

document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = document.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};

Body:
I am pretty much sure the bottleneck here is the getElementsByClassName function, the browser needs to re-scan the whole html each time to find your element. I suggest you give your elements a unique id id="row1", id="row2", ... instead of a unique class name and use getElementById which is much faster.

 var Elements = document.getElementsById('row' + iCheckbox);


问:
Visual Studio GUI mouse cursor flickering between pointer and resize
In Visual Studio 2012 I have recently encountered a problem where if I use the GUI designer for adding/removing/modifying items from the toolbox on a form. The cursor flickers insanely between the resize and regular cursor whenever I select a combobox or textbox. I have not removed/added/edited the graphics card or drivers, I've not had any new hardware added or removed so I am not too sure what is happening or why this problem has surfaced itself.

Even the ComboBox tasks (small play button where you add or bind items) flickers insanely. Oddly enough this does not happen with buttons/radio buttons/checklists etc. It has only been happening with ComboBoxes and TextBoxes.

Laptop: Thinkpad T410 Win 7 64bit, intel i5 M 560 2.67GHz, 8gb Ram, Intel HD Graphics, Windows Experience Index rating 4.3.

答:
The link codeLearner provided showed me how to resolve the issue.

Try turning off per monitor awareness via unchecking Tools->Options->Environment->General->“Optimize rendering for screens…”


问:
Submit a form and then insert values in a php function
I have a form where i want to submit two entries. Its the entry_id and email. I have a php function that begins something like this:

```<code>    public function theFunction($data) {
    if (false && !empty($data['email']) && !empty($data['entry_id']) ) {
        $sql = $this->db->select()
            ->from('votes')
            ->where('entry_id = ?', $data['entry_id'])
            ->where('email = ?', $data['email'])
            ->order('created DESC');
</code>```

But how am i supposed to call this function from a php file and bringing the values from the form with me, this is far as i've come but it doesent seem to work:

```<code>$fields = array("email","entry_id");
$data = array();
foreach($fields as $field){
    $data[$field] = $_POST[$field];
}

echo theFunction($data);
</code>```

Does anyone know how i should do?

答:
This looks fine aside from this:

```<code>if (false && !empty($data['email']) && !empty($data['entry_id']) ) {
</code>```

This will never be true because of the false.

Body:
I have a form where i want to submit two entries. Its the entry_id and email. I have a php function that begins something like this:

    public function theFunction($data) {
    if (false && !empty($data['email']) && !empty($data['entry_id']) ) {
        $sql = $this->db->select()
            ->from('votes')
            ->where('entry_id = ?', $data['entry_id'])
            ->where('email = ?', $data['email'])
            ->order('created DESC');

But how am i supposed to call this function from a php file and bringing the values from the form with me, this is far as i've come but it doesent seem to work:

$fields = array("email","entry_id");
$data = array();
foreach($fields as $field){
    $data[$field] = $_POST[$field];
}

echo theFunction($data);

Does anyone know how i should do?

Body:
This looks fine aside from this:

if (false && !empty($data['email']) && !empty($data['entry_id']) ) {

This will never be true because of the false.


问:
Is it good practice to use a for-loop to set a variable?
For example, if I wanted to set x to the first element in an array that isn't equal to 0, I could write:

```<code>int x = 0;
for(; x<arr.length && arr[x] != 0; x++) {}
//use x
</code>```

Is this bad practice?

Also, hopefully this is a scenario that is basic enough to not be too opinionated.

答:
TL:DR - It's not exactly "good or bad practice", but it's not a normal way to do this.

It may take some searching, but each language likely has a way to do exactly what you want without a subjectively odd loop.

Long answer

Your way is a non-standard way to do this, but it does work. However, it'll probably cause some confusion and likely not pass a code review.

I started thinking about this in JavaScript, but I had to do some research to find a different way. I did find one. The default for not finding a value is -1, though. I modified the example code to produce the results you're looking for.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

Or use Find to get the element  instead of the index.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const array1 = [0, 0, 0, 0, 0, 0, 130, 44];

const isLargeNumber = (element) => element != 0;

let index = array1.findIndex(isLargeNumber);

console.log(index);          // 6
console.log(array1[index]);  // 130```
</div>
</div>
</p>
<p>For C#, it looks similar, but not exactly the same. Using Linq, you can't directly get the index, but if you put it into an anonymous object first, then you can.</p>
<pre class="lang-c# prettyprint-override"><code>int[] array1 = {0, 0, 0, 0, 0, 0, 130, 44};

int index = array1.Select((s, i) => new {i, s})
    .First(a => a.s != 0)
    .i;

// Or do a simpler Linq query to get the element instead
int element = array1.First(a => a != 0);

Console.WriteLine(index);          // 6
Console.WriteLine(array1[index]);  // 130
Console.WriteLine(element);        // 130
</code>```

Here's an example in Java, but I'm not going to duplicate the code.

Fetch first element of stream matching the criteria

Body:
For example, if I wanted to set x to the first element in an array that isn't equal to 0, I could write:

int x = 0;
for(; x<arr.length && arr[x] != 0; x++) {}
//use x

Is this bad practice?

Also, hopefully this is a scenario that is basic enough to not be too opinionated.

Body:
TL:DR - It's not exactly "good or bad practice", but it's not a normal way to do this.

It may take some searching, but each language likely has a way to do exactly what you want without a subjectively odd loop.

Long answer

Your way is a non-standard way to do this, but it does work. However, it'll probably cause some confusion and likely not pass a code review.

I started thinking about this in JavaScript, but I had to do some research to find a different way. I did find one. The default for not finding a value is -1, though. I modified the example code to produce the results you're looking for.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

Or use Find to get the element  instead of the index.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const array1 = [0, 0, 0, 0, 0, 0, 130, 44];

const isLargeNumber = (element) => element != 0;

let index = array1.findIndex(isLargeNumber);

console.log(index);          // 6
console.log(array1[index]);  // 130

For C#, it looks similar, but not exactly the same. Using Linq, you can't directly get the index, but if you put it into an anonymous object first, then you can.

int[] array1 = {0, 0, 0, 0, 0, 0, 130, 44};

int index = array1.Select((s, i) => new {i, s})
    .First(a => a.s != 0)
    .i;

// Or do a simpler Linq query to get the element instead
int element = array1.First(a => a != 0);

Console.WriteLine(index);          // 6
Console.WriteLine(array1[index]);  // 130
Console.WriteLine(element);        // 130

Here's an example in Java, but I'm not going to duplicate the code.

Fetch first element of stream matching the criteria


问:
using saxon extensions with ProfessionalTransformerFactory FEATURE_SECURE_PROCESSING
I know this question has been answered in a way before, but I am trying to get some definitive answers.

I am trying to adapt the barcode4j extension that was written long ago for xalan 8, which we use in FOP transformations from xml data to pdf through xslt.

I requested and received an evaluation license for Saxon PE, and in fits and starts I was able to modify the barcode4j extension to work with Saxon PE version 10.6!  I was overjoyed until I realized that Saxon Extensions of all types are disallowed when FEATURE_SECURE_PROCESSING is set true.  So my questions are these:

Is there still no exception in any version of Saxon for extensions that are specifically registered in the config?

Do I need to build on my progress and create a Saxon function instead, a la the Sql functions?

Having done that, would I be able to do something as simple as this (for example):

```<code>        File f = new File ("/tmp/config.txt");
        StreamSource source = new StreamSource(f);
        //Setup XSLT
        Configuration config = Configuration.readConfiguration(source);
        ProfessionalTransformerFactory factory = (ProfessionalTransformerFactory) TransformerFactory.newInstance();
        factory.setConfiguration(config);
        Processor processor = (Processor) config.getProcessor();

        // Here extension happens, test comes from class Test -> Test.java
        ExtensionFunction  barcode = new BarcodeFunction() ;
        processor.registerExtensionFunction(barcode);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      Transformer transformer = factory.newTransformer(xslt);
        //Setup input for XSLT transformation
        Source src = new StreamSource(new StringReader(xml));

        //Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Start XSLT transformation and FOP processing
        transformer.transform(src, res);
</code>```

And assuming a function, approximately how would this adapt to our xslt:

```<code>                                                               <fo:block text-align="center" font-size="18pt">
                                                                  <fo:instream-foreign-object>
                                                                    <bc:barcode message="{//packing_list_d/@packing_list_no}" orientation="90">
                                                                    <code39>
                                                                            <height>18.635mm</height>
                                                                            <module-width>0.25mm</module-width>
                                                                            <human-readable>none</human-readable>
                                                                            <quiet-zone enabled="true"/>
                                                                    </code39>
                                                                    </bc:barcode>
                                                                 </fo:instream-foreign-object>
                                                             </fo:block>
</code>```

I think at one time we had played around with a custom java function and ended up with this:

```<code>                                                                     <xsl:variable name="barcode-cfg">
                                                                       <barcode orientation="90">
                                                                        <code39>
                                                                            <height>18.635mm</height>
                                                                            <module-width>0.25mm</module-width>
                                                                            <human-readable>none</human-readable>
                                                                            <quiet-zone enabled="true"/>
                                                                        </code39>
                                                                      </barcode>
                                                                     </xsl:variable>
                                                                   <xsl:copy-of select="barcode:generate($barcode-cfg, //packing_list_d/@packing_list_no)"/>
</code>```

Is that about what we would need to do with a Saxon function?

I have read about how FEATURE_SECURE_PROCESSING is not necessarily "secure," but our customers and our consultants are able to upload xslt for fop transformations, so we do need both the secure feature and the ability to register and run our custom function for barcodes!!

答:
FEATURE_SECURE_PROCESSING is a pretty blunt instrument. I suspect that all the things it prevents you doing can be individually constrained using finer-grained mechanisms. If you want to disable some of the things it disallows and not others, then select those you want to disable and treat them one by one. For example you can disable external document access with a URIResolver, and you can disable untrusted reflexive extension functions by registering a DynamicLoader with the Configuration that checks what classes are being dynamically loaded and only allows those you want to allow.

Are you using FEATURE_SECURE_PROCESSING because you really don't trust the XSLT stylesheet author, or are you using it because it sounds good?

Body:
I know this question has been answered in a way before, but I am trying to get some definitive answers.

I am trying to adapt the barcode4j extension that was written long ago for xalan 8, which we use in FOP transformations from xml data to pdf through xslt.

I requested and received an evaluation license for Saxon PE, and in fits and starts I was able to modify the barcode4j extension to work with Saxon PE version 10.6!  I was overjoyed until I realized that Saxon Extensions of all types are disallowed when FEATURE_SECURE_PROCESSING is set true.  So my questions are these:

Is there still no exception in any version of Saxon for extensions that are specifically registered in the config?

Do I need to build on my progress and create a Saxon function instead, a la the Sql functions?

Having done that, would I be able to do something as simple as this (for example):

        File f = new File ("/tmp/config.txt");
        StreamSource source = new StreamSource(f);
        //Setup XSLT
        Configuration config = Configuration.readConfiguration(source);
        ProfessionalTransformerFactory factory = (ProfessionalTransformerFactory) TransformerFactory.newInstance();
        factory.setConfiguration(config);
        Processor processor = (Processor) config.getProcessor();

        // Here extension happens, test comes from class Test -> Test.java
        ExtensionFunction  barcode = new BarcodeFunction() ;
        processor.registerExtensionFunction(barcode);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      Transformer transformer = factory.newTransformer(xslt);
        //Setup input for XSLT transformation
        Source src = new StreamSource(new StringReader(xml));

        //Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Start XSLT transformation and FOP processing
        transformer.transform(src, res);

And assuming a function, approximately how would this adapt to our xslt:

                                                               <fo:block text-align="center" font-size="18pt">
                                                                  <fo:instream-foreign-object>
                                                                    <bc:barcode message="{//packing_list_d/@packing_list_no}" orientation="90">
                                                                    <code39>
                                                                            <height>18.635mm</height>
                                                                            <module-width>0.25mm</module-width>
                                                                            <human-readable>none</human-readable>
                                                                            <quiet-zone enabled="true"/>
                                                                    </code39>
                                                                    </bc:barcode>
                                                                 </fo:instream-foreign-object>
                                                             </fo:block>

I think at one time we had played around with a custom java function and ended up with this:

                                                                     <xsl:variable name="barcode-cfg">
                                                                       <barcode orientation="90">
                                                                        <code39>
                                                                            <height>18.635mm</height>
                                                                            <module-width>0.25mm</module-width>
                                                                            <human-readable>none</human-readable>
                                                                            <quiet-zone enabled="true"/>
                                                                        </code39>
                                                                      </barcode>
                                                                     </xsl:variable>
                                                                   <xsl:copy-of select="barcode:generate($barcode-cfg, //packing_list_d/@packing_list_no)"/>

Is that about what we would need to do with a Saxon function?

I have read about how FEATURE_SECURE_PROCESSING is not necessarily "secure," but our customers and our consultants are able to upload xslt for fop transformations, so we do need both the secure feature and the ability to register and run our custom function for barcodes!!


问:
Sharing files, and how to stay updated?
I have a program I use on multiple computers, that I would like to keep in sync to each other.

The files shared are .json and .txt files. Am I just able to serialize back to the file every so often without cause for concern? The software is used to make transactions on an inventory, it is only used on 1 computer, and then I use the software to make purchases or restock the items after purchased. I just want to be able to access it from my computer without having to walk to the other computer, close it, and open it on my computer make my changes and close it, walk back and open it back up.

I haven't dug into this at all, as I'm not sure what exactly it is called that I am looking for.

I would think if I can just serialize back to the file it would be ok, but maybe there is an easy way to check if the file has been saved over since I have had it open on my computer?

答:
If you want to check whether or not the file was altered since some defined point in time look at the FileInfo. If you have several computers running put the file on a shared folder and use a FileSystemWatcher. In general I think there is nothing principally not working with serializing/deserializing data to disc.

Nevertheless I would suggest backing up data and considering concurrency.

Title: Sharing files, and how to stay updated?


问:
gjs/gnome-shell-extension: Updating button text every 60 seconds
I want to write a simple gnome extension that prints some text on my top bar from a text file. I managed to print the text but i'm having trouble with updating it every 60 seconds. Is it even possible with gjs?

this is what i came up with:

```<code>const {St, Clutter} = imports.gi;
const Main = imports.ui.main;
const GLib = imports.gi.GLib;

let panelButton;

function init () {
// Create a Button with "Hello World" text
panelButton = new St.Bin({
    style_class : "panel-button",
});

let fileContents = String(GLib.file_get_contents("path/to/myfile.txt")[1]);

let panelButtonText = new St.Label({
    text : fileContents,
    y_align: Clutter.ActorAlign.CENTER,
});
panelButton.set_child(panelButtonText);
}

function enable () {
// Add the button to the panel
Main.panel._centerBox.insert_child_at_index(panelButton, 2);
}

function disable () {
// Remove the added button from panel
Main.panel._centerBox.remove_child(panelButton);
}
</code>```

答:
If you want to have your extension approved by ego you'd possibly want to do it more like this (destroy in disable what you create in enable):

in extension.js:

```<code>let timeout = null;
</code>```

in function enable():

```<code>    timeout = GLib.timeout_add(GLib.PRIORITY_DEFAULT, (60 * 1000), () => {
        // ...do the right thing...
        return GLib.SOURCE_CONTINUE;
    });
</code>```

in function disable():

```<code>    if (timeout) {
        GLib.Source.remove(timeout);
        timeout = null;
    }
</code>```

Body:
I want to write a simple gnome extension that prints some text on my top bar from a text file. I managed to print the text but i'm having trouble with updating it every 60 seconds. Is it even possible with gjs?

this is what i came up with:

const {St, Clutter} = imports.gi;
const Main = imports.ui.main;
const GLib = imports.gi.GLib;

let panelButton;

function init () {
// Create a Button with "Hello World" text
panelButton = new St.Bin({
    style_class : "panel-button",
});

let fileContents = String(GLib.file_get_contents("path/to/myfile.txt")[1]);

let panelButtonText = new St.Label({
    text : fileContents,
    y_align: Clutter.ActorAlign.CENTER,
});
panelButton.set_child(panelButtonText);
}

function enable () {
// Add the button to the panel
Main.panel._centerBox.insert_child_at_index(panelButton, 2);
}

function disable () {
// Remove the added button from panel
Main.panel._centerBox.remove_child(panelButton);
}

Body:
If you want to have your extension approved by ego you'd possibly want to do it more like this (destroy in disable what you create in enable):

in extension.js:

let timeout = null;

in function enable():

    timeout = GLib.timeout_add(GLib.PRIORITY_DEFAULT, (60 * 1000), () => {
        // ...do the right thing...
        return GLib.SOURCE_CONTINUE;
    });

in function disable():

    if (timeout) {
        GLib.Source.remove(timeout);
        timeout = null;
    }


问:
How to input all 50 states in the United States without having to type them all in R?
I am trying to delete the rows in my dataset that has a U.S state name. I hope there is a way to input into the code without typing all 50 of them.
Below I am sharing the big picture and where I would like to have these states input.</p>
```<code>cshealthpredictors %>%
 filter(!region %in% c("Alabama", "Arkansas" ,"Missouri","Texas","Georgia"))
</code>```

答:
As @Ritchie mentions in the comments there's a built in for that in base R.

state.name
#>  [1] "Alabama"        "Alaska"         "Arizona"        "Arkansas"
#>  [5] "California"     "Colorado"       "Connecticut"    "Delaware"
#>  [9] "Florida"        "Georgia"        "Hawaii"         "Idaho"
#> [13] "Illinois"       "Indiana"        "Iowa"           "Kansas"
#> [17] "Kentucky"       "Louisiana"      "Maine"          "Maryland"
#> [21] "Massachusetts"  "Michigan"       "Minnesota"      "Mississippi"
#> [25] "Missouri"       "Montana"        "Nebraska"       "Nevada"
#> [29] "New Hampshire"  "New Jersey"     "New Mexico"     "New York"
#> [33] "North Carolina" "North Dakota"   "Ohio"           "Oklahoma"
#> [37] "Oregon"         "Pennsylvania"   "Rhode Island"   "South Carolina"
#> [41] "South Dakota"   "Tennessee"      "Texas"          "Utah"
#> [45] "Vermont"        "Virginia"       "Washington"     "West Virginia"
#> [49] "Wisconsin"      "Wyoming"
```

Created on 2022-02-10 by the reprex package (v2.0.1)

Body:
I am trying to delete the rows in my dataset that has a U.S state name. I hope there is a way to input into the code without typing all 50 of them.
Below I am sharing the big picture and where I would like to have these states input.

cshealthpredictors %>%
 filter(!region %in% c("Alabama", "Arkansas" ,"Missouri","Texas","Georgia"))

Body:
As @Ritchie mentions in the comments there's a built in for that in base R.

state.name
#>  [1] "Alabama"        "Alaska"         "Arizona"        "Arkansas"
#>  [5] "California"     "Colorado"       "Connecticut"    "Delaware"
#>  [9] "Florida"        "Georgia"        "Hawaii"         "Idaho"
#> [13] "Illinois"       "Indiana"        "Iowa"           "Kansas"
#> [17] "Kentucky"       "Louisiana"      "Maine"          "Maryland"
#> [21] "Massachusetts"  "Michigan"       "Minnesota"      "Mississippi"
#> [25] "Missouri"       "Montana"        "Nebraska"       "Nevada"
#> [29] "New Hampshire"  "New Jersey"     "New Mexico"     "New York"
#> [33] "North Carolina" "North Dakota"   "Ohio"           "Oklahoma"
#> [37] "Oregon"         "Pennsylvania"   "Rhode Island"   "South Carolina"
#> [41] "South Dakota"   "Tennessee"      "Texas"          "Utah"
#> [45] "Vermont"        "Virginia"       "Washington"     "West Virginia"
#> [49] "Wisconsin"      "Wyoming"

Created on 2022-02-10 by the reprex package (v2.0.1)


问:
Analysis of algorithms
I am reading algorithm analysis topic. Here is the text snippet from the book

When n doubles, the running time goes up by a factor of 2 for linear
  programs, 4 for quadratic programs, and  8 for cubic programs.
  Programs that run in logarithmic time take only an additive constant
  longer when n doubles,  and programs that run in O(n log n) take
  slightly more than twice as long to run under the same circumstances.

These increases can be hard to spot if the lower-order terms have
  relatively large coefficients and n is not large enough.

My question is what does author mean lower-order terms have relatively large coefficients? Can any one explain with example

Thanks!

答: When using O notation, you specify the largest term of the function that is your performance bound.  For example, if the performance was always bound by f = c3n3 + c2n2 + c1n + c0, you would say that is is O(n3).  The author is saying that when n is small, the coefficients may have a larger impact than n on the performance, for example if c2 were very large and c3 very small, the performance may appear to be O(n2) until the size of n dominates the coefficients if you only go by the relative performance for specific small instances of n.

Title: Analysis of algorithms


问:
Websocket client not connecting to websocket server
I have a NET Core 3.1 API in which I create a websocket server and start it when the API runs

Program.cs class in API:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace aspnetcore_api_server
{
    public class Program
    {
        public class ServerData : WebSocketBehavior
        {
            protected override void OnMessage(MessageEventArgs e)
            {
                Console.WriteLine("WS Status: Received message from client: " + e.Data);
                Send(e.Data);
            }
        }

        public static void Main(string[] args)
        {
            var wssv = new WebSocketServer("ws://127.0.0.1:1234");

            wssv.Start();

            Console.WriteLine("WS Server started on ws://127.0.0.1:1234");

            Console.ReadKey();
            wssv.Stop();
        }
    }
}
```
<p>Then I have a ASP NET MVC web app from which I'm trying to start a connection with the server:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using WebSocketSharp;

namespace aspnet_client
{
    public class WebSocketService
    {
        public WebSocketService()
        {
        }

        public void StartConnection()
        {
            using (WebSocket ws = new WebSocket("ws://127.0.0.1:1234"))
            {
                ws.Connect();
                ws.Send("Hello from client ASP NET web app!");
            }
        }

        private static void Ws_OnMessage(object sender, MessageEventArgs e)
        {
            Console.WriteLine("Receiveed from the server: " + e.Data);
        }
    }
}
</code>```

When I try to send the message to the server by doing ws.Send from the client, it throws an error stating: System.InvalidOperationException: 'The current state of the connection is not Open.'

In the CMD I am running a command netstat -aon and I can clearly see that the TCP port is open and listening (see attached image).

I'm using WebSocketSharp on both sides Client and Server.

Can someone throw some light about what I could be doing wrong or missing here?

答:
it looks like you might want to add the service

on the server side

wssv.AddWebSocketService<ServerData >("/ServerData");

on the client side your url will want to have /ServerData at the end

Body:
I have a NET Core 3.1 API in which I create a websocket server and start it when the API runs

Program.cs class in API:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace aspnetcore_api_server
{
    public class Program
    {
        public class ServerData : WebSocketBehavior
        {
            protected override void OnMessage(MessageEventArgs e)
            {
                Console.WriteLine("WS Status: Received message from client: " + e.Data);
                Send(e.Data);
            }
        }

        public static void Main(string[] args)
        {
            var wssv = new WebSocketServer("ws://127.0.0.1:1234");

            wssv.Start();

            Console.WriteLine("WS Server started on ws://127.0.0.1:1234");

            Console.ReadKey();
            wssv.Stop();
        }
    }
}

Then I have a ASP NET MVC web app from which I'm trying to start a connection with the server:

using System;
using WebSocketSharp;

namespace aspnet_client
{
    public class WebSocketService
    {
        public WebSocketService()
        {
        }

        public void StartConnection()
        {
            using (WebSocket ws = new WebSocket("ws://127.0.0.1:1234"))
            {
                ws.Connect();
                ws.Send("Hello from client ASP NET web app!");
            }
        }

        private static void Ws_OnMessage(object sender, MessageEventArgs e)
        {
            Console.WriteLine("Receiveed from the server: " + e.Data);
        }
    }
}

When I try to send the message to the server by doing ws.Send from the client, it throws an error stating: System.InvalidOperationException: 'The current state of the connection is not Open.'

In the CMD I am running a command netstat -aon and I can clearly see that the TCP port is open and listening (see attached image).

I'm using WebSocketSharp on both sides Client and Server.

Can someone throw some light about what I could be doing wrong or missing here?


问:
CSP error for bootstrap image in navbar hamburger
I just added content security policy to my Django site. I have everything working correctly except these two errors for images that I had no idea what they were

I spent a bunch of time trying to figure it out until I noticed that the icon on the bootstrap hamburger menu was gone

In the CSS I found this telling me that this must be the image in the navbar causing this error.

I found a few workarounds online but they presented security vulnerabilities and i would like to do it properly How can I go about solving this issue.

CSP

```<code>CSP_STYLE_SRC = ("'self'",
    "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css",
    ...

    )

CSP_SCRIPT_SRC = ("'self'",
    "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/",
    ...

    )
</code>```

答:
From the code snippets, it looks like you are using https://django-csp.readthedocs.io/en/latest/configuration.html package to handle the setting of the CSP directives and that is a great choice for the Django projects.

The most secure scenario would be if you allow loading of the content from the same domain and strictly forbid any other resources, it isn't practical though. A good enough strategy would be if you allow 'self' and only explicit paths like https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css. Values like https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/, cdn.jsdelivr.net or https: could raise concerns as they will be allowing a wide range of resources.

In your case data: might be required for the img-src directive or default-src which will act as a fallback in case you don't have an explicit img-src directive value.

https://csp-evaluator.withgoogle.com/ could give you more security recommendations for your current CSP configuration and specific domains that you are using.

Body:
I just added content security policy to my Django site. I have everything working correctly except these two errors for images that I had no idea what they were

I spent a bunch of time trying to figure it out until I noticed that the icon on the bootstrap hamburger menu was gone

In the CSS I found this telling me that this must be the image in the navbar causing this error.

I found a few workarounds online but they presented security vulnerabilities and i would like to do it properly How can I go about solving this issue.

CSP

CSP_STYLE_SRC = ("'self'",
    "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css",
    ...

    )

CSP_SCRIPT_SRC = ("'self'",
    "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/",
    ...

    )


问:
Check if two numbers have same digits
I need to write a program which will check if two numbers have same digits.
For example:

```<code>a = 4423, b = 2433;
</code>```

Even though their digits don't appear the same amount if times, they have same digits.

```<code>#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}
</code>```

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

答:
Using arrays is not necessary, but it sure becomes clean code:

```<code>// Remove duplicate characters from sorted array
void remove_dups(char *str)
{
    char *cur = str;
    while(*cur)
    {
        *str = *cur;
        while(*++cur == *str);
        ++str;
    }
    *str = 0;
}

int cmp(const void *a, const void *b)
{
    return *(char*)a - *(char*)b;
}

int same_digit(int a, int b)
{
    char A[22], B[22]; // Room for 64 bit. Increase if necessary.
    char Aun[11], Bun[11]; // 10 digits

    sprintf(A, "%d", a);
    sprintf(B, "%d", b);

    qsort(A, strlen(A), sizeof *A, cmp);
    qsort(B, strlen(B), sizeof *B, cmp);

    remove_dups(A);
    remove_dups(B);

    return !strcmp(A, B);
}
</code>```

Demo

Many C coders will frown on this. And it's not completely without good reason. This is how you typically would solve things in Python or Javascript. If you're writing serious C code, there's probably a reason to why you're not choosing a more high level language. And it's quite likely that those reasons has to do with the performance C can offer.

However, there's absolutely nothing that prevents you from starting with this and optimize it later when you have concluded that this code indeed is a bottleneck with a profiler. And who knows? It may be the case that this is faster. Don't do premature optimization.

There are actually many problems involving digits that becomes so much easier if you convert the numbers to arrays of digits first. And many problems involving arrays becomes much easier if you sort the arrays. Don't be afraid to have this approach as a standard tool in your toolbox.

Furthermore, it's quite common that a naive solution for unsorted arrays is O(n²) while a naive solution for a sorted array is just O(n). And since sorting can be done in O(n * log n) or better, you often get a pretty good solution. Sure, since n in this case typically is less than 10, so a naive O(n²) is probably faster anyway. But it's worth remembering. I believe that you would have to write pretty fancy code to solve this in O(n * log n) without arrays. If it's at all possible. (Not saying that it's likely not possible. Only that I don't know)

Title: Check if two numbers have same digits

Body:
I need to write a program which will check if two numbers have same digits.
For example:

a = 4423, b = 2433;

Even though their digits don't appear the same amount if times, they have same digits.

#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

Body:
Using arrays is not necessary, but it sure becomes clean code:

// Remove duplicate characters from sorted array
void remove_dups(char *str)
{
    char *cur = str;
    while(*cur)
    {
        *str = *cur;
        while(*++cur == *str);
        ++str;
    }
    *str = 0;
}

int cmp(const void *a, const void *b)
{
    return *(char*)a - *(char*)b;
}

int same_digit(int a, int b)
{
    char A[22], B[22]; // Room for 64 bit. Increase if necessary.
    char Aun[11], Bun[11]; // 10 digits

    sprintf(A, "%d", a);
    sprintf(B, "%d", b);

    qsort(A, strlen(A), sizeof *A, cmp);
    qsort(B, strlen(B), sizeof *B, cmp);

    remove_dups(A);
    remove_dups(B);

    return !strcmp(A, B);
}

Demo

Many C coders will frown on this. And it's not completely without good reason. This is how you typically would solve things in Python or Javascript. If you're writing serious C code, there's probably a reason to why you're not choosing a more high level language. And it's quite likely that those reasons has to do with the performance C can offer.

However, there's absolutely nothing that prevents you from starting with this and optimize it later when you have concluded that this code indeed is a bottleneck with a profiler. And who knows? It may be the case that this is faster. Don't do premature optimization.

There are actually many problems involving digits that becomes so much easier if you convert the numbers to arrays of digits first. And many problems involving arrays becomes much easier if you sort the arrays. Don't be afraid to have this approach as a standard tool in your toolbox.

Furthermore, it's quite common that a naive solution for unsorted arrays is O(n²) while a naive solution for a sorted array is just O(n). And since sorting can be done in O(n * log n) or better, you often get a pretty good solution. Sure, since n in this case typically is less than 10, so a naive O(n²) is probably faster anyway. But it's worth remembering. I believe that you would have to write pretty fancy code to solve this in O(n * log n) without arrays. If it's at all possible. (Not saying that it's likely not possible. Only that I don't know)


问:
Python Dash standalone HTML file same as Plotly
I usually do plots with Plotly and save them as standalone HTML files, which is extremely convenient for sharing them with colleagues and to "freeze" the data that is being displayed. This is an example I made with

```<code>plotly.offline.plot(
    plotly_plot,
    filename = 'standalone great plot.html',
)
</code>```

Now I want to do the same with a very simple Dash app that has no server-side requirements at all, it is just a bunch of Plotly figures and some text. How can I do this?

Example of what I want

Consider the first example that is shown in this tutorial, which I copy-paste here for easiness:

```<code># -*- coding: utf-8 -*-

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

When I run this with Python and then open http://127.0.0.1:8050/ in my browser I see this:

so as can be seen this is basically a single Plotly figure with some text. So it must be somehow possible to produce the standalone HTML file with this content.

I want to replicate the behavior of plotly.offline.plot with this. How can I do it? I have tried to do "File → Save Page As" in my web browser but the resulting HTML fails to display because the server (the Python app.py file) is not running.

答:
The subject is old but I was looking for the same question for making a html file with clickable dashtable.

For standalone plotly figure with static text, you could have a look at jupyter notebook. notebook can be convert to standalone html file while keeping interactive plot.

Body:
I usually do plots with Plotly and save them as standalone HTML files, which is extremely convenient for sharing them with colleagues and to "freeze" the data that is being displayed. This is an example I made with

plotly.offline.plot(
    plotly_plot,
    filename = 'standalone great plot.html',
)

Now I want to do the same with a very simple Dash app that has no server-side requirements at all, it is just a bunch of Plotly figures and some text. How can I do this?

Example of what I want

Consider the first example that is shown in this tutorial, which I copy-paste here for easiness:

# -*- coding: utf-8 -*-

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

When I run this with Python and then open http://127.0.0.1:8050/ in my browser I see this:

so as can be seen this is basically a single Plotly figure with some text. So it must be somehow possible to produce the standalone HTML file with this content.

I want to replicate the behavior of plotly.offline.plot with this. How can I do it? I have tried to do "File → Save Page As" in my web browser but the resulting HTML fails to display because the server (the Python app.py file) is not running.


问:
How to display raw data from CSV in Excel
When I open a CSV file in Excel, data is formatted into values that aren't useful.

For example, I have a CSV with raw data

```<code>id,        studyid, studystartdatetime,      19960333152518,     19960444074329
10219922,  330732,  2020-10-26 07:22:03.000, 13.728111605495413, 0.8199649107182145
10222451,  331814,  2020-11-03 10:28:10.000, 43.369795528728545, 0.8648709765481933
</code>```

and when I open this in Excel, it shows me

```<code>id,        studyid, studystartdatetime,   2E+13,     2E+13
10219922,  330732,  22:03.0,              13.72811,  0.81996
10222451,  331814,  28:10.0,              43.36979,  0.86487
</code>```

How can I disable any type of formatting that occurs and view the raw data? There is going to be hundreds of columns in the CSVs I am using, so reformatting each column is not an option.

答:
Go to Data -> From Text/CSV

Choose your CSV file from File Explorer

Select Transform Data

Select all cells with Ctrl-A

Click Use First Row as Headers

Click Datatype: Any and select Text and click Replace current, if prompted.

Click Close and Load

Body:
When I open a CSV file in Excel, data is formatted into values that aren't useful.

For example, I have a CSV with raw data

id,        studyid, studystartdatetime,      19960333152518,     19960444074329
10219922,  330732,  2020-10-26 07:22:03.000, 13.728111605495413, 0.8199649107182145
10222451,  331814,  2020-11-03 10:28:10.000, 43.369795528728545, 0.8648709765481933

and when I open this in Excel, it shows me

id,        studyid, studystartdatetime,   2E+13,     2E+13
10219922,  330732,  22:03.0,              13.72811,  0.81996
10222451,  331814,  28:10.0,              43.36979,  0.86487

How can I disable any type of formatting that occurs and view the raw data? There is going to be hundreds of columns in the CSVs I am using, so reformatting each column is not an option.


问:
Why does the hover transform scale is so bad?
I have this code using hover, when i use it is all ok , bit when I remove the mouse the element returns back so fast and It makes it look improper.

.cmd-1:hover {
  transform: scale(1.1);
  transition: 0.7s;
  color: gold;
  transition: all 0.7s ease-in-out;
}
```

答:
The problem is that as soon as the user moves the mouse away the element loses its :hover state and with it it loses the transition  you have set.

So, put that transition on the element without the hover. It will be inherited when the element is hovered also so both directions will ease to their new sizes.

.cmd-1 {
  transition: all 0.7s ease-in-out;
}

.cmd-1:hover {
  transform: scale(1.1);
  transition: 0.7s;
  color: gold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cmd-1">HELLO
</div>.</code>```

Body:
The problem is that as soon as the user moves the mouse away the element loses its :hover state and with it it loses the transition  you have set.

So, put that transition on the element without the hover. It will be inherited when the element is hovered also so both directions will ease to their new sizes.

.cmd-1 {
  transition: all 0.7s ease-in-out;
}

.cmd-1:hover {
  transform: scale(1.1);
  transition: 0.7s;
  color: gold;
}

<div class="cmd-1">HELLO
</div>.